diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 3e4e235..7bf61b4 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,5 +1,13 @@ # 开发交接(2026-10-20) +## 本轮BPM系统设置改造 + +用户已确认BPM可恢复启停、轻量连接检测和原生被动监听方案,本轮在既有本机测试工作树顺序实施。连接停用改为保留账号/会话的暂停,启用恢复检查;真正删除才清除身份。卡片分别显示登录会话、订单接口与到达监听状态,后台复用近期成功业务请求,明确区分认证过期、权限不足和网络失败。 + +原生SignalR仅接收已核实的待办/待阅变化线索;首次连接、重连与定期完整对账读取真实列表,事件合并、分页原子提交与来源隔离保留。新监听不触发PDF、归档、发信或BPM节点动作。真实系统已验证鉴权协商、JSON握手和心跳,尚未观察自然业务事件,不能宣称全部流程版本的自然到达已验收。细节见[研究证据与方案](bpm-connection-monitoring-research-2026-10-20.md)、[实施计划](superpowers/plans/2026-10-20-bpm-passive-monitoring.md)与[本轮验收](bpm-monitoring-verification-2026-10-20.md)。 + +专项回归133项通过;新鲜完整504项中503通过、0失败、1可选ZCode CLI跳过,240个JS/CJS文件语法通过。本机测试服务启动检查随后补记于验收文档。更新前已停服并保护备份;原账号、密钥、31份采样、31份字段草稿和业务配置须保持,自动通知为false、version:1。不操作服务机,不发送真实邮件,不办理BPM,不推送或合并。 + ## 工作区与版本 当前本地开发分支为 codex/modular-refactor,工作区 C:/Users/ABS/.codex/worktrees/modular-refactor/Order Notification Automation。原Z盘源码不改。未推送或合并;本轮导航及部署检查见[订单通知管理验收](notification-navigation-verification-2026-10-19.md),前次执行闭环见[执行闭环验收](web-closure-verification-2026-10-19.md)。 diff --git a/docs/bpm-connection-monitoring-research-2026-10-20.md b/docs/bpm-connection-monitoring-research-2026-10-20.md new file mode 100644 index 0000000..c3f6982 --- /dev/null +++ b/docs/bpm-connection-monitoring-research-2026-10-20.md @@ -0,0 +1,99 @@ +# BPM连接与被动监听:核验结果和方案草案 + +日期:2026-10-20(北京时间)。范围:系统设置中的BPM启停、连接检测及流程到达监听。状态:用户已确认,改造代码已实施并进行完整验证;实际结果见[BPM监听验收](bpm-monitoring-verification-2026-10-20.md)。 + +本机工作树 `C:/Users/ABS/.codex/worktrees/modular-refactor/Order Notification Automation`,基线 `2d63491`。保留当前测试服务、原账号和数据;自动发信继续暂停,不办理BPM节点,不操作服务机。 + +## 一、现有实现的具体问题 + +| 位置 | 实际行为 | 本次需要改善的地方 | +|---|---|---| +| BPM连接卡片 | 启用状态下有“停用连接”,停用后仅能删除 | 提供完整的启用/停用按钮和清楚的运行状态 | +| 停用接口 | 关闭浏览器后删除该连接会话和托管账号;工作区状态还会删除身份与检查信息 | 将暂停使用与清除凭据分开,正常启停应可恢复 | +| 后台托管 | 启动即检查,每5分钟通过浏览器访问并验证门户 | 复用正常业务请求的成功证据;近期健康时减少额外浏览器检查 | +| 手工检查 | 通过浏览器重进门户,验证账号菜单;主要输出门户登录状态 | 单独表达身份状态、业务接口可读状态和监听状态 | +| 到达记录 | 每15秒判断调度,默认每5分钟拉取待阅列表 | 有原生变化事件时及时同步,无须每次等完整周期 | +| 真实订单执行 | 另行读取真实待办,现有自动执行受通知启用设置门控 | 保持待办与待阅的区别;监听不绕过现有执行与发信门控 | +| 状态记录 | 重复成功检查也逐次记审计 | 保留最近证据;状态变化、失败和人工操作才形成主要审计记录 | + +主要代码依据:`web/modules/bpm/view.js`、`src/modules/bpm/api.cjs`、`session-manager.cjs`、`custodian.cjs`、`scanner.cjs`、`scan-store.cjs` 和 `src/modules/workspace/store.cjs`。 + +## 二、被动监听已经核实到哪一步 + +### 当前线上源码 + +使用现有加密会话,以只读SQLite方式取得会话,内部解密后直接请求已授权门户源码;没有导出Cookie、登录密码或Bearer值,没有调用登录提交。未实例化会写入业务状态的WorkspaceStore或RuleStore。 + +| 资源 | 实测结果 | +|---|---| +| `/Yiez/src/push/SignalR.js` | HTTP200;继承SignalRAbstract,通道为 `hubs/system` | +| `/Yiez/src/push/SignalRAbstract.js` | HTTP200;使用SignalR JSON协议,带现有登录Token,支持自动重连 | +| `/Yiez/src/workbench/Abstract.js` | HTTP200;工作待办与待阅事件分别转发为 `worklistChanged`、`informlistChanged` | +| 门户PortalAbstract源码 | 注册 `taskinstanceChanged`、`worklistChanged`、`informlistChanged` 等事件;此前缓存与当前核心协议相互印证 | + +上述脚本通过实际类继承和已观察加载器映射逐级定位,没有枚举未知接口。 + +### 当前线上传输 + +2026-10-20 15:07:使用已存在会话对 `/hubs/system/negotiate` 执行鉴权协商,返回HTTP200,可用传输包括WebSockets、ServerSentEvents、LongPolling。 + +随后建立临时WebSocket连接,发送且仅发送SignalR JSON协议握手,服务端确认成功;20秒观察中收到1次心跳。结束后关闭连接,没有调用任何Hub业务方法,也没有办理节点、标记已阅或发送邮件。 + +**结论:** 原生被动通道的鉴权、连接及协议握手可用。观察窗口中没有真实业务变化事件,不能宣称已经完成“真实订单到达 → 自动同步”的现场验收,也不能证明所有代际的流程都会完整推送。 + +研究代码和非业务证据保存在忽略目录 `output/verification/bpm-monitor-research` 及 `research-bpm-passive.cjs`。这些是一次性研究文件,不作为正式监听器,也不随服务启动。 + +## 三、建议的改造 + +这次涉及连接生命周期、会话健康和监听调度,按架构调整设计。优先实现以下明确范围,其他系统设置暂不扩大。 + +### 1. 启用和停用 + +- 已启用卡片显示“停用连接”按钮,已停用卡片显示“启用连接”按钮;执行中显示进度并禁重。 +- 停用后停止该连接监听、自动检查和新的扫描,并关闭相关临时浏览器上下文。已接受的异步工作须完成清理;迟到响应不能把停用连接改回已连接。 +- 停用保留加密托管账号、会话和历史记录。启用后先核验已有会话,再恢复监听与对账;过期才进入既有续登流程。 +- 删除连接与清除托管账号仍是独立动作,不用启停按钮承担清除身份的作用。以前已停用并清除过的凭据不能恢复,应明确提示重新配置。 +- 启停沿用管理员权限,操作者范围、当前状态和并发版本均由服务端校验。内存禁用标记与持久启停状态要一致,服务重启继续有效。 + +### 2. 连接检测 + +卡片展示三项简要结果: + +| 结果 | 依据 | +|---|---| +| 登录会话 | 最近经过认证的门户或业务请求;显示观察时间,不能拿旧成功冒充实时检查 | +| 订单接口 | 实际只读待办查询的成功/失败;与普通待阅查询分别记录 | +| 到达监听 | 已连接、重连中、轮询兜底、已暂停及最近同步时间 | + +检测顺序:已有请求近期成功则复用健康证据;需要手工验证或证据过期时执行轻量只读接口检查。只有明确认证失效才进入已有合法续登;超时、网络断开、服务端错误不能触发反复提交账号密码。 + +同连接的手工检查、后台保活、事件同步及重新登录合并/互斥;事件风暴不能造成重复浏览器与重复请求。人工登录窗口打开时,监听和自动工作应主动协调让出,不改动用户正在输入的表单。 + +### 3. 到达监听 + +推荐“原生推送触发+重连对账+低频轮询兜底”: + +1. 连接启用且身份可用时订阅原生系统通道,支持握手、心跳超时、有限退避重连和停止清理。 +2. `worklistChanged` 触发真实待办同步;`informlistChanged` 触发待阅到达记录同步。通用变化事件作为刷新线索,不能直接当作订单或发送指令。 +3. 短时间连续变化合并,单连接同步串行;同步中再次收到变化时最多补跑一次,避免丢掉最后一次变化或无限并发。 +4. 首次连接与每次重连成功都进行一次完整对账;按既有稳定事件身份去重,不仅比较数量。 +5. 暂按现有5分钟配置保留完整对账;监听不可用时退回该低频扫描,页面显示实际模式。无真实事件不能伪称正在实时发现订单。 +6. 列表全部分页成功后才提交本次结果;断线、列表变化、部分分页失败不清空历史、不提交半批数据。重试有界并与连接状态协调。 +7. 扫描遵守业务日历;计划发送仍要求窗口完整性与截止后的扫描证据,不能用一次推送或“数量没变”替代。 +8. 当前自动通知暂停期间,只更新允许的只读监听与到达信息,不通过事件绕过现有PDF/归档/发送门控。处理与发信开关拆分另列范围。 + +原生SSE/LongPolling也是服务器可用传输,但本工具首选已实际握手的WebSocket;本轮不同时维护多套传输实现。若WebSocket异常,明确退回现有查询对账。 + +## 四、验收必须覆盖 + +- 启停按钮、管理员与负责人权限、重复点击、版本冲突、启停跨重启。 +- 停用中关闭监听、在途请求清理、迟到响应不复活连接;启用保留身份;真正删除仍清除身份。 +- 正常业务请求更新健康状态;成功、认证过期、权限不足、网络超时、门户故障分别显示和处理,不反复重登。 +- SignalR握手/心跳/断线重连、Token失效、停止期间退避定时器、重启后恢复。 +- 事件突发、同步中再次变化、相同数量的新旧任务替换、分页失败原子性、重新连接漏消息对账。 +- 待阅与真实待办来源不混合;关闭发信、历史忽略、去重、冻结批次和BPM不办理等边界保持。 +- 采用本地假Hub与假BPM覆盖自动化回归;真实到达事件现场验证需等待自然发生的通知,不人为办理节点制造事件。 + +## 五、交付边界 + +本次方案已获用户确认并进入实施。原研究证据保留;改造、验证和本机运行状态以本轮验收文档为准。自动通知继续暂停,服务机更新另行安排。 diff --git a/docs/bpm-monitoring-verification-2026-10-20.md b/docs/bpm-monitoring-verification-2026-10-20.md new file mode 100644 index 0000000..6817d31 --- /dev/null +++ b/docs/bpm-monitoring-verification-2026-10-20.md @@ -0,0 +1,53 @@ +# BPM启停、连接检测与原生监听验收 + +日期:2026-10-20(北京时间)。基线:`2d63491`;工作树 `C:/Users/ABS/.codex/worktrees/modular-refactor/Order Notification Automation`,分支 `codex/modular-refactor`。用户已确认[核验与方案](bpm-connection-monitoring-research-2026-10-20.md)。本轮不操作服务机,不发送真实邮件,不办理BPM节点,自动通知保持暂停。 + +## 交付行为 + +| 操作 | 实际边界 | +|---|---| +| 停用/启用 | 管理员按钮,携带连接版本;正常停用保留加密账号、Cookie和记录。启用恢复待检查,先复用/验证已有会话。旧版本不能覆盖新启停状态,重复目标状态幂等。 | +| 停用中清理 | 先持久停用并阻止新工作,再关闭活动浏览器上下文、终止监听并排空已接受工作;迟到检查/事件不复活连接。 | +| 删除 | 独立确认动作,仅已停用连接可删除;清除身份成功后删除记录,失败保留停用记录。历史上已经清除的凭据不能凭新启用按钮恢复。 | +| 连接检测 | 登录会话、真实待办接口、监听通道分开显示,带实际观察时间;近期成功业务请求可复用。手工和后台同时检查合并一次;过期或强制检查才重新查询。 | +| 认证恢复 | 仅401或已知登录跳转可请求既有续登;403为权限问题,网络错误或未知跳转不触发密码提交。验证码、冷却和人工窗口互斥继续生效。 | +| 原生推送 | 固定门户系统Hub,短期Token只在内存使用;只发送JSON协议握手和ping,处理已观察的三类变化事件名,不调用Hub业务方法、不保存事件参数。 | +| 事件同步 | 待办/待阅分开读取,短时间事件合并,同步中再变化补跑一次;初次连接、重连及低频完整对账读取真实列表,不能用数量或推送参数作为订单凭据。 | +| 回退与恢复 | 通道不可用明确显示轮询兜底;握手/心跳超时、安全帧上限、退避重连和停止清理有自动化覆盖。身份更换后旧事件失效并重新订阅。 | +| 到达记录 | 可切换真实待办与待阅;待办身份含实例/任务/修订,全部分页成功才提交,失败保留旧数据。旧接口默认仍查待阅,数据和核验状态不混用。 | +| 页面刷新 | 只读取本地状态,不触发远端检测;不会清空账号输入,过期快照不重新显示已删除连接;离页不接受迟到结果。 | +| 归档/发信 | 新监听只更新允许的只读到达信息,未新增PDF、归档、邮件或BPM节点动作。实际订单协调器、时段、公司日历、批次冻结和通知启用门控不替换。 | + +## 核验记录 + +- 修改前重点基础:21通过、0失败,日志 `output-bpm-monitor-baseline.log`。 +- 重点BPM、工作区与应用生命周期回归:133通过、0失败,退出码0;日志 `output-bpm-monitor-focused.log`。 +- 新增回归先后复现并修正:缺失可恢复启停、过期版本启用、停用等待浏览器工作死锁、重复连接检查、出错通道未立即回退、身份变化旧事件、403误触续登、未知外域跳转误判认证、待办成功冒充待阅核验。 +- 本地HTTP升级服务与Node原生WebSocket实际进行握手和传输,测试Hub鉴权、事件名过滤、心跳超时、异常帧、取消与清理;不是单纯模拟内部事件回调。协调器同时验证SQLite实际保存、同数量替换、失败原子性、日历与角色限制。 +- 当前锁定依赖 `npm ci` 已成功;没有新增包或更改Node版本下限。JS/CJS语法检查共240文件通过。 +- 新鲜完整 `npm test`:504项,503通过、0失败、0取消、1项可选ZCode CLI跳过,退出码0;耗时1,239,305.5966毫秒(约20分39秒)。日志 `output-bpm-monitor-full-test.log`。本次完整套件启动后未修改业务源码。 + +完整套件已通过。测试Hub与专项结果不能替代真实BPM自然到达事件的现场验收。 + +## 已有线上证据与限制 + +研究阶段实际读取门户SignalR实现,鉴权协商200;真实WebSocket JSON握手成功,20秒中收到心跳。没有人为办理节点制造业务事件,没有观察到自然到达事件,因此不声称已完成所有流程版本的实时事件覆盖。 + +本轮将原生推送作为变化线索,并保留配置的低频完整对账;实际模式、最近同步与HTTP证据分别展示。没有推送事件时依然依靠真实查询补漏。 + +## 本机数据与更新 + +已停止原本机测试实例,受当前用户ACL保护的备份位于 `%LOCALAPPDATA%/OrderNotificationAutomationBackups/bpm-monitor-20261020-151755`。保留状态、配置和PDF;未读取或复制account-recovery。 + +修改前自动通知 `enabled:false`、`version:1`,用户1个、采样31份、字段草稿31份、邮件批次0个。临时测试会在自身目录创建身份;已有业务密钥需逐文件比对,不能因临时测试新增密钥就误判已有密钥变化。 + +完整套件通过,接下来恢复本机测试服务并核对双端口、实际监听模式与原账号/密钥/规则/采样/草稿/批次。BPM扫描库新增kind列与来源分区属于本轮预期迁移;新增只读待办记录不是执行、归档或发信。 + +## 代码职责 + +本地复核已逐项检查:持久停用先于在途排空、启停/删除串行与版本校验、暂停身份保留及删除失败可重试、身份变化使旧订阅失效、重连重新读取当前会话Token、明确认证失效才允许既有续登、角色/负责人限制,以及推送不进入执行或发送引擎。自动化重点覆盖真实本地WebSocket传输和SQLite落库;不将测试Hub事件当作线上自然事件证据。 + +- `connection-lifecycle.cjs`:连接状态版本与在途清理;`connection-health.cjs`:安全观察快照。 +- `access-client.cjs`/`auth-redirect.cjs`:轻量检查及已知认证跳转判定。 +- `signalr-client.cjs`:受限传输;`arrival-monitor.cjs`:调度、合并、重连及对账。 +- 会话管理、BPM提供器、到达存储、应用装配与系统页面复用这些模块,保留原执行/发送引擎。 diff --git a/docs/design-requirements.md b/docs/design-requirements.md index 8906f7e..3a9f00c 100644 --- a/docs/design-requirements.md +++ b/docs/design-requirements.md @@ -48,6 +48,14 @@ Excel 的15类规则是唯一业务分类。流程名称、版本、配置节点 海外订单通知书默认正文采用类别引导语、多条订单摘要、统一实际归档目录和签名;机芯号、型号、客户简称、出货方式、数量从标题段落独立提取。一个事件多个摘要不自动拆成多个PDF任务。其他类别格式保持兼容,附件仍按类别规则;旧模板变量保持原义,新增订单明细、存放地址、类别名称变量。已冻结批次不重新生成正文。 +## BPM接入与到达监听 + +连接以管理员启用/停用按钮控制,携带版本;停用保留账号、会话和历史,删除为独立清除动作。停用先发布状态、阻止新请求并关闭活动浏览器上下文,再排空在途工作;迟到响应不能复活连接。 + +连接页分别显示登录、真实待办接口与监听状态。复用近期业务HTTP成功证据,手工/后台检查合并,优先轻量请求;明确认证失效才走既有续登,权限不足、网络故障和未知跳转不重复提交凭据。 + +原生SignalR变化事件触发只读同步,初始/重连和配置间隔执行完整对账;断线退避,通道不可用显示轮询兜底。待办与待阅分别存储查询、分别核验,不能用计数或推送内容代替完整列表。监听遵守公司日历,不绕过PDF/归档/发送门控;自然事件覆盖仍须现场核验。详见[BPM本轮验收](bpm-monitoring-verification-2026-10-20.md)。 + ## 安全、运维与上线 状态保存在部署机 %LOCALAPPDATA%/OrderNotificationAutomation,BPM身份/会话、邮箱、存储、助手敏感配置用本机加密身份保护;日志不包含密码、Cookie和授权码。密钥、数据库、原邮件、业务PDF、截图不提交Git。30天工作台会话、活动续期,改密撤销旧会话;仅管理员管理团队,操作员仅连接负责人范围,viewer只读。 diff --git a/docs/superpowers/plans/2026-10-20-bpm-passive-monitoring.md b/docs/superpowers/plans/2026-10-20-bpm-passive-monitoring.md new file mode 100644 index 0000000..067455a --- /dev/null +++ b/docs/superpowers/plans/2026-10-20-bpm-passive-monitoring.md @@ -0,0 +1,69 @@ +# BPM可恢复启停与被动监听 Implementation Plan + +> **For agentic workers:** 使用 executing-plans 在当前会话顺序实施,不自动分派子代理。用户已确认方案,不重复请求设计或本机测试服务更新批准。 + +**Goal:** BPM连接可恢复启停,连接检查复用业务健康证据,以原生变化事件及时同步待办/待阅,并用完整对账补漏。 + +**Architecture:** 连接生命周期服务串行协调持久状态、会话和监听;独立SignalR客户端只处理协议/心跳/事件名,监听协调器负责退避、事件合并和只读对账。会话管理接入轻量业务检查及健康观察;待办与待阅在同一到达存储中使用不同来源命名空间、查询明确区分,正式执行仍沿用原门控。 + +**Tech Stack:** Node.js24现有运行时(项目Node.js下限保持22.13)、CommonJS、原生WebSocket、Playwright APIRequestContext、SQLite、原生JS/Tabler;不新增依赖。 + +**Spec:** [用户已确认的核验与方案](../../bpm-connection-monitoring-research-2026-10-20.md)。已现场验证系统Hub鉴权、JSON握手和心跳;真实业务变化现场观察仍待自然事件。 + +## Global Constraints + +- 仅在 C:/Users/ABS/.codex/worktrees/modular-refactor/Order Notification Automation,codex/modular-refactor 开发;原共享检出不改。 +- 不发真实邮件,不办理/标记BPM节点,不重置账号,不打印凭据,不操作服务机,不推送或合并。 +- 连接停用保留身份,删除单独清除。启停管理员权限、并发版本、迟到结果和在途清理必须测试。 +- 推送只作变化线索,不能作为订单/归档/发送凭据;历史与真实待办不混同,现有窗口、日历、冻结和发送暂停保持。 +- 本机更新前停服备份;保留账号、密钥、规则、31份采样和草稿,完成全量测试再启动并检查状态。 + +## 文件与接口 + +| 文件 | 职责及接口 | +|---|---| +| bpm/connection-lifecycle.cjs | `BpmConnectionLifecycle.change(id,enabled,input,user)` 串行版本启停;`remove`清除身份后删除 | +| bpm/connection-health.cjs | 最近认证/待办/待阅证据与安全状态快照 | +| bpm/access-client.cjs | 已观察门户与首个待办分页的轻量认证检查,不返回业务字段或Token给页面 | +| bpm/signalr-client.cjs | `connect(storageState,{signal,onEvent,onClose})`;握手后返回可停止句柄,内存持有短期Token | +| bpm/arrival-monitor.cjs | `start/stop/stopConnection/snapshot`;连接重试、事件合并、初始/重连/低频对账 | +| bpm/session-manager.cjs | `suspend/resume`保留身份;`disable`仍用于真正删除;健康复用与注入轻量检查 | +| bpm/scan-store.cjs | 运行记录区分kind;todo来源保留事件身份,默认旧查询仍为inform | +| bpm/api.cjs、workspace/api.cjs、app/dashboard.cjs、app/application.cjs | 启停/检测/监听集成,按原权限返回安全状态 | +| web/modules/bpm/view.js、arrivals.js | 按钮、三个状态、动态观察、待办/待阅筛选;不覆盖未保存输入 | + +## Task 1:可恢复连接启停 + +- [x] 写失败测试:停用保留加密账号/会话,启用恢复待检查,重复动作幂等,并发旧版本409,在途结果不能复活连接,真正删除才清除身份。 +- [x] Workspace连接增加版本,旧连接按0读取;生命周期服务先发布停用,再停止监听和会话工作;同连接启停/删除串行。 +- [x] BPM接口新增enable,disable接受新UI的version并兼容旧空请求;角色与body校验保持。前端按钮发送版本、禁重并保留表单保护。 +- [x] 运行生命周期、BPM HTTP/UI与workspace回归。 + +## Task 2:复用健康证据和轻量连接检查 + +- [x] 写失败测试:近期成功业务请求避免浏览器检查;认证失效可走既有续登,网络故障不提交凭据;状态过期不伪装实时成功。 +- [x] 独立健康观察和轻量访问客户,按已核实源检查首个分页,401/403/网络故障分开。健康证据与身份变更绑定,停用/换账号会失效。 +- [x] 正常待阅/待办请求更新对应观察,后台托管优先复用;人工检查强制只读验证。仅明确认证失效进入既有受冷却保护的续登。 +- [x] Workspace审计合并重复成功,保留状态变化和人工动作;运行BPM会话/托管与检测回归。 + +## Task 3:SignalR只读传输 + +- [x] 本地假Hub测试真实WebSocket:JSON握手、ping、事件过滤、连接失败、心跳超时、异常帧和停止。真实协议层不靠模拟调用内部回调验证。 +- [x] 实现仅固定门户或显式本地测试地址的客户端,HTTP不跟随未知跳转,凭据不进日志;握手前消息不能触发同步,拒绝过大帧。 +- [x] 有界心跳/握手超时,及时清理API上下文、WS和定时器;监听停止不再重连。 + +## Task 4:监听对账与到达页面 + +- [x] 写失败测试:事件突发合并、同步中再次变化补跑、重连全量对账、相同数量替换、分页失败原子性、停用/日历和低频兜底。 +- [x] 监听器按连接维护generation与AbortController,状态仅展示真实连接/回退;手工登录占用时让出。 +- [x] 工作待办与待阅分别同步,todo身份包含实例/任务/修订;到达页可筛选,历史记录不删除。暂停通知时不通过监听创建PDF/归档/邮件。 +- [x] 应用由监听器统一自动扫描调度,保留手工scan;现有订单执行门控及截止后完整性检查不替换。 +- [x] 页面动态更新安全状态,不刷新或覆盖用户正在填写的账号;授权、会话失效与离页迟到响应回归。 + +## Task 5:交付和本机验证 + +- [x] 同步设计要求、操作清单、交接和验收;说明现场自然事件尚未观察,不能以心跳代替业务到达验收。 +- [x] `npm ci`、新鲜完整 `npm test`、全部JS/CJS语法、文档链接和差异检查通过;测试限临时状态、假BPM/Hub与回环SMTP。 +- [ ] 本地评审生命周期、恢复、Token更新、权限与副作用;提交代码。 +- [ ] 备份后更新本机服务,核对双端口、原身份/数据和自动通知暂停;只读检查真实监听握手/模式,等待自然事件,不制造BPM节点操作。 +- [x] 保留当前分支及工作树,无推送合并。 diff --git a/docs/superpowers/specs/2026-10-16-bpm-login-design.md b/docs/superpowers/specs/2026-10-16-bpm-login-design.md index 4696141..f907d3b 100644 --- a/docs/superpowers/specs/2026-10-16-bpm-login-design.md +++ b/docs/superpowers/specs/2026-10-16-bpm-login-design.md @@ -1,5 +1,7 @@ # BPM Web 登录与会话 +2026-10-20更新:正常启停已改为保留身份的可恢复按钮,连接检查与原生监听方案见[BPM本轮验收](../../bpm-monitoring-verification-2026-10-20.md)。下文为原阶段设计,清除身份仅在删除/显式解除托管时执行。 + 用户已确认多人在各自电脑访问一台服务器,并明确只维护新版 BPM。唯一业务入口为 https://bpmn.skyworthdigital.com,登录跳转为 https://sso.skyworthdigital.com;不访问、不检查、不提供旧版入口。账号密码由用户在工作台托管表单输入,验证码在远程登录画面完成,不导入现有浏览器 Cookie。 每个连接使用独立 Playwright context,工作台通过受鉴权的 JPEG 帧和有限输入事件控制服务器浏览器。仅连接负责人及管理员可登录或检查。同一连接一次只允许一个工作台登录会话控制,空闲 10 分钟关闭,最多同时 3 个;退出工作台释放其控制。不得暴露 CDP、任意脚本执行、任意网址或 Cookie 接口。生产仅允许新版门户和 SSO 两个 HTTPS 域名,禁止下载和文件上传。 diff --git a/docs/superpowers/specs/2026-10-16-bpm-scan-design.md b/docs/superpowers/specs/2026-10-16-bpm-scan-design.md index cf57b27..c715a77 100644 --- a/docs/superpowers/specs/2026-10-16-bpm-scan-design.md +++ b/docs/superpowers/specs/2026-10-16-bpm-scan-design.md @@ -1,5 +1,7 @@ # BPM 自动扫描与到达日期视图 +2026-10-20更新:正常启停已改为保留身份的可恢复按钮,连接检查与原生监听方案见[BPM本轮验收](../../bpm-monitoring-verification-2026-10-20.md)。下文为原阶段设计,清除身份仅在删除/显式解除托管时执行。 + 日期口径:流程到达当前账号的 startTime,按 Asia/Shanghai 分日。不得用发起日期、流水号中的日期或扫描时间替代。缺失日期拒绝本次扫描,不制造日期。 新版门户公开列表模块经认证实测:GET /skyworth/todo/v2/workflow/get_process_of_inform_v4 与 GET /bpm/worklist/informlist,page/start/limit 分页,响应 total/children。两者均属于新版门户入口,不增加旧网站支持。门户 HTML 提供当前客户端 Bearer,使用服务端加密 Cookie 取回,只在内存使用。 diff --git a/docs/web-action-inventory.md b/docs/web-action-inventory.md index 410e258..0fc0e5d 100644 --- a/docs/web-action-inventory.md +++ b/docs/web-action-inventory.md @@ -73,9 +73,11 @@ | 编号 / 操作 | 权限、前置条件 | 实际执行及结果位置 | 失败 / 验收 | 状态 | |---|---|---|---|---| -| B01 新建/停用/删除连接 | 管理员;负责人有效;先停用再删 | 加密身份与连接记录 | 会话撤销/并发校验;bpm-* | 已验证可用 | +| B01 新建/启用/停用/删除连接 | 管理员;版本;先停用再删 | 按钮启停保留身份;删除才清除;在途工作排空 | 旧版本409、迟到不复活、跨重启;connection-lifecycle/bpm-http/bpm-ui | 专项验收 | | B02 远程登录、输入、刷新、返回门户、关闭 | 管理员/负责人;有效会话租约 | 白名单浏览器画面,关闭释放 | 禁任意域、下载、弹窗、过期输入;bpm-* | 已验证可用 | | B03 托管账号、更新/移除、填入、检查保存 | 管理员/负责人;本机或HTTPS | DPAPI加密会话/身份,真实状态 | 不绕验证码,不写回明文;bpm-account-* | 已验证可用 | +| B04 连接检查与状态观察 | 管理员/负责人检查,其他角色按原只读范围 | 登录/待办/监听三项;复用业务证据,轻量检查与续登分离 | 403/401/网络分开、检查合并、输入保留;connection-health/bpm-ui | 专项验收 | +| B05 原生监听、重连、完整对账、到达类型切换 | 启用连接、日历与原执行门控 | 事件名仅提示变化,待办/待阅分开,失败原子保留 | 真实本地Hub、事件合并、同数量替换、停止清理;signalr-client/arrival-monitor/bpm-scan-http-ui | 专项验收 | | M01 添加/编辑邮箱、保留空密码、保存/取消 | 管理员;本机/HTTPS、有效参数 | 加密SMTP/IMAP配置与版本 | 错误保留输入;mail-ui/mail-http | 已验证可用 | | M02 检查邮箱、收取模板、自发测试 | 管理员;已托管非只读邮箱 | 验证状态、收件记录、自身测试记录 | SMTP/IMAP异常明确;未知结果先核验;mail-service | 已验证可用 | | M03 只读邮箱、文件夹、日期/主题查询、正文/返回 | 管理员;IMAP;最多31天 | 只读Sent历史、To/Cc/附件名 | UID变化重查;不标读删移;history-* | 已验证可用 | @@ -92,7 +94,7 @@ | 编号 / 操作 | 前置条件 / 实际执行 | 结果与故障验收 | 状态 | |---|---|---|---| -| J01 会话托管、只读到达扫描 | 已配置身份、日历允许;保留原到达记录链路 | 超时、验证码、租约互斥、去重;bpm-custody/scan | 已验证可用 | +| J01 会话托管、原生变化监听与只读对账 | 已配置身份与日历;保留低频完整查询 | 心跳、退避、身份更新、验证码、互斥、去重及源隔离;bpm-monitor/scan | 专项验收 | | J02 分类订单协调与发送 | 真实待办、精确节点、字段、归档、SMTP;正式关闭 | 公司日历、两个窗口、周一/调休、历史忽略;execution/dispatcher/window | 已验证可用 | | J03 每分钟模板收取 | 已启用IMAP与来源白名单 | UID去重、断线、并发配置防旧写回;mail-service | 已验证可用 | | J04 新PDF归档、健康观测、进程守护 | 原有启用条件与状态所有权 | worker超时、重启、双端口健康;storage/health/service | 已验证可用 | diff --git a/src/app/application.cjs b/src/app/application.cjs index cbad96b..3317c0b 100644 --- a/src/app/application.cjs +++ b/src/app/application.cjs @@ -13,6 +13,8 @@ const { MailStore } = require('../modules/mail/store.cjs'); const { MailService } = require('../modules/mail/service.cjs'); const { BpmScanStore } = require('../modules/bpm/scan-store.cjs'); const { BpmScanner } = require('../modules/bpm/scanner.cjs'); +const {BpmAccessClient}=require('../modules/bpm/access-client.cjs'); +const {BpmArrivalMonitor}=require('../modules/bpm/arrival-monitor.cjs'); const { AssistantStore } = require('../modules/assistant/store.cjs'); const { AssistantService } = require('../modules/assistant/service.cjs'); const { ZcodeRuntime } = require('../modules/assistant/zcode-runtime.cjs'); @@ -56,7 +58,7 @@ async function main(options = {}) { if(errors.length)throw new AggregateError(errors,'关闭服务时部分资源清理失败。'); })(); let server,dashboard,store,workspace,bpmSessions,custodian; - let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,orderRules,orderDispatcher,orderExecution,orderProvider,orderArchive,assistantStore,assistant,health; + let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,orderRules,orderDispatcher,orderExecution,orderProvider,orderArchive,assistantStore,assistant,health,bpmMonitor; try { const tokenPath = path.join(stateDir,'pairing.key'); let token; @@ -74,10 +76,10 @@ async function main(options = {}) { workspace=new WorkspaceStore(path.join(stateDir,'workspace')); // Register conditional closures before constructing later resources; partial startup follows the same path. cleanup.push(()=>closeServer(server)); - cleanup.push(()=>health?.close(),()=>assistant?.stop(),()=>orderDispatcher?.stop(),()=>orderExecution?.stop(),()=>notifications?.stop(),()=>storage?.stop(),()=>scanner?.stop(),()=>mail?.stop(),()=>custodian?.stop(),()=>bpmSessions?.shutdown()); + cleanup.push(()=>bpmMonitor?.stop(),()=>health?.close(),()=>assistant?.stop(),()=>orderDispatcher?.stop(),()=>orderExecution?.stop(),()=>notifications?.stop(),()=>storage?.stop(),()=>scanner?.stop(),()=>mail?.stop(),()=>custodian?.stop(),()=>bpmSessions?.shutdown()); cleanup.push(()=>closeServer(dashboard),()=>workspace.close()); cleanup.push(()=>mailStore?.close(),()=>scanStore?.close(),()=>storageStore?.close(),()=>notificationStore?.close(),()=>orderRules?.close(),()=>assistantStore?.close()); - bpmSessions=new BpmSessionManager({stateDir:path.join(stateDir,'bpm-sessions')}); + bpmSessions=new BpmSessionManager({stateDir:path.join(stateDir,'bpm-sessions'),accessClient:new BpmAccessClient()}); custodian=new BpmCustodian({workspace,manager:bpmSessions}); mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore}); mailStore.migrateLegacy(store.settings().templates); @@ -88,13 +90,14 @@ async function main(options = {}) { orderProvider=new BpmOrderProvider({manager:bpmSessions});orderArchive=new OrderArchiveProvider({storage,outputDir,journal:orderRules}); orderExecution=new OrderExecutionCoordinator({store:orderRules,workspace,provider:orderProvider,archive:orderArchive,mail,dashboard:store,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides,systemPrincipal:custodian.principal}); orderDispatcher=new OrderRuleDispatcher({store:orderRules,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides,providersReady:()=>{const cap=orderExecution.snapshot().capabilities;return ['liveTodo','pdfExport','automaticArchive'].every(key=>cap?.[key]===true);},templateResolver:(categoryId,rule)=>require('../modules/mail/rule-template.cjs').ruleTemplate(mailStore,categoryId,rule),attachmentReader:file=>orderArchive.read(file)}); + bpmMonitor=new BpmArrivalMonitor({workspace,manager:bpmSessions,scanner,provider:orderProvider,settings:()=>store.settings()}); assistantStore=new AssistantStore(path.join(stateDir,'assistant'));assistantStore.recover();assistant=new AssistantService({store:assistantStore,runtime:new ZcodeRuntime({stateDir:path.join(stateDir,'assistant','runtime')}),dashboard:store,workspace,scanner,storage,orderRules,orderExecution}); health=new RuntimeHealth({stateDir,startedAt,instanceId:watchdog.instanceId,workspace,scanner,storage,mail,execution:orderExecution}); 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,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true}); - await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();scanner.start(); + dashboard=createDashboard({store,workspace,outputDir,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true}); + 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(); orderDispatcher.start(); @@ -104,7 +107,7 @@ async function main(options = {}) { console.log(`Web 看板:http://127.0.0.1:${dashboardPort}\n${store.users().length?'使用已创建的工作台账号登录。':'首次请在部署机创建管理员。'}`); if(dashboardHost==='0.0.0.0')for(const list of Object.values(os.networkInterfaces()))for(const address of list || [])if(address.family==='IPv4' && !address.internal)console.log(`局域网地址:http://${address.address}:${dashboardPort}`); } - return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,orderRules,orderDispatcher,orderExecution,assistant,health,stop}; + return {server,dashboard,workspace,bpmSessions,bpmMonitor,custodian,mail,scanner,storage,notifications,orderRules,orderDispatcher,orderExecution,assistant,health,stop}; }catch(error){try{await stop();}catch(cleanupError){error.cleanupError=cleanupError;}throw error;} } module.exports={main}; diff --git a/src/app/dashboard.cjs b/src/app/dashboard.cjs index ece43fd..67fc0a0 100644 --- a/src/app/dashboard.cjs +++ b/src/app/dashboard.cjs @@ -13,9 +13,11 @@ const {respondToPing}=require('../platform/service/ping.cjs'); const {createAssets,PREVIEW_CSP}=require('./assets.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,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}) { const auth=createAuth({store,bpmSessions}); + const bpmLifecycle=workspace?new BpmConnectionLifecycle({workspace,manager:bpmSessions,monitor:bpmMonitor}):null; let assetFor;try{assetFor=createAssets();}catch(error){auth.close();throw error;} const server=http.createServer(async(request,response)=>{ if(respondToPing(request,response,watchdog))return; @@ -34,15 +36,15 @@ function createDashboard({store,outputDir,workspace,bpmSessions,mail,scanner,sto if(authResult.handled)return; const {user,token}=authResult; if(route==='/api/health' && request.method==='GET'){if(!health)fail(503,'健康状态服务未启动。');return reply(200,health.snapshot(user));} - if(await bpmApi({workspace,bpmSessions,user,sessionId:token,route,method:request.method,body,request,response,reply,trustedProxy}))return; + if(await bpmApi({workspace,bpmSessions,bpmLifecycle,user,sessionId:token,route,method:request.method,body,request,response,reply,trustedProxy}))return; if(await mailApi({mail,workspace,user,route,method:request.method,body,request,response,reply,trustedProxy}))return; - if(await bpmScanApi({scanner,workspace,user,sessionId:token,url,route,method:request.method,body,reply}))return; + if(await bpmScanApi({scanner,workspace,bpmMonitor,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(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,route,method:request.method,body,reply,response}))return; if(await assistantApi({assistant,workspace,user,sessionId:token,route,method:request.method,body,request,reply,trustedProxy}))return; - if(workspaceApi({workspace,store,user,route,method:request.method,body,reply,bpmSessions}))return; + if(workspaceApi({workspace,store,user,route,method:request.method,body,reply,bpmSessions,bpmMonitor}))return; if(await dashboardApi({store,outputDir,workspace,mail,scanner,storage,orderRules,user,route,request,response,body,reply,fail}))return; fail(404,'没有找到此页面或操作。'); }catch(error){if(!response.headersSent){if(!error.status)console.error('看板处理失败:',error.message);reply(error.status || 500,{error:error.status?error.message:'处理失败,请检查服务日志。'});}else response.end();} diff --git a/src/modules/bpm/access-client.cjs b/src/modules/bpm/access-client.cjs new file mode 100644 index 0000000..df19001 --- /dev/null +++ b/src/modules/bpm/access-client.cjs @@ -0,0 +1,29 @@ +'use strict'; +const {loadPlaywright}=require('../../platform/browser.cjs'); +const {TODO_SOURCES}=require('./todo-client.cjs'); +const {BpmListClient}=require('./list-client.cjs'); +const {isLoginRedirect}=require('./auth-redirect.cjs'); +const fail=(status,message)=>{throw Object.assign(new Error(message),{status});}; +class BpmAccessClient{ + constructor(options={}){this.baseURL=new BpmListClient(options).baseURL;} + async check(storageState){ + const checkedAt=new Date().toISOString();let request,authenticated=false; + try{ + if(!storageState)fail(401,'尚未保存 BPM 会话。'); + request=await loadPlaywright().request.newContext({baseURL:this.baseURL,storageState,timeout:15000}); + const get=async(route,options={})=>{const response=await request.get(route,{...options,maxRedirects:0});const status=response.status(); + if(status===401||status>=300&&status<400&&isLoginRedirect(response.headers().location||'',this.baseURL))fail(401,'BPM 会话需要续登。'); + if(status===403)fail(403,'该账号没有读取此业务接口的权限。');if(status!==200)fail(502,'BPM 接口暂不可用。'); + const bytes=await response.body();if(bytes.length>2*1024*1024)fail(502,'BPM 检查响应过大。');return bytes.toString('utf8');}; + const html=await get('/'),token=/Yiez\.clientId\s*=\s*['"]([^'"\s<>]{1,16000})['"]/.exec(html)?.[1]; + if(!token){if(/id=["']kc-form-login["']/.test(html))fail(401,'BPM 会话需要续登。');fail(502,'门户认证响应无法验证。');} + authenticated=true; + for(const [,route]of TODO_SOURCES){let data;try{data=JSON.parse(await get(route,{params:{page:1,start:0,limit:1},headers:{Authorization:'Bearer '+token}}));}catch(e){if(e.status)throw e;fail(502,'待办接口格式不正确。');} + if(data.success===false||!Array.isArray(data.children)||!Number.isSafeInteger(data.total)||data.total<0||data.children.length>1||data.total>0&&!data.children.length)fail(502,'待办接口检查未通过。'); + } + return {status:'connected',checkedAt,checks:{portal:{ok:true,message:'已验证登录和待办读取。'}},todo:'healthy',storageState:await request.storageState()}; + }catch(e){const auth=e.status===401;return {status:auth?'login_required':authenticated?'connected':'error',checkedAt,checks:{portal:{ok:authenticated&&!auth,message:auth?'BPM 会话需要续登。':authenticated?'登录会话有效,待办读取暂不可用。':'BPM 网络或门户暂不可用。'}},todo:auth?'login_required':e.status===403?'forbidden':'error',...(authenticated&&!auth?{storageState:await request.storageState().catch(()=>undefined)}:{})};} + finally{await request?.dispose();} + } +} +module.exports={BpmAccessClient}; diff --git a/src/modules/bpm/api.cjs b/src/modules/bpm/api.cjs index 4990093..6682f10 100644 --- a/src/modules/bpm/api.cjs +++ b/src/modules/bpm/api.cjs @@ -17,8 +17,8 @@ async function managerCall(work){ const status=messages[error?.status]?error.status:502;fail(status,messages[status] || 'BPM 暂时无法连接,请稍后重试。'); } } -async function bpmApi({workspace,bpmSessions,user,sessionId,route,method,body,request,response,reply,trustedProxy=false}){ - const match=/^\/api\/connections\/([\w-]+)\/(?:login\/(open|frame|input|navigate|save|close|fill-account)|(check|disable|delete)|(account)(\/(?:clear|check))?)$/.exec(route); +async function bpmApi({workspace,bpmSessions,bpmLifecycle,user,sessionId,route,method,body,request,response,reply,trustedProxy=false}){ + const match=/^\/api\/connections\/([\w-]+)\/(?:login\/(open|frame|input|navigate|save|close|fill-account)|(check|disable|enable|delete)|(account)(\/(?:clear|check))?)$/.exec(route); if(!match || !workspace)return false; const [,id,login,other,account,suffix]=match;const action=login || other || (suffix==='/clear'?'clear-account':suffix==='/check'?'check-account':account); if(action==='account'?!['GET','POST'].includes(method):method!==(action==='frame'?'GET':'POST'))fail(405,'此操作不支持当前请求方式。'); @@ -27,11 +27,13 @@ async function bpmApi({workspace,bpmSessions,user,sessionId,route,method,body,re if(user.role!=='admin')fail(403,'仅管理员可以删除连接。');emptyBody(body); if(connection.status!=='disabled')fail(409,'请先停用连接再删除。'); if(!bpmSessions)fail(503,'BPM 登录服务暂不可用,请稍后重试。'); - await managerCall(()=>bpmSessions.disable(id));reply(200,workspace.deleteConnection(id,user));return true; + reply(200,await bpmLifecycle.remove(id,user));return true; } - if(action==='disable'){ - if(user.role!=='admin')fail(403,'仅管理员可以停用连接。');emptyBody(body); - if(bpmSessions)await managerCall(()=>bpmSessions.disable(id));reply(200,workspace.disableConnection(id,user));return true; + if(action==='disable'||action==='enable'){ + if(user.role!=='admin')fail(403,'仅管理员可以启用或停用连接。'); + if(!body||Array.isArray(body)||Object.keys(body).some(k=>k!=='version'))fail(400,'请提供当前连接版本。'); + const input=action==='disable'&&!Object.keys(body).length?{version:connection.version||0}:body; + reply(200,await bpmLifecycle.change(id,action==='enable',input,user));return true; } if(connection.status==='disabled')fail(409,'此连接已停用。'); if(!secureBpmTransport(request,trustedProxy))fail(403,'请在部署机本地或 HTTPS 页面中登录 BPM。'); diff --git a/src/modules/bpm/arrival-monitor.cjs b/src/modules/bpm/arrival-monitor.cjs new file mode 100644 index 0000000..00fe74e --- /dev/null +++ b/src/modules/bpm/arrival-monitor.cjs @@ -0,0 +1,74 @@ +'use strict'; +const crypto=require('node:crypto'); +const {dayPolicy}=require('../../shared/schedule.cjs'); +const {normalizeArrival}=require('./list-client.cjs'); +const {BpmSignalRClient}=require('./signalr-client.cjs'); +function todoArrival(row){ + if(row.source!=='todo'||!['portal-v4','portal-v8'].includes(row.portalSource)||row.instanceId==null||row.revision==null)throw Object.assign(new Error('真实待办身份不完整。'),{status:502}); + return {...normalizeArrival({taskId:row.taskId,startTime:row.receivedAt,serialNum:row.serialNum,processName:row.processName,activityName:row.nodeName,processInstanceSubject:row.title},'todo:'+row.portalSource),kind:'todo',instanceId:String(row.instanceId),revision:row.revision,processVersion:row.processVersion||'',recordKey:JSON.stringify([row.instanceId,row.taskId,row.revision])}; +} +class BpmArrivalMonitor{ + constructor({workspace,manager,scanner,provider,settings,hubClient=new BpmSignalRClient(),clock=()=>Date.now(),debounceMs=750,pollMs=5000,retryMs=[2000,5000,15000,60000]}){ + Object.assign(this,{workspace,manager,scanner,provider,settings,hubClient,clock,debounceMs,pollMs,retryMs});this.entries=new Map();this.todoPending=new Map();this.stopped=false; + this.principal={user:{username:'系统监听',role:'admin'},sessionId:'monitor:'+crypto.randomUUID()}; + } + allowed(){const config=this.scanner.store.config();return config.enabled&&dayPolicy(new Date(this.clock()),this.settings().schedule,this.workspace.snapshot().calendar.overrides).scan;} + active(entry){return !this.stopped&&this.entries.get(entry.id)===entry&&this.workspace.getConnection(entry.id).status!=='disabled';} + snapshot(id){const e=this.entries.get(id);return e?{status:e.status,lastSignalAt:e.lastSignalAt||null,lastSyncAt:e.lastSyncAt||null,lastFailureAt:e.lastFailureAt||null,nextRetryAt:Number.isFinite(e.nextRetry)?new Date(e.nextRetry).toISOString():null}: {status:this.workspace.getConnection(id).status==='disabled'||!this.scanner.store.config().enabled?'paused':'waiting',lastSignalAt:null,lastSyncAt:null};} + start(){if(this.timer||this.stopped)return;this.timer=setInterval(()=>this.tick().catch(()=>{}),this.pollMs);this.timer.unref?.();this.tick().catch(()=>{});} + async tick(){ + if(this.stopped)return;const config=this.scanner.store.config(),connections=this.workspace.snapshot().connections,ids=new Set(connections.map(c=>c.id)); + for(const id of this.entries.keys())if(!ids.has(id)||!config.enabled||this.workspace.getConnection(id).status==='disabled')await this.stopConnection(id); + if(!config.enabled)return; + for(const c of connections){ + if(c.status==='disabled'||c.status==='disconnected'&&!c.lastConnectedAt)continue; + let entry=this.entries.get(c.id);if(!entry){entry={id:c.id,status:'connecting',nextRetry:0,nextReconcile:this.clock()+config.intervalMinutes*60000,failures:0,dirty:new Set(),controller:new AbortController(),attempt:0};this.entries.set(c.id,entry);} + if(entry.handle&&entry.epoch!==(this.manager.epoch?.(c.id)||0)){await this.stopConnection(c.id);continue;} + if(!entry.handle&&!entry.connecting&&this.clock()>=entry.nextRetry)this.connect(entry,c); + if(this.clock()>=entry.nextReconcile){entry.nextReconcile=this.clock()+config.intervalMinutes*60000;this.queue(entry,['todo','inform']);} + else if(entry.dirty.size&&!entry.sync&&!entry.debounce)this.queue(entry,[]); + } + } + retry(entry,status='polling',delay){if(!this.active(entry))return;if(entry.connectedAt&&this.clock()-entry.connectedAt>60000)entry.failures=0;entry.status=status;entry.nextRetry=this.clock()+(delay??this.retryMs[Math.min(entry.failures++,this.retryMs.length-1)]);} + connect(entry,connection){ + const attempt=++entry.attempt;let closed=false;entry.status=entry.failures?'reconnecting':'connecting'; + entry.connecting=(async()=>{ + if(this.manager.sessions.has(entry.id))throw Object.assign(new Error('人工登录窗口正在使用。'),{status:409}); + const result=await this.manager.ensure(connection,this.principal);if(!this.active(entry))return; + if(result.status!=='connected'){this.retry(entry,result.status==='login_required'?'login_required':'polling',5*60000);return;} + entry.epoch=this.manager.epoch?.(entry.id)||0;const handle=await this.manager.run(entry.id,async()=>{ + this.manager.authorize(connection,this.principal);if(this.manager.sessions.has(entry.id))throw Object.assign(new Error('人工登录窗口正在使用。'),{status:409}); + const saved=await this.manager.vault().read(entry.id); + return this.hubClient.connect(saved?.storageState,{signal:entry.controller.signal,onEvent:name=>{if(!this.active(entry)||entry.attempt!==attempt||entry.epoch!==(this.manager.epoch?.(entry.id)||0))return;entry.lastSignalAt=new Date(this.clock()).toISOString();this.queue(entry,name==='worklistChanged'?['todo']:name==='informlistChanged'?['inform']:['todo','inform']);},onClose:()=>{closed=true;if(this.active(entry)&&entry.attempt===attempt){entry.handle=null;this.retry(entry);}}}); + }); + if(!handle)return;if(!this.active(entry)||closed){await handle.stop();return;} + entry.handle=handle;entry.connectedAt=this.clock();entry.status='listening';entry.nextRetry=Infinity;entry.nextReconcile=this.clock()+this.scanner.store.config().intervalMinutes*60000;this.queue(entry,['todo','inform']); + })().catch(error=>{if(!this.active(entry))return;if(error.status===401)this.manager.observe?.(entry.id,'portal',error);this.retry(entry,error.status===409?'busy':error.status===401?'login_required':'polling',error.status===409?5000:error.status===401?5*60000:undefined);if(![401,409].includes(error.status))this.queue(entry,['todo','inform']);}).finally(()=>{entry.connecting=null;}); + } + queue(entry,kinds){if(!this.active(entry))return;for(const kind of kinds)entry.dirty.add(kind);if(entry.sync||entry.debounce||!entry.dirty.size||!this.allowed()||this.manager.sessions.has(entry.id))return; + entry.debounce=setTimeout(()=>{entry.debounce=null;if(!this.active(entry)||!this.allowed())return;const kinds=[...entry.dirty];entry.dirty.clear();entry.sync=this.synchronize(entry,kinds).finally(()=>{entry.sync=null;if(entry.dirty.size&&this.active(entry))this.queue(entry,[]);});},this.debounceMs);entry.debounce.unref?.(); + } + async synchronize(entry,kinds){let valid=true; + for(const kind of kinds){if(!this.active(entry))return; + try{ + if(kind==='inform'){await this.scanner.scan(entry.id,this.principal);} + else await this.startTodoScan(entry.id,this.principal).promise; + }catch(error){valid=false;entry.lastFailureAt=new Date(this.clock()).toISOString();} + } + if(valid&&this.active(entry))entry.lastSyncAt=new Date(this.clock()).toISOString(); + } + startTodoScan(id,principal){ + const fail=(message,status)=>{throw Object.assign(new Error(message),{status});};if(this.stopped)fail('监听服务正在停止。',503); + const connection=this.workspace.getConnection(id);if(!principal?.sessionId||!['admin','operator'].includes(principal.user?.role)||principal.user.role!=='admin'&&connection.owner!==principal.user.username)fail('仅连接负责人或管理员可以同步。',403); + if(connection.status==='disabled')fail('此连接已停用。',409);if(this.todoPending.has(id))fail('待办对账正在运行。',409); + const runId=this.scanner.store.begin(id,principal.user.username,'todo'); + const promise=Promise.resolve().then(async()=>{ + try{let rows;try{rows=await this.provider.scan(connection,principal);}catch(error){if(error.status!==401)throw error;const result=await this.manager.ensure(connection,principal);if(result.status!=='connected')throw error;rows=await this.provider.scan(connection,principal);} + if(this.stopped||this.workspace.getConnection(id).status==='disabled')fail('连接已暂停,本次对账未提交。',409);return {...this.scanner.store.complete(runId,id,rows.map(todoArrival)),runId}; + }catch(error){this.scanner.store.fail(runId,error.status===401?'需要恢复BPM登录。':error.status===409?'连接忙碌或已暂停。':'待办对账失败,请稍后重试。');throw error;} + }).finally(()=>this.todoPending.delete(id));this.todoPending.set(id,promise);return {runId,promise}; + } + async stopConnection(id){const entry=this.entries.get(id);if(!entry){await this.todoPending.get(id)?.catch(()=>{});return;}this.entries.delete(id);entry.controller.abort();clearTimeout(entry.debounce);await Promise.allSettled([entry.handle?.stop(),entry.connecting,entry.sync,this.todoPending.get(id)]);} + async stop(){this.stopped=true;clearInterval(this.timer);this.timer=null;await Promise.all([...this.entries.keys()].map(id=>this.stopConnection(id)));await Promise.allSettled([...this.todoPending.values()]);} +} +module.exports={BpmArrivalMonitor,todoArrival}; diff --git a/src/modules/bpm/auth-redirect.cjs b/src/modules/bpm/auth-redirect.cjs new file mode 100644 index 0000000..849634f --- /dev/null +++ b/src/modules/bpm/auth-redirect.cjs @@ -0,0 +1,3 @@ +'use strict'; +function isLoginRedirect(location,baseURL){try{const target=new URL(location,baseURL);if(target.username||target.password)return false;return target.origin==='https://sso.skyworthdigital.com'&&target.pathname.startsWith('/realms/')||target.origin===new URL(baseURL).origin&&/^\/(?:login|signin)(?:\/|$)/i.test(target.pathname);}catch{return false;}} +module.exports={isLoginRedirect}; diff --git a/src/modules/bpm/connection-health.cjs b/src/modules/bpm/connection-health.cjs new file mode 100644 index 0000000..4edc5f1 --- /dev/null +++ b/src/modules/bpm/connection-health.cjs @@ -0,0 +1,14 @@ +'use strict'; +class BpmConnectionHealth{ + constructor({clock=()=>Date.now(),freshMs=5*60*1000}={}){this.clock=clock;this.freshMs=freshMs;this.values=new Map();} + observe(id,source,status='healthy'){ + if(!['portal','todo','inform'].includes(source)||!['healthy','login_required','forbidden','error','unknown'].includes(status))return; + const value=this.values.get(id)||{};value[source]={status,checkedAt:new Date(this.clock()).toISOString()}; + if(status==='healthy')value.portal={status:'healthy',checkedAt:new Date(this.clock()).toISOString()}; + if(status==='login_required')value.portal={status,checkedAt:new Date(this.clock()).toISOString()};this.values.set(id,value); + } + recent(id){const portal=this.values.get(id)?.portal;return !!(portal?.status==='healthy'&&this.clock()-Date.parse(portal.checkedAt){throw Object.assign(new Error(message),{status});}; +class BpmConnectionLifecycle{ + constructor({workspace,manager,monitor}){Object.assign(this,{workspace,manager,monitor});this.pending=new Map();} + run(id,work){const before=this.pending.get(id)||Promise.resolve(),task=before.catch(()=>{}).then(work);this.pending.set(id,task);task.finally(()=>{if(this.pending.get(id)===task)this.pending.delete(id);}).catch(()=>{});return task;} + async invoke(method,id){try{await this.manager?.[method]?.(id);}catch(error){fail('BPM 连接操作未完成,请刷新状态后重试。',[409,503].includes(error.status)?error.status:502);}} + change(id,enabled,input,user){return this.run(id,async()=>{ + if(user.role!=='admin')fail('仅管理员可以启用或停用连接。',403); + if(typeof enabled!=='boolean'||!input||Object.keys(input).some(k=>k!=='version')||!Number.isInteger(input.version)||input.version<0)fail('请提供当前连接版本。',400); + const current=this.workspace.getConnection(id); + if((current.status!=='disabled')!==enabled&&(current.version||0)!==input.version)fail('连接状态已变化,请刷新后重试。',409); + if(!enabled){ + // Publish the pause before draining, so late workers cannot restore connectivity. + const saved=this.workspace.setConnectionEnabled(id,false,input,user); + const pausing=this.invoke('suspend',id);await Promise.all([pausing,this.monitor?.stopConnection(id)]);return saved; + } + await this.invoke('resume',id); + return this.workspace.setConnectionEnabled(id,true,input,user); + });} + remove(id,user){return this.run(id,async()=>{ + if(user.role!=='admin')fail('仅管理员可以删除连接。',403); + if(this.workspace.getConnection(id).status!=='disabled')fail('请先停用连接再删除。',409); + if(!this.manager)fail('BPM 登录服务暂不可用。',503); + await this.monitor?.stopConnection(id);await this.invoke('disable',id);return this.workspace.deleteConnection(id,user); + });} +} +module.exports={BpmConnectionLifecycle}; diff --git a/src/modules/bpm/custodian.cjs b/src/modules/bpm/custodian.cjs index 19985ea..bc14df4 100644 --- a/src/modules/bpm/custodian.cjs +++ b/src/modules/bpm/custodian.cjs @@ -21,7 +21,7 @@ class BpmCustodian { if(!account.configured && !connection.lastConnectedAt && !['connected','unchecked','login_required'].includes(connection.status))continue; const result=await this.manager.ensure(connection,this.principal); // The connection can be disabled while its remote check is in flight. - if(this.workspace.getConnection(connection.id).status!=='disabled')this.workspace.updateConnectionSession(connection.id,result,this.principal.user); + if(this.workspace.getConnection(connection.id).status!=='disabled')this.workspace.updateConnectionSession(connection.id,result,this.principal.user,{audit:false}); }catch(cause){ // Interactive leases and transient browser failures are retried on the next cycle. // The manager returns checked upstream failures as structured results. diff --git a/src/modules/bpm/list-client.cjs b/src/modules/bpm/list-client.cjs index d57a37c..ddf2d4d 100644 --- a/src/modules/bpm/list-client.cjs +++ b/src/modules/bpm/list-client.cjs @@ -1,6 +1,7 @@ 'use strict'; const sanitize=require('sanitize-html'); const {loadPlaywright}=require('../../platform/browser.cjs'); +const {isLoginRedirect}=require('./auth-redirect.cjs'); const fail=(message,status=502)=>Object.assign(new Error(message),{status}); const SOURCES=[['portal-v8','bpm/worklist/informlist'],['portal-v4','skyworth/todo/v2/workflow/get_process_of_inform_v4']]; function plain(value,max=8000){ @@ -30,14 +31,15 @@ class BpmListClient{ const request=await loadPlaywright().request.newContext({baseURL:this.baseURL,storageState,timeout:20000}); const get=async(route,options={})=>{ let response;try{response=await request.get(route,{...options,maxRedirects:0});}catch{throw fail('BPM 查询连接失败,请稍后重试。');} - const status=response.status();if(status>=300&&status<400)throw fail('BPM 查询发生登录跳转,需要续登。',401); - if([401,403].includes(status))throw fail('BPM 会话需要续登。',401); + const status=response.status();if(status>=300&&status<400)throw fail('BPM 查询发生跳转,请检查连接。',isLoginRedirect(response.headers().location||'',this.baseURL)?401:502); + if(status===401)throw fail('BPM 会话需要续登。',401); + if(status===403)throw fail('BPM 业务列表没有读取权限。',403); if(status!==200)throw fail('BPM 查询失败,请稍后重试。'); const body=await response.body();if(body.length>10*1024*1024)throw fail('BPM 查询响应过大。');return body.toString('utf8'); }; try{ const html=await get('/'),token=/Yiez\.clientId\s*=\s*['"]([^'"\s<>]{1,16000})['"]/.exec(html)?.[1]; - if(!token)throw fail('BPM 会话需要续登。',401); + if(!token)throw fail('BPM 认证响应无法验证。',/id=["']kc-form-login["']/.test(html)?401:502); const rows=[]; for(const [source,route]of this.sources){ let total=null;const seen=new Set(); diff --git a/src/modules/bpm/order-provider.cjs b/src/modules/bpm/order-provider.cjs index 1f0989d..0ddd67a 100644 --- a/src/modules/bpm/order-provider.cjs +++ b/src/modules/bpm/order-provider.cjs @@ -26,8 +26,8 @@ class BpmOrderProvider{ try{const rows=await this.saved(connection,principal,state=>this.client.scan(state)); const safe=rows.map(row=>{const entry=row.detailUrl?safeEntry(row.detailUrl):null;return {...row,detailUrl:entry?entry.target.href:row.detailUrl?detailURL(row.detailUrl,this.allowLocal).href:undefined};}); this.entries.set(connection.id,new Map(rows.filter(r=>r.detailUrl).map(r=>[r.taskId,{url:r.detailUrl,row:r,at:Date.now()}]))); - this.checks={...this.checks,liveTodo:true,checkedAt:new Date().toISOString(),message:'真实待办接口已读取;各类别表单仍需字段与归档现场核验。'};return safe;} - catch(error){this.checks={...this.checks,liveTodo:false,message:error.message};throw error;} + this.manager.observe?.(connection.id,'todo');this.checks={...this.checks,liveTodo:true,checkedAt:new Date().toISOString(),message:'真实待办接口已读取;各类别表单仍需字段与归档现场核验。'};return safe;} + catch(error){this.manager.observe?.(connection.id,'todo',error);this.checks={...this.checks,liveTodo:false,message:error.message};throw error;} } captureFields(connection,principal,row){return this.capture(connection,principal,row,{fieldsOnly:true});} async capture(connection,principal,row,{fieldsOnly=false}={}){ diff --git a/src/modules/bpm/scan-api.cjs b/src/modules/bpm/scan-api.cjs index a689e71..6afe898 100644 --- a/src/modules/bpm/scan-api.cjs +++ b/src/modules/bpm/scan-api.cjs @@ -1,21 +1,22 @@ 'use strict'; -async function bpmScanApi({scanner,workspace,user,sessionId,url,route,method,body,reply}){ +async function bpmScanApi({scanner,workspace,bpmMonitor,user,sessionId,url,route,method,body,reply}){ if(!route.startsWith('/api/bpm-scan')&&route!=='/api/arrivals')return false; const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});}; if(!scanner)fail('BPM 扫描暂不可用。',503); if(route==='/api/arrivals'&&method==='GET'){ - const filters={connectionId:url.searchParams.get('connectionId')||'',q:url.searchParams.get('q')||'',before:url.searchParams.get('before')||'',days:Number(url.searchParams.get('days')||7)}; + const filters={connectionId:url.searchParams.get('connectionId')||'',q:url.searchParams.get('q')||'',before:url.searchParams.get('before')||'',days:Number(url.searchParams.get('days')||7),kind:url.searchParams.get('kind')||'inform'}; reply(200,scanner.store.list(filters));return true; } - if(route==='/api/bpm-scan'&&method==='GET'){reply(200,{...scanner.store.status(),connections:workspace.snapshot().connections.map(({id,name,status,owner})=>({id,name,status,owner}))});return true;} + if(route==='/api/bpm-scan'&&method==='GET'){reply(200,{...scanner.store.status(),connections:workspace.snapshot().connections.map(({id,name,status,owner})=>({id,name,status,owner,monitoring:bpmMonitor?.snapshot(id)}))});return true;} if(route==='/api/bpm-scan/config'&&method==='POST'){ if(user.role!=='admin')fail('仅管理员可以配置自动扫描。',403); const config=scanner.store.saveConfig(body);workspace.record(user,'保存自动扫描',`${config.enabled?'开启':'暂停'},间隔 ${config.intervalMinutes} 分钟`);reply(200,config);return true; } if(route==='/api/bpm-scan/run'&&method==='POST'){ - if(!body||Object.keys(body).some(k=>k!=='connectionId')||typeof body.connectionId!=='string')fail('请选择 BPM 连接。'); + if(!body||Object.keys(body).some(k=>!['connectionId','kind'].includes(k))||typeof body.connectionId!=='string'||body.kind!==undefined&&!['todo','inform'].includes(body.kind))fail('请选择 BPM 连接及有效到达类型。'); // A scan may span many pages. The UI polls the durable run instead of holding a request open. - const {promise,runId}=scanner.startScan(body.connectionId,{user,sessionId}); + if(body.kind==='todo'&&!bpmMonitor)fail('真实待办监听服务尚未启动。',503); + const {promise,runId}=body.kind==='todo'?bpmMonitor.startTodoScan(body.connectionId,{user,sessionId}):scanner.startScan(body.connectionId,{user,sessionId}); promise.catch(()=>{});reply(202,{runId});return true; } return false; diff --git a/src/modules/bpm/scan-store.cjs b/src/modules/bpm/scan-store.cjs index 53aa4bc..7f4af02 100644 --- a/src/modules/bpm/scan-store.cjs +++ b/src/modules/bpm/scan-store.cjs @@ -11,6 +11,7 @@ class BpmScanStore{ CREATE INDEX IF NOT EXISTS arrivals_day ON arrivals(day DESC); CREATE TABLE IF NOT EXISTS runs(id TEXT PRIMARY KEY,connection_id TEXT NOT NULL,actor TEXT NOT NULL,started_at TEXT NOT NULL,finished_at TEXT,status TEXT NOT NULL,seen INTEGER,added INTEGER,message TEXT); 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'"); } catch(error) { try { this.db?.close(); } catch {} throw error; @@ -19,19 +20,20 @@ class BpmScanStore{ transaction(fn){this.db.exec('BEGIN IMMEDIATE');try{const r=fn();this.db.exec('COMMIT');return r;}catch(e){this.db.exec('ROLLBACK');throw e;}} config(){return JSON.parse(this.db.prepare('SELECT value FROM config WHERE id=1').get().value);} saveConfig(input){if(!input||Object.keys(input).some(k=>!['enabled','intervalMinutes'].includes(k))||typeof input.enabled!=='boolean'||!Number.isInteger(input.intervalMinutes)||input.intervalMinutes<1||input.intervalMinutes>1440)throw invalid('扫描间隔需为 1–1440 分钟。');this.db.prepare('UPDATE config SET value=? WHERE id=1').run(JSON.stringify(input));return this.config();} - begin(connectionId,actor){const id=crypto.randomUUID();this.db.prepare('INSERT INTO runs(id,connection_id,actor,started_at,status) VALUES(?,?,?,?,?)').run(id,connectionId,actor,new Date().toISOString(),'running');return id;} + begin(connectionId,actor,kind='inform'){if(!['inform','todo'].includes(kind))throw invalid('到达类型无效。');const id=crypto.randomUUID();this.db.prepare('INSERT INTO runs(id,connection_id,actor,started_at,status,kind) VALUES(?,?,?,?,?,?)').run(id,connectionId,actor,new Date().toISOString(),'running',kind);return id;} complete(id,connectionId,rows){return this.transaction(()=>{ let added=0;const now=new Date().toISOString(); const insert=this.db.prepare('INSERT OR IGNORE INTO arrivals VALUES(?,?,?,?,?,?,?)');const update=this.db.prepare('UPDATE arrivals SET day=?,value=?,last_seen=? WHERE connection_id=? AND source=? AND task_id=?'); - for(const row of rows){if(!row.arrivalDay||!row.taskId||!row.source)throw invalid('流程记录无效。');const value=JSON.stringify(row);added+=Number(insert.run(connectionId,row.source,row.taskId,row.arrivalDay,value,now,now).changes);update.run(row.arrivalDay,value,now,connectionId,row.source,row.taskId);} + for(const row of rows){if(!row.arrivalDay||!row.taskId||!row.source)throw invalid('流程记录无效。');const value=JSON.stringify(row),key=row.recordKey||row.taskId;added+=Number(insert.run(connectionId,row.source,key,row.arrivalDay,value,now,now).changes);update.run(row.arrivalDay,value,now,connectionId,row.source,key);} this.db.prepare('UPDATE runs SET status=?,finished_at=?,seen=?,added=?,message=? WHERE id=? AND status=?').run('success',now,rows.length,added,'',id,'running');this.prune();return {seen:rows.length,added}; });} fail(id,message){this.db.prepare('UPDATE runs SET status=?,finished_at=?,message=? WHERE id=?').run('error',new Date().toISOString(),message,id);this.prune();} prune(){this.db.exec("DELETE FROM runs WHERE status!='running' AND id NOT IN(SELECT id FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 200)");} - status(){return {config:this.config(),total:this.db.prepare('SELECT COUNT(*) n FROM arrivals').get().n,runs:this.db.prepare('SELECT id,connection_id AS connectionId,actor,started_at AS startedAt,finished_at AS finishedAt,status,seen,added,message FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 30').all()};} - list({connectionId='',q='',before='',days=7}={}){ + status(){return {config:this.config(),total:this.db.prepare("SELECT COUNT(*) n FROM arrivals WHERE source NOT LIKE 'todo:%'").get().n,todoTotal:this.db.prepare("SELECT COUNT(*) n FROM arrivals WHERE source LIKE 'todo:%'").get().n,runs:this.db.prepare('SELECT id,connection_id AS connectionId,actor,started_at AS startedAt,finished_at AS finishedAt,status,seen,added,message,kind FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 30').all()};} + list({connectionId='',q='',before='',days=7,kind='inform'}={}){ + if(!['inform','todo'].includes(kind))throw invalid('到达类型无效。'); if(typeof q!=='string'||q.length>200||typeof connectionId!=='string'||connectionId.length>200||typeof before!=='string'||(before&&!/^\d{4}-\d{2}-\d{2}$/.test(before))||!Number.isInteger(days)||days<1||days>31)throw invalid('查询条件无效。'); - const conditions=[],args=[];if(connectionId){conditions.push('connection_id=?');args.push(connectionId);}if(q){conditions.push("value LIKE ? ESCAPE '\\'");args.push('%'+q.replace(/[\\%_]/g,'\\$&')+'%');} + const conditions=[kind==='todo'?"source LIKE 'todo:%'":"source NOT LIKE 'todo:%'"],args=[];if(connectionId){conditions.push('connection_id=?');args.push(connectionId);}if(q){conditions.push("value LIKE ? ESCAPE '\\'");args.push('%'+q.replace(/[\\%_]/g,'\\$&')+'%');} const where=conditions.length?' WHERE '+conditions.join(' AND '):'';const total=this.db.prepare('SELECT COUNT(*) n FROM arrivals'+where).get(...args).n; if(before){conditions.push('dayr.day);const shown=dates.slice(0,days); diff --git a/src/modules/bpm/session-manager.cjs b/src/modules/bpm/session-manager.cjs index 17c1ef4..b20f850 100644 --- a/src/modules/bpm/session-manager.cjs +++ b/src/modules/bpm/session-manager.cjs @@ -5,6 +5,7 @@ const crypto = require('node:crypto'); const { BpmVault } = require('../../platform/security/vault.cjs'); const { loadPlaywright, browserOptions } = require('../../platform/browser.cjs'); const { BpmListClient } = require('./list-client.cjs'); +const {BpmConnectionHealth}=require('./connection-health.cjs'); const DEFAULT_URLS = { main: 'https://bpmn.skyworthdigital.com/' }; const { LOGIN_FORMS, fillSavedForm, automaticSubmitForm } = require('./login-form.cjs'); const TTL = 10 * 60 * 1000; @@ -14,7 +15,7 @@ const safe = cause => cause?.status ? cause : error('BPM 浏览器暂不可用 const object = (value, fields) => value && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).every(key => fields.includes(key)); class BpmSessionManager { - constructor({ stateDir, browserFactory, urls, allowedOrigins, probe, loginForms } = {}) { + constructor({ stateDir, browserFactory, urls, allowedOrigins, probe, loginForms,accessClient } = {}) { this.stateDir = path.resolve(stateDir); fs.mkdirSync(this.stateDir, { recursive: true }); if (urls!==undefined && !object(urls,['main'])) throw error('BPM 地址配置无效。'); this.urls = { ...DEFAULT_URLS, ...urls }; @@ -38,6 +39,7 @@ class BpmSessionManager { } this.browserFactory = browserFactory || (() => loadPlaywright().chromium.launch(browserOptions())); this.probe = probe || this.defaultProbe.bind(this); + this.accessClient=accessClient;this.health=new BpmConnectionHealth();this.accessChecks=new Map();this.sessionEpochs=new Map(); this.sessions = new Map(); this.operations = new Map(); this.disabled = new Set(); this.revokedSessionHashes=new Set(); this.stopped = false; } allowed(url) { try { const parsed = new URL(url); return !parsed.username && !parsed.password && this.allowedOrigins.has(parsed.origin); } catch { return false; } } @@ -62,6 +64,7 @@ class BpmSessionManager { // authentication; first custody can reuse a user's already saved manual login. await this.vault().write('account:'+connection.id,stored); if (previous && previous.username.trim().toLowerCase()!==stored.username.toLowerCase()) { + this.health.clear(connection.id);this.sessionEpochs.set(connection.id,this.epoch(connection.id)+1); try{await this.vault().remove(connection.id);await this.closeLease(connection.id);} catch(cause){await this.vault().write('account:'+connection.id,previous);throw cause;} } @@ -81,6 +84,7 @@ class BpmSessionManager { return this.run(connection?.id,async()=>{ this.authorize(connection,principal); const lease=await this.getLease(connection.id,principal,true); await this.settleNavigation(lease); return this.fillSavedAccount(lease); }); } async automaticSubmit(lease,stored,submit=false) { + if(this.stopped||this.disabled.has(lease.id))throw error('此连接已停止自动登录。',409); return automaticSubmitForm(lease,stored,submit,this.loginForms); } @@ -88,11 +92,34 @@ class BpmSessionManager { await this.captureSessions(lease); const storageState=await lease.context.storageState({indexedDB:true}); await this.vault().write(lease.id,{storageState,sessionStorage:lease.sessionStorage}); + this.sessionEpochs.set(lease.id,this.epoch(lease.id)+1); } canPersistVerified(result) { return result.status==='connected' && result.checks.portal.ok; } + epoch(id){return this.sessionEpochs.get(id)||0;} + observe(id,source,cause){this.health.observe(id,source,cause?cause.status===401?'login_required':cause.status===403?'forbidden':'error':'healthy');} + async checkAccess(connection,principal){ + this.authorize(connection,principal);const id=connection.id; + if(this.accessChecks.has(id)){const result=await this.accessChecks.get(id);this.authorize(connection,principal);return result;} + const task=this.run(id,async()=>{ + this.authorize(connection,principal);if(this.sessions.has(connection.id))throw error('此连接正在登录窗口中使用。',409); + const saved=await this.vault().read(connection.id),result=await this.accessClient.check(saved?.storageState);this.authorize(connection,principal); + this.health.observe(connection.id,'portal',result.status==='connected'?'healthy':result.status==='login_required'?'login_required':'error'); + this.health.observe(connection.id,'todo',result.todo||'unknown'); + if(result.storageState&&result.status==='connected')await this.vault().write(connection.id,{...saved,storageState:result.storageState}); + return {status:result.status,identity:connection.identity||'',checkedAt:result.checkedAt,checks:result.checks}; + });this.accessChecks.set(id,task);try{return await task;}finally{if(this.accessChecks.get(id)===task)this.accessChecks.delete(id);} + } async ensure(connection,principal) { + if(this.accessClient){ + this.authorize(connection,principal); + if(this.health.recent(connection.id))return {status:'connected',identity:connection.identity||'',checkedAt:this.health.snapshot(connection.id).portal.checkedAt,checks:{portal:{ok:true,message:'最近业务请求已验证登录。'}}}; + const result=await this.checkAccess(connection,principal);if(result.status!=='login_required')return result; + } + return this.ensureBrowser(connection,principal); + } + async ensureBrowser(connection,principal) { return this.run(connection?.id,async()=>{ this.authorize(connection,principal); if (this.sessions.has(connection.id)) throw error('此连接正在登录窗口中使用。',409); @@ -128,7 +155,7 @@ class BpmSessionManager { this.authorize(connection,principal); if(this.sessions.has(connection.id))throw error('此连接正在登录窗口中使用,请关闭后扫描。',409); const saved=await this.vault().read(connection.id); - const rows=await (this.listClient ||= new BpmListClient()).scan(saved?.storageState); + let rows;try{rows=await (this.listClient ||= new BpmListClient()).scan(saved?.storageState);this.observe(connection.id,'inform');}catch(cause){this.observe(connection.id,'inform',cause);throw cause;} this.authorize(connection,principal);return rows; }); try{return await query();}catch(cause){if(cause.status!==401)throw cause;} @@ -382,6 +409,7 @@ class BpmSessionManager { }); } async check(connection,principal) { + if(this.accessClient)return this.checkAccess(connection,principal); return this.run(connection?.id,async()=>{ this.authorize(connection,principal); const transient=!this.sessions.has(connection.id); @@ -402,6 +430,8 @@ class BpmSessionManager { for(const hash of revoked)this.revokedSessionHashes.add(hash); await Promise.all([...this.sessions.values()].filter(lease=>revoked.has(crypto.createHash('sha256').update(lease.sessionId).digest('hex'))).map(lease=>this.run(lease.id,()=>this.closeLease(lease.id)))); } + async suspend(id) { this.disabled.add(id);this.health.clear(id);await this.sessions.get(id)?.context?.close().catch(()=>{}); await this.run(id,()=>this.closeLease(id)); } + async resume(id) { await this.run(id,async()=>{this.disabled.delete(id);this.health.clear(id);}); } async disable(id) { this.disabled.add(id); await this.run(id,async()=>{ await this.closeLease(id); await this.vault().remove(id); await this.vault().remove('account:'+id); }); } async shutdown() { this.stopped=true; diff --git a/src/modules/bpm/signalr-client.cjs b/src/modules/bpm/signalr-client.cjs new file mode 100644 index 0000000..c9e6e60 --- /dev/null +++ b/src/modules/bpm/signalr-client.cjs @@ -0,0 +1,48 @@ +'use strict'; +const {loadPlaywright}=require('../../platform/browser.cjs'); +const {BpmListClient}=require('./list-client.cjs'); +const {isLoginRedirect}=require('./auth-redirect.cjs'); +const hints=new Set(['worklistChanged','informlistChanged','taskinstanceChanged']); +const failure=(message,status=502,code='BPM_HUB_UNAVAILABLE')=>Object.assign(new Error(message),{status,code}); +class BpmSignalRClient{ + constructor({handshakeMs=10000,heartbeatMs=45000,pingMs=15000,maxFrameBytes=65536,...options}={}){this.baseURL=new BpmListClient(options).baseURL;Object.assign(this,{handshakeMs,heartbeatMs,pingMs,maxFrameBytes});} + async connect(storageState,{signal,onEvent=()=>{},onClose=()=>{}}={}){ + signal?.throwIfAborted();let request,ws,closeConnection;const abort=()=>{request?.dispose().catch(()=>{});closeConnection?.('stopped');};signal?.addEventListener('abort',abort,{once:true}); + try{ + if(!storageState)throw failure('尚未保存 BPM 会话。',401); + request=await loadPlaywright().request.newContext({baseURL:this.baseURL,storageState,timeout:15000});signal?.throwIfAborted(); + const home=await request.get('/',{maxRedirects:0});if(home.status()===401||home.status()>=300&&home.status()<400&&isLoginRedirect(home.headers().location||'',this.baseURL))throw failure('BPM 监听需要恢复登录。',401);if(home.status()===403)throw failure('BPM 监听没有访问权限。',403);if(home.status()!==200)throw failure('BPM 门户暂不可用。'); + const bytes=await home.body();if(bytes.length>2*1024*1024)throw failure('BPM 认证响应过大。');const token=/Yiez\.clientId\s*=\s*['"]([^'"\s<>]{1,16000})['"]/.exec(bytes.toString())?.[1];if(!token)throw failure('BPM 认证响应无法验证。'); + const response=await request.post('/hubs/system/negotiate',{params:{negotiateVersion:1},headers:{Authorization:'Bearer '+token},maxRedirects:0}); + if(response.status()===401)throw failure('BPM 监听会话已过期。',401);if(response.status()===403)throw failure('BPM 监听没有访问权限。',403);if(response.status()!==200)throw failure('BPM 监听通道暂不可用。'); + const body=await response.body();if(body.length>65536)throw failure('BPM 监听协商响应过大。');let data;try{data=JSON.parse(body.toString());}catch{throw failure('BPM 监听协商响应无效。');} + if(typeof data.connectionToken!=='string'||data.connectionToken.length>16000||!data.availableTransports?.some(t=>t.transport==='WebSockets')||data.url||data.error)throw failure('BPM 监听不支持当前连接方式。'); + signal?.throwIfAborted();const target=new URL('/hubs/system',this.baseURL);target.protocol=target.protocol==='https:'?'wss:':'ws:';target.searchParams.set('id',data.connectionToken);target.searchParams.set('access_token',token); + return await new Promise((resolve,reject)=>{ + let ready=false,done=false,pending='',lastReceived=Date.now(),handshakeTimer,pingTimer,heartbeatTimer;let physicallyClosed;const closed=new Promise(r=>physicallyClosed=r); + const cleanup=()=>{clearTimeout(handshakeTimer);clearInterval(pingTimer);clearInterval(heartbeatTimer);signal?.removeEventListener('abort',abort);}; + const finish=(reason,error)=>{if(done)return;done=true;cleanup();try{ws.close();}catch{}if(!ready)reject(error||failure('BPM 监听连接未完成。'));try{onClose({reason});}catch{}}; + closeConnection=reason=>finish(reason,new DOMException('Aborted','AbortError')); + ws=new WebSocket(target.href);ws.addEventListener('open',()=>{if(done)return;ws.send(JSON.stringify({protocol:'json',version:1})+'\x1e');}); + handshakeTimer=setTimeout(()=>finish('handshake_timeout',failure('BPM 监听握手超时。',502,'BPM_HUB_HANDSHAKE')),this.handshakeMs); + ws.addEventListener('message',event=>{ + if(done)return;if(typeof event.data!=='string'||Buffer.byteLength(pending+event.data)>this.maxFrameBytes)return finish('invalid_frame');pending+=event.data; + while(pending.includes('\x1e')){const split=pending.indexOf('\x1e'),raw=pending.slice(0,split);pending=pending.slice(split+1);if(!raw)continue;let message;try{message=JSON.parse(raw);}catch{return finish('invalid_frame');}if(!message||typeof message!=='object'||Array.isArray(message))return finish('invalid_frame');lastReceived=Date.now(); + if(!ready){if(Object.keys(message).length)return finish('handshake_error',failure('BPM 监听握手未通过。',502,'BPM_HUB_HANDSHAKE'));ready=true;clearTimeout(handshakeTimer); + pingTimer=setInterval(()=>{if(!done&&ws.readyState===WebSocket.OPEN)ws.send('{"type":6}\x1e');},this.pingMs);pingTimer.unref?.(); + heartbeatTimer=setInterval(()=>{if(Date.now()-lastReceived>=this.heartbeatMs)finish('heartbeat_timeout');},Math.max(20,Math.min(5000,this.heartbeatMs/2)));heartbeatTimer.unref?.(); + resolve({stop:async()=>{finish('stopped');let timer;try{await Promise.race([closed,new Promise(r=>{timer=setTimeout(r,1000);})]);}finally{clearTimeout(timer);}},closed});continue; + } + if(message.type===7)return finish('server_closed'); + if(message.type===1&&hints.has(message.target)){const name=message.target;queueMicrotask(()=>{if(!done)try{onEvent(name);}catch{}});} + } + }); + ws.addEventListener('error',()=>finish('transport_error')); + ws.addEventListener('close',()=>{physicallyClosed();finish('disconnected');}); + if(signal?.aborted)closeConnection('stopped'); + }); + }catch(e){signal?.removeEventListener('abort',abort);if(signal?.aborted)throw new DOMException('Aborted','AbortError');if(e.status||e.name==='AbortError')throw e;throw failure('BPM 监听暂不可用。');} + finally{await request?.dispose();} + } +} +module.exports={BpmSignalRClient}; diff --git a/src/modules/dashboard/api.cjs b/src/modules/dashboard/api.cjs index 2802420..d4eae28 100644 --- a/src/modules/dashboard/api.cjs +++ b/src/modules/dashboard/api.cjs @@ -11,7 +11,7 @@ const handled=(...args)=>{reply(...args);return true;}; const rules=orderRules?.snapshot(),published=rules?.rules?.filter(r=>r.status==='enabled')||[]; const capabilities=rules?.capabilities||{},ready=['liveTodo','pdfExport','automaticArchive'].every(key=>capabilities[key]===true); const automation={enabled:rules?.settings?.enabled===true,ready,reason:rules?.settings?.enabled!==true?'分类自动发信已暂停;请先完成类别字段、目录、邮箱与预览核验。':ready?'分类执行链路已完成实际接入检查。':'分类执行链路仍有未通过的实际检查,请查看订单执行中的阻塞原因。'}; - return handled(200,{stats:{total:jobs.length,today:todayJobs.length,completed:jobs.filter(job=>job.status==='success').length,failed:jobs.filter(job=>['error','interrupted'].includes(job.status)).length,running:jobs.filter(job=>job.status==='running').length},scan,automation,connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'Excel 分类规则',ready:published.length>0,detail:`15类规则,已发布 ${published.length} 类;实际字段按流程版本核验`},{name:'BPM 待办执行',ready:capabilities.liveTodo===true,detail:capabilities.liveTodo===true?'真实待办接口检查通过;各类别仍需字段核验':'请在订单通知管理的订单执行中检查实时待办,字段映射在业务设置维护'},{name:'到达历史扫描',ready:!!scan?.runs.some(r=>r.status==='success'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 已收录 ${scan.total} 条流程`:'历史扫描服务未启动'},{name:'存储服务器',ready:!!storage?.store.servers().some(s=>s.enabled&&s.state.readable&&s.state.writable),detail:storage?`已配置 ${storage.store.servers().length} 个 SMB 存储服务器`:'存储服务未启动'},{name:'邮件渠道',ready:mailChannels.some(c=>!c.readOnly&&c.state.smtp),detail:`已配置 ${mailChannels.length} 个邮箱`},{name:'邮件模板',ready:mailTemplates.some(t=>t.status==='active'),detail:`${mailTemplates.filter(t=>t.status==='active').length} 个已生效,${mailTemplates.filter(t=>t.status==='pending').length} 个待确认;按类别显式关联`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:jobs.slice(0,6).map(publicJob),audit:store.audit().slice(0,5)}); + return handled(200,{stats:{total:jobs.length,today:todayJobs.length,completed:jobs.filter(job=>job.status==='success').length,failed:jobs.filter(job=>['error','interrupted'].includes(job.status)).length,running:jobs.filter(job=>job.status==='running').length},scan,automation,connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'Excel 分类规则',ready:published.length>0,detail:`15类规则,已发布 ${published.length} 类;实际字段按流程版本核验`},{name:'BPM 待办执行',ready:capabilities.liveTodo===true,detail:capabilities.liveTodo===true?'真实待办接口检查通过;各类别仍需字段核验':'请在订单通知管理的订单执行中检查实时待办,字段映射在业务设置维护'},{name:'到达历史扫描',ready:!!scan?.runs.some(r=>r.status==='success'&&(r.kind||'inform')==='inform'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 已收录 ${scan.total} 条流程`:'历史扫描服务未启动'},{name:'存储服务器',ready:!!storage?.store.servers().some(s=>s.enabled&&s.state.readable&&s.state.writable),detail:storage?`已配置 ${storage.store.servers().length} 个 SMB 存储服务器`:'存储服务未启动'},{name:'邮件渠道',ready:mailChannels.some(c=>!c.readOnly&&c.state.smtp),detail:`已配置 ${mailChannels.length} 个邮箱`},{name:'邮件模板',ready:mailTemplates.some(t=>t.status==='active'),detail:`${mailTemplates.filter(t=>t.status==='active').length} 个已生效,${mailTemplates.filter(t=>t.status==='pending').length} 个待确认;按类别显式关联`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:jobs.slice(0,6).map(publicJob),audit:store.audit().slice(0,5)}); } if(route==='/api/settings') { if(request.method==='GET')return handled(200,store.settings()); diff --git a/src/modules/workspace/api.cjs b/src/modules/workspace/api.cjs index 12cff21..b92e971 100644 --- a/src/modules/workspace/api.cjs +++ b/src/modules/workspace/api.cjs @@ -1,8 +1,8 @@ // This router is called only after dashboard authentication and same-origin validation. -function workspaceApi({workspace,store,user,route,method,body,reply,bpmSessions}){ +function workspaceApi({workspace,store,user,route,method,body,reply,bpmSessions,bpmMonitor}){ if(!workspace)return false; const members=()=>store.users(); - if(route==='/api/workspace' && method==='GET'){const snapshot=workspace.snapshot(members());snapshot.capabilities.remoteLogin=Boolean(bpmSessions);reply(200,snapshot);return true;} + if(route==='/api/workspace' && method==='GET'){const snapshot=workspace.snapshot(members());snapshot.capabilities.remoteLogin=Boolean(bpmSessions);snapshot.connections=snapshot.connections.map(c=>({...c,health:bpmSessions?.health?.snapshot(c.id)||{},monitoring:bpmMonitor?.snapshot(c.id)||{status:c.status==='disabled'?'paused':'waiting'}}));reply(200,snapshot);return true;} if(method!=='POST')return false; if(route==='/api/calendar'){reply(200,workspace.saveCalendar(body,user));return true;} if(route==='/api/exceptions'){reply(201,workspace.createException(body,user,members()));return true;} diff --git a/src/modules/workspace/store.cjs b/src/modules/workspace/store.cjs index 2382d96..51e90e4 100644 --- a/src/modules/workspace/store.cjs +++ b/src/modules/workspace/store.cjs @@ -100,7 +100,7 @@ class WorkspaceStore { markSessionChecksPending(){ return this.transaction(()=>{let count=0;for(const row of this.db.prepare('SELECT id,value FROM connections').all()){const item=JSON.parse(row.value);if(item.status!=='connected')continue;item.status='unchecked';this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),row.id);count++;}return count;}); } - updateConnectionSession(id,result,actor){ + updateConnectionSession(id,result,actor,{audit=true}={}){ authorize(actor,['admin','operator']);object(result,['status','identity','checkedAt','checks']); if(!['connected','login_required','error'].includes(result.status))fail('连接检查状态不正确。'); const identity=text(result.identity,'BPM 账号',200); @@ -110,17 +110,26 @@ class WorkspaceStore { if((result.status==='connected')!==checks.portal.ok)fail('连接检查结果不完整。'); return this.transaction(()=>{ const item=this.getConnection(id);if(actor.role!=='admin' && item.owner!==actor.username)fail('仅连接负责人或管理员可以操作此连接。',403);if(item.status==='disabled')fail('此连接已停用。',409); + const changed=item.status!==result.status||item.identity!==identity||JSON.stringify(item.checks)!==JSON.stringify(checks); const at=new Date().toISOString();Object.assign(item,{status:result.status,identity,checkedAt:result.checkedAt,checks,updatedAt:at});if(item.status==='connected')item.lastConnectedAt=result.checkedAt; this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),id); if(['error','login_required'].includes(item.status) && item.lastConnectedAt){ const existing=this.db.prepare('SELECT value FROM exceptions').all().map(row=>JSON.parse(row.value)).some(entry=>entry.connectionId===id && entry.kind==='bpm_login' && entry.status!=='resolved'); if(!existing){const unavailable=item.status==='error',title=unavailable?'BPM 连接需要检查:'+item.name:item.name+' 需要登录验证',description=unavailable?'新版 BPM 暂时无法连接,请检查网络和连接状态。':'BPM 自动续登未完成,请连接负责人检查托管账号或完成登录验证。';const task={id:crypto.randomUUID(),title,description,component:'bpm',priority:'high',owner:item.owner,status:'in_progress',version:1,kind:'bpm_login',connectionId:id,createdAt:at,updatedAt:at,history:[{at,actor:actor.username,action:'create',note:unavailable?'连接检查未通过':'连接检查需要登录验证'}]};this.db.prepare('INSERT INTO exceptions(id,value) VALUES(?,?)').run(task.id,JSON.stringify(task));this.record(actor,unavailable?'创建 BPM 连接检查待办':'创建 BPM 续登待办',item.name);} } - this.record(actor,'检查 BPM 连接',item.name+':'+item.status);return item; + if(audit||changed)this.record(actor,'检查 BPM 连接',item.name+':'+item.status);return item; }); } disableConnection(id,actor){ - authorize(actor,['admin']);return this.transaction(()=>{const item=this.getConnection(id);if(item.status==='disabled')return item;item.status='disabled';for(const key of ['identity','checks','checkedAt','lastConnectedAt','savedAt'])delete item[key];item.updatedAt=new Date().toISOString();this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),id);this.record(actor,'停用连接',item.name);return item;}); + return this.setConnectionEnabled(id,false,{version:this.getConnection(id).version||0},actor); + } + setConnectionEnabled(id,enabled,input,actor){ + authorize(actor,['admin']);return this.transaction(()=>{ + const item=this.getConnection(id);if((item.status!=='disabled')===enabled)return item; + if(!Number.isInteger(input?.version)||input.version!==(item.version||0))fail('连接状态已变化,请刷新后重试。',409); + item.status=enabled?'unchecked':'disabled';item.version=(item.version||0)+1;item.updatedAt=new Date().toISOString(); + this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),id);this.record(actor,enabled?'启用连接':'停用连接',item.name);return item; + }); } deleteConnection(id,actor){ authorize(actor,['admin']);return this.transaction(()=>{const item=this.getConnection(id);if(item.status!=='disabled')fail('请先停用连接再删除。',409);this.db.prepare('DELETE FROM connections WHERE id=?').run(id);this.record(actor,'删除连接',item.name);return {id,deleted:true};}); diff --git a/tests/bpm/arrival-monitor.test.cjs b/tests/bpm/arrival-monitor.test.cjs new file mode 100644 index 0000000..b073f10 --- /dev/null +++ b/tests/bpm/arrival-monitor.test.cjs @@ -0,0 +1,23 @@ +'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 {WorkspaceStore}=require('../../src/modules/workspace/store.cjs'),{BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs'),{BpmScanner}=require('../../src/modules/bpm/scanner.cjs'); +let Monitor;try{Monitor=require('../../src/modules/bpm/arrival-monitor.cjs').BpmArrivalMonitor;}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;} +async function until(predicate){const end=Date.now()+2500;while(!predicate()){if(Date.now()>end)throw Error('Monitor condition was not reached');await new Promise(r=>setTimeout(r,10));}} +function fixture(t){assert.equal(typeof Monitor,'function');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-monitor-')),workspace=new WorkspaceStore(path.join(dir,'workspace')),store=new BpmScanStore(path.join(dir,'scan')),actor={username:'admin',role:'admin'},connection=workspace.createConnection({name:'监听连接',owner:'admin'},actor,[actor]);let now=Date.parse('2026-10-20T01:00:00Z'),todo=[{source:'todo',portalSource:'portal-v4',taskId:'T1',instanceId:'I1',revision:0,processName:'测试订单评审',nodeName:'通知节点',processVersion:'1',serialNum:'S1',title:'订单号:TEST-1',receivedAt:'2026-10-20T00:00:00Z'}],hold=null,connects=0,todoCalls=0,failed=false,epoch=0,hubFailure=0;let callbacks; + workspace.updateConnectionSession(connection.id,{status:'connected',identity:'fixture',checkedAt:new Date(now).toISOString(),checks:{portal:{ok:true,message:'ok'}}},actor); + const manager={epoch:()=>epoch,sessions:new Map(),ensure:async()=>({status:'connected'}),run:async(_,fn)=>fn(),authorize(){},vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})}),scanArrivals:async()=>[{source:'portal-v4',taskId:'INFORM',arrivalDay:'2026-10-20',arrivedAt:'2026-10-20T00:00:00Z',subject:'只读待阅'}]}; + const provider={scan:async()=>{todoCalls++;if(hold)await hold;if(failed)throw Object.assign(Error('temporary query failure'),{status:502});return structuredClone(todo);}},scanner=new BpmScanner({workspace,store,manager,settings:()=>({schedule:{weekends:true}}),clock:()=>new Date(now)}); + const hubClient={connect:async(_,options)=>{connects++;callbacks=options;if(hubFailure)throw Object.assign(Error('hub denied'),{status:hubFailure});return {stop:async()=>{}};}}; + const monitor=new Monitor({workspace,manager,scanner,provider,hubClient,settings:()=>({schedule:{weekends:true}}),clock:()=>now,debounceMs:15,pollMs:10,retryMs:[20,40]}); + t.after(async()=>{await monitor.stop();await scanner.stop();store.close();workspace.close();fs.rmSync(dir,{recursive:true,force:true});}); + return {workspace,store,monitor,connection,actor,get todoCalls(){return todoCalls;},get connects(){return connects;},hint(name){callbacks.onEvent(name);},disconnect(){callbacks.onClose({reason:'disconnected'});},bumpEpoch:()=>epoch++,setHubFailure:value=>hubFailure=value,setTodo:value=>todo=value,setFailure:value=>failed=value,setHold:value=>hold=value,advance:ms=>now+=ms,until}; +} +test('initial and reconnected subscriptions reconcile real todo and inform sources separately, including equal-count replacement',async t=>{const f=fixture(t);f.monitor.start();await until(()=>f.store.list({kind:'todo'}).total===1&&f.store.list().total===1);assert.equal(f.monitor.snapshot(f.connection.id).status,'listening');f.setTodo([{source:'todo',portalSource:'portal-v4',taskId:'T2',instanceId:'I2',revision:1,processName:'测试订单评审',nodeName:'通知节点',serialNum:'S2',title:'订单号:TEST-2',receivedAt:'2026-10-20T00:10:00Z'}]);f.disconnect();f.advance(100);await until(()=>f.connects>=2&&f.store.list({kind:'todo'}).total===2);assert.equal(f.store.list().total,1);assert.equal(f.store.list({kind:'todo'}).groups[0].items.some(r=>r.taskId==='T2'),true);}); +test('hint bursts coalesce and a hint during synchronization schedules exactly one followup',async t=>{const f=fixture(t);f.monitor.start();await until(()=>f.todoCalls===1&&f.monitor.snapshot(f.connection.id).lastSyncAt);let release;f.setHold(new Promise(r=>release=r));for(let i=0;i<20;i++)f.hint('worklistChanged');await until(()=>f.todoCalls===2);for(let i=0;i<20;i++)f.hint('worklistChanged');release();f.setHold(null);await until(()=>f.todoCalls===3);await new Promise(r=>setTimeout(r,60));assert.equal(f.todoCalls,3);}); +test('failed reconciliation retains prior rows and fallback polling recovers without a pushed event',async t=>{const f=fixture(t);f.monitor.start();await until(()=>f.store.list({kind:'todo'}).total===1);f.setFailure(true);f.hint('worklistChanged');await until(()=>f.store.status().runs.some(r=>r.kind==='todo'&&r.status==='error'));assert.equal(f.store.list({kind:'todo'}).total,1);f.setFailure(false);f.advance(5*60*1000+1);await until(()=>f.monitor.snapshot(f.connection.id).lastSyncAt===new Date(Date.parse('2026-10-20T01:00:00Z')+5*60*1000+1).toISOString());assert.equal(f.store.list({kind:'todo'}).total,1);}); +test('pause removes listener and late callbacks cannot reconnect or commit new arrivals',async t=>{const f=fixture(t);f.monitor.start();await until(()=>f.store.list({kind:'todo'}).total===1);f.workspace.disableConnection(f.connection.id,f.actor);await f.monitor.stopConnection(f.connection.id);f.hint('worklistChanged');f.disconnect();f.advance(1000000);await f.monitor.tick();await new Promise(r=>setTimeout(r,40));assert.equal(f.connects,1);assert.equal(f.todoCalls,1);assert.equal(f.monitor.snapshot(f.connection.id).status,'paused');}); +test('manual todo reconciliation enforces ownership and only commits after every row is valid',async t=>{const f=fixture(t);assert.equal(typeof f.monitor.startTodoScan,'function');assert.throws(()=>f.monitor.startTodoScan(f.connection.id,{user:{username:'other',role:'operator'},sessionId:'x'}),e=>e.status===403);await f.monitor.startTodoScan(f.connection.id,{user:f.actor,sessionId:'manual'}).promise;assert.equal(f.store.list({kind:'todo'}).total,1);f.setTodo([{source:'todo',portalSource:'portal-v4',taskId:'bad',instanceId:'bad',revision:1,title:'订单号:BAD',receivedAt:'not-a-date'}]);await assert.rejects(f.monitor.startTodoScan(f.connection.id,{user:f.actor,sessionId:'manual'}).promise);assert.equal(f.store.list({kind:'todo'}).total,1);}); +test('company calendar pauses automatic synchronization while retaining the listener and queued change',async t=>{const f=fixture(t);f.workspace.saveCalendar({version:1,overrides:[{date:'2026-10-20',kind:'pause',scan:false,send:false,note:'隔离验证'}]},f.actor);f.monitor.start();await until(()=>f.monitor.snapshot(f.connection.id).status==='listening');f.hint('worklistChanged');await new Promise(r=>setTimeout(r,45));assert.equal(f.todoCalls,0);f.advance(86400000);await f.monitor.tick();await until(()=>f.store.list({kind:'todo'}).total===1);}); + +test('identity changes retire old hints and establish a fresh subscription before reconciliation',async t=>{const f=fixture(t);await f.monitor.tick();await until(()=>f.todoCalls===1&&f.monitor.snapshot(f.connection.id).lastSyncAt);f.bumpEpoch();f.hint('worklistChanged');await new Promise(r=>setTimeout(r,45));assert.equal(f.todoCalls,1);await f.monitor.tick();await f.monitor.tick();await until(()=>f.connects===2&&f.todoCalls===2);}); +test('a denied push channel falls back immediately to authorized readonly lists',async t=>{const f=fixture(t);f.setHubFailure(403);f.monitor.start();await until(()=>f.store.list({kind:'todo'}).total===1);assert.equal(f.monitor.snapshot(f.connection.id).status,'polling');}); diff --git a/tests/bpm/bpm-http.test.cjs b/tests/bpm/bpm-http.test.cjs index 760851a..e142aa1 100644 --- a/tests/bpm/bpm-http.test.cjs +++ b/tests/bpm/bpm-http.test.cjs @@ -2,12 +2,12 @@ const {test}=require('node:test');const assert=require('node:assert/strict');con const {Store}=require('../../src/modules/dashboard/store.cjs');const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');const {createDashboard}=require('../../src/app/dashboard.cjs'); const result=(status='connected')=>({status,identity:'alice@bpm',checkedAt:'2026-10-16T01:00:00.000Z',checks:{portal:{ok:status==='connected',message:'门户检查'}}}); async function setup(t,options={}){ - const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-http-'));const store=new Store(path.join(dir,'users'));const admin=store.bootstrap('admin','Test-password-123');for(const [username,role] of [['alice','operator'],['bob','operator'],['reader','viewer']])store.addUser({username,password:'Test-password-123',role},'admin');const workspace=new WorkspaceStore(path.join(dir,'workspace'));let lease;let next=result();let disabled=0,released=0;const jpg=Buffer.from([255,216,255,217]); - const manager={open:async(connection,principal)=>{if(lease && lease!==principal.sessionId)throw Object.assign(new Error('占用'),{status:409});lease=principal.sessionId;return {active:true,viewport:{width:1280,height:800},expiresAt:'2026-10-16T02:00:00.000Z',host:'bpmn.skyworthdigital.com'};},frame:async(id,p)=>{assert.ok(id);if(lease!==p.sessionId)throw Object.assign(new Error('占用'),{status:409});return jpg;},input:async(id,p,action)=>{assert.equal(action.type,'text');return {ok:true};},navigate:async(id,p,action)=>({target:action.target}),save:async()=>next,check:async()=>next,close:async(id,p)=>{if(lease && lease!==p.sessionId)throw Object.assign(new Error('占用'),{status:409});lease=null;return {ok:true};},releaseSession:async(token)=>{if(lease===token)lease=null;released++;},disable:async()=>{disabled++;lease=null;}}; + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-http-'));const store=new Store(path.join(dir,'users'));const admin=store.bootstrap('admin','Test-password-123');for(const [username,role] of [['alice','operator'],['bob','operator'],['reader','viewer']])store.addUser({username,password:'Test-password-123',role},'admin');const workspace=new WorkspaceStore(path.join(dir,'workspace'));let lease;let next=result();let disabled=0,released=0,suspended=0;const jpg=Buffer.from([255,216,255,217]); + const manager={open:async(connection,principal)=>{if(lease && lease!==principal.sessionId)throw Object.assign(new Error('占用'),{status:409});lease=principal.sessionId;return {active:true,viewport:{width:1280,height:800},expiresAt:'2026-10-16T02:00:00.000Z',host:'bpmn.skyworthdigital.com'};},frame:async(id,p)=>{assert.ok(id);if(lease!==p.sessionId)throw Object.assign(new Error('占用'),{status:409});return jpg;},input:async(id,p,action)=>{assert.equal(action.type,'text');return {ok:true};},navigate:async(id,p,action)=>({target:action.target}),save:async()=>next,check:async()=>next,close:async(id,p)=>{if(lease && lease!==p.sessionId)throw Object.assign(new Error('占用'),{status:409});lease=null;return {ok:true};},releaseSession:async(token)=>{if(lease===token)lease=null;released++;},suspend:async()=>{suspended++;lease=null;},resume:async()=>{},disable:async()=>{disabled++;lease=null;}}; const server=createDashboard({store,workspace,outputDir:dir,...(options.noManager?{}:{bpmSessions:manager}),trustedProxy:options.trustedProxy});await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));t.after(async()=>{await new Promise(resolve=>server.close(resolve));workspace.close();fs.rmSync(dir,{recursive:true,force:true});});const base='http://127.0.0.1:'+server.address().port; function call(route,body,cookie,extra={}){return new Promise((resolve,reject)=>{const host=extra.host||'127.0.0.1:'+server.address().port;const request=http.request(base+route,{method:body===undefined?'GET':'POST',headers:{Host:host,...(body===undefined?{}:{Origin:extra.origin||'http://'+host,'Content-Type':'application/json'}),...(cookie?{Cookie:cookie}:{}),...(extra.headers||{})}},response=>{const chunks=[];response.on('data',x=>chunks.push(x));response.on('end',()=>{const bytes=Buffer.concat(chunks);resolve({status:response.statusCode,headers:response.headers,bytes,json:()=>JSON.parse(bytes.toString())});});});request.on('error',reject);request.end(body===undefined?undefined:JSON.stringify(body));});} const login=async(username)=>(await call('/api/login',{username,password:'Test-password-123'})).headers['set-cookie'][0].split(';')[0];const cookie=await login('admin');const connection=(await call('/api/connections',{name:'BPM',owner:'alice'},cookie)).json();const route='/api/connections/'+connection.id; - return {call,login,cookie,workspace,store,manager,connection,route,setResult:value=>{next=value;},counts:()=>({disabled,released}),jpg}; + return {call,login,cookie,workspace,store,manager,connection,route,setResult:value=>{next=value;},counts:()=>({disabled,released,suspended}),jpg}; } test('deleting a disabled connection enforces admin, cleans custody first, and preserves the entry on cleanup failure',async t=>{ const s=await setup(t);const endpoint=s.route+'/delete'; @@ -62,10 +62,10 @@ test('transport never trusts remote LAN address with local Host or forwarded HTT assert.equal(secureBpmTransport(request('workspace.example','127.0.0.1',false,'https,http'),true),false); assert.equal(secureBpmTransport(request('workspace.example','127.0.0.1',false,'https'),true),true); }); -test('manager errors do not leak browser secrets and failed disable leaves persisted connection enabled',async t=>{ +test('manager errors do not leak browser secrets and failed pause remains disabled without exposing manager errors',async t=>{ const s=await setup(t);s.manager.open=async()=>{throw new Error('password=NEVER-EXPOSE cookie=PRIVATE');}; const failed=await s.call(s.route+'/login/open',{},s.cookie);assert.equal(failed.status,502);assert.ok(!failed.bytes.toString().includes('NEVER-EXPOSE')); - s.manager.disable=async()=>{throw new Error('cookie=PRIVATE');};const disabled=await s.call(s.route+'/disable',{},s.cookie);assert.equal(disabled.status,502);assert.equal(s.workspace.getConnection(s.connection.id).status,'disconnected'); + s.manager.suspend=async()=>{throw new Error('cookie=PRIVATE');};const disabled=await s.call(s.route+'/disable',{},s.cookie);assert.equal(disabled.status,502);assert.equal(s.workspace.getConnection(s.connection.id).status,'disabled'); }); test('portal metadata persists safely, unavailable and login tasks deduplicate, and restart clears readiness',async t=>{ const s=await setup(t);const alice=await s.login('alice');assert.equal((await s.call('/api/workspace',undefined,alice)).json().capabilities.remoteLogin,true); @@ -77,7 +77,7 @@ test('portal metadata persists safely, unavailable and login tasks deduplicate, s.setResult(result('login_required'));for(let n=0;n<2;n++)assert.equal((await s.call(s.route+'/check',{},alice)).status,200);assert.equal(s.workspace.snapshot().exceptions.length,1);assert.equal(s.workspace.snapshot().exceptions[0].component,'bpm');assert.equal(s.workspace.snapshot().exceptions[0].id,attentionId); s.setResult({...result(),cookies:[{value:'PRIVATE_COOKIE'}],password:'PRIVATE_PASSWORD'});assert.equal((await s.call(s.route+'/check',{},alice)).status,400);assert.ok(!JSON.stringify(s.workspace.snapshot()).includes('PRIVATE_')); s.setResult(result());await s.call(s.route+'/check',{},alice);s.workspace.markSessionChecksPending();const after=s.workspace.getConnection(s.connection.id);assert.equal(after.status,'unchecked');assert.equal(after.identity,'alice@bpm');assert.equal(after.checkedAt,'2026-10-16T01:00:00.000Z'); - assert.equal((await s.call(s.route+'/disable',{},alice)).status,403);assert.equal(s.counts().disabled,0);assert.equal((await s.call(s.route+'/disable',{},s.cookie)).status,200);assert.equal(s.counts().disabled,1);assert.equal((await s.call(s.route+'/login/open',{},alice)).status,409); + assert.equal((await s.call(s.route+'/disable',{},alice)).status,403);assert.equal(s.counts().disabled,0);assert.equal((await s.call(s.route+'/disable',{},s.cookie)).status,200);assert.equal(s.counts().suspended,1);assert.equal(s.counts().disabled,0);assert.equal((await s.call(s.route+'/login/open',{},alice)).status,409); const noManager=await setup(t,{noManager:true});assert.equal((await noManager.call('/api/workspace',undefined,noManager.cookie)).json().capabilities.remoteLogin,false);assert.equal((await noManager.call(noManager.route+'/login/open',{},noManager.cookie)).status,503); }); @@ -123,3 +123,5 @@ test('account availability is authenticated, owner scoped, strict and duplicate const failed=await s.call(s.route+'/account',{username:'existing',password:'SECRET'},owner); assert.equal(failed.status,409);assert.match(failed.json().error,/账号.*已/);assert.equal(failed.bytes.includes(Buffer.from('PRIVATE')),false); }); + +test('BPM lifecycle endpoints resume with the current version and reject stale or unauthorized enables',async t=>{const s=await setup(t);const paused=await s.call(s.route+'/disable',{version:0},s.cookie);assert.equal(paused.status,200);assert.equal(paused.json().version,1);assert.equal(s.counts().disabled,0);assert.equal(s.counts().suspended,1);assert.equal((await s.call(s.route+'/enable',{version:0},s.cookie)).status,409);assert.equal((await s.call(s.route+'/enable',{version:1},await s.login('alice'))).status,403);const enabled=await s.call(s.route+'/enable',{version:1},s.cookie);assert.equal(enabled.status,200);assert.equal(enabled.json().status,'unchecked');assert.equal(enabled.json().version,2);}); diff --git a/tests/bpm/bpm-scan-http-ui.test.cjs b/tests/bpm/bpm-scan-http-ui.test.cjs index 83840b9..2d8d25b 100644 --- a/tests/bpm/bpm-scan-http-ui.test.cjs +++ b/tests/bpm/bpm-scan-http-ui.test.cjs @@ -26,9 +26,15 @@ test('browser displays separate arrival days, searches, scans and preserves PDF await page.locator('[data-arrival-day="2026-10-15"]').waitFor();assert.equal(await page.locator('[data-arrival-day]').count(),2); const background=normalizeArrival({taskId:'background',serialNum:'BG-1',processName:'新增流程',startTime:'2026-10-16T12:00:00',processInstanceSubject:'后台扫描新增'},'portal-v8');scanStore.complete(scanStore.begin('fixture','系统扫描'),'fixture',[background]); await page.getByText('后台扫描新增',{exact:true}).waitFor({timeout:20000}); - await page.getByLabel('搜索流程记录',{exact:true}).fill('昨天');await page.getByRole('button',{name:'查询',exact:true}).click();await page.getByText('昨天的流程',{exact:true}).waitFor();assert.equal(await page.locator('[data-arrival-day]').count(),1); + await page.getByLabel('搜索流程记录',{exact:true}).fill('昨天');await page.getByRole('button',{name:'查询',exact:true}).click();await page.waitForFunction(()=>document.querySelectorAll('[data-arrival-day]').length===1);await page.getByText('昨天的流程',{exact:true}).waitFor();assert.equal(await page.locator('[data-arrival-day]').count(),1); await page.getByRole('button',{name:'立即扫描',exact:true}).click();await page.getByText(/扫描完成/).waitFor(); await page.getByRole('button',{name:'PDF 导出记录',exact:true}).click();await page.locator('#record-search').waitFor();assert.equal(await page.locator('#record-search').isVisible(),true); await page.route('**/api/bpm-scan',route=>route.fulfill({status:503,contentType:'application/json',body:JSON.stringify({error:'扫描暂不可用'})})); await page.getByRole('link',{name:'工作总览',exact:true}).click();await page.getByRole('link',{name:'订单与导出记录',exact:true}).click();await page.locator('#pdf-fallback').waitFor();await page.locator('#pdf-fallback').click();await page.locator('#record-search').waitFor(); }); +test('todo arrival queries stay separate from inform history and cannot invoke an unavailable todo listener',async t=>{ + const {call,login,scanner,scanStore}=await setup(t),cookie=await login('admin');await scanner.scan('fixture',{user:{username:'admin',role:'admin'},sessionId:'fixture'}); + const row=require('../../src/modules/bpm/arrival-monitor.cjs').todoArrival({source:'todo',portalSource:'portal-v4',taskId:'TODO-1',instanceId:'INSTANCE',revision:1,processName:'订单流程',nodeName:'通知节点',title:'待办样例',receivedAt:'2026-10-20T01:00:00Z'});scanStore.complete(scanStore.begin('fixture','系统监听','todo'),'fixture',[row]); + const todo=await (await call('/api/arrivals?kind=todo',undefined,cookie)).json();assert.equal(todo.total,1);assert.equal(todo.groups[0].items[0].kind,'todo');assert.equal((await (await call('/api/arrivals',undefined,cookie)).json()).total,2);assert.equal((await call('/api/arrivals?kind=unknown',undefined,cookie)).status,400);assert.equal((await call('/api/bpm-scan/run',{connectionId:'fixture',kind:'todo'},cookie)).status,503); +}); +test('a successful todo observation does not claim that the independent inform-history source was verified',async t=>{const {call,login,scanStore}=await setup(t),cookie=await login('admin'),row=require('../../src/modules/bpm/arrival-monitor.cjs').todoArrival({source:'todo',portalSource:'portal-v4',taskId:'TODO',instanceId:'I',revision:1,processName:'订单流程',nodeName:'通知节点',title:'待办样例',receivedAt:'2026-10-20T01:00:00Z'});scanStore.complete(scanStore.begin('fixture','系统监听','todo'),'fixture',[row]);const overview=await (await call('/api/overview',undefined,cookie)).json();assert.equal(overview.connections.find(c=>c.name==='到达历史扫描').ready,false);}); diff --git a/tests/bpm/bpm-scan.test.cjs b/tests/bpm/bpm-scan.test.cjs index 3734b97..aea605a 100644 --- a/tests/bpm/bpm-scan.test.cjs +++ b/tests/bpm/bpm-scan.test.cjs @@ -49,3 +49,6 @@ test('SQLite keeps history across rescan and restart, daily pagination and searc const bad=store.begin('c','甲');assert.throws(()=>store.complete(bad,'c',[rows[0],{...rows[1],arrivalDay:null}]));assert.equal(store.list().total,2);store.fail(bad,'扫描失败');assert.equal(store.status().runs[0].status,'error'); store.saveConfig({enabled:false,intervalMinutes:10},'甲');assert.equal(store.status().config.enabled,false); }); +test('a forbidden list response is a permission failure and must not request credential renewal',async t=>{ + const server=http.createServer((req,res)=>{if(req.url==='/')return res.end('');res.writeHead(403);res.end();});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));const client=new BpmListClient({baseURL:'http://127.0.0.1:'+server.address().port+'/',allowLocal:true});await assert.rejects(client.scan({cookies:[],origins:[]}),e=>e.status===403); +}); diff --git a/tests/bpm/bpm-ui.test.cjs b/tests/bpm/bpm-ui.test.cjs index a3d506c..4025ef3 100644 --- a/tests/bpm/bpm-ui.test.cjs +++ b/tests/bpm/bpm-ui.test.cjs @@ -39,6 +39,7 @@ async function fixture(t,{user={username:'alice',role:'operator'},connections,ac if(url.pathname.endsWith('/save'))await saveGate; if(url.pathname.endsWith('/save')||url.pathname.endsWith('/check'))result={connection:{id:'one',name:'业务连接',owner:'alice',status:'connected',identity:'Alice',checkedAt:new Date().toISOString(),checks:{portal:{ok:true,message:'已登录'}}}}; if(url.pathname.endsWith('/account/check'))result={available:body?.username!=='already-used'}; + if(url.pathname.endsWith('/enable')||url.pathname.endsWith('/disable')){const id=url.pathname.split('/').at(-2),item=connections.find(c=>c.id===id);item.status=url.pathname.endsWith('/enable')?'unchecked':'disabled';item.version=(item.version||0)+1;result={...item};} await route.fulfill({json:result}); }); await page.goto(base); @@ -80,11 +81,11 @@ test('auto-renew setup rejects a duplicate username before sending credentials a assert.equal(await f.page.getByRole('button',{name:/^(管理账号|开启自动续登)$/}).count(),1); }); -test('portal login displays one portal check and saves connected without legacy controls',async t=>{ +test('portal login displays session, business and monitoring checks without legacy controls',async t=>{ const f=await fixture(t,{connections:[{id:'one',name:'新版 BPM',owner:'alice',status:'connected',checks:{portal:{ok:true,message:'新版已登录'}}}]}); assert.equal(await f.page.getByText('旧版入口',{exact:true}).count(),0); assert.equal(await f.page.getByText('bpm.skyworthdigital.com',{exact:true}).count(),0); - assert.equal(await f.page.locator('.bpm-checks>div').count(),1); + assert.match(await f.page.locator('.bpm-checks').innerText(),/登录会话.*新版已登录/); await f.page.getByRole('button',{name:'远程登录',exact:true}).click(); assert.equal(await f.page.getByRole('button',{name:'旧版入口',exact:true}).count(),0); await f.page.getByRole('button',{name:'新版门户',exact:true}).click(); @@ -92,7 +93,7 @@ test('portal login displays one portal check and saves connected without legacy await f.page.getByRole('button',{name:'检查并保存',exact:true}).click(); await f.page.getByText('连接已检查并保存。',{exact:true}).waitFor(); assert.equal(await f.page.getByText('已连接',{exact:true}).count(),1); - assert.equal(await f.page.locator('.bpm-checks>div').count(),1); + assert.match(await f.page.locator('.bpm-checks').innerText(),/登录会话.*已登录/); assert.deepEqual(f.calls.filter(c=>c.path.endsWith('/navigate')).map(c=>c.body),[{target:'main'},{target:'reload'}]); }); test('account management loads metadata only for enabled owner or admin connections',async t=>{ @@ -302,3 +303,11 @@ for(const pendingAction of ['open','save'])test(`document unload sends authentic const close=calls.find(c=>c.path.endsWith('/close'));assert.ok(close,'unload must dispatch close before the held request completes'); assert.equal(close.body,'{}');assert.match(close.cookie,/session=fixture-session/);assert.equal(close.origin,fixtureBase); }); + +test('admin pauses and resumes using explicit buttons and the current version',async t=>{const f=await fixture(t,{user:{username:'admin',role:'admin'},connections:[{id:'toggle',name:'可恢复连接',owner:'alice',status:'connected',version:4,identity:'fixture'}]});await f.page.getByRole('button',{name:'停用连接',exact:true}).click();await f.page.getByRole('button',{name:'启用连接',exact:true}).waitFor();assert.equal(await f.page.getByRole('button',{name:'检查连接',exact:true}).count(),0);assert.deepEqual(f.calls.find(c=>c.path.endsWith('/disable')).body,{version:4});await f.page.getByRole('button',{name:'启用连接',exact:true}).click();await f.page.getByRole('button',{name:'停用连接',exact:true}).waitFor();assert.deepEqual(f.calls.find(c=>c.path.endsWith('/enable')).body,{version:5});assert.equal(await f.page.getByRole('switch').count(),0);}); + +test('connection cards distinguish authenticated session, todo permission and passive-listener status',async t=>{const f=await fixture(t,{connections:[{id:'one',name:'分层检测',owner:'alice',status:'connected',health:{portal:{status:'healthy',checkedAt:new Date().toISOString()},todo:{status:'forbidden',checkedAt:new Date().toISOString()}},monitoring:{status:'listening',lastSyncAt:new Date().toISOString()}}]});await f.page.getByText('订单接口 · 无读取权限',{exact:false}).waitFor();await f.page.getByText('到达监听 · 推送已连接',{exact:false}).waitFor();await f.page.getByRole('button',{name:'开启自动续登',exact:true}).click();await f.page.getByLabel('BPM 账号',{exact:true}).fill('not-yet-saved');await new Promise(r=>setTimeout(r,5200));assert.equal(await f.page.getByLabel('BPM 账号',{exact:true}).inputValue(),'not-yet-saved');}); +test('a delayed background snapshot cannot resurrect a connection after deletion',async t=>{ + const connection={id:'off',name:'旧连接',owner:'alice',status:'disabled',version:1},f=await fixture(t,{user:{username:'admin',role:'admin'},connections:[connection]});let arrive,release;const arrived=new Promise(r=>arrive=r),gate=new Promise(r=>release=r); + await f.page.route('**/api/workspace',async route=>{arrive();await gate;await route.fulfill({json:{connections:[connection],capabilities:{remoteLogin:true}}});});await arrived;f.page.once('dialog',dialog=>dialog.accept());await f.page.getByRole('button',{name:'删除',exact:true}).click();await f.page.getByText('连接已删除。',{exact:true}).waitFor();const response=f.page.waitForResponse(r=>r.url().endsWith('/api/workspace'));release();await response;await f.page.waitForTimeout(100);assert.equal(await f.page.getByRole('heading',{name:'旧连接',exact:true}).count(),0); +}); diff --git a/tests/bpm/connection-health.test.cjs b/tests/bpm/connection-health.test.cjs new file mode 100644 index 0000000..5f74102 --- /dev/null +++ b/tests/bpm/connection-health.test.cjs @@ -0,0 +1,22 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),http=require('node:http'); +const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs'); +test('concurrent manual and background checks share one authenticated request',async t=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-shared-check-'));let release,started,probes=0;const gate=new Promise(r=>release=r),begun=new Promise(r=>started=r),manager=new BpmSessionManager({stateDir:dir,accessClient:{check:async()=>{probes++;started();await gate;return {status:'connected',checkedAt:new Date().toISOString(),checks:{portal:{ok:true,message:'ok'}},todo:'healthy'};}}});manager._vault={read:async()=>({storageState:{cookies:[],origins:[]}}),destroy(){}};t.after(async()=>{await manager.shutdown();fs.rmSync(dir,{recursive:true,force:true});});const c={id:'c',owner:'admin',status:'connected'},p={user:{username:'admin',role:'admin'},sessionId:'same'};const a=manager.ensure(c,p);await begun;const b=manager.check(c,p);release();await Promise.all([a,b]);assert.equal(probes,1); +}); +test('recent authenticated traffic avoids browser checks but expiry or identity invalidation requires fresh evidence',async t=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-health-'));let probes=0,browsers=0;const manager=new BpmSessionManager({stateDir:dir,accessClient:{check:async()=>{probes++;return {status:'connected',checkedAt:new Date().toISOString(),checks:{portal:{ok:true,message:'已验证'}},todo:'healthy'};}},browserFactory:()=>{browsers++;throw Error('Unexpected browser');}}); + manager._vault={read:async()=>({storageState:{cookies:[],origins:[]}}),write:async()=>{},destroy(){}};const c={id:'c',owner:'admin',status:'connected',identity:'fixture'},p={user:{username:'admin',role:'admin'},sessionId:'health'};t.after(async()=>{await manager.shutdown();fs.rmSync(dir,{recursive:true,force:true});}); + manager.observe('c','inform');const result=await manager.ensure(c,p);assert.equal(result.status,'connected');assert.equal(probes,0);assert.equal(browsers,0);await manager.check(c,p);assert.equal(probes,1);await manager.suspend('c');await manager.resume('c');await manager.ensure(c,p);assert.equal(probes,2); +}); +test('an upstream network failure never triggers browser credential submission',async t=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-probe-'));let browsers=0;const manager=new BpmSessionManager({stateDir:dir,accessClient:{check:async()=>({status:'error',checkedAt:new Date().toISOString(),checks:{portal:{ok:false,message:'网络暂不可用'}},todo:'error'})},browserFactory:()=>{browsers++;throw Error('must not login');}});manager._vault={read:async()=>({storageState:{cookies:[],origins:[]}}),destroy(){}};t.after(async()=>{await manager.shutdown();fs.rmSync(dir,{recursive:true,force:true});});const result=await manager.ensure({id:'c',owner:'admin',status:'connected'},{user:{username:'admin',role:'admin'},sessionId:'network'});assert.equal(result.status,'error');assert.equal(browsers,0); +}); +let Access;try{Access=require('../../src/modules/bpm/access-client.cjs').BpmAccessClient;}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;} +test('lightweight probes distinguish permission failure from expired authentication without loading order details',async t=>{ + assert.equal(typeof Access,'function');let mode='ok',urls=[];const server=http.createServer((req,res)=>{urls.push(req.url);if(req.url==='/'){res.end('');return;}if(mode==='auth'){res.writeHead(401);return res.end();}if(mode==='forbidden'){res.writeHead(403);return res.end();}res.setHeader('Content-Type','application/json');res.end(JSON.stringify({total:4,children:[{taskId:1}]}));});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));const client=new Access({baseURL:'http://127.0.0.1:'+server.address().port+'/',allowLocal:true}); + const state={cookies:[],origins:[]},ok=await client.check(state);assert.equal(ok.status,'connected');assert.equal(ok.todo,'healthy');assert.equal(urls.filter(u=>u!=='/').every(u=>u.includes('limit=1')),true);assert.equal(JSON.stringify(ok).includes('fixture-token'),false);mode='forbidden';const forbidden=await client.check(state);assert.equal(forbidden.status,'connected');assert.equal(forbidden.todo,'forbidden');mode='auth';assert.equal((await client.check(state)).status,'login_required'); +}); +test('an unrecognized external redirect is a transport failure rather than proof that credentials expired',async t=>{ + const server=http.createServer((req,res)=>{res.writeHead(302,{Location:'https://untrusted.invalid/login'});res.end();});await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(()=>new Promise(r=>server.close(r)));const client=new Access({baseURL:'http://127.0.0.1:'+server.address().port+'/',allowLocal:true});assert.equal((await client.check({cookies:[],origins:[]})).status,'error'); +}); diff --git a/tests/bpm/connection-lifecycle.test.cjs b/tests/bpm/connection-lifecycle.test.cjs new file mode 100644 index 0000000..368f7b2 --- /dev/null +++ b/tests/bpm/connection-lifecycle.test.cjs @@ -0,0 +1,13 @@ +'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 {WorkspaceStore}=require('../../src/modules/workspace/store.cjs'); +const {BpmSessionManager}=require('../../src/modules/bpm/session-manager.cjs'); +let Lifecycle;try{Lifecycle=require('../../src/modules/bpm/connection-lifecycle.cjs').BpmConnectionLifecycle;}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;} +function fixture(t){assert.equal(typeof Lifecycle,'function');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-lifecycle-')),workspace=new WorkspaceStore(path.join(dir,'workspace')),manager=new BpmSessionManager({stateDir:path.join(dir,'sessions'),browserFactory:()=>{throw Error('A toggle must not launch a browser');}}),admin={username:'admin',role:'admin'},connection=workspace.createConnection({name:'测试连接',owner:'admin'},admin,[admin]); + const secrets=new Map([[connection.id,{storageState:{cookies:[{name:'fixture',value:'private'}]}}],['account:'+connection.id,{username:'fixture',password:'private'}]]);manager._vault={read:async key=>secrets.get(key)||null,remove:async key=>secrets.delete(key),destroy(){}}; + t.after(async()=>{await manager.shutdown();workspace.close();fs.rmSync(dir,{recursive:true,force:true});});return {dir,workspace,manager,admin,connection,secrets,service:new Lifecycle({workspace,manager})};} +test('pause and resume retain account and cookies, increment versions, and survive workspace reopen',async t=>{const f=fixture(t),id=f.connection.id;const paused=await f.service.change(id,false,{version:0},f.admin);assert.equal(paused.status,'disabled');assert.equal(paused.version,1);assert.equal(f.secrets.size,2);const again=await f.service.change(id,false,{version:0},f.admin);assert.equal(again.version,1);const enabled=await f.service.change(id,true,{version:1},f.admin);assert.equal(enabled.status,'unchecked');assert.equal(enabled.version,2);assert.equal(f.secrets.size,2);assert.equal(f.manager.disabled.has(id),false);const reopened=new WorkspaceStore(path.join(f.dir,'workspace'));assert.equal(reopened.getConnection(id).status,'unchecked');assert.equal(reopened.getConnection(id).version,2);reopened.close();}); +test('stale enable cannot undo a newer pause, and only admins change lifecycle',async t=>{const f=fixture(t),id=f.connection.id;await f.service.change(id,false,{version:0},f.admin);await assert.rejects(f.service.change(id,true,{version:0},f.admin),e=>e.status===409);await assert.rejects(f.service.change(id,true,{version:1},{username:'admin',role:'operator'}),e=>e.status===403);assert.equal(f.workspace.getConnection(id).status,'disabled');}); +test('pause publishes disabled before draining in-flight work and a late check cannot revive it',async t=>{const f=fixture(t),id=f.connection.id;let release,arrive;const started=new Promise(r=>arrive=r),gate=new Promise(r=>release=r);const active=f.manager.run(id,async()=>{arrive();await gate;assert.throws(()=>f.workspace.updateConnectionSession(id,{status:'connected',identity:'fixture',checkedAt:new Date().toISOString(),checks:{portal:{ok:true,message:'ok'}}},f.admin),e=>e.status===409);});await started;const stopping=f.service.change(id,false,{version:0},f.admin);await new Promise(r=>setImmediate(r));assert.equal(f.workspace.getConnection(id).status,'disabled');release();await active;await stopping;assert.equal(f.secrets.size,2);}); +test('deletion alone clears account and session and requires a disabled connection',async t=>{const f=fixture(t),id=f.connection.id;await assert.rejects(f.service.remove(id,f.admin),e=>e.status===409);await f.service.change(id,false,{version:0},f.admin);await f.service.remove(id,f.admin);assert.equal(f.secrets.size,0);assert.throws(()=>f.workspace.getConnection(id),e=>e.status===404);}); +test('pause closes an active browser context before waiting for its queued operation to drain',async t=>{const f=fixture(t),id=f.connection.id;let release,closed=false;const gate=new Promise(r=>release=r);f.manager.sessions.set(id,{context:{close:async()=>{closed=true;release();}}});const work=f.manager.run(id,()=>gate);const stopping=f.service.change(id,false,{version:0},f.admin);try{await new Promise(r=>setImmediate(r));await new Promise(r=>setImmediate(r));assert.equal(closed,true);}finally{release();await work;await stopping;}assert.equal(f.secrets.size,2);}); diff --git a/tests/bpm/signalr-client.test.cjs b/tests/bpm/signalr-client.test.cjs new file mode 100644 index 0000000..4a7ca45 --- /dev/null +++ b/tests/bpm/signalr-client.test.cjs @@ -0,0 +1,8 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict');const {signalrHub}=require('../fixtures/signalr-hub.cjs'); +let Client;try{Client=require('../../src/modules/bpm/signalr-client.cjs').BpmSignalRClient;}catch(e){if(e.code!=='MODULE_NOT_FOUND')throw e;} +const state={cookies:[],origins:[]}; +test('real hub handshake accepts only known change hints and sends no business invocation',async t=>{assert.equal(typeof Client,'function');const hub=await signalrHub(t),events=[];let notify;const received=new Promise(r=>notify=r);const client=new Client({baseURL:hub.baseURL,allowLocal:true}),handle=await client.connect(state,{onEvent:name=>{events.push(name);if(events.length===2)notify();}});hub.emit({type:1,target:'worklistChanged',arguments:[{private:'not passed'}]});hub.emit({type:1,target:'executeApproval',arguments:[]});hub.emit({type:1,target:'informlistChanged',arguments:[]});await received;await handle.stop();assert.deepEqual(events,['worklistChanged','informlistChanged']);assert.deepEqual(hub.messages[0],{protocol:'json',version:1});assert.equal(hub.messages.some(m=>m.type===1),false);}); +test('missing handshake and heartbeat fail with bounded safe reasons and release the connection',async t=>{assert.equal(typeof Client,'function');const missing=await signalrHub(t,{handshake:false});await assert.rejects(new Client({baseURL:missing.baseURL,allowLocal:true,handshakeMs:70}).connect(state),e=>e.code==='BPM_HUB_HANDSHAKE');const quiet=await signalrHub(t,{pings:false});let close;const closed=new Promise(r=>close=r);const handle=await new Client({baseURL:quiet.baseURL,allowLocal:true,heartbeatMs:80,pingMs:30}).connect(state,{onClose:close});assert.equal((await closed).reason,'heartbeat_timeout');await handle.stop();}); +test('abort and unauthorized negotiation never expose credentials or leave retry work running',async t=>{assert.equal(typeof Client,'function');const denied=await signalrHub(t,{authStatus:401});await assert.rejects(new Client({baseURL:denied.baseURL,allowLocal:true}).connect(state),e=>e.status===401&&!e.message.includes('fixture-token'));const controller=new AbortController();controller.abort();await assert.rejects(new Client({baseURL:denied.baseURL,allowLocal:true}).connect(state,{signal:controller.signal}),e=>e.name==='AbortError');}); +test('oversized or malformed hub frames close safely instead of delivering a forged event',async t=>{assert.equal(typeof Client,'function');const hub=await signalrHub(t),events=[];let close;const closed=new Promise(r=>close=r);const handle=await new Client({baseURL:hub.baseURL,allowLocal:true,maxFrameBytes:256}).connect(state,{onEvent:n=>events.push(n),onClose:close});hub.raw('x'.repeat(300));assert.equal((await closed).reason,'invalid_frame');assert.deepEqual(events,[]);await handle.stop();}); diff --git a/tests/fixtures/signalr-hub.cjs b/tests/fixtures/signalr-hub.cjs new file mode 100644 index 0000000..4371036 --- /dev/null +++ b/tests/fixtures/signalr-hub.cjs @@ -0,0 +1,15 @@ +'use strict'; +const http=require('node:http'),crypto=require('node:crypto'); +function frame(text){const bytes=Buffer.from(text);if(bytes.length<126)return Buffer.concat([Buffer.from([0x81,bytes.length]),bytes]);const header=Buffer.alloc(4);header[0]=0x81;header[1]=126;header.writeUInt16BE(bytes.length,2);return Buffer.concat([header,bytes]);} +async function signalrHub(t,{handshake=true,pings=true,authStatus=200}={}){ + const sockets=new Set(),messages=[];let pingsSent=0; + const server=http.createServer((req,res)=>{if(req.url==='/'){res.end('');return;}if(req.url==='/hubs/system/negotiate?negotiateVersion=1'){if(req.method!=='POST'||req.headers.authorization!=='Bearer fixture-token'){res.writeHead(401);return res.end();}res.writeHead(authStatus,{'Content-Type':'application/json'});return res.end(JSON.stringify({connectionToken:'fixture-connection',availableTransports:[{transport:'WebSockets'}]}));}res.writeHead(404);res.end();}); + server.on('upgrade',(req,socket)=>{const url=new URL(req.url,'http://fixture');if(url.pathname!=='/hubs/system'||url.searchParams.get('access_token')!=='fixture-token'||url.searchParams.get('id')!=='fixture-connection'){socket.end('HTTP/1.1 401 Unauthorized\r\n\r\n');return;} + const accept=crypto.createHash('sha1').update(req.headers['sec-websocket-key']+'258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64');socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: '+accept+'\r\n\r\n');sockets.add(socket);let pending=Buffer.alloc(0); + socket.on('data',chunk=>{pending=Buffer.concat([pending,chunk]);while(pending.length>=2){let length=pending[1]&127,at=2;if(length===126){if(pending.length<4)return;length=pending.readUInt16BE(2);at=4;}if(length===127){socket.destroy();return;}const masked=!!(pending[1]&128);if(pending.lengthsockets.delete(socket));socket.on('error',()=>{}); + }); + await new Promise(r=>server.listen(0,'127.0.0.1',r));t.after(async()=>{for(const socket of sockets)socket.destroy();await new Promise(r=>server.close(r));}); + return {baseURL:'http://127.0.0.1:'+server.address().port+'/',messages,sockets,get pingsSent(){return pingsSent;},emit(value){for(const socket of sockets)socket.write(frame(JSON.stringify(value)+'\x1e'));},raw(text){for(const socket of sockets)socket.write(frame(text));},disconnect(){for(const socket of sockets)socket.destroy();}}; +} +module.exports={signalrHub}; diff --git a/web/modules/bpm/arrivals.js b/web/modules/bpm/arrivals.js index ab16119..f98a066 100644 --- a/web/modules/bpm/arrivals.js +++ b/web/modules/bpm/arrivals.js @@ -1,6 +1,6 @@ 'use strict'; window.OrderViews=(()=>{ - let api,esc,formatDate,notify,user,filters={q:'',connectionId:''}; + let api,esc,formatDate,notify,user,filters={q:'',connectionId:'',kind:'inform'}; const configure=options=>{if(user?.username!==options.user.username)filters={q:'',connectionId:''};({api,esc,formatDate,notify,user}=options);}; async function records(container,isActive,renderPdf){ let initial; @@ -16,21 +16,21 @@ window.OrderViews=(()=>{ container.innerHTML=`
`; const panel=container.querySelector('#order-panel'); const active=()=>isActive()&&mode==='arrivals'; - function toolbar(){panel.innerHTML=`

BPM 自动扫描

管理连接${user.role!=='viewer'?'':''}
${user.role==='admin'?`
扫描设置
业务日历
`:''}

按到达日期

`; - panel.querySelector('#arrival-filter').onsubmit=event=>{event.preventDefault();filters={q:panel.querySelector('#arrival-query').value.trim(),connectionId:panel.querySelector('#arrival-connection').value};load(false).catch(showError);}; + function toolbar(){panel.innerHTML=`

BPM 自动扫描

管理连接${user.role!=='viewer'?'':''}
${user.role==='admin'?`
扫描设置
业务日历
`:''}

按到达日期

`; + panel.querySelector('#arrival-filter').onsubmit=event=>{event.preventDefault();filters={q:panel.querySelector('#arrival-query').value.trim(),connectionId:panel.querySelector('#arrival-connection').value,kind:panel.querySelector('#arrival-kind').value};load(false).catch(showError);}; panel.querySelector('#arrival-more').onclick=()=>load(true).catch(showError); panel.querySelector('#scan-config')?.addEventListener('submit',async event=>{event.preventDefault();const button=event.target.querySelector('button');button.disabled=true;try{status.config=await api('/bpm-scan/config',{enabled:panel.querySelector('#scan-enabled').checked,intervalMinutes:Number(panel.querySelector('#scan-interval').value)});if(active()){summary();notify('扫描设置已保存。');}}catch(e){showError(e);}finally{button.disabled=false;}}); panel.querySelector('#scan-now')?.addEventListener('click',async()=>{ const button=panel.querySelector('#scan-now');button.disabled=true; try{const selected=panel.querySelector('#arrival-connection').value,connections=status.connections.filter(c=>c.status!=='disabled'&&(!selected||c.id===selected)&&(user.role==='admin'||c.owner===user.username));if(!connections.length)throw Error('没有可扫描的连接,请先在 BPM 连接中完成登录。'); - for(const c of connections)await api('/bpm-scan/run',{connectionId:c.id});if(active()){panel.querySelector('#scan-result').textContent='正在扫描…';await refresh();watch();} + for(const c of connections)await api('/bpm-scan/run',{connectionId:c.id,...(filters.kind==='todo'?{kind:'todo'}:{})});if(active()){panel.querySelector('#scan-result').textContent='正在扫描…';await refresh();watch();} }catch(e){showError(e);}finally{if(active())button.disabled=false;} });summary(); } function showError(e){if(active())notify(e.message,'danger');} function summary(){ - if(!active())return;panel.querySelector('#scan-summary').textContent=`${status.config.enabled?'已开启':'已暂停'} · 每 ${status.config.intervalMinutes} 分钟 · 按业务日历运行`; - const latest=status.runs[0],ok=status.runs.find(r=>r.status==='success'); + if(!active())return;panel.querySelector('#scan-summary').textContent=`${status.config.enabled?'已开启':'已暂停'} · 推送连接 ${status.connections.filter(c=>c.monitoring?.status==='listening').length} 个 · 每 ${status.config.intervalMinutes} 分钟完整对账 · 按业务日历运行`; + const runs=status.runs.filter(r=>(r.kind||'inform')===(filters.kind||'inform')),latest=runs[0],ok=runs.find(r=>r.status==='success'); const el=panel.querySelector('#scan-result');el.className='small mt-3 '+(latest?.status==='error'?'text-danger':'text-secondary'); el.textContent=latest?.status==='running'?'正在扫描…':latest?.status==='error'?`${names.get(latest.connectionId)||'BPM'}:${latest.message}`:ok?`扫描完成 · ${formatDate(ok.finishedAt)} · 本次 ${ok.seen} 条,新增 ${ok.added} 条`:'尚无扫描记录'; } diff --git a/web/modules/bpm/view.js b/web/modules/bpm/view.js index c6c9a16..8f0169a 100644 --- a/web/modules/bpm/view.js +++ b/web/modules/bpm/view.js @@ -6,7 +6,7 @@ window.BpmLogin=(()=>{ async function mount(container,{api,esc,formatDate,notify,user,isActive=()=>true}){ await dispose(); if(!isActive())return; - let disposed=false,remote=null,accountBusy=false,data,connections=[]; + let disposed=false,remote=null,accountBusy=false,data,connections=[],statusTimer,statusRevision=0,mutationBusy=false; const accounts=new Map(),accountRequests=new Map(); const live=()=>!disposed&&isActive(); const $=selector=>container.querySelector(selector); @@ -20,7 +20,7 @@ window.BpmLogin=(()=>{ 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;container.querySelectorAll('[data-account-form]').forEach(form=>form.reset());return remote?release(remote,options):Promise.resolve();}}; + 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();}}; 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;} @@ -28,16 +28,16 @@ window.BpmLogin=(()=>{ if(!valid(r)||r.busy)return; r.queue=r.queue.then(()=>{if(valid(r)&&!r.failed)return api(route(r.id,'login/input'),action);}).catch(()=>{if(valid(r)){r.failed=true;feedback('输入未送达,请关闭后重新打开登录窗口。');}}); } - function update(result,id){const saved=result.connection||result;connections=connections.map(c=>c.id===id?{...c,...saved,id}:c);drawCards();} + function update(result,id){++statusRevision;const saved=result.connection||result;connections=connections.map(c=>c.id===id?{...c,...saved,id}:c);drawCards();} function rememberAccount(id,result){const metadata={configured:result.configured===true,username:typeof result.username==='string'?result.username:'',updatedAt:result.updatedAt||null};accounts.set(id,metadata);return metadata;} function loadAccount(id){ if(accounts.has(id))return Promise.resolve(accounts.get(id)); if(!accountRequests.has(id))accountRequests.set(id,api(route(id,'account')).then(result=>rememberAccount(id,result)).finally(()=>accountRequests.delete(id))); return accountRequests.get(id); } - function accountSummary(c){const account=accounts.get(c.id);return account?(account.configured?`自动续登已开启 · ${account.username} · 每 5 分钟检查`:'自动续登未开启'):'正在加载账号…';} + function accountSummary(c){const account=accounts.get(c.id);return account?(account.configured?`自动续登已开启 · ${account.username} · 按请求与会话状态维护`:'自动续登未开启'):'正在加载账号…';} function refreshAccountSummary(){if(live()){container.querySelectorAll('[data-account-summary]').forEach(el=>{const c=connections.find(c=>c.id===el.dataset.accountSummary);if(c)el.textContent=accountSummary(c);});container.querySelectorAll('[data-account]').forEach(button=>button.textContent=accounts.get(button.dataset.account)?.configured?'管理账号':'开启自动续登');}} - function accountControls(busy){accountBusy=busy;if(live())container.querySelectorAll('[data-login],[data-check],[data-disable],[data-delete],[data-account]').forEach(el=>el.disabled=busy||!!remote);} + function accountControls(busy){accountBusy=busy;if(live())container.querySelectorAll('[data-login],[data-check],[data-disable],[data-enable],[data-delete],[data-account]').forEach(el=>el.disabled=busy||!!remote);} async function editAccount(button){ const id=button.dataset.account; if(remote||accountBusy||!live())return; @@ -75,14 +75,30 @@ window.BpmLogin=(()=>{ }; }catch(error){feedback(error.message);}finally{if(live()&&button.isConnected)button.disabled=false;} } + function observations(c){ + const health=c.health||{},state={healthy:'可用',login_required:'需要登录',forbidden:'无读取权限',error:'暂不可用',unknown:'尚未检查'},monitor={listening:'推送已连接',connecting:'正在连接',reconnecting:'正在重连',polling:'轮询兜底',login_required:'需要登录',busy:'人工登录中',paused:'已暂停',waiting:'等待就绪'}; + const portal=health.portal,legacy=c.checks?.portal; + const row=(label,value,at)=>'
'+label+' · '+esc(value)+''+(at?''+esc(formatDate(at))+'':'')+'
'; + return row('登录会话',portal?(Date.now()-Date.parse(portal.checkedAt)>300000?'上次检查'+(state[portal.status]||'待确认'):state[portal.status]||'待确认'):legacy?.message||'尚未检查',portal?.checkedAt||c.checkedAt)+row('订单接口',state[health.todo?.status]||'尚未检查',health.todo?.checkedAt)+row('到达监听',monitor[c.monitoring?.status]||'等待就绪',c.monitoring?.lastSyncAt); + } + async function refreshStatus(){ + if(!live())return; + try{ + if(accountBusy||mutationBusy)return;const request=statusRevision,next=await api('/workspace');if(!live()||request!==statusRevision)return; + const rows=next.connections||[],changed=JSON.stringify(connections.map(c=>[c.id,c.status,c.version]))!==JSON.stringify(rows.map(c=>[c.id,c.status,c.version]));connections=rows; + if(changed&&!remote&&!container.querySelector('[data-account-form]'))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)health.innerHTML=observations(c);} + }catch{}finally{if(live())statusTimer=setTimeout(refreshStatus,5000);} + } function drawCards(){ if(!live())return; container.querySelectorAll('[data-account-form]').forEach(form=>form.reset()); - $('#bpm-list').innerHTML=connections.length?connections.map(c=>`

${esc(c.name)}

负责人 ${esc(c.owner||'未分配')}
${status(c)}
新版门户bpmn.skyworthdigital.com
${c.identity?`
登录账号 ${esc(c.identity)}
`:''}${c.checkedAt?`
上次检查 ${esc(formatDate(c.checkedAt))}
`:''}${c.checks?`
${[['portal','新版门户']].map(([key,label])=>`
${label} · ${c.checks[key]?.ok?'已登录':'待登录'}${esc(c.checks[key]?.message||'待检查')}
`).join('')}
`:''}
${c.status!=='disabled'&&authorized(c)?``:c.status==='disabled'&&user.role==='admin'?``:''}
`).join(''):'

还没有 BPM 连接

请管理员添加连接并指定负责人。

'; + $('#bpm-list').innerHTML=connections.length?connections.map(c=>`

${esc(c.name)}

负责人 ${esc(c.owner||'未分配')}
${status(c)}
新版门户bpmn.skyworthdigital.com
${c.identity?`
登录账号 ${esc(c.identity)}
`:''}${c.checkedAt?`
上次检查 ${esc(formatDate(c.checkedAt))}
`:''}
${observations(c)}
${c.status!=='disabled'&&authorized(c)?``:c.status==='disabled'&&user.role==='admin'?``:''}
`).join(''):'

还没有 BPM 连接

请管理员添加连接并指定负责人。

'; container.querySelectorAll('[data-account]').forEach(button=>button.onclick=()=>editAccount(button)); container.querySelectorAll('[data-login]').forEach(button=>button.onclick=()=>open(button.dataset.login)); container.querySelectorAll('[data-check]').forEach(button=>button.onclick=()=>mutate(button,'check','连接状态已更新。')); - container.querySelectorAll('[data-disable]').forEach(button=>button.onclick=()=>mutate(button,'disable','连接已停用。')); + container.querySelectorAll('[data-disable]').forEach(button=>button.onclick=()=>mutate(button,'disable','连接已停用,账号和会话已保留。')); + container.querySelectorAll('[data-enable]').forEach(button=>button.onclick=()=>mutate(button,'enable','连接已启用,正在恢复检查与监听。')); container.querySelectorAll('[data-delete]').forEach(button=>button.onclick=()=>removeConnection(button)); } async function removeConnection(button){ @@ -90,11 +106,11 @@ window.BpmLogin=(()=>{ const id=button.dataset.delete,connection=connections.find(c=>c.id===id); if(!connection||connection.status!=='disabled'||user.role!=='admin')return; if(!window.confirm('删除“'+connection.name+'”?该连接的托管账号和 Cookie 将一并清除,删除后无法恢复。'))return; - accountControls(true); - try{await api(route(id,'delete'),{});if(!live())return;connections=connections.filter(c=>c.id!==id);accounts.delete(id);drawCards();feedback('连接已删除。','success');} + ++statusRevision;accountControls(true); + try{await api(route(id,'delete'),{});if(!live())return;++statusRevision;connections=connections.filter(c=>c.id!==id);accounts.delete(id);drawCards();feedback('连接已删除。','success');} catch(error){feedback(error.message);}finally{accountControls(false);} } - async function mutate(button,action,message){button.disabled=true;try{const result=await api(route(button.dataset[action],action),{});if(!live())return;update(result,button.dataset[action]);feedback(message,'success');}catch(error){feedback(error.message);}finally{if(live())button.disabled=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){ if(!valid(r))return; try{ @@ -153,9 +169,10 @@ window.BpmLogin=(()=>{ try{ data=await api('/workspace');if(!live())return;connections=data.connections||[]; container.innerHTML=`
${user.role==='admin'?`

添加 BPM 连接

`:''}
`; - 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;connections.unshift(result.connection||result);event.target.reset();drawCards();feedback('连接已创建。','success');}catch(error){feedback(error.message);}finally{if(live())button.disabled=false;}}; + 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); }catch(error){if(live())throw error;} } return {mount,dispose};