From a9d050d87a096b8456b112138f380b32ccf15eb4 Mon Sep 17 00:00:00 2001 From: abaishu0730 Date: Thu, 22 Oct 2026 18:33:52 +0800 Subject: [PATCH] feat: process BPM notification tasks with verified readonly forms --- docs/HANDOFF.md | 15 +- docs/business-configuration.md | 4 +- docs/design-requirements.md | 2 + ...22-bpm-category-template-implementation.md | 10 +- ...26-10-22-notification-task-test-results.md | 71 +++++++ docs/unattended-system-design.md | 2 +- src/bpm-form-contracts.cjs | 22 +++ src/bpm-form-contracts.json | 160 +++++++++++++++ src/bpm-list-client.cjs | 8 +- src/bpm-notification-source.cjs | 23 +++ src/bpm-order-detail.cjs | 3 +- src/bpm-readonly-form.cjs | 183 ++++++++++++++++++ src/bpm-session-manager.cjs | 16 +- src/notifications.cjs | 4 +- src/order-pipeline.cjs | 18 +- src/order-workflow-api.cjs | 1 + src/order-workflow.cjs | 21 +- tests/bpm-dynamicarea.test.cjs | 43 ++++ tests/bpm-form-contracts.test.cjs | 30 +++ tests/bpm-hiddenexpress.test.cjs | 36 ++++ tests/bpm-notification-source.test.cjs | 28 +++ tests/bpm-readonly-form.test.cjs | 74 +++++++ tests/bpm-row-scope.test.cjs | 44 +++++ tests/order-pipeline.test.cjs | 25 ++- tests/order-workflow-plan.test.cjs | 4 +- tests/order-workflow-task-identity.test.cjs | 45 +++++ tests/order-workflow-ui.test.cjs | 7 + web/order-workflow.js | 14 +- 28 files changed, 879 insertions(+), 34 deletions(-) create mode 100644 docs/superpowers/plans/2026-10-22-notification-task-test-results.md create mode 100644 src/bpm-form-contracts.cjs create mode 100644 src/bpm-form-contracts.json create mode 100644 src/bpm-notification-source.cjs create mode 100644 src/bpm-readonly-form.cjs create mode 100644 tests/bpm-dynamicarea.test.cjs create mode 100644 tests/bpm-form-contracts.test.cjs create mode 100644 tests/bpm-hiddenexpress.test.cjs create mode 100644 tests/bpm-notification-source.test.cjs create mode 100644 tests/bpm-readonly-form.test.cjs create mode 100644 tests/bpm-row-scope.test.cjs create mode 100644 tests/order-workflow-task-identity.test.cjs diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 8572e7a..0882387 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,17 +1,28 @@ # 开发交接(2026-10-18) +## 2026-10-22:通知任务去重与本机受控实测(最新) + +业务负责人已确认:**按 `source + taskId` 处理一次 BPM 通知任务;新任务即使订单号相同也单独处理,不要求额外业务版本号。** 本节替代下文及旧计划中“业务版本必填、tid+pid+订单号+业务版本去重”的要求。详情仍须有可靠 tid/pid、订单号和精确版本字段适配器;不伪造 `revision=0`。同任务字段变化或存在多个旧版本记录时阻断,保留原成功结果,人工核对。 + +- 新增真实 todo 来源读取,瞬时 SSO 参数仅留内存且按连接隔离;持久化去令牌详情链接。采集详情前重新读取任务,核对流程、节点、详情标识、原文摘要和收到时间,旧证据变化就阻断。 +- 只读详情显式使用 `GetFormProcessData`,页面脚本禁用;不会标已阅、审批或保存。列表流程版本与表单 V 版本分别保存。不同名称/无 V 表单只按真实采样中已确认的完整路径、列表流程和列表版本关联;历史路径证据不能证明当前到达或规则可发布。 +- 以 `WriteToTable` 的绑定字段和返回表行生成静态 PDF,不能把 `xdatasource Filter` 的原单查询条件误当显示行过滤条件。行关系或条件可见性不明确时阻断,不静默删明细。 +- 本轮已有一条真实海外订单完成只读采集、3 页 PDF、桌面归档字节/摘要复核、SMTP 接受。仅发隔离 QQ,Cc 空、附件空、摘要原文保留;QQ 实际收件待用户核对。15 类历史字段/模板回放不代表 15 类真实闭环通过。 +- 原本机服务仍运行 **modular-refactor** 版本与原数据;本分支测试使用独立状态目录,未把新链路部署到原服务。两个版本的配置/数据库结构不同,禁止直接指向原数据启动本分支。旧版本有 5 类附件策略与当前要求冲突、当前节点配置也需核对,因此自动处理和自动发信保持暂停,不重复发送原队列或本轮已成功测试邮件。 +- 原数据完整备份位于本机 `OrderNotificationAutomationBackups`;业务 PDF、回执、运行数据库和原始采样仅留本地忽略目录。逐类结果与剩余项见 [测试记录](superpowers/plans/2026-10-22-notification-task-test-results.md)。 + ## 2026-10-22:分类模板通知代码增量 当前分支仍为 `codex/smb-storage`。本次按业务负责人明确提供的 BPM 匹配与分类模板计划开发,入口见 [实施与验收记录](superpowers/plans/2026-10-22-bpm-category-template-implementation.md)。本节优先于下文早期“未实施”的说明;不代表已部署或已完成真实业务验收。 - 分类规则按流程 + 当前节点精确匹配,表单版本只用于选择显式字段适配器。产品线、模板和收件组由分类指定,草稿经服务器采集的真实只读样本检查后才可发布。 -- 订单版本必须具备 `tid + pid + 当前订单号 + 业务版本`;不再用流程实例号代替缺失业务版本。同一版本的字段变化会阻断。列表摘要保留原始换行,节点时间缺失时保留 `list.receivedAt` 来源标记。 +- 订单处理身份现按上节最新确认的 BPM 通知任务;保留 tid/pid、订单号与可选的上游业务版本证据。同一任务的字段变化会阻断。列表摘要保留原始换行,节点时间缺失时保留 `list.receivedAt` 来源标记。 - 新增受保护的 `OrderPipeline`,复用现有 PDF 导出器、SMB 归档和邮件通道。归档回执含路径、字节数和 SHA-256;归档失败不创建通知事件,重试不重做成功 PDF。 - 通知事件进入既有通知库,但标识为订单工作流管理,通用通知调度器不会重复处理。批次按分类、规则版本、模板和窗口冻结;PDF 不进附件;SMTP 部分拒收和结果不明均为 `unknown`,重启不自动重发。 - 新页面入口为 `#order-center`、`#mail-batches`、`#order-rules`(兼容 `#rules`),不重复放顶部导航;展示候选阻断、步骤证据、模板版本及核验记录。 - **新订单链路的自动处理和发送默认关闭,本轮未启用、未更新运行服务。** 测试收件人硬限制为指定隔离邮箱。原工作台账号、业务文件和数据库未迁移。 -真实环境尚须核对 V13 页面所需只读接口、流程步骤结构和业务版本字段。详情读取只放行经过限制的表单 GET 和静态资源,不为页面初始化而放开不明 POST/动作接口。历史到达记录没有明确详情链接或 `tid/pid` 时,必须重新取得权威关联,不能把另一张同流程订单的链接拼到该记录。 +V13 已实测固定的只读 GetFormProcessData 接口,其他表单仍需逐类核对 PDF 与真实到达。除该固定读取契约外,不放开不明 POST/动作接口。历史到达记录没有明确详情链接或 `tid/pid` 时,必须重新取得权威关联,不能把另一张同流程订单的链接拼到该记录。 本次另修复全量回归发现的 Windows 中文快捷方式路径问题:使用 `IShellLinkW/IPersistFile`,保留既有登录启动行为,没有实际安装或修改当前服务自启动。 diff --git a/docs/business-configuration.md b/docs/business-configuration.md index 303ad37..a1b13a5 100644 --- a/docs/business-configuration.md +++ b/docs/business-configuration.md @@ -1,6 +1,8 @@ # 后续业务资料整理表 -2026-10-22:BPM 订单来源使用 [分类模板实施规则](superpowers/plans/2026-10-22-bpm-category-template-implementation.md)。流程 + 节点决定分类,表单版本选择字段适配器,产品线和模板由分类明确指定,业务版本不可缺省。下文“版本留空取摘要”等说明仅适用于既有通用来源接口,不适用于 BPM 订单工作流。 +2026-10-22 最新确认:BPM 订单来源使用 [分类模板实施规则](superpowers/plans/2026-10-22-bpm-category-template-implementation.md)。流程 + 节点决定分类,表单版本选择字段适配器,产品线和模板由分类明确指定。按 `source + taskId` 去重,一任务只归档/通知一次;新任务即使同订单号也单独处理。业务版本有则留作证据、缺失不阻断,不伪造 0。下文“版本留空取摘要”等说明仅适用于既有通用来源接口,不适用于 BPM 订单工作流。 + +列表版本(例如 3.2)与表单版本(例如 V13)不同。异名表单须精确命中已核验的完整表单路径、列表流程及列表版本;无 V 表单的适配器键使用 `list:<列表版本>|form:<完整路径>`,`formVersion` 保持空值,不虚构版本号。路径关联不等于真实通知节点验收,字段适配器仍须检查并发布。 本轮交付通用配置能力。下面的信息整理完成后,可在工作台录入并联调,不需要把服务器地址或产业接口人写进源码。 diff --git a/docs/design-requirements.md b/docs/design-requirements.md index 8674541..b62ff6b 100644 --- a/docs/design-requirements.md +++ b/docs/design-requirements.md @@ -4,6 +4,8 @@ 2026-10-22 增补:业务负责人已明确提供并授权实施 [BPM 分类模板计划](superpowers/plans/2026-10-22-bpm-category-template-implementation.md)。该链路以分类规则指定产品线、邮件模板及收件组,版本适配器精确对应表单版本;PDF/SMB 归档成功是创建通知事件的前置条件,归档与通知仍分别保存状态。此约束替代下文早期“PDF 归档不影响通知”和按产业独立猜模板的描述;归档完成不代表邮件完成,也不直接绕过分类、版本、收件组及发送窗口检查。自动处理、PDF 自动执行和自动发送在真实业务验收前保持关闭。 +同日后续确认:处理单位为 **BPM 通知任务**,去重键为 `source + taskId`;新任务即使同一订单号也独立归档和通知。业务版本不必额外提供,不以默认 0、内容摘要或流程实例号补出业务版本。tid/pid、订单号及精确字段适配器仍是必要证据;同任务数据变化或多个历史版本冲突必须人工核对。该确认替代早期“业务版本必填”的要求。用户已授权本机隔离测试实际发送,收件人仍强制隔离邮箱;受控测试成功不代表已经部署或允许旧运行配置自动发送。 + ## 1. 产品目标与运行方式 团队成员在各自电脑访问同一台常驻服务器,通过 Web 管理 BPM 连接、流程到达记录、业务日历、异常、邮件模板和收件群组。正式工作台使用真实持久数据,不预置演示账号或虚构订单,不提供默认管理员密码。 diff --git a/docs/superpowers/plans/2026-10-22-bpm-category-template-implementation.md b/docs/superpowers/plans/2026-10-22-bpm-category-template-implementation.md index d6c2117..704971f 100644 --- a/docs/superpowers/plans/2026-10-22-bpm-category-template-implementation.md +++ b/docs/superpowers/plans/2026-10-22-bpm-category-template-implementation.md @@ -2,11 +2,13 @@ 用户于 2026-10-22 明确批准会话中的“BPM 订单匹配与分类模板通知实施计划”。该计划替代此前设计草稿的停止实施状态,不代表业务自动运行或真实发送已获本轮启用授权。 +后续确认优先:用户采用“按 BPM 通知任务去重”,不要求额外业务版本。用户也已授权本机隔离真实发信测试。本轮只发送一条已授权真实海外订单的受控测试,自动处理/发送仍关闭;不操作服务机,不重发已成功邮件。详细边界和逐类结果见 [测试记录](2026-10-22-notification-task-test-results.md)。 + ## 顺序与验收 1. 只读详情适配器:复用托管会话,限制 BPM 域名/读取请求;明确 tid/pid、表单版本和字段证据;不办理流程。 2. 分类配置:精确流程+当前节点;版本只选适配器;产品线、PDF 模板、邮件模板、收件组、通知类型、批次方式、启停;真实样本检查后发布。 -3. 统一任务:复用 OrderWorkflow/Store,版本键 tid+pid+当前订单号+业务版本;缺失阻断;步骤证据独立持久化和恢复。 +3. 统一任务:复用 OrderWorkflow/Store,处理键 source+taskId;保留 tid/pid/当前订单号,可选上游业务版本;缺必要详情标识阻断;步骤证据独立持久化和恢复。 4. PDF/SMB:复用现有生成及存储服务;成功步骤不重做;归档失败阻断通知。 5. 模板通知:按分类+模板+窗口分批;四个变量;冻结版本/正文/收件人;附件固定为空;仅隔离测试邮箱。 6. 页面记录与恢复:订单和批次可追溯;viewer 只读;发送结果 unknown 禁止自动重发,管理员核验。 @@ -23,9 +25,9 @@ | `order-template-bridge.cjs` | 渲染产品线、订单号、日期、订单列表四变量,保留原始换行;冻结模板和渲染结果,附件为空 | | 工作台 | 分类配置、真实记录样本检查、订单步骤/字段证据、候选采集恢复、邮件批次和管理员核验 | -原有 BPM 列表存储继续按连接、来源、任务标识去重;同一任务重新扫描或规则版本变化会重新检查详情,业务版本键决定是否产生新任务。同一版本即使非邮件映射字段发生变化,也必须人工核实版本,不能重做新内容 PDF。 +原有 BPM 列表存储继续按连接、来源、任务标识去重;业务处理按来源+通知任务去重,同任务跨连接仍只处理一次。新任务即使订单号相同也独立。同一任务即使非邮件映射字段发生变化,也必须人工核实,不能重做新内容 PDF。单条旧键记录恢复时保留原键,核对任务和全部字段;同任务存在多个旧版本时禁止执行/发批次,人工核对后再决定恢复方式,不静默合并或选择某一条。 -当前节点没有独立进入时间时,使用列表收到时间,保存 `list.receivedAt`。业务版本只接受明确采集值或经确认的字段适配路径,不以 tid、pid、标题、型号或内容摘要填补。 +当前节点没有独立进入时间时,使用列表收到时间,保存 `list.receivedAt`。业务版本只接受明确采集值或经确认的字段适配路径,不以 tid、pid、标题、型号或内容摘要填补;缺失为 null,技术版本使用任务标记,并明确保存来源。 ## 发送与恢复约定 @@ -42,6 +44,6 @@ 新增 HTTP/浏览器集成测试使用临时状态目录、随机端口、虚构 BPM 详情、实际 PDF 渲染和本地 `FileArea` 归档,验证 SHA-256、通知队列、幂等与页面字段证据。它不调用真实 BPM/SMTP/SMB,自动处理和发送均关闭。测试结束关闭临时服务并删除测试目录。 -真实 V13 表单仍需现场只读验收。尤其须确认页面需要的字段读取接口及流程步骤表结构、业务版本权威字段、列表与详情的 tid/pid 关联。未确认时检查返回阻断,不能绕过检查发布或启用自动处理;不能把本次隔离测试称作真实业务闭环验收。 +真实 V13 已完成一条现场只读采集与实际 PDF/桌面归档/SMTP 接受测试;列表收到时间与原文摘要、tid/pid、表单 V13 与列表 3.2 分别核对。另 14 类没有本轮合格新到达,不得将历史字段回放当作真实闭环;QQ 收件、正式 SMB、逐类 PDF/节点验收及旧运行服务兼容接入仍未完成。未核验类别仍保持阻断,不能绕过检查发布或启用自动处理。 运行数据库、日志、截图、临时导出文件和测试报告不进入 Git;本地旧设计草稿保持在工作区,单独排除提交。 diff --git a/docs/superpowers/plans/2026-10-22-notification-task-test-results.md b/docs/superpowers/plans/2026-10-22-notification-task-test-results.md new file mode 100644 index 0000000..746cf6c --- /dev/null +++ b/docs/superpowers/plans/2026-10-22-notification-task-test-results.md @@ -0,0 +1,71 @@ +# BPM 通知任务实测与逐类验收记录 + +日期:2026-10-22。本记录只描述本轮已观测结果,不表示完整业务闭环验收或正式投产。 + +## 最新业务规则 + +业务负责人已确认采用 **BPM 来源 + 通知任务号** 去重。同一任务一次归档、一次业务通知;新的通知任务即使订单号相同也独立处理。业务版本不是必填项,有权威值则保留,没有则为 null,不伪造 revision=0。同任务字段发生变化、多个旧业务版本对应同一任务时进入待核对状态。 + +分类仍按列表流程 + 当前节点精确匹配;产品线、收件组和模板由分类指定。表单版本只决定字段适配器,列表流程版本与表单版本分别保存。异名/无 V 表单依据已授权只读采样中的完整路径、列表流程和列表版本关联;该路径证据不等于真实到达或自动发布资格。 + +归档成功是通知事件的前提;归档失败不发信,通知失败不重复成功 PDF。PDF 不作为邮件附件。BPM 不标已阅、不审批、不修改流程。SMTP 结果不明时禁止自动重发。 + +## 一条真实海外订单 + +本轮直接读取授权 BPM 待办,得到 14 条海外运营订单评审任务,当前节点为订单专员(生效)。列表流程版本为 3.2,最终表单为 V13;接口没有提供业务版本,未补默认值。 + +其中一条任务在独立测试状态目录完成: + +| 步骤 | 已观测结果 | +|---|---| +| 详情 | 只读 GetFormProcessData,636 个显式字段,保留来源和列表原文 | +| PDF | 实际生成 3 页,逐页检查;9 行备注及 3 行物料保留 | +| 桌面归档 | 实际写入独立测试目录,384011 字节;原 PDF 与归档 SHA-256 相同 | +| 通知 | 使用分类绑定模板,正文包含列表摘要原文,附件数 0 | +| SMTP | 北京时间 18:11:48 接受 1 封,To 仅隔离 QQ,Cc 空 | +| 实际收件 | 待用户在 QQ 邮箱核对;SMTP 接受不等于最终收件 | +| 幂等边界 | 已成功测试邮件不重发;本轮没有发送其他类别邮件 | + +业务 PDF、具体任务/订单标识、完整字段、消息回执和数据库仅保存在本机忽略目录,不随代码提交。归档根位于桌面的 `订单通知全类测试-20261022`;本地证据入口为 `output/business-flow-test/live-overseas-result.json`。 + +已知排版待验收项:本次静态表单的备注序号重复显示为 1,9 行备注正文均保留。尚未实现厂商动态行号规则,不应把当前 PDF 排版称为最终验收完成。 + +## 15 类验收矩阵 + +“字段/模板通过”指读取已有采样做字段映射校验和原文模板预览;历史采样保留原来源、节点和时间,没有改成新到达,没有导入原运行订单库。这些结果不能证明所有流程、表单 PDF 或真实收件已通过。 + +| 分类 | 字段/原文模板预览 | 本轮真实 PDF → 桌面归档 → SMTP | +|---|---|---| +| 海外订单通知书 | 通过 | 1 条实际完成,QQ 收件待核对 | +| 海外订单更改通知书 | 通过 | 当前没有合格新到达,未执行 | +| 新零售订单通知书 | 通过 | 当前没有合格新到达,未执行 | +| 新零售订单更改通知书 | 通过 | 当前没有合格新到达,未执行 | +| 国内订单通知书 | 通过 | 当前没有合格新到达,未执行 | +| 运营商事业部订单通知书 | 通过 | 当前没有合格新到达,未执行 | +| 智能硬件订单通知书 | 通过 | 当前没有合格新到达,未执行 | +| 小湃订单通知书 | 通过 | 当前没有合格新到达,未执行 | +| 国内/运营商/零售/智能硬件订单更改 | 已有样本通过;零售国内返工订单更改评审缺样本 | 当前没有合格新到达,未执行 | +| 国内/运营商/零售/智能硬件返工订单 | 通过 | 当前没有合格新到达,未执行 | +| 加工订单通知书 | 通过 | 当前没有合格新到达,未执行 | +| 备损订单通知书 | 通过 | 当前没有合格新到达,未执行 | +| 备损订单更改通知书 | 通过 | 当前没有合格新到达,未执行 | +| 试产订单通知书 | 通过 | 当前没有合格新到达,未执行 | +| 试产订单更改通知书 | 通过 | 当前没有合格新到达,未执行 | + +当前证据覆盖 32 份只读采样的表单路径关系;每类至少一个字段样本通过,不代表每类的全部流程都有样本。缺少样本的流程不能用标题、其他流程或相似表单猜测补齐。惠州额外通知已有旧版本隔离专项,未在本轮用真实惠州新任务验收发送。 + +## 运行状态与后续缺口 + +原本机测试工作台运行在 18766,保留原账号、15 类配置和原记录,源代码仍来自 modular-refactor。原状态已完整备份并验证。此次新分支链路使用独立状态目录受控测试,不直接覆盖原运行数据;两个分支配置与数据库结构不同,尚未完成兼容接入,不能称新代码已部署到原工作台。 + +原配置有 5 个更改单类别仍带 PDF 附件策略,与当前空附件约束冲突;旧节点配置也与本轮实际海外节点不同。为避免误发,自动处理和自动发信保持关闭,保留原队列,不补发旧订单。 + +尚待完成:其他类别真实当前通知节点与逐类 PDF 检查、缺失流程采样、QQ 实际收件核对、正式 SMB 端到端、旧配置/运行数据兼容接入、惠州真实双路通知,以及持续调度与恢复实机验收。不操作服务机,不以历史回放或单条 SMTP 成功宣称全业务闭环。 + +## 代码验证 + +本轮执行 npm ci;通知任务与来源/恢复专项 27/27 通过,表单绑定/动态行/条件隐藏/主子表作用域专项 35/35 通过。新鲜全量 `npm test -- --test-concurrency=1`:290 项,289 通过、0 失败、1 项可选官方 ZCode 本地模型集成跳过,用时约 437 秒。全量包括异名/无 V 表单、单行外部 TaskID 阻断、旧键恢复、多旧版本任务重试阻断和真实来源页面读取等新增回归。 + +最终独立代码复审未发现剩余具体 P1/P2;语法与暂存差异检查通过。暂存内容扫描未发现凭据模式或业务 PDF、图片、数据库、日志和 output 文件。复审和测试证据保存在本地忽略目录,不代替真实逐类业务验收。 + +新增保护包括:每连接瞬时 SSO 缓存隔离、详情前重读任务元数据、业务版本可缺失、旧键恢复、旧重复任务阻断、静态表单脚本禁用、未知动作/跳转阻断、归档失败不入队、发送中重启转 unknown、部分拒收不自动重发。厂商查询/导入 Filter 不用于过滤当前持久行;不能证明主子行关系或可见性时整份 PDF 阻断,不删行冒充成功。 diff --git a/docs/unattended-system-design.md b/docs/unattended-system-design.md index 2d36abf..90f36ca 100644 --- a/docs/unattended-system-design.md +++ b/docs/unattended-system-design.md @@ -24,7 +24,7 @@ - **常驻本地程序**:负责周期扫描、任务状态、模板、归档、上传、发送调度及日志。调度属于本工具,不能以对话中的提醒代替实际业务运行。 - **浏览器执行端**:保持可访问 BPM 的浏览器会话,按任务自动打开/检查订单标签页。现有扩展需要增加后台任务入口与就绪判断,不能把手动导出扩展宣称为无人值守版本。 -- **持久状态库**:以任务标识与业务版本识别订单,分别记录发现、导出、上传、待发、发送成功、失败、结果待核实。现有内存中最近 20 个导出任务仅适用于手动版,不能充当无人值守状态库。 +- **持久状态库**:按 2026-10-22 最新确认,以 BPM 来源 + 通知任务号识别处理单位,业务版本有则保存、缺失不补造;新任务独立处理,同任务字段变化或旧版本重复记录进入人工核对。分别记录发现、导出、上传、待发、发送成功、失败、结果待核实。现有内存中最近 20 个导出任务仅适用于手动版,不能充当无人值守状态库。 - **配置与运行面板**:编辑筛选条件、两个发送时间、模板、产品线群组、服务器和邮件渠道;查看当前登录状态、上次扫描、待发量、发送记录及异常。运行账户与敏感配置不写入源码或普通日志。 - **常驻条件**:需要一台在发送时段运行且可访问 BPM、210 服务器和邮件服务的机器。若使用浏览器会话,还需明确公司登录过期策略;没有合法自动续期方式时,不能保证永久不需人工登录。 diff --git a/src/bpm-form-contracts.cjs b/src/bpm-form-contracts.cjs new file mode 100644 index 0000000..8830dc1 --- /dev/null +++ b/src/bpm-form-contracts.cjs @@ -0,0 +1,22 @@ +'use strict'; +const {contracts}=require('./bpm-form-contracts.json'); +const fail=message=>{throw Object.assign(new Error(message),{status:409});}; + +// These contracts associate a sampled full form path with list metadata. They +// never classify an order or establish a history sample as a current arrival. +function resolveFormIdentity(identity,{processName,listProcessVersion}){ + const path=decodeURIComponent(identity.url.pathname); + const candidates=contracts.filter(contract=>contract.path===path); + const formName=identity.processName,formVersion=identity.processVersion||null; + if(candidates.length){ + const process=candidates.filter(contract=>contract.processName===processName); + if(!process.length)fail('列表流程与已核验的完整表单路径不一致。'); + if(!listProcessVersion||!process.some(contract=>contract.listVersion===String(listProcessVersion)))fail('列表流程版本与已核验的表单契约不一致。'); + return {processName,processVersion:formVersion||'list:'+listProcessVersion+'|form:'+path,formName,formVersion,formPath:path,formMatchSource:'verified-form-contract'}; + } + // Preserve the original strict same-name, explicitly versioned contract. + // Aliases and forms without a V-number always require a verified full path. + if(!formVersion||!processName||processName!==formName)fail('列表流程与详情表单不一致,或完整表单路径尚未核验。'); + return {processName,processVersion:formVersion,formName,formVersion,formPath:path,formMatchSource:'exact-versioned-form-name'}; +} +module.exports={resolveFormIdentity}; diff --git a/src/bpm-form-contracts.json b/src/bpm-form-contracts.json new file mode 100644 index 0000000..2fe27eb --- /dev/null +++ b/src/bpm-form-contracts.json @@ -0,0 +1,160 @@ +{ + "evidence": "authorized-readonly-form-samples-2026-10-22", + "contracts": [ + { + "processName": "海外宽带接入产品订单更改评审", + "listVersion": "2.1", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/海外宽带接入产品/海外宽带接入产品订单更改评审V9.aspx" + }, + { + "processName": "海外IPC订单更改评审", + "listVersion": "1.4", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/海外运营订单评审/海外IPC订单更改评审V4.aspx" + }, + { + "processName": "中试样机制作申请", + "listVersion": "1.3", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/试产订单评审/中试样机制作申请V2.aspx" + }, + { + "processName": "海外返工订单更改评审", + "listVersion": "1.1", + "path": "/YZSoft/Forms/XForm/海外返工订单/海外返工订单更改.aspx" + }, + { + "processName": "海外运营订单更改评审", + "listVersion": "1.9", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/海外运营订单评审/海外运营订单更改评审V7.aspx" + }, + { + "processName": "海外IPC订单评审", + "listVersion": "1.8", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/海外运营订单评审/海外IPC订单评审V5.aspx" + }, + { + "processName": "海外宽带接入产品订单", + "listVersion": "3.6", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/海外宽带接入产品/海外宽带接入产品订单评审V15.aspx" + }, + { + "processName": "新零售订单评审", + "listVersion": "1.0", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/新零售订单评审/新零售订单评审.aspx" + }, + { + "processName": "零售国内订单评审", + "listVersion": "3.2", + "path": "/YZSoft/Forms/XForm/零售产品部订单评审/零售产品部订单评审V11.aspx" + }, + { + "processName": "零售订单评审", + "listVersion": "1.0", + "path": "/YZSoft/Forms/XForm/零售产品部订单评审/零售产品部订单评审V12.aspx" + }, + { + "processName": "加工订单评审", + "listVersion": "1.0", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/加工订单评审/加工订单通知书.aspx" + }, + { + "processName": "海外返工订单评审", + "listVersion": "1.6", + "path": "/YZSoft/Forms/XForm/海外返工订单/海外返工订单.aspx" + }, + { + "processName": "宽带事业订单更改评审", + "listVersion": "2.3", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/宽带事业订单评审/宽带事业订单更改评审V12.aspx" + }, + { + "processName": "备损订单更改评审", + "listVersion": "1.4", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/备损订单评审/备损更改订单评审V2.aspx" + }, + { + "processName": "智能硬件解决方案订单更改评审", + "listVersion": "1.6", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/智能硬件解决方案订单/智能硬件解决方案订单更改通知书V7.aspx" + }, + { + "processName": "国内、宽带返工订单评审", + "listVersion": "2.7", + "path": "/YZSoft/Forms/XForm/国内宽带返工订单评审/国内和宽带返工订单评审V8.aspx" + }, + { + "processName": "新零售订单更改评审", + "listVersion": "1.2", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/新零售订单评审/新零售订单更改评审.aspx" + }, + { + "processName": "零售返工订单评审", + "listVersion": "1.0", + "path": "/YZSoft/Forms/XForm/国内零售返工订单/零售国内返工订单评审V1.aspx" + }, + { + "processName": "零售国内订单更改评审", + "listVersion": "2.1", + "path": "/YZSoft/Forms/XForm/零售产品部订单评审/零售产品部订单更改评审V9.aspx" + }, + { + "processName": "研发样机制作申请", + "listVersion": "1.2", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/试产订单评审/研发样机制作申请V1.aspx" + }, + { + "processName": "零售订单更改评审", + "listVersion": "1.0", + "path": "/YZSoft/Forms/XForm/零售产品部订单评审/零售产品部订单更改评审V10.aspx" + }, + { + "processName": "国内运营订单更改评审", + "listVersion": "2.1", + "path": "/YZSoft/Forms/XForm/国内订单评审/国内运营订单更改评审V10.aspx" + }, + { + "processName": "宽带事业订单评审", + "listVersion": "3.9", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/宽带事业订单评审/宽带事业订单评审V16.aspx" + }, + { + "processName": "零售国内返工订单评审", + "listVersion": "1.4", + "path": "/YZSoft/Forms/XForm/国内零售返工订单/零售国内返工订单评审.aspx" + }, + { + "processName": "智能硬件解决方案订单评审", + "listVersion": "2.1", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/智能硬件解决方案订单/智能硬件解决方案订单通知书V8.aspx" + }, + { + "processName": "试产订单更改评审", + "listVersion": "1.2", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/试产订单评审/试产订单更改评审V1.aspx" + }, + { + "processName": "备损订单评审", + "listVersion": "2.0", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/备损订单评审/备损订单评审V5.aspx" + }, + { + "processName": "海外运营订单评审", + "listVersion": "3.2", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/海外运营订单评审/海外运营订单评审V13.aspx" + }, + { + "processName": "试产订单评审", + "listVersion": "2.1", + "path": "/YZSoft/Forms/XForm/2012订单评审系列/试产订单评审/试产订单评审V8.aspx" + }, + { + "processName": "国内运营订单评审", + "listVersion": "3.9", + "path": "/YZSoft/Forms/XForm/国内订单评审/国内订单评审V18.aspx" + }, + { + "processName": "国内、宽带返工订单更改评审", + "listVersion": "1.7", + "path": "/YZSoft/Forms/XForm/国内宽带返工订单评审/国内和宽带返工订单更改评审V6.aspx" + } + ] +} diff --git a/src/bpm-list-client.cjs b/src/bpm-list-client.cjs index a4a6110..b6a21f4 100644 --- a/src/bpm-list-client.cjs +++ b/src/bpm-list-client.cjs @@ -24,9 +24,9 @@ function normalizeArrival(row,source){ return {source,taskId:String(row.taskId),serialNum:plain(row.serialNum,250),processName:plain(row.processName,250),activityName:plain(row.activityName,250),subject:plain(row.processInstanceSubject,20000,true),initiator:plain(row.processInstanceInitiatorShortName||row.processInstanceInitiator,250),arrivedAt,arrivalDay,...identity,...(detailUrl?{detailUrl}:{})}; } class BpmListClient{ - constructor({baseURL='https://bpmn.skyworthdigital.com/',pageSize=100,allowLocal=false}={}){ + constructor({baseURL='https://bpmn.skyworthdigital.com/',pageSize=100,allowLocal=false,sources=SOURCES,normalize=normalizeArrival}={}){ const u=new URL(baseURL);if(u.href!=='https://bpmn.skyworthdigital.com/'&&!(allowLocal&&['127.0.0.1','localhost','[::1]'].includes(u.hostname)&&['http:','https:'].includes(u.protocol)&&u.pathname==='/'&&!u.username&&!u.password&&!u.search&&!u.hash))throw fail('BPM 地址不受支持。',400); - this.baseURL=u.href;this.pageSize=pageSize; + this.baseURL=u.href;this.pageSize=pageSize;this.sources=sources;this.normalize=normalize; } async scan(storageState){ if(!storageState)throw fail('BPM 会话需要续登。',401); @@ -42,13 +42,13 @@ class BpmListClient{ const html=await get('/'),token=/Yiez\.clientId\s*=\s*['"]([^'"\s<>]{1,16000})['"]/.exec(html)?.[1]; if(!token)throw fail('BPM 会话需要续登。',401); const rows=[]; - for(const [source,route]of SOURCES){ + for(const [source,route]of this.sources){ let total=null;const seen=new Set(); for(let page=1;page<=100;page++){ let data;try{data=JSON.parse(await get(route,{params:{page,start:(page-1)*this.pageSize,limit:this.pageSize},headers:{Authorization:'Bearer '+token}}));}catch(cause){if(cause.status)throw cause;throw fail('BPM 列表数据格式不正确。');} if(!Array.isArray(data.children)||!Number.isSafeInteger(data.total)||data.total<0||data.total>10000||data.success===false)throw fail('BPM 列表分页数据不完整。'); if(total!==null&&total!==data.total)throw fail('BPM 列表正在变化,请重新扫描。');total=data.total; - for(const raw of data.children){const row=normalizeArrival(raw,source);if(seen.has(row.taskId))throw fail('BPM 列表分页重复,请重新扫描。');seen.add(row.taskId);rows.push(row);} + for(const raw of data.children){const row=this.normalize(raw,source);if(seen.has(row.taskId))throw fail('BPM 列表分页重复,请重新扫描。');seen.add(row.taskId);rows.push(row);} if(seen.size===total)break; if(!data.children.length||data.children.length>this.pageSize||seen.size>total||page===100)throw fail('BPM 列表分页不完整,请重新扫描。'); } diff --git a/src/bpm-notification-source.cjs b/src/bpm-notification-source.cjs new file mode 100644 index 0000000..e5dfaaa --- /dev/null +++ b/src/bpm-notification-source.cjs @@ -0,0 +1,23 @@ +'use strict'; +const {BpmListClient,normalizeArrival}=require('./bpm-list-client.cjs'); +const {parseEntryURL}=require('./bpm-readonly-form.cjs'); +const SOURCES=[['todo-v8','bpm/worklist'],['todo-v4','skyworth/todo/v2/workflow/get_process_of_work_v4']]; +const fail=message=>Object.assign(new Error(message),{status:409}); +const signature=row=>JSON.stringify([row.source,row.taskId,row.processInstanceId,row.processName,row.activityName,row.processVersion,row.tid,row.pid,row.subject,row.arrivedAt,row.serialNum]); +function normalizeNotificationTask(raw,source){ + const row=normalizeArrival(raw,source); + if(!['string','number'].includes(typeof raw.processInstanceId)||!String(raw.processInstanceId))throw fail('BPM 通知任务缺少流程实例标识。'); + const result={...row,recordKind:'notification-task',processInstanceId:String(raw.processInstanceId),processVersion:String(raw.processVersion??'')}; + if(typeof raw.executionPointerId==='string'&&raw.executionPointerId){const entry=parseEntryURL(raw.executionPointerId);for(const key of ['tid','pid'])if(raw[key]!==undefined&&String(raw[key])!==entry[key])throw fail('BPM 通知任务与详情标识不一致。');result.tid=entry.tid;result.pid=entry.pid;result.detailUrl=(entry.target||entry.url).href;} + // Absence of a business revision remains absence. Task identity is the + // processing unit; no fabricated revision=0 enters the captured evidence. + if(Object.hasOwn(raw,'revision')&&raw.revision!==null&&['string','number'].includes(typeof raw.revision))result.reportedRevision=raw.revision; + return result; +} +class BpmNotificationClient extends BpmListClient{ + constructor(options={}){ + const entries=new Map();super({...options,sources:SOURCES,normalize:(raw,source)=>{const row=normalizeNotificationTask(raw,source);if(raw.executionPointerId&&row.detailUrl)entries.set(JSON.stringify([row.source,row.taskId]),{entry:raw.executionPointerId,signature:signature(row),expiresAt:Date.now()+300000});return row;}});this.entries=entries; + } + entryFor(row){const found=this.entries.get(JSON.stringify([row.source,row.taskId]));if(!found||found.expiresAtloadPlaywright().chromium.launch(browserOptions()),timeout=20000}){ +async function captureDetail({storageState,sessionStorage={},detailUrl,processName,nodeName,browserFactory=()=>loadPlaywright().chromium.launch(browserOptions()),timeout=20000,readonlyData=false,fieldsOnly=false,listProcessVersion=null,requestFactory}){ + if(readonlyData===true)return require('./bpm-readonly-form.cjs').captureReadonlyForm({storageState,detailUrl,processName,nodeName,browserFactory,timeout,fieldsOnly,listProcessVersion,...(requestFactory?{requestFactory}:{})}); const identity=parseDetailUrl(detailUrl);if(!storageState)fail('BPM 会话需要续登。',401);if(processName&&identity.processName!==processName)fail('列表流程名称与详情表单不一致。'); const browser=await browserFactory();let context; try{ diff --git a/src/bpm-readonly-form.cjs b/src/bpm-readonly-form.cjs new file mode 100644 index 0000000..f1c0a22 --- /dev/null +++ b/src/bpm-readonly-form.cjs @@ -0,0 +1,183 @@ +'use strict'; +const crypto=require('node:crypto'); +const {loadPlaywright,browserOptions}=require('./runtime.cjs'); +const ORIGIN='https://bpm.skyworthdigital.com'; +const MAX_BYTES=12_000_000; +const fail=(message,status=409)=>{throw Object.assign(new Error(message),{status});}; +function baseURL(value){let url;try{url=new URL(value,ORIGIN);}catch{fail('BPM 只读表单地址无效。',403);}if(url.origin!==ORIGIN||url.username||url.password||url.hash)fail('BPM 只读表单地址不受支持。',403);return url;} +function uniqueParams(url,keys){if([...url.searchParams.keys()].length!==keys.length||keys.some(key=>url.searchParams.getAll(key).length!==1)||[...url.searchParams.keys()].some(key=>!keys.includes(key)))fail('BPM 只读表单参数无效,不能包含办理动作。',403);} +function processURL(value){const url=baseURL(value);if(url.pathname!=='/YZSoft/Forms/Process.aspx')fail('BPM 只读入口必须指向已核验的流程表单。',403);uniqueParams(url,['tid','pid']);const tid=url.searchParams.get('tid'),pid=url.searchParams.get('pid');if(!/^\d{1,30}$/.test(tid||'')||!/^\d{1,30}$/.test(pid||''))fail('BPM 只读表单 tid/pid 无效。',403);return {url,tid,pid,kind:'process'};} +function finalURL(value){const url=baseURL(value);if(!url.pathname.startsWith('/YZSoft/Forms/XForm/'))fail('BPM 最终只读表单地址无效。',403);uniqueParams(url,['tid','pid']);const tid=url.searchParams.get('tid'),pid=url.searchParams.get('pid');if(!/^\d{1,30}$/.test(tid||'')||!/^\d{1,30}$/.test(pid||''))fail('BPM 只读表单 tid/pid 无效。',403);let pathname;try{pathname=decodeURIComponent(url.pathname);}catch{fail('BPM 表单路径编码无效。',403);}const match=pathname.match(/\/([^/]+?)(V\d+)?\.aspx$/i);if(!match||pathname.includes('\\')||pathname.split('/').some(part=>['.','..'].includes(part)))fail('BPM 最终表单路径无效。',403);if(!match[2]&&!require('./bpm-form-contracts.json').contracts.some(contract=>contract.path===pathname))fail('无版本表单的完整路径尚未核验。',403);return {url,tid,pid,kind:'form',processName:match[1],processVersion:match[2]?.toUpperCase()||null};} +function parseEntryURL(value){ + const url=baseURL(value); + if(url.pathname==='/sso/ssologin.aspx'){ + uniqueParams(url,['ReturnUrl','todo_token','todo_account']);if(!url.searchParams.get('todo_token')||!url.searchParams.get('todo_account')||url.href.length>24000)fail('BPM 临时登录参数不完整。',403); + const target=processURL(url.searchParams.get('ReturnUrl'));return {url,kind:'sso',target:target.url,tid:target.tid,pid:target.pid}; + } + if(url.pathname==='/YZSoft/Forms/Process.aspx')return processURL(url.href); + return finalURL(url.href); +} +async function loadForm(request,entry,{timeout=20000}={}){ + const start=parseEntryURL(entry);let current=start; + for(let hop=0;hop<3;hop++){ + let response;try{response=await request.get(current.url.href,{maxRedirects:0,timeout});}catch{fail('BPM 只读表单连接失败。',502);} + const status=response.status(); + if([301,302,303,307,308].includes(status)){ + const location=response.headers().location;if(!location)fail('BPM 表单跳转缺少目标。',403);let next;try{next=new URL(location,current.url);}catch{fail('BPM 表单跳转目标无效。',403);} + if(current.kind==='sso')current=processURL(next.href);else if(current.kind==='process')current=finalURL(next.href);else fail('BPM 最终表单不允许再次跳转。',403); + if(current.tid!==start.tid||current.pid!==start.pid)fail('BPM 表单跳转的 tid/pid 与原始任务冲突。',403);continue; + } + if(status!==200)fail([401,403].includes(status)?'BPM 表单会话已失效。':'BPM 只读表单查询失败。',[401,403].includes(status)?401:502); + if(current.kind!=='form')fail('BPM 未到达已核验的最终表单。',403); + const bytes=await response.body();if(bytes.length>MAX_BYTES)fail('BPM 表单响应超过采集上限。'); + return {url:current.url,bytes,identity:{tid:current.tid,pid:current.pid,processName:current.processName,processVersion:current.processVersion}}; + } + fail('BPM 表单跳转次数超过只读链路上限。',403); +} +async function loadData(request,value,{timeout=20000}={}){ + const identity=finalURL(value instanceof URL?value.href:value); + const xml='GetFormProcessData'+identity.pid+''; + let response;try{response=await request.post(ORIGIN+'/YZSoft/BPM/XMLService/DataProvider.ashx',{data:xml,headers:{'Content-Type':'text/xml'},maxRedirects:0,timeout});}catch{fail('BPM 表单字段只读请求失败。',502);} + const status=response.status();if([301,302,303,307,308,401,403].includes(status))fail('BPM 表单数据会话失效,需要重新核验连接。',401);if(status!==200)fail('BPM 表单字段读取失败。',502); + const bytes=await response.body();if(bytes.length>MAX_BYTES)fail('BPM 表单字段响应超过采集上限。');let data;try{data=JSON.parse(bytes.toString('utf8'));}catch{fail('BPM 表单字段响应不是有效数据。',502);} + if(data?.success!==true||!Array.isArray(data.Tables)||data.Tables.length>200||data.Tables.some(table=>!table||typeof table.TableName!=='string'||!table.TableName||table.TableName.length>200||!Array.isArray(table.Rows)||table.Rows.length>4000||table.Rows.some(row=>!row||typeof row!=='object'||Array.isArray(row))))fail('BPM 表单字段数据不完整或未通过权限检查。',502); + return data.Tables.filter(table=>table.FormTable===true); +} +function flattenTables(tables){ + const fields={},sources={},seen=new Map();let count=0; + const assign=(key,value,source)=>{const normalized=key.toLowerCase();if(seen.has(normalized)&&JSON.stringify(seen.get(normalized))!==JSON.stringify(value))fail('BPM 后端字段存在多个冲突值。');if(!Object.hasOwn(fields,key)&&++count>10000)fail('BPM 表单字段数量超过采集上限。');seen.set(normalized,value);fields[key]=structuredClone(value);sources[key]=source;}; + for(const table of tables){ + if(table.FormTable!==true)continue;const prefix=(table.DataSource?table.DataSource+':':'')+table.TableName,columns=[...new Set(table.Rows.flatMap(row=>Object.keys(row)))]; + for(const column of columns){const key=prefix+'.'+column;if(key.length>500||/[\x00-\x1f]/.test(key))fail('BPM 字段路径无效。');const values=table.Rows.map(row=>Object.hasOwn(row,column)?row[column]:null),source={source:'DataProvider.GetFormProcessData',table:table.TableName,dataSource:table.DataSource||'',column}; + if(values.length===1)assign(key,values[0],{...source,rowIndex:0}); + else if(values.length>1){assign(key,values,{...source,multiple:true});values.forEach((value,rowIndex)=>assign(prefix+'['+rowIndex+'].'+column,value,{...source,rowIndex}));} + } + } + if(!Object.keys(fields).length)fail('BPM 表单没有已授权的业务字段。');return {fields,sources}; +} + +// This function runs in a script-disabled document. Backend rows are assigned to +// repeated DOM rows only when a complete, one-to-one row schema proves the order. +function hydrateReadonlyDocument({tables,fieldsOnly=false}){ + const form=document.querySelector('form');if(!form)return {blocker:'BPM 静态表单不存在。'}; + const hiddenPredicates=new Map(); + const visible=element=>{for(let node=element;node;node=node.parentElement){const predicate=hiddenPredicates.get(node.getAttribute('hiddenexpress')||''),style=getComputedStyle(node);if(predicate?.known&&predicate.value||node.hidden||['hidden','password','file'].includes(node.type)||style.display==='none'||['hidden','collapse'].includes(style.visibility))return false;}return true;}; + const binding=element=>element.getAttribute('xdatabind')||element.getAttribute('data-xdatabind')||element.getAttribute('data-bind'); + let bindings=[...form.querySelectorAll('[xdatabind],[data-xdatabind],[data-bind]')];const values=new Map(),resolved=new Map(),detailTables=new Set(); + const processSteps=[];for(const table of document.querySelectorAll('table')){const rows=[...table.rows],header=rows.find(row=>[...row.cells].some(cell=>/^(节点|环节|步骤|活动名称|节点名称)$/.test(cell.textContent.trim()))&&[...row.cells].some(cell=>/^(状态|处理状态)$/.test(cell.textContent.trim())));if(!header)continue;const labels=[...header.cells].map(cell=>cell.textContent.trim()),ni=labels.findIndex(label=>/^(节点|环节|步骤|活动名称|节点名称)$/.test(label)),si=labels.findIndex(label=>/^(状态|处理状态)$/.test(label));for(const row of rows.slice(rows.indexOf(header)+1)){const name=row.cells[ni]?.textContent.trim(),status=row.cells[si]?.textContent.trim();if(name&&status)processSteps.push({name,status});}} + if(fieldsOnly)return {processSteps,snapshot:null}; + // Interpret only a small declarative grammar. Unknown fields and unsupported + // expressions stay visible; no source expression is passed to eval/Function. + const predicateFields=new Map();for(const table of tables){if(table.FormTable!==true||table.Rows.length!==1)continue;const prefix=((table.DataSource?table.DataSource+':':'')+table.TableName).toLowerCase();for(const [column,value]of Object.entries(table.Rows[0])){const key=prefix+'.'+column.toLowerCase();if(value===null||['string','number','boolean'].includes(typeof value)){if(predicateFields.has(key)&&predicateFields.get(key)!==value)predicateFields.set(key,undefined);else predicateFields.set(key,value);}}} + const predicate=expression=>{ + try{ + if(expression.length>2000)throw Error();const tokens=[];let index=0; + while(index256)throw Error(); + } + let cursor=0,depth=0;const take=type=>tokens[cursor]?.type===type?(cursor++,true):false; + const atom=()=>{if(++depth>32)throw Error();let result;if(take('(')){result=or();if(!take(')'))throw Error();}else{const token=tokens[cursor++];if(token?.type==='value')result=token.value;else if(token?.type==='field'){const key=token.name.toLowerCase();if(!predicateFields.has(key)||predicateFields.get(key)===undefined)throw Error();result=predicateFields.get(key);}else throw Error();}depth--;return result;}; + const comparison=()=>{let left=atom();const operator=tokens[cursor]?.type;if(['==','!=','===','!=='].includes(operator)){cursor++;const right=atom();if(operator==='==')left=left==right;else if(operator==='!=')left=left!=right;else if(operator==='===')left=left===right;else left=left!==right;}return left;}; + const and=()=>{let result=comparison();while(take('&&')){const right=comparison();result=Boolean(result)&&Boolean(right);}return result;}; + const or=()=>{let result=and();while(take('||')){const right=and();result=Boolean(result)||Boolean(right);}return result;}; + const result=or();if(cursor!==tokens.length)throw Error();return {known:true,value:Boolean(result)}; + }catch{return {known:false};} + }; + for(const element of document.querySelectorAll('[hiddenexpress]')){const expression=element.getAttribute('hiddenexpress')||'';if(!hiddenPredicates.has(expression))hiddenPredicates.set(expression,expression.trim()?predicate(expression):{known:true,value:false});} + const uncertainVisibility=element=>{for(let node=element;node;node=node.parentElement){const expression=node.getAttribute('hiddenexpress');if(expression!==null&&hiddenPredicates.get(expression)?.known===false)return true;}return false;}; + const blocked=()=>({blocker:'明细多行表单的行数、字段或表格关系不明确,PDF 快照已阻断;可仅采集字段供核对。'}); + const currentTaskScopeError=table=>{ + if(!table.Rows.length||!table.Rows.some(row=>Object.keys(row).some(column=>/^TaskID$/i.test(column))))return null; + const readTask=row=>{const columns=Object.keys(row).filter(column=>/^TaskID$/i.test(column));if(columns.length!==1)return null;const value=row[columns[0]];if(typeof value==='string'&&value.trim())return value;if(typeof value==='number'&&Number.isSafeInteger(value))return String(value);return null;}; + const masters=tables.filter(candidate=>candidate.FormTable===true&&/(?:^|_)Applicant$/i.test(candidate.TableName)); + if(masters.length!==1||masters[0].Rows.length!==1)return '明细缺少唯一当前主表 Applicant.TaskID,PDF 作用域校验已阻断。'; + const current=readTask(masters[0].Rows[0]);if(current===null)return '当前主表 Applicant.TaskID 不是明确的单一值,PDF 作用域校验已阻断。'; + if(table===masters[0])return null; + if(table.Rows.some(row=>readTask(row)!==current))return '明细 TaskID 与当前主表不一致或缺失,PDF 作用域校验已阻断;不会过滤后继续生成。'; + return null; + }; + // Vendor ParseDynamicArea defines zero-based startRowIndex and row count. + // Only a declared single template row is expanded; header/footer stay intact. + const selector='[xdatabind],[data-xdatabind],[data-bind]',expandedPrefixes=new Set(); + for(const host of form.querySelectorAll('table[dynamicarea]')){ + const ownBindings=[...host.querySelectorAll(selector)].filter(visible);if(!ownBindings.length)continue; + const marker=/^\s*(0|[1-9]\d*)\s*,\s*1\s*$/.exec(host.getAttribute('dynamicarea')||'');if(!marker)return blocked(); + const start=Number(marker[1]),hostRows=[...host.rows];if(!Number.isSafeInteger(start)||start>=hostRows.length||hostRows.some(row=>[...row.cells].some(cell=>cell.rowSpan!==1)))return blocked(); + const template=hostRows[start]; + if(ownBindings.some(element=>element.closest('table')!==host||element.closest('tr')!==template||element.parentElement?.closest(selector)))return blocked(); + const matches=tables.filter(table=>{const prefix=((table.DataSource?table.DataSource+':':'')+table.TableName).toLowerCase();return ownBindings.every(element=>{const key=binding(element).toLowerCase();return key.startsWith(prefix+'.')&&/^[\p{L}\p{N}_]+$/u.test(key.slice(prefix.length+1));});}); + if(matches.length!==1)return blocked();const table=matches[0],prefix=((table.DataSource?table.DataSource+':':'')+table.TableName).toLowerCase(); + const scopeError=currentTaskScopeError(table);if(scopeError)return {blocker:scopeError}; + if(expandedPrefixes.has(prefix)||bindings.filter(element=>visible(element)&&binding(element)?.toLowerCase().startsWith(prefix+'.')).some(element=>element.closest('table')!==host))return blocked(); + expandedPrefixes.add(prefix); + const datasource=host.getAttribute('xdatasource'); + if(datasource){ + // Vendor WriteToTable comes from bound columns. DataSource/Filter describe + // lookup/import, not a predicate for persisted current-order display rows. + const entries=datasource.split(';').map(part=>part.trim()).filter(Boolean),names=entries.filter(part=>/^TableName:/i.test(part));if(names.length!==1||names[0].slice(names[0].indexOf(':')+1).trim().toLowerCase()!==table.TableName.toLowerCase()||entries.some(part=>!/^TableName:[\p{L}\p{N}_]+$/iu.test(part)&&!/^Filter:[\p{L}\p{N}_]+->[\p{L}\p{N}_:.]+$/iu.test(part)))return blocked(); + } + const groups=new Map();for(const element of ownBindings){const key=binding(element).toLowerCase(),list=groups.get(key)||[];list.push(element);groups.set(key,list);} + const datamap=host.getAttribute('datamap'); + if(datamap){const mapped=new Set();for(const part of datamap.split(';').map(part=>part.trim()).filter(Boolean)){const pair=part.split('->');if(pair.length!==2||pair[1].toLowerCase()!==prefix+'.'+pair[0].toLowerCase()||mapped.has(pair[1].toLowerCase()))return blocked();mapped.add(pair[1].toLowerCase());}if([...groups.keys()].some(key=>!mapped.has(key))||[...mapped].some(key=>!groups.has(key)))return blocked();} + for(const controls of groups.values())if(controls.length>1){const type=controls[0].type;if(!['checkbox','radio'].includes(type)||controls.some(control=>control.type!==type||!control.hasAttribute('value')||!control.value.trim())||new Set(controls.map(control=>control.value)).size!==controls.length)return blocked();} + const rows=[]; + for(const [rowIndex,row]of table.Rows.entries()){ + const assignments=new Map(); + for(const [key,controls]of groups){const column=key.slice(prefix.length+1),columns=Object.keys(row).filter(name=>name.toLowerCase()===column);if(columns.length!==1)return blocked();const value=row[columns[0]],item={value,rowIndex}; + if(controls.length>1){let selected;if(value===null||value==='')selected=[];else if(Array.isArray(value)&&controls[0].type==='checkbox'&&value.every(option=>['string','number','boolean'].includes(typeof option)))selected=value.map(String);else if(['string','number','boolean'].includes(typeof value))selected=[String(value)];else return blocked();const choices=new Set(controls.map(control=>control.value));if(new Set(selected).size!==selected.length||selected.some(option=>!choices.has(option)))return blocked();for(const control of controls)assignments.set(control,{...item,choiceSelected:selected.includes(control.value)}); + }else assignments.set(controls[0],item); + } + rows.push(assignments); + } + const sourceElements=[...template.querySelectorAll(selector)]; + for(const assignments of rows){const clone=template.cloneNode(true);template.parentElement.insertBefore(clone,template);const targets=[...clone.querySelectorAll(selector)];for(const [element,item]of assignments){const target=targets[sourceElements.indexOf(element)];if(!target||!visible(target))return blocked();resolved.set(target,item);}} + template.remove(); + } + bindings=[...form.querySelectorAll(selector)]; + for(const table of tables){ + const prefix=((table.DataSource?table.DataSource+':':'')+table.TableName).toLowerCase(),bound=bindings.filter(element=>visible(element)&&(binding(element)?.toLowerCase().startsWith(prefix+'.')||binding(element)?.toLowerCase().startsWith(prefix+'['))); + for(const [rowIndex,row]of table.Rows.entries())for(const [column,value]of Object.entries(row)){const key=prefix+'.'+column.toLowerCase(),items=values.get(key)||[];items.push({value,rowIndex});values.set(key,items);} + if(!bound.length)continue; + const scopeError=currentTaskScopeError(table);if(scopeError)return {blocker:scopeError}; + if(bound.every(element=>resolved.has(element)))continue; + if(table.Rows.length>1){ + const rows=new Map(),keys=new Set(bound.map(element=>binding(element).toLowerCase()));let container,section; + for(const element of bound){const row=element.closest('tr'),host=element.closest('table'),cell=element.closest('td,th'),key=binding(element).toLowerCase(),items=values.get(key);if(!row||!host||row.closest('table')!==host||!cell||cell.rowSpan!==1||element.parentElement?.closest('[xdatabind],[data-xdatabind],[data-bind]')||!items||items.length!==table.Rows.length)return blocked();if(container&&(container!==host||section!==row.parentElement))return blocked();container=host;section=row.parentElement;const columns=rows.get(row)||new Map();if(columns.has(key))return blocked();columns.set(key,element);rows.set(row,columns);} + if(rows.size!==table.Rows.length||detailTables.has(container))return blocked();detailTables.add(container); + for(const [index,columns]of [...rows.values()].entries()){if(columns.size!==keys.size||[...keys].some(key=>!columns.has(key)))return blocked();for(const [key,element]of columns)resolved.set(element,values.get(key)[index]);} + }else for(const element of bound){const items=values.get(binding(element).toLowerCase());if(items?.length===1)resolved.set(element,items[0]);} + } + for(const element of bindings.filter(visible))if(!resolved.has(element))return {blocker:uncertainVisibility(element)?'字段所在 hiddenexpress 的可见性不能安全确认,PDF 快照已阻断;不能猜测隐藏缺失字段。':'可见字段缺少已核实的后端值,PDF 快照已阻断。'}; + const printable=(element,item)=>{if(Object.hasOwn(item||{},'choiceSelected'))return item.choiceSelected?'☑':'☐';const raw=item?.value;if(raw!==null&&typeof raw==='object')return null;const text=raw==null?'':String(raw);if(['radio','checkbox'].includes(element.type))return raw===true||text===element.value?'☑':'☐';if(element.tagName==='SELECT')return [...element.options].find(option=>option.value===text)?.textContent||text;return text;}; + for(const [element,item]of resolved)if(printable(element,item)===null)return {blocker:'字段包含多个或复合值,PDF 快照已阻断。'}; + const copy=document.documentElement.cloneNode(true),originals=[document.documentElement,...document.documentElement.querySelectorAll('*')],copies=[copy,...copy.querySelectorAll('*')]; + for(let index=originals.length-1;index>=0;index--){const original=originals[index],target=copies[index];if(!visible(original)||['SCRIPT','IFRAME','OBJECT','EMBED','BUTTON','LINK','META','BASE'].includes(original.tagName)||['hidden','password','file','submit','button','reset'].includes(original.type)||original.getAttribute('printout')==='false'){target.remove();continue;} + const item=resolved.get(original); + if(['INPUT','TEXTAREA','SELECT'].includes(original.tagName)){const span=document.createElement('span');span.textContent=item?printable(original,item):original.value||'';span.style.whiteSpace='pre-wrap';target.replaceWith(span);} + else {if(item)target.textContent=printable(original,item);for(const attribute of [...target.attributes])if(/^on/i.test(attribute.name)||['action','srcdoc','srcset','formaction','value','href','poster','background'].includes(attribute.name.toLowerCase()))target.removeAttribute(attribute.name);} + } + copy.querySelectorAll('#taskCommentForm,#TaskCommentCount').forEach(node=>node.remove()); + const styles=[];for(const sheet of document.styleSheets)try{styles.push([...sheet.cssRules].map(rule=>rule.cssText).join('\n'));}catch{} + const warnings=[...document.querySelectorAll('[hiddenexpress]')].some(element=>visible(element)&&uncertainVisibility(element))?['部分 hiddenexpress 不能静态确认,相关内容保持可见,未执行表达式代码。']:[]; + return {processSteps,snapshot:{html:copy.outerHTML,styles,width:1264,images:[],warnings}}; +} +function allowedResource(value){try{const url=baseURL(value);return !url.search&&!/(?:approve|fulfill|markread|upload|delete)/i.test(url.pathname)&&/\.(?:css|png|jpe?g|gif|webp|woff2?|ttf|ico)$/i.test(url.pathname);}catch{return false;}} +async function captureReadonlyForm({storageState,detailUrl,processName,nodeName,listProcessVersion=null,fieldsOnly=false,requestFactory=options=>loadPlaywright().request.newContext(options),browserFactory=()=>loadPlaywright().chromium.launch(browserOptions()),timeout=20000}){ + if(!storageState)fail('BPM 会话需要续登。',401);if(typeof nodeName!=='string'||!nodeName.trim())fail('BPM 到达记录缺少明确当前节点。'); + let request,browser,context; + try{ + request=await requestFactory({storageState,timeout});const loaded=await loadForm(request,detailUrl,{timeout}),identity={...loaded.identity,...require('./bpm-form-contracts.cjs').resolveFormIdentity({...loaded.identity,url:loaded.url},{processName,listProcessVersion})},tables=await loadData(request,loaded.url,{timeout}),evidence=flattenTables(tables); + browser=await browserFactory();context=await browser.newContext({storageState,javaScriptEnabled:false,serviceWorkers:'block',acceptDownloads:false,permissions:[]});const images=[]; + await context.route('**/*',async route=>{try{const incoming=route.request();if(incoming.method()!=='GET')return await route.abort();if(incoming.url()===loaded.url.href&&incoming.isNavigationRequest())return await route.fulfill({status:200,contentType:'text/html; charset=utf-8',body:loaded.bytes});if(incoming.isNavigationRequest()||!allowedResource(incoming.url()))return await route.abort();const response=await request.get(incoming.url(),{maxRedirects:0,timeout});if(response.status()!==200)return await route.abort();const bytes=await response.body();if(bytes.length>MAX_BYTES)return await route.abort();const contentType=(response.headers()['content-type']||'').split(';')[0];if(/^image\/(png|jpeg|gif|webp)$/.test(contentType))images.push({url:incoming.url(),data:'data:'+contentType+';base64,'+bytes.toString('base64')});return await route.fulfill({status:200,headers:{'content-type':contentType||'application/octet-stream'},body:bytes});}catch{await route.abort().catch(()=>{});}}); + if(context.routeWebSocket)await context.routeWebSocket(/.*/,socket=>socket.close());const page=await context.newPage();page.on('dialog',dialog=>dialog.dismiss().catch(()=>{}));page.on('download',download=>download.cancel().catch(()=>{})); + const response=await page.goto(loaded.url.href,{waitUntil:'load',timeout});if(!response||response.status()!==200||page.url()!==loaded.url.href)fail('BPM 静态表单未能只读加载。',401); + const hydrated=await page.evaluate(hydrateReadonlyDocument,{tables,fieldsOnly});if(hydrated.blocker)fail(hydrated.blocker);if(hydrated.snapshot)hydrated.snapshot.images=images; + const capturedAt=new Date().toISOString(),detail={readOnly:true,...identity,formVersion:identity.formVersion,listProcessVersion,processInstanceId:identity.pid,nodeName,nodeSource:'list.activityName',fields:evidence.fields,fieldSources:evidence.sources,processSteps:hydrated.processSteps||[],capturedAt,fieldSource:'DataProvider.GetFormProcessData'}; + const evidenceHash=crypto.createHash('sha256').update(JSON.stringify(detail)).digest('hex');detail.evidenceHash=evidenceHash; + return {...identity,detail,snapshot:hydrated.snapshot||null,capturedAt,evidenceHash,detailUrl:loaded.url.href,fieldsOnly,blockedRequests:[]}; + }catch(error){if(error.status)throw error;fail('BPM 只读字段或静态快照采集失败。',502);}finally{await context?.close().catch(()=>{});await browser?.close().catch(()=>{});await request?.dispose?.().catch(()=>{});} +} +module.exports={parseEntryURL,loadForm,loadData,flattenTables,hydrateReadonlyDocument,captureReadonlyForm,allowedResource}; diff --git a/src/bpm-session-manager.cjs b/src/bpm-session-manager.cjs index 03f4ee6..5ab63ba 100644 --- a/src/bpm-session-manager.cjs +++ b/src/bpm-session-manager.cjs @@ -180,11 +180,22 @@ class BpmSessionManager { this.authorize(connection,principal); if(this.sessions.has(connection.id))throw error('此连接正在登录窗口中使用,请关闭后采集详情。',409); const saved=await this.vault().read(connection.id); - const {captureDetail}=require('./bpm-order-detail.cjs'); - const result=await captureDetail({storageState:saved?.storageState,sessionStorage:saved?.sessionStorage,detailUrl:arrival.detailUrl,processName:arrival.processName,nodeName:arrival.activityName}); + const capture=this.detailReader||require('./bpm-order-detail.cjs').captureDetail;let detailUrl=arrival.detailUrl,readonlyData=false; + if(arrival.recordKind==='notification-task'){ + const client=this.notificationClientFor(connection.id); + const fresh=(await client.scan(saved?.storageState)).find(row=>row.source===arrival.source&&row.taskId===arrival.taskId); + if(!fresh)throw error('该通知任务已不在当前待办列表,不能沿用旧记录。',409); + if(['processInstanceId','processName','activityName','processVersion','tid','pid','subject','arrivedAt','serialNum'].some(key=>String(fresh[key]??'')!==String(arrival[key]??'')))throw error('BPM 通知任务、节点或摘要时间已变化,请重新只读核对。',409); + detailUrl=client.entryFor(fresh);readonlyData=true; + } + const result=await capture({storageState:saved?.storageState,sessionStorage:saved?.sessionStorage,detailUrl,processName:arrival.processName,nodeName:arrival.activityName,listProcessVersion:arrival.processVersion,readonlyData}); this.authorize(connection,principal);return result; }); } + async scanOrderTasks(connection,principal){ + return this.run(connection?.id,async()=>{this.authorize(connection,principal);if(this.sessions.has(connection.id))throw error('此连接正在登录窗口中使用,请关闭后读取通知任务。',409);const saved=await this.vault().read(connection.id),client=this.notificationClientFor(connection.id);const rows=await client.scan(saved?.storageState);this.authorize(connection,principal);return rows;}); + } + notificationClientFor(id){this.notificationClients||=new Map();if(!this.notificationClients.has(id))this.notificationClients.set(id,this.notificationClientFactory?this.notificationClientFactory(id):new (require('./bpm-notification-source.cjs').BpmNotificationClient)());return this.notificationClients.get(id);} authorize(connection, principal) { if (!connection || typeof connection.id !== 'string' || !connection.id || connection.id.length > 200) throw error('连接标识无效。'); if (!principal?.sessionId || !principal.user || !['admin','operator'].includes(principal.user.role) || (principal.user.role !== 'admin' && connection.owner !== principal.user.username)) throw error('只有连接负责人或管理员可以操作。',403); @@ -432,6 +443,7 @@ class BpmSessionManager { await Promise.all([...this.sessions.keys()].map(id=>this.closeLease(id))); if (this.browserPromise) await (await this.browserPromise.catch(()=>null))?.close().catch(()=>{}); this._vault?.destroy(); + this.notificationClients?.clear(); } } module.exports={BpmSessionManager}; diff --git a/src/notifications.cjs b/src/notifications.cjs index 02f5c2d..b0e3476 100644 --- a/src/notifications.cjs +++ b/src/notifications.cjs @@ -32,7 +32,7 @@ class NotificationStore{ items(){return this.db.prepare('SELECT * FROM items ORDER BY rowid DESC LIMIT 100').all().map(r=>this.item(r));} pending(attempts,industries){if(!industries.length)return [];return this.db.prepare("SELECT * FROM items WHERE owner='generic' AND status IN('pending','blocked') AND attempts'?').join(',')+") ORDER BY rowid LIMIT 200").all(attempts,...industries).map(r=>this.item(r));} blockUnmapped(industries){this.db.prepare("UPDATE items SET status='blocked',error='此产业尚未配置接口人收件组。' WHERE owner='generic' AND status IN('pending','blocked')"+(industries.length?' AND industry NOT IN('+industries.map(()=>'?').join(',')+')':'')).run(...industries);} - syncOrder(order){const id=hash(['order-workflow',order.versionKey,order.businessVersion,order.productLine].join('\0'));this.db.prepare("UPDATE items SET status=?,error=?,batch_id=? WHERE id=? AND owner='order-workflow'").run(order.notification?.status||order.status,order.notification?.error||null,order.notification?.batchId||null,id);} + syncOrder(order){const id=hash(['order-workflow',order.versionKey,order.version||order.businessVersion,order.productLine].join('\0'));this.db.prepare("UPDATE items SET status=?,error=?,batch_id=? WHERE id=? AND owner='order-workflow'").run(order.notification?.status||order.status,order.notification?.error||null,order.notification?.batchId||null,id);} block(id,message){this.db.prepare("UPDATE items SET status='blocked',error=? WHERE id=? AND status IN('pending','blocked')").run(message,id);} prepare(items,snapshot){return this.transaction(()=>{const id=crypto.randomUUID();this.db.prepare('INSERT INTO batches VALUES(?,?,?,?,?)').run(id,'prepared',this.encode(id,snapshot),null,new Date().toISOString());for(const item of items){const result=this.db.prepare("UPDATE items SET status='reserved',attempts=attempts+1,error=NULL,batch_id=? WHERE id=? AND status IN('pending','blocked')").run(id,item.id);if(!result.changes)fail('通知队列已变化,请重试。',409);}return id;});} mark(id,status,message=null){this.transaction(()=>{this.db.prepare('UPDATE batches SET status=?,error=? WHERE id=?').run(status,message,id);if(status!=='sending')this.db.prepare('UPDATE items SET status=?,error=? WHERE batch_id=?').run(status==='failed'?'pending':status,message,id);});} @@ -45,7 +45,7 @@ class NotificationService{ map(data){if(!data||typeof data!=='object'||Array.isArray(data))fail('通知来源必须是 JSON 对象。');const config=this.store.settings(),raw=Object.fromEntries(Object.entries(config.fieldMap).map(([key,p])=>[key,valueAt(data,p)]));if(!['string','number'].includes(typeof raw.id)||!String(raw.id).trim()||String(raw.id).length>200||/[\x00-\x1f]/.test(String(raw.id))||typeof raw.industry!=='string'||!raw.industry.trim()||raw.industry.length>100||/[\x00-\x1f]/.test(raw.industry)||typeof raw.brief!=='string'||!raw.brief.trim()||raw.brief.length>20000)fail('通知 ID、产业和简要说明不能为空,正文最多 20000 字。');if(raw.subject!==undefined&&(typeof raw.subject!=='string'||raw.subject.length>300||/[\r\n\x00]/.test(raw.subject)))fail('通知标题最多 300 字,不能包含换行。');if(raw.version!==undefined&&(!['string','number'].includes(typeof raw.version)||String(raw.version).length>200||/[\x00-\x1f]/.test(String(raw.version))))fail('来源版本无效。');if(raw.occurredAt!==undefined&&(typeof raw.occurredAt!=='string'||!Number.isFinite(Date.parse(raw.occurredAt))))fail('业务时间无效。');return {source:config.sourceName,sourceKey:config.sourceKey,sourceId:String(raw.id).trim(),sourceVersion:raw.version===undefined||raw.version===''?hash(raw.brief):String(raw.version),industry:raw.industry.trim(),brief:raw.brief,subject:raw.subject||raw.industry.trim()+'业务通知',occurredAt:raw.occurredAt||this.clock().toISOString()};} preview(data){try{const event=this.map(data),group=this.settings().groups.find(g=>g.productLine===event.industry);return {valid:!!group,event,to:group?.to||[],cc:group?.cc||[],issues:group?[]:['此产业尚未配置接口人收件组。']};}catch(e){if(!e.status)throw e;return {valid:false,issues:[e.message]};}} ingest(data){return this.store.ingest(this.map(data));} - ingestOrder(order){if(order?.steps?.archive?.status!=='success'||!order.archive?.archiveId||!order.versionKey||!order.businessVersion||!order.templateId||!order.ruleId||!order.productLine||!order.brief)fail('订单通知必须有成功归档及已确认的订单版本证据。',409);return this.store.ingest({owner:'order-workflow',source:order.source,sourceKey:'order-workflow',sourceId:order.versionKey,sourceVersion:order.businessVersion,industry:order.productLine,brief:order.brief,subject:order.subject,occurredAt:order.businessTime,orderVersionKey:order.versionKey,ruleId:order.ruleId,templateId:order.templateId});} + ingestOrder(order){if(order?.steps?.archive?.status!=='success'||!order.archive?.archiveId||!order.versionKey||!(order.version||order.businessVersion)||!order.templateId||!order.ruleId||!order.productLine||!order.brief)fail('订单通知必须有成功归档及已确认的通知任务证据。',409);return this.store.ingest({owner:'order-workflow',source:order.source,sourceKey:'order-workflow',sourceId:order.versionKey,sourceVersion:order.version||order.businessVersion,industry:order.productLine,brief:order.brief,subject:order.subject,occurredAt:order.businessTime,orderVersionKey:order.versionKey,ruleId:order.ruleId,templateId:order.templateId});} syncOrder(order){this.store.syncOrder(order);} saveSettings(input){if(this.running)fail('通知正在发送,请稍后修改配置。',409);if(input?.enabled){const c=this.mail.store.publicChannel(input.channelId);if(!c.state.smtp)fail('请先验证发件邮箱的 SMTP 连接。',409);if(!this.settings().groups.length)fail('请先配置产业接口人收件组。',409);}const old=this.store.settings(),saved=this.store.saveSettings(input);if(saved.enabled&&!old.enabled)this.resetSchedule(this.clock());return saved;} resetSchedule(now){const schedule=this.settings().schedule,calendar=this.calendar();const state={signature:JSON.stringify([schedule,calendar]),next:nextSlots(schedule,now,1,calendar)[0]};this.store.setSchedule(state);return state;} diff --git a/src/order-pipeline.cjs b/src/order-pipeline.cjs index 2034adf..e3c1eed 100644 --- a/src/order-pipeline.cjs +++ b/src/order-pipeline.cjs @@ -19,7 +19,7 @@ function latestElapsedSlot(now,schedule,calendar){ class OrderPipeline{ constructor({workflow,store,scanStore,workspace,manager,jobs,storage,mail,notifications,settings,calendar=()=>[],outputDir,render=renderSnapshot,clock=()=>new Date()}){ - Object.assign(this,{workflow,store,scanStore,workspace,manager,jobs,storage,mail,notifications,settings,calendar,outputDir,render,clock});this.pending=new Map();this.stopped=false;this.sending=null;this.principal={sessionId:'order-pipeline:'+crypto.randomUUID(),user:{username:'订单任务',role:'admin'}}; + Object.assign(this,{workflow,store,scanStore,workspace,manager,jobs,storage,mail,notifications,settings,calendar,outputDir,render,clock});this.pending=new Map();this.discovery=new Map();this.lastDiscovery=new Map();this.stopped=false;this.sending=null;this.principal={sessionId:'order-pipeline:'+crypto.randomUUID(),user:{username:'订单任务',role:'admin'}}; } config(){return {...DEFAULTS,...this.store.meta('config',{})};} saveConfig(input){ @@ -34,6 +34,11 @@ class OrderPipeline{ authorize(arrival,principal){const connection=this.workspace.getConnection(arrival.connectionId);if(connection.status==='disabled'||!principal?.sessionId||!['admin','operator'].includes(principal.user?.role)||(principal.user.role!=='admin'&&connection.owner!==principal.user.username))throw fail('只有连接负责人或管理员可以读取和处理此订单。',403);return connection;} arrivals(){return this.store.candidates();} options(){return {templates:this.mail.store.templates(),groups:this.settings().groups,connections:this.workspace.snapshot?.().connections?.map(({id,name})=>({id,name}))||[],adapters:{}};} + async scanSource(connectionId,principal){ + const connection=this.authorize({connectionId},principal);if(this.discovery.has(connectionId))return this.discovery.get(connectionId);if(this.stopped)throw fail('订单服务正在停止。'); + const runId=this.scanStore.begin(connectionId,principal.user.username); + const task=(async()=>{try{const rows=await this.manager.scanOrderTasks(connection,principal);this.authorize({connectionId},principal);const result=this.scanStore.complete(runId,connectionId,rows);this.lastDiscovery.set(connectionId,+this.clock());return {...result,runId};}catch(error){this.scanStore.fail(runId,error.status?error.message:'BPM 通知任务只读查询失败。');throw error;}})().finally(()=>this.discovery.delete(connectionId));this.discovery.set(connectionId,task);return task; + } async checkRule(ruleId,input,principal){ const arrival=this.scanStore.getArrival(input.connectionId,input.source,input.taskId);if(!arrival)throw fail('所选 BPM 到达记录不存在。',404);this.authorize(arrival,principal); this.workflow.invalidateCheck(ruleId); @@ -83,6 +88,7 @@ class OrderPipeline{ }catch(error){candidate.status='blocked';candidate.error=error.status?error.message:'详情或规则读取失败,请检查连接和采集记录。';candidate.code=error.code||'DETAIL_FAILED';this.store.putCandidate(candidate);return {status:'blocked',candidate};} } async execute(input,snapshot,principal,candidate){ + this.workflow.assertUniqueTask(input); let order=input; try{ if(order.steps.pdf?.status!=='success'){ @@ -116,14 +122,14 @@ class OrderPipeline{ } } async retry(key,principal){ - const order=this.workflow.get(key);if(!order)throw fail('订单版本不存在。',404);this.authorize(order.arrival,principal); + const order=this.workflow.get(key);if(!order)throw fail('订单版本不存在。',404);this.authorize(order.arrival,principal);this.workflow.assertUniqueTask(order); const candidate=this.arrivals().find(row=>row.orderVersionKey===key)||{id:idFor(order.arrival),...structuredClone(order.arrival),orderVersionKey:key,status:'recovering'}; if(this.pending.has(candidate.id))throw fail('订单任务正在运行。');if(!['archive_error','pdf_error','detail_error','notification_error','interrupted'].includes(order.status))throw fail('只能重试明确失败或中断的步骤。'); const task=(async()=>{ if(!candidate.snapshot&&order.steps.pdf?.status!=='success'){ const capture=await this.manager.captureOrderDetail(this.workspace.getConnection(order.arrival.connectionId),principal,order.arrival); const preview=new OrderWorkflow({clock:this.clock}).identify({arrival:order.arrival,detail:capture.detail,rule:order.ruleSnapshot,mapping:order.ruleSnapshot.adapters[capture.detail.processVersion]}); - if(preview.order.versionKey!==key||JSON.stringify(preview.order.sources)!==JSON.stringify(order.sources)||JSON.stringify(preview.order.detailSnapshot.fields)!==JSON.stringify(order.detailSnapshot.fields))throw fail('恢复采集的业务版本或字段已变化,原任务不能使用新内容的 PDF。'); + if(preview.order.source!==order.source||preview.order.taskId!==order.taskId||preview.order.tid!==order.tid||preview.order.pid!==order.pid||preview.order.orderNo!==order.orderNo||JSON.stringify(preview.order.sources)!==JSON.stringify(order.sources)||JSON.stringify(preview.order.detailSnapshot.fields)!==JSON.stringify(order.detailSnapshot.fields))throw fail('恢复采集的通知任务或字段已变化,原任务不能使用新内容的 PDF。'); candidate.snapshot=capture.snapshot;this.store.putCandidate(candidate); } let current=order.status==='notification_error'||order.steps.archive?.status==='success'?this.workflow.update(key,draft=>{draft.status='archived';}):this.workflow.start(key);if(current.status==='detail_capturing')current=this.workflow.markDetailReady(key,order.detailEvidence||{});return this.execute(current,candidate.snapshot,principal,candidate); @@ -140,6 +146,10 @@ class OrderPipeline{ } async perform(){ const config=this.config();if(!config.enabled)return;const seen=new Map(this.arrivals().map(row=>[row.id,row])); + if(dayPolicy(this.clock(),this.settings().schedule,this.calendar()).scan){ + const interval=(this.scanStore.config?.().intervalMinutes||5)*60000; + for(const connection of this.workspace.snapshot?.().connections||[]){if(this.stopped)break;if(connection.status==='disabled'||+this.clock()-(this.lastDiscovery.get(connection.id)||0)[rule.id,rule.version,rule.status])); const changed=!old||JSON.stringify(old.ruleRevision)!==revision||old.lastSeenAt!==arrival.lastSeenAt||old.arrivedAt!==arrival.arrivedAt||old.subject!==arrival.subject; @@ -150,7 +160,7 @@ class OrderPipeline{ for(const order of this.workflow.listOrders())if(order.notification)this.notifications?.syncOrder(order); } start(){if(!this.timer){this.timer=setInterval(()=>this.tick().catch(()=>{}),15000);this.timer.unref?.();}} - async stop(){this.stopped=true;clearInterval(this.timer);await this.ticking;await Promise.allSettled([...this.pending.values()]);if(this.sending)await this.sending;} + async stop(){this.stopped=true;clearInterval(this.timer);await this.ticking;await Promise.allSettled([...this.pending.values(),...this.discovery.values()]);if(this.sending)await this.sending;} resetSchedule(now=this.clock()){ const schedule=this.settings().schedule,calendar=this.calendar(),state={signature:JSON.stringify([schedule,calendar]),next:nextSlots(schedule,now,1,calendar)[0]};this.store.setMeta('schedule',state);return state; } diff --git a/src/order-workflow-api.cjs b/src/order-workflow-api.cjs index c64fec7..ec1de9c 100644 --- a/src/order-workflow-api.cjs +++ b/src/order-workflow-api.cjs @@ -27,6 +27,7 @@ async function orderWorkflowApi({workflow,pipeline,workspace,user,sessionId,rout reply(200,result);return true; } if(route==='/api/order-workflow/settings'){admin();const result=service().saveConfig(body);audit('保存订单任务运行设置',result.enabled?'启用':'暂停');reply(200,result);return true;} + if(route==='/api/order-workflow/source-scan'){keys(body,['connectionId']);if(typeof body.connectionId!=='string'||!body.connectionId)fail('请选择授权 BPM 连接。');const result=await service().scanSource(body.connectionId,{user,sessionId});audit('只读采集 BPM 通知任务',body.connectionId);reply(200,result);return true;} const retry=/^\/api\/order-workflow\/orders\/([^/]+)\/retry$/.exec(route); if(retry){keys(body,[]);const id=decodeURIComponent(retry[1]);reply(200,await service().retry(id,{user,sessionId}));audit('重试失败订单步骤',id);return true;} const retryArrival=/^\/api\/order-workflow\/arrivals\/([^/]+)\/retry$/.exec(route); diff --git a/src/order-workflow.cjs b/src/order-workflow.cjs index 45f96d4..91a8740 100644 --- a/src/order-workflow.cjs +++ b/src/order-workflow.cjs @@ -54,6 +54,7 @@ class OrderWorkflow{ this.clock=clock;this.schedule=schedule;this.store=store;this.orders=new Map((store?.orders?.()||[]).map(order=>[order.versionKey,order]));this.batches=new Map((store?.batches?.()||[]).map(batch=>[batch.id,batch]));this.ruleMap=new Map((store?.rules?.()||[]).map(rule=>[rule.id,rule])); } persistOrder(order){this.store?.putOrder?.(order);}persistBatch(batch){this.store?.putBatch?.(batch);} + assertUniqueTask(order){if([...this.orders.values()].filter(saved=>saved.source===order.source&&saved.taskId===String(order.taskId)).length>1)throw new OrderWorkflowError('TASK_IDENTITY_CONFLICT','同一 BPM 通知任务存在多个旧版本记录,必须人工核对,不能重复归档或通知。');} saveRule(rule){ if(!rule||typeof rule.id!=='string'||!rule.id||typeof rule.processName!=='string'||!rule.processName.trim()||typeof rule.nodeName!=='string'||!rule.nodeName.trim()||typeof rule.productLine!=='string'||!rule.productLine.trim()||typeof rule.templateId!=='string'||!rule.templateId.trim()||!rule.adapters||typeof rule.adapters!=='object'||Array.isArray(rule.adapters))throw new OrderWorkflowError('RULE_INVALID','分类规则缺少流程、节点、产品线、模板或版本适配器。'); for(const [version,mapping] of Object.entries(rule.adapters))if(!version.trim()||!mapping||typeof mapping!=='object'||Array.isArray(mapping))throw new OrderWorkflowError('RULE_INVALID','字段适配器版本无效。'); @@ -84,20 +85,23 @@ class OrderWorkflow{ identify(input){ let {arrival,detail,mapping,rule}=input||{};if(!arrival?.source||!present(arrival.taskId))throw new OrderWorkflowError('SOURCE_ID_MISSING','缺少 BPM 来源和任务号。');if(!detail||typeof detail.fields!=='object'||Array.isArray(detail.fields))throw new OrderWorkflowError('DETAIL_MISSING','缺少订单详情字段。'); if(!rule){const resolved=this.resolveRule(arrival,detail);rule=resolved.rule;mapping=resolved.mapping;}else if(!mapping&&rule.adapters?.[String(detail.processVersion||'')])mapping=rule.adapters[String(detail.processVersion)];if(!mapping)throw new OrderWorkflowError('ADAPTER_MISSING','当前表单版本没有字段适配器。');exactRule(arrival,detail,rule); - const mappedVersion=mapping.businessVersion?readCandidate({arrival,detail},mapping.businessVersion,'业务版本'):null; + let mappedVersion=null;if(mapping.businessVersion){try{mappedVersion=readCandidate({arrival,detail},mapping.businessVersion,'业务版本');}catch(error){if(error.code!=='MISSING_FIELD')throw error;}} const businessVersion=mappedVersion?.value??detail.businessVersion; - if(!present(detail.tid)||!present(detail.pid)||!present(businessVersion)||![detail.tid,detail.pid,businessVersion].every(value=>['string','number'].includes(typeof value)))throw new OrderWorkflowError('VERSION_MISSING','缺少 tid、pid 或明确的业务版本标识。');if(!present(detail.processVersion))throw new OrderWorkflowError('FORM_VERSION_MISSING','缺少表单版本。'); + if(!present(detail.tid)||!present(detail.pid)||![detail.tid,detail.pid].every(value=>['string','number'].includes(typeof value)))throw new OrderWorkflowError('VERSION_MISSING','缺少 tid 或 pid 详情标识。'); + if(present(businessVersion)&&!['string','number'].includes(typeof businessVersion))throw new OrderWorkflowError('VERSION_MISSING','上游业务版本字段必须是明确文本或数值。'); + if(!present(detail.processVersion))throw new OrderWorkflowError('FORM_VERSION_MISSING','缺少表单版本。'); const source={arrival,detail},orderNo=readCandidate(source,mapping.orderNo,'订单号'),serialNo=readCandidate(source,mapping.serialNo,'流水号'),productCode=readCandidate(source,mapping.productCode,'产品编号'),modelFull=readCandidate(source,mapping.modelFull,'完整型号'),modelShort=readCandidate(source,mapping.modelShort,'短型号'),customer=readCandidate(source,mapping.customer,'客户'),brief=readCandidate(source,mapping.brief,'简要说明'); if(!present(rule.productLine))throw new OrderWorkflowError('RULE_INVALID','分类规则必须指定产品线。'); - const productLine={path:'rule.productLine',value:rule.productLine},version=String(businessVersion),currentOrderNo=text(orderNo.value),tid=String(detail.tid),pid=String(detail.pid),versionKey=hash(JSON.stringify([tid,pid,currentOrderNo,version])); + const productLine={path:'rule.productLine',value:rule.productLine},reportedVersion=present(businessVersion)?String(businessVersion):null,version=reportedVersion||'bpm-task:'+arrival.source+'/'+arrival.taskId,currentOrderNo=text(orderNo.value),tid=String(detail.tid),pid=String(detail.pid),versionKey=hash(JSON.stringify([arrival.source,String(arrival.taskId)])); const businessTime=detail.businessTime||arrival.arrivedAt||arrival.receivedAt||null,businessTimeSource=detail.businessTime?'detail.businessTime':businessTime?'list.receivedAt':null;if(!businessTime)throw new OrderWorkflowError('BUSINESS_TIME_MISSING','缺少业务时间和列表收到时间。');const now=this.clock().toISOString(); - const order={id:hash([arrival.source,currentOrderNo].join('\0')),versionKey,version,businessVersion:version,tid,pid,orderNo:currentOrderNo,source:arrival.source,taskId:String(arrival.taskId),processName:arrival.processName,processVersion:String(detail.processVersion),nodeName:detail.nodeName||arrival.activityName||'',serialNo:text(serialNo.value),productCode:text(productCode.value),modelFull:text(modelFull.value),modelShort:text(modelShort.value),customer:text(customer.value),productLine:productLine.value,brief:String(brief.value),subject:String(detail.subject||arrival.subject||''),businessTime,businessTimeSource,sourceRevision:detail.sourceRevision||version,sources:{orderNo,serialNo,productCode,modelFull,modelShort,customer,brief,productLine},ruleId:rule.id,templateId:rule.templateId||null,status:'identified',steps:{discovery:{status:'success',source:'bpm-readonly'},detail:{status:'pending'},pdf:{status:'pending'},archive:{status:'pending'},notification:{status:'pending'}},createdAt:now,updatedAt:now}; - order.ruleSnapshot=clone(rule);order.detailSnapshot=clone(detail);order.arrival=clone(arrival);order.sources.businessVersion=mappedVersion||{path:'detail.businessVersion',value:version}; - const existing=this.orders.get(versionKey);if(existing){if(existing.ruleId!==order.ruleId||existing.brief!==order.brief||JSON.stringify(existing.sources)!==JSON.stringify(order.sources)||JSON.stringify(existing.detailSnapshot?.fields)!==JSON.stringify(detail.fields))throw new OrderWorkflowError('VERSION_CONTENT_CONFLICT','同一订单版本的分类或字段证据已变化,请人工确认业务版本。');return {status:'duplicate',order:clone(existing)};}this.persistOrder(order);this.orders.set(versionKey,order);return {status:'matched',order:clone(order)}; + const order={id:hash([arrival.source,currentOrderNo].join('\0')),versionKey,version,businessVersion:reportedVersion,versionSource:reportedVersion?'bpm.businessVersion':'bpm.taskId',tid,pid,orderNo:currentOrderNo,source:arrival.source,taskId:String(arrival.taskId),processName:arrival.processName,processVersion:String(detail.processVersion),nodeName:detail.nodeName||arrival.activityName||'',serialNo:text(serialNo.value),productCode:text(productCode.value),modelFull:text(modelFull.value),modelShort:text(modelShort.value),customer:text(customer.value),productLine:productLine.value,brief:String(brief.value),subject:String(detail.subject||arrival.subject||''),businessTime,businessTimeSource,sourceRevision:detail.sourceRevision||version,sources:{orderNo,serialNo,productCode,modelFull,modelShort,customer,brief,productLine},ruleId:rule.id,templateId:rule.templateId||null,status:'identified',steps:{discovery:{status:'success',source:'bpm-readonly'},detail:{status:'pending'},pdf:{status:'pending'},archive:{status:'pending'},notification:{status:'pending'}},createdAt:now,updatedAt:now}; + order.ruleSnapshot=clone(rule);order.detailSnapshot=clone(detail);order.arrival=clone(arrival);order.sources.businessVersion=mappedVersion||{path:reportedVersion?'detail.businessVersion':'not-provided',value:reportedVersion}; + this.assertUniqueTask(order);const existing=this.orders.get(versionKey)||[...this.orders.values()].find(saved=>saved.source===arrival.source&&saved.taskId===String(arrival.taskId)); + if(existing){if(existing.tid!==order.tid||existing.pid!==order.pid||existing.orderNo!==order.orderNo||existing.ruleId!==order.ruleId||existing.brief!==order.brief||JSON.stringify(existing.sources)!==JSON.stringify(order.sources)||JSON.stringify(existing.detailSnapshot?.fields)!==JSON.stringify(detail.fields))throw new OrderWorkflowError('VERSION_CONTENT_CONFLICT','同一 BPM 通知任务的分类或字段证据已变化,保留原处理结果并等待核对。');return {status:'duplicate',order:clone(existing)};}this.persistOrder(order);this.orders.set(versionKey,order);return {status:'matched',order:clone(order)}; } get(versionKey){const order=this.orders.get(versionKey);return order?clone(order):null;}listOrders(){return [...this.orders.values()].map(clone);} update(versionKey,work){const saved=this.orders.get(versionKey);if(!saved)throw new OrderWorkflowError('ORDER_NOT_FOUND','订单版本不存在。');const order=clone(saved);order.steps||={};work(order);order.updatedAt=this.clock().toISOString();this.persistOrder(order);this.orders.set(versionKey,order);return clone(order);} - start(versionKey){return this.update(versionKey,order=>{if(!['identified','detail_error','pdf_error','archive_error','interrupted'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前订单不能开始处理。');if(order.steps.pdf?.status==='success'){order.status='pdf_success';return;}if(order.steps.detail?.status==='success'){order.status='detail_ready';return;}order.status='detail_capturing';order.steps.detail={status:'running',startedAt:this.clock().toISOString()};});} + start(versionKey){return this.update(versionKey,order=>{this.assertUniqueTask(order);if(!['identified','detail_error','pdf_error','archive_error','interrupted'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前订单不能开始处理。');if(order.steps.pdf?.status==='success'){order.status='pdf_success';return;}if(order.steps.detail?.status==='success'){order.status='detail_ready';return;}order.status='detail_capturing';order.steps.detail={status:'running',startedAt:this.clock().toISOString()};});} markDetailReady(versionKey,detailEvidence={}){return this.update(versionKey,order=>{if(!['detail_capturing','detail_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','详情尚未处于采集状态。');order.detailEvidence=clone(detailEvidence);order.steps.detail={status:'success',...clone(detailEvidence)};order.status='detail_ready';});} beginPdf(versionKey){return this.update(versionKey,order=>{if(!['detail_ready','pdf_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能生成 PDF。');order.status='pdf_pending';order.steps.pdf={status:'running',startedAt:this.clock().toISOString()};});} beginArchive(versionKey){return this.update(versionKey,order=>{if(order.steps.pdf?.status!=='success'||!['pdf_success','archive_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能归档。');order.status='archive_pending';order.steps.archive={status:'running',startedAt:this.clock().toISOString()};});} @@ -111,6 +115,7 @@ class OrderWorkflow{ const candidates=[...this.orders.values()].filter(order=>['notification_pending','blocked'].includes(order.status)&&['pending','blocked'].includes(order.notification?.status)&&Date.parse(order.notification.occurredAt)<=Date.parse(cutoff)).map(clone),grouped=new Map(); const block=(order,message)=>{order.notification.status='blocked';order.notification.error=message;order.steps.notification={status:'blocked',error:message};order.status='blocked';}; for(const order of candidates){ + try{this.assertUniqueTask(order);}catch(error){block(order,error.message);continue;} const notification=order.notification,productLine=order.productLine,templateId=order.templateId,rule=order.ruleSnapshot||{}; const group=groups[rule.recipientGroupId||productLine]; if(!Array.isArray(group?.to)||!group.to.length){block(order,'分类规则没有已确认的收件组。');continue;} @@ -131,7 +136,7 @@ class OrderWorkflow{ saveGraph(orders,batches){if(this.store?.putGraph)this.store.putGraph(orders,batches);else {orders.forEach(order=>this.persistOrder(order));batches.forEach(batch=>this.persistBatch(batch));}orders.forEach(order=>this.orders.set(order.versionKey,order));batches.forEach(batch=>this.batches.set(batch.id,batch));} freezeBatch(cutoff,options={}){return this.freezeBatches(cutoff,options)[0];} getBatch(id){const batch=this.batches.get(id);return batch?clone(batch):null;}listBatches(){return [...this.batches.values()].map(clone);} - markBatchSending(id){return this.updateBatch(id,'sending');}markBatchSent(id){return this.updateBatch(id,'sent');}markBatchFailed(id,message){return this.updateBatch(id,'failed',message);} + markBatchSending(id){const batch=this.getBatch(id);for(const key of batch?.orderVersionKeys||[]){const order=this.get(key);if(!order)throw new OrderWorkflowError('ORDER_NOT_FOUND','批次关联订单不存在。');this.assertUniqueTask(order);}return this.updateBatch(id,'sending');}markBatchSent(id){return this.updateBatch(id,'sent');}markBatchFailed(id,message){return this.updateBatch(id,'failed',message);} updateBatch(id,status,error=null){const saved=this.batches.get(id);if(!saved)throw new OrderWorkflowError('BATCH_NOT_FOUND','批次不存在。');const allowed={prepared:['sending','failed'],sending:['sent','unknown'],failed:['sending','failed'],unknown:[]};if(!allowed[saved.status]?.includes(status))throw new OrderWorkflowError('INVALID_BATCH_STATE','当前批次不能执行此操作。');const batch={...clone(saved),status,error,updatedAt:this.clock().toISOString()};if(status==='sending'||status==='failed')batch.attempts=(batch.attempts||0)+1;const orders=batch.orderVersionKeys.map(key=>this.get(key)).filter(Boolean);for(const order of orders){order.status=status==='failed'?'batched':status;order.notification.status=status;order.steps.notification={status,batchId:id,...(error?{error}:{})};}this.saveGraph(orders,[batch]);return clone(batch);} markBatchUnknown(id,message){return this.updateBatch(id,'unknown',String(message));} resolveBatch(id,{resolution,note},actor){const saved=this.getBatch(id);if(!saved||!['unknown','failed'].includes(saved.status))throw new OrderWorkflowError('RESOLUTION_INVALID','只能核验结果不明或明确失败的批次。');if(!['sent','retry'].includes(resolution)||typeof note!=='string'||note.trim().length<5)throw new OrderWorkflowError('RESOLUTION_INVALID','请填写至少 5 字的核验依据。');const batch={...saved,status:resolution==='sent'?'sent':'prepared',resolution,verification:{actor,note:note.trim(),at:this.clock().toISOString()}};if(resolution==='retry')batch.attempts=0;const orders=batch.orderVersionKeys.map(key=>this.get(key)).filter(Boolean);for(const order of orders){order.status=resolution==='sent'?'sent':'batched';order.notification.status=resolution==='sent'?'sent':'reserved';order.steps.notification={status:order.status,batchId:id};}this.saveGraph(orders,[batch]);return clone(batch);} diff --git a/tests/bpm-dynamicarea.test.cjs b/tests/bpm-dynamicarea.test.cjs new file mode 100644 index 0000000..497f29d --- /dev/null +++ b/tests/bpm-dynamicarea.test.cjs @@ -0,0 +1,43 @@ +'use strict'; +const test=require('node:test');const assert=require('node:assert/strict'); +const {loadPlaywright,browserOptions}=require('../src/runtime.cjs'); +const {hydrateReadonlyDocument}=require('../src/bpm-readonly-form.cjs'); +const remarkTable='OFR_WY_ProductRequirementInfo_Remark',materialTable='OFR_WY_Review_Struct_MaterialChange'; +const remarksHTML=`
`; +const materialHTML=`
结构物料
STATIC FOOTER
`; +const materialRow=(index)=>({attribute:index%2?'change':'new',MaterialNew:'NEW-'+index,MaterialAmount:index+1,MaterialChangeContent:'CHANGE-'+index,MaterialOld:'OLD-'+index,MaterialChange_ECN:index%2?'销单BOM':'产品BOM',MaterialChange_Sealed:index%2?'':'需封样',MaterialChange_SealedTime:'DATE-'+index}); + +async function fixture(t){const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const context=await browser.newContext({javaScriptEnabled:false}),page=await context.newPage(),requests=[];await context.route('**/*',route=>{requests.push(route.request().url());return route.abort();});return async(html,tables,fieldsOnly=false)=>{requests.length=0;await page.setContent(html);return {...await page.evaluate(hydrateReadonlyDocument,{tables,fieldsOnly}),requests:[...requests]};};} +const backend=(TableName,Rows)=>({TableName,Rows,FormTable:true}); + +test('declared 0,1 remarks template preserves each backend row and blank data has zero detail rows',{timeout:30000},async t=>{ + const hydrate=await fixture(t); + for(const count of [0,1,9]){const rows=Array.from({length:count},(_,index)=>({Remark:'REMARK-'+index})),result=await hydrate(remarksHTML,[backend(remarkTable,rows)]);assert.equal(result.blocker,undefined);assert.equal((result.snapshot.html.match(/{ + const hydrate=await fixture(t); + for(const count of [0,1,3]){const rows=Array.from({length:count},(_,index)=>materialRow(index)),result=await hydrate(materialHTML,[backend(materialTable,rows)]);assert.equal(result.blocker,undefined);assert.equal((result.snapshot.html.match(/{ + const hydrate=await fixture(t),rows=[{Remark:'ONE'},{Remark:'TWO'}]; + const invalid=[remarksHTML.replace('dynamicarea="0,1"','dynamicarea="3,1"'),remarksHTML.replace('dynamicarea="0,1"','dynamicarea="0,2"'),remarksHTML.replace('dynamicarea="0,1"','dynamicarea="-1,1"'),remarksHTML.replace('TableName:'+remarkTable,'TableName:OTHER'),remarksHTML.replace('Remark->'+remarkTable+'.Remark','Remark->OTHER.Remark'),remarksHTML.replace('',''),remarksHTML.replace('',''),remarksHTML.replace('',''),remarksHTML.replace('',''),remarksHTML.replace('','
')]; + for(const html of invalid){const result=await hydrate(html,[backend(remarkTable,rows)]);assert.ok(result.blocker,'must reject '+html.slice(0,130));} +}); + +test('duplicate checkbox choices require matching type distinct explicit values and an unambiguous backend selection',{timeout:30000},async t=>{ + const hydrate=await fixture(t),rows=[materialRow(0),materialRow(1)]; + for(const html of [materialHTML.replace('value="销单BOM"','value="产品BOM"'),materialHTML.replace('type="checkbox" value="销单BOM"','type="text" value="销单BOM"'),materialHTML.replace('value="销单BOM"','')]){const result=await hydrate(html,[backend(materialTable,rows)]);assert.ok(result.blocker);} + const unknown=await hydrate(materialHTML,[backend(materialTable,[{...materialRow(0),MaterialChange_ECN:'unknown-choice'},materialRow(1)])]);assert.ok(unknown.blocker); + const comma=await hydrate(materialHTML,[backend(materialTable,[{...materialRow(0),MaterialChange_ECN:'产品BOM,销单BOM'}])]);assert.ok(comma.blocker); + const array=await hydrate(materialHTML,[backend(materialTable,[{...materialRow(0),MaterialChange_ECN:['产品BOM','销单BOM']}])]);assert.equal(array.blocker,undefined);assert.equal((array.snapshot.html.match(/☑/g)||[]).length,3); +}); + +test('undeclared generic single-row templates do not expand and fieldsOnly remains unchanged',{timeout:30000},async t=>{ + const hydrate=await fixture(t),tables=[backend(remarkTable,[{Remark:'ONE'},{Remark:'TWO'}])];assert.ok((await hydrate(remarksHTML.replace('dynamicarea="0,1"',''),tables)).blocker);const fields=await hydrate(remarksHTML,tables,true);assert.equal(fields.snapshot,null);assert.equal(fields.blocker,undefined); +}); + +test('dynamic row expansion never evaluates hidden expressions or executes page scripts',{timeout:30000},async t=>{ + const hydrate=await fixture(t),html=remarksHTML.replace('',''),result=await hydrate(html,[backend(remarkTable,[{Remark:'ONE'},{Remark:'TWO'}])]);assert.equal(result.blocker,undefined);assert.doesNotMatch(result.snapshot.html,/',result=await hydrate(html);assert.equal(result.blocker,undefined);assert.equal(await page.evaluate(()=>globalThis.PAGE_EXECUTED),undefined);assert.deepEqual(requests,[]);const fields=await hydrate('
'+missingRadios+'
',undefined,true);assert.equal(fields.snapshot,null);assert.equal(fields.blocker,undefined); +}); diff --git a/tests/bpm-notification-source.test.cjs b/tests/bpm-notification-source.test.cjs new file mode 100644 index 0000000..2ca9637 --- /dev/null +++ b/tests/bpm-notification-source.test.cjs @@ -0,0 +1,28 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict'); +const {normalizeNotificationTask,BpmNotificationClient}=require('../src/bpm-notification-source.cjs'); +const raw={taskId:'100',processInstanceId:'200',processName:'海外运营订单评审',activityName:'订单专员(生效)',processVersion:'3.2',startTime:'2026-10-22T13:00:00+08:00',processInstanceSubject:'第一行\n第二行',executionPointerId:'https://bpm.skyworthdigital.com/sso/ssologin.aspx?'+new URLSearchParams({ReturnUrl:'/YZSoft/Forms/Process.aspx?tid=200&pid=100',todo_token:'EPHEMERAL-TEST',todo_account:'fixture'})}; +test('notification normalization retains real task identity and raw summary without inventing revision',()=>{ + const row=normalizeNotificationTask(raw,'todo-v4');assert.equal(row.source,'todo-v4');assert.equal(row.taskId,'100');assert.equal(row.processInstanceId,'200');assert.equal(row.tid,'200');assert.equal(row.pid,'100');assert.equal(row.subject,'第一行\n第二行');assert.equal(row.processVersion,'3.2');assert.equal(Object.hasOwn(row,'revision'),false);assert.equal(JSON.stringify(row).includes('EPHEMERAL-TEST'),false);assert.equal(new URL(row.detailUrl).pathname,'/YZSoft/Forms/Process.aspx'); +}); +test('notification entry cache cannot be reused for a different task or changed node',()=>{ + const client=new BpmNotificationClient();const row=client.normalize(raw,'todo-v4');assert.match(client.entryFor(row),/todo_token=/);assert.throws(()=>client.entryFor({...row,activityName:'其他节点'}));assert.throws(()=>client.entryFor({...row,taskId:'other'})); +}); +test('notification links reject an unrelated host and explicit form/list identity conflicts',()=>{ + assert.throws(()=>normalizeNotificationTask({...raw,executionPointerId:'https://evil.example/approve?tid=200&pid=100'},'todo-v4')); + assert.throws(()=>normalizeNotificationTask({...raw,tid:'999'},'todo-v4')); + assert.throws(()=>normalizeNotificationTask({...raw,executionPointerId:raw.executionPointerId+'&action=approve'},'todo-v4')); +}); +test('session manager verifies a fresh real notification before using its ephemeral readonly entry',async t=>{ + const fs=require('node:fs'),os=require('node:os'),path=require('node:path'),{BpmSessionManager}=require('../src/bpm-session-manager.cjs');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-task-source-'));const manager=new BpmSessionManager({stateDir:dir});t.after(async()=>{await manager.shutdown();fs.rmSync(dir,{recursive:true,force:true});});const row=normalizeNotificationTask(raw,'todo-v4'),connection={id:'c',owner:'owner',status:'connected'},principal={user:{username:'owner',role:'operator'},sessionId:'s'}; + manager.vault=()=>({read:async()=>({storageState:{cookies:[],origins:[]}})});const client={scan:async()=>[row],entryFor:()=>raw.executionPointerId};manager.notificationClientFactory=()=>client;manager.detailReader=async input=>({readOnly:input.readonlyData===true,node:input.nodeName,urlRedacted:!input.detailUrl.includes('evil.example')}); + const result=await manager.captureOrderDetail(connection,principal,row);assert.equal(result.readOnly,true);assert.equal(result.node,'订单专员(生效)'); + await assert.rejects(()=>manager.captureOrderDetail(connection,principal,{...row,activityName:'变更后的节点'}),/变化|不一致/); + client.scan=async()=>[{...row,subject:'后台已更新的标题'}];await assert.rejects(()=>manager.captureOrderDetail(connection,principal,row),/变化|不一致/); + client.scan=async()=>[];await assert.rejects(()=>manager.captureOrderDetail(connection,principal,row),/不存在|不在/); +}); +test('two BPM accounts never share ephemeral notification SSO entries',async t=>{ + const fs=require('node:fs'),os=require('node:os'),path=require('node:path'),{BpmSessionManager}=require('../src/bpm-session-manager.cjs'),dir=fs.mkdtempSync(path.join(os.tmpdir(),'bpm-account-cache-')),manager=new BpmSessionManager({stateDir:dir});t.after(async()=>{await manager.shutdown();fs.rmSync(dir,{recursive:true,force:true});});const row=normalizeNotificationTask(raw,'todo-v4'),principal={user:{username:'owner',role:'operator'},sessionId:'s'},created=[]; + manager.vault=()=>({read:async()=>({storageState:{cookies:[],origins:[]}})});manager.notificationClientFactory=id=>{created.push(id);return {scan:async()=>[row],entryFor:()=>id};};manager.detailReader=async input=>({entry:input.detailUrl}); + const [a,b]=await Promise.all(['a','b'].map(id=>manager.captureOrderDetail({id,owner:'owner',status:'connected'},principal,row)));assert.equal(a.entry,'a');assert.equal(b.entry,'b');assert.deepEqual(created.sort(),['a','b']); +}); diff --git a/tests/bpm-readonly-form.test.cjs b/tests/bpm-readonly-form.test.cjs new file mode 100644 index 0000000..45c1bac --- /dev/null +++ b/tests/bpm-readonly-form.test.cjs @@ -0,0 +1,74 @@ +'use strict'; +const test=require('node:test');const assert=require('node:assert/strict'); +const {loadPlaywright,browserOptions}=require('../src/runtime.cjs'); +const {parseEntryURL,loadForm,loadData,flattenTables}=require('../src/bpm-readonly-form.cjs'); +const {captureDetail}=require('../src/bpm-order-detail.cjs'); +const origin='https://bpm.skyworthdigital.com'; +const processURL=origin+'/YZSoft/Forms/Process.aspx?tid=1001&pid=2001'; +const finalURL=origin+'/YZSoft/Forms/XForm/海外运营订单评审V13.aspx?tid=1001&pid=2001'; +const entryURL=origin+'/sso/ssologin.aspx?'+new URLSearchParams({ReturnUrl:'/YZSoft/Forms/Process.aspx?tid=1001&pid=2001',todo_token:'EPHEMERAL-TOKEN',todo_account:'fixture'}); +const reply=(status,body='',location)=>({status:()=>status,headers:()=>location?{location}:{},body:async()=>Buffer.from(typeof body==='string'?body:JSON.stringify(body))}); +const formTables=[{TableName:'OFR_WY_Applicant',FormTable:true,Rows:[{OrderNum:'000123',SN:'SN-1',Revision:3,Optional:null}]},{TableName:'OFR_WY_BInfo',FormTable:true,Rows:[{CustomerName:'示例客户'}]}]; +const formHTML='
订单
客户
'; + +test('entry validator permits only explicit SSO Process and final form identities',()=>{ + assert.equal(parseEntryURL(entryURL).tid,'1001');assert.equal(parseEntryURL(processURL).pid,'2001');assert.equal(parseEntryURL(finalURL).processVersion,'V13'); + for(const url of [entryURL+'&action=approve',entryURL+'&todo_token=duplicate',entryURL.replace('ReturnUrl=','other='),processURL+'&tid=9',processURL.replace('https:','http:'),processURL.replace('bpm.skyworthdigital.com','evil.example'),origin+'/sso/ssologin.aspx?'+new URLSearchParams({ReturnUrl:'https://evil.example/',todo_token:'EPHEMERAL-TOKEN',todo_account:'fixture'})])assert.throws(()=>parseEntryURL(url)); +}); + +test('form loader follows only SSO Process same-identity XForm and never retains the ephemeral URL',async()=>{ + const calls=[],responses=[reply(302,'',processURL),reply(302,'',finalURL),reply(200,formHTML)]; + const loaded=await loadForm({get:async(url,options)=>{calls.push({url,options});return responses.shift();}},entryURL); + assert.equal(loaded.url.href,new URL(finalURL).href);assert.equal(loaded.bytes.toString(),formHTML);assert.deepEqual(calls.map(call=>call.options.maxRedirects),[0,0,0]);assert.equal(JSON.stringify(loaded).includes('EPHEMERAL-TOKEN'),false); +}); + +test('form redirects cannot change ids, skip Process or leave the verified origin',async()=>{ + for(const location of [finalURL,processURL.replace('pid=2001','pid=999'),origin+'/YZSoft/Forms/Process.aspx?tid=1001&pid=2001&action=read','https://evil.example/form']){ + const calls=[];await assert.rejects(()=>loadForm({get:async url=>{calls.push(url);return reply(302,'',location);}},entryURL));assert.equal(calls.length,1); + } + await assert.rejects(()=>loadForm({get:async()=>reply(302,'',finalURL.replace('pid=2001','pid=999'))},processURL)); +}); + +test('DataProvider generates only GetFormProcessData PID XML with redirects disabled',async()=>{ + const calls=[];const tables=await loadData({post:async(url,options)=>{calls.push({url,options});return reply(200,{success:true,Tables:formTables});}},new URL(finalURL)); + assert.equal(tables.length,2);assert.equal(calls[0].url,origin+'/YZSoft/BPM/XMLService/DataProvider.ashx');assert.equal(calls[0].options.data,'GetFormProcessData2001');assert.equal(calls[0].options.maxRedirects,0); + await assert.rejects(()=>loadData({post:async()=>{throw Error('must not call');}},new URL(finalURL.replace('pid=2001','pid=bad')))); + await assert.rejects(()=>loadData({post:async()=>reply(302,'','https://evil.example/')},new URL(finalURL)),error=>error.status===401); + await assert.rejects(()=>loadData({post:async()=>reply(200,{success:true,Tables:[{TableName:'X',FormTable:true,Rows:[null]}]})},new URL(finalURL))); + await assert.rejects(()=>loadData({post:async()=>{throw Error('must not call');}},new URL(finalURL+'&method=Approve'))); + await assert.rejects(()=>loadData({post:async()=>reply(200,{success:true,Tables:[]})},new URL(processURL))); +}); + +test('raw backend values and multiple detail rows remain explicit and conflicting duplicate paths block',()=>{ + const result=flattenTables([...formTables,{TableName:'Detail',FormTable:true,Rows:[{Qty:2},{Qty:7}]}]);assert.equal(result.fields['OFR_WY_Applicant.Revision'],3);assert.equal(result.fields['OFR_WY_Applicant.Optional'],null);assert.deepEqual(result.fields['Detail.Qty'],[2,7]);assert.equal(result.fields['Detail[0].Qty'],2);assert.equal(result.fields['Detail[1].Qty'],7);assert.equal(result.sources['Detail[1].Qty'].rowIndex,1); + assert.throws(()=>flattenTables([{TableName:'T',FormTable:true,Rows:[{Id:1}]},{TableName:'T',FormTable:true,Rows:[{Id:2}]}]),/冲突|多个/); +}); + +function transport(html=formHTML,tables=formTables,entry=finalURL){ + const calls=[];let disposed=false; + return {calls,get disposed(){return disposed;},async get(url,options){calls.push({method:'GET',url,options});if(entry===entryURL&&url===new URL(entryURL).href)return reply(302,'',processURL);if(url===processURL)return reply(302,'',finalURL);if(url===new URL(finalURL).href)return reply(200,html);throw Error('Unexpected read');},async post(url,options){calls.push({method:'POST',url,options});return reply(200,{success:true,Tables:tables});},async dispose(){disposed=true;}}; +} + +test('explicit readonlyData mode hydrates a static form and keeps list version/node provenance',{timeout:30000},async()=>{ + const request=transport(),result=await captureDetail({storageState:{cookies:[],origins:[]},detailUrl:finalURL,processName:'海外运营订单评审',nodeName:'订单专员(生效)',listProcessVersion:'portal-revision-17',readonlyData:true,requestFactory:async()=>request,browserFactory:()=>loadPlaywright().chromium.launch(browserOptions())}); + assert.equal(result.detail.fields['OFR_WY_Applicant.OrderNum'],'000123');assert.equal(result.detail.fields['OFR_WY_Applicant.Revision'],3);assert.equal(result.detail.formVersion,'V13');assert.equal(result.detail.processVersion,'V13');assert.equal(result.detail.listProcessVersion,'portal-revision-17');assert.equal(result.detail.nodeName,'订单专员(生效)');assert.equal(result.detail.nodeSource,'list.activityName');assert.deepEqual(result.detail.processSteps,[]);assert.equal(result.detail.fieldSources['OFR_WY_Applicant.OrderNum'].source,'DataProvider.GetFormProcessData'); + assert.match(result.snapshot.html,/000123/);assert.match(result.snapshot.html,/示例客户/);assert.match(result.snapshot.styles.join('\n'),/border-collapse/);assert.doesNotMatch(result.snapshot.html,/UNTRUSTED-HIDDEN|DOM-PASSWORD|call.method==='POST').length,1);assert.equal(request.disposed,true); +}); + +test('ambiguous multirow PDF does not flatten rows but explicit fieldsOnly can retain backend evidence',{timeout:30000},async()=>{ + const html='
',tables=[{TableName:'Detail',FormTable:true,Rows:[{Qty:2},{Qty:7}]}]; + const options={storageState:{cookies:[],origins:[]},detailUrl:finalURL,processName:'海外运营订单评审',nodeName:'订单专员(生效)',readonlyData:true,browserFactory:()=>loadPlaywright().chromium.launch(browserOptions())}; + await assert.rejects(()=>captureDetail({...options,requestFactory:async()=>transport(html,tables)}),/多行|明细|快照/); + const result=await captureDetail({...options,fieldsOnly:true,requestFactory:async()=>transport(html,tables)});assert.deepEqual(result.detail.fields['Detail.Qty'],[2,7]);assert.equal(result.snapshot,null);assert.equal(result.detail.fields['Detail[1].Qty'],7); +}); + +test('complete repeated rows hydrate in order without replacing every row with the same value',{timeout:30000},async()=>{ + const html='
',tables=[{TableName:'Detail',FormTable:true,Rows:[{Qty:2,Model:'A'},{Qty:7,Model:'B'}]}]; + const result=await captureDetail({storageState:{cookies:[],origins:[]},detailUrl:finalURL,processName:'海外运营订单评审',nodeName:'订单专员(生效)',readonlyData:true,requestFactory:async()=>transport(html,tables),browserFactory:()=>loadPlaywright().chromium.launch(browserOptions())});assert.match(result.snapshot.html,/>2<.*>A<.*>7<.*>B{ + const request=transport(formHTML,formTables,entryURL),result=await captureDetail({storageState:{cookies:[],origins:[]},detailUrl:entryURL,processName:'海外运营订单评审',nodeName:'订单专员(生效)',readonlyData:true,requestFactory:async()=>request,browserFactory:()=>loadPlaywright().chromium.launch(browserOptions())}); + assert.equal(result.detailUrl,new URL(finalURL).href);assert.doesNotMatch(JSON.stringify(result),/EPHEMERAL-TOKEN|todo_token|todo_account|DOM-PASSWORD|UNTRUSTED-HIDDEN/);assert.deepEqual(request.calls.map(call=>call.method),['GET','GET','GET','POST']);assert.equal(result.detail.fields['OFR_WY_Applicant.Optional'],null); + const failing={get:async()=>{throw Error(entryURL);}};await assert.rejects(()=>loadForm(failing,entryURL),error=>!error.message.includes('EPHEMERAL-TOKEN')&&!error.message.includes('todo_token')); +}); diff --git a/tests/bpm-row-scope.test.cjs b/tests/bpm-row-scope.test.cjs new file mode 100644 index 0000000..100cef2 --- /dev/null +++ b/tests/bpm-row-scope.test.cjs @@ -0,0 +1,44 @@ +'use strict'; +const test=require('node:test');const assert=require('node:assert/strict'); +const {loadPlaywright,browserOptions}=require('../src/runtime.cjs'); +const {hydrateReadonlyDocument,flattenTables}=require('../src/bpm-readonly-form.cjs'); +const child='OFR_WY_ProductRequirementInfo_Remark',master='OFR_WY_Applicant'; +const html=`
`; +const table=(TableName,Rows)=>({TableName,Rows,FormTable:true}); +async function fixture(t){const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const context=await browser.newContext({javaScriptEnabled:false}),page=await context.newPage();await context.route('**/*',route=>route.abort());return async(tables,{fieldsOnly=false,markup=html}={})=>{await page.setContent(markup);return page.evaluate(hydrateReadonlyDocument,{tables,fieldsOnly});};} + +test('persisted current-task rows are displayed without applying the unrelated lookup Original filter',{timeout:30000},async t=>{ + const hydrate=await fixture(t),rows=Array.from({length:9},(_,index)=>({TaskID:111,Remark:'CURRENT-'+index})),tables=[table(master,[{TaskID:111,TaskID_Original:999}]),table(child,rows)],result=await hydrate(tables); + assert.equal(result.blocker,undefined);assert.equal((result.snapshot.html.match(/{ + const hydrate=await fixture(t),parent=table(master,[{TaskID:111,TaskID_Original:999}]); + for(const rows of [[{TaskID:111,Remark:'CURRENT'},{TaskID:999,Remark:'UNRELATED'}],[{TaskID:111,Remark:'CURRENT'},{Remark:'MISSING TASK'}],[{TaskID:111,Remark:'CURRENT'},{TaskID:null,Remark:'NULL TASK'}]]){const tables=[parent,table(child,rows)],result=await hydrate(tables);assert.match(result.blocker,/TaskID|作用域|主表/);const raw=flattenTables(tables);assert.equal(raw.fields[child+'[1].Remark'],rows[1].Remark);const fieldsOnly=await hydrate(tables,{fieldsOnly:true});assert.equal(fieldsOnly.blocker,undefined);assert.equal(fieldsOnly.snapshot,null);} +}); + +test('multirow TaskID association requires one explicit scalar current Applicant TaskID',{timeout:30000},async t=>{ + const hydrate=await fixture(t),detail=table(child,[{TaskID:111,Remark:'ONE'},{TaskID:111,Remark:'TWO'}]); + for(const tables of [[detail],[table(master,[{TaskID_Original:111}]),detail],[table(master,[{TaskID:[111]}]),detail],[table(master,[{TaskID:111},{TaskID:111}]),detail],[table(master,[{TaskID:111}]),table('Other_Applicant',[{TaskID:111}]),detail]])assert.match((await hydrate(tables)).blocker,/TaskID|作用域|主表/); +}); + +test('numeric and string representations of the same explicit TaskID preserve current detail rows',{timeout:30000},async t=>{ + const hydrate=await fixture(t),result=await hydrate([table(master,[{TaskID:'111',TaskID_Original:'999'}]),table(child,[{TaskID:111,Remark:'ONE'},{TaskID:'111',Remark:'TWO'}])]);assert.equal(result.blocker,undefined);assert.match(result.snapshot.html,/ONE.*TWO/s); +}); + +test('scope validation also applies to already expanded undeclared detail rows',{timeout:30000},async t=>{ + const hydrate=await fixture(t),markup=`
`,result=await hydrate([table(master,[{TaskID:111}]),table(child,[{TaskID:111,Remark:'CURRENT'},{TaskID:999,Remark:'UNRELATED'}])],{markup});assert.match(result.blocker,/TaskID|作用域|主表/); +}); + +test('one wrong-task child row cannot bypass the current master guard',{timeout:30000},async t=>{ + const hydrate=await fixture(t),tables=[table(master,[{TaskID:111,TaskID_Original:999}]),table(child,[{TaskID:999,Remark:'EXTERNAL SINGLE ROW'}])],result=await hydrate(tables);assert.match(result.blocker,/TaskID|作用域|主表/);assert.equal(flattenTables(tables).fields[child+'.Remark'],'EXTERNAL SINGLE ROW');const fieldsOnly=await hydrate(tables,{fieldsOnly:true});assert.equal(fieldsOnly.blocker,undefined);assert.equal(fieldsOnly.snapshot,null); +}); + +test('single current child empty child and unrelated no-TaskID lookup remain usable',{timeout:30000},async t=>{ + const hydrate=await fixture(t),markup='
'+html.replace(/^|<\/form>$/g,'')+'
',lookup=table('UnrelatedLookup',[{Name:'STATIC LOOKUP'}]),parent=table(master,[{TaskID:111,TaskID_Original:999}]); + for(const rows of [[{TaskID:111,Remark:'CURRENT SINGLE ROW'}],[]]){const result=await hydrate([parent,table(child,rows),lookup],{markup});assert.equal(result.blocker,undefined);assert.match(result.snapshot.html,/111/);assert.match(result.snapshot.html,/STATIC LOOKUP/);if(rows.length)assert.match(result.snapshot.html,/CURRENT SINGLE ROW/);} +}); + +test('one wrong-task ordinary bound table is blocked even without a dynamicarea marker',{timeout:30000},async t=>{ + const hydrate=await fixture(t),markup='
',tables=[table(master,[{TaskID:111}]),table('OFR_WY_BInfo',[{TaskID:999,CustomerName:'EXTERNAL CUSTOMER'}])];assert.match((await hydrate(tables,{markup})).blocker,/TaskID|作用域|主表/); +}); diff --git a/tests/order-pipeline.test.cjs b/tests/order-pipeline.test.cjs index 5af9d3c..b463778 100644 --- a/tests/order-pipeline.test.cjs +++ b/tests/order-pipeline.test.cjs @@ -20,8 +20,8 @@ test('archive failure creates no notification and retry reuses successful PDF',a const f=fixture(t,{archiveFails:true});await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'test'});let order=f.workflow.listOrders()[0];assert.equal(order.status,'archive_error');assert.equal(order.notification,undefined);assert.equal(f.calls.pdf,1); await f.pipeline.retry(order.versionKey,{user:{username:'owner',role:'operator'},sessionId:'test'});order=f.workflow.get(order.versionKey);assert.equal(order.status,'notification_pending');assert.equal(f.calls.pdf,1);assert.equal(f.calls.detail,1);assert.equal(f.calls.archive,2); }); -test('missing business version creates a persistent blocked candidate without generating a PDF',async t=>{ - const f=fixture(t);f.pipeline.manager.captureOrderDetail=async()=>({detail:{...d,businessVersion:undefined}});await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'test'});assert.equal(f.workflow.listOrders().length,0);assert.equal(f.pipeline.arrivals()[0].status,'blocked');assert.match(f.pipeline.arrivals()[0].error,/业务版本/);assert.equal(f.calls.pdf,0); +test('an authoritative BPM task proceeds without fabricating a missing business revision',async t=>{ + const f=fixture(t);f.pipeline.manager.captureOrderDetail=async()=>({detail:{...d,businessVersion:undefined},snapshot:{html:'
真实采集快照
',styles:[]}});await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'test'});assert.equal(f.workflow.listOrders().length,1);assert.equal(f.workflow.listOrders()[0].businessVersion,null);assert.equal(f.workflow.listOrders()[0].status,'notification_pending');assert.equal(f.calls.pdf,1); }); test('sample URL cannot splice another order into a stored arrival even if flow and node match',async t=>{ const f=fixture(t);await assert.rejects(()=>f.pipeline.checkRule('r',{connectionId:'c',source:'portal-v4',taskId:'t',detailUrl:a.detailUrl.replace('tid=1','tid=77')},{user:{username:'owner',role:'admin'},sessionId:'s'}),/关联|不一致/);assert.equal(f.calls.detail,0); @@ -39,10 +39,31 @@ test('recovery reconstructs an arrival link after a crash between order insert a const f=fixture(t),order=f.workflow.identify({arrival:a,detail:d}).order;f.workflow.start(order.versionKey);f.workflow.markDetailReady(order.versionKey);f.workflow.update(order.versionKey,draft=>{draft.status='interrupted';}); await f.pipeline.retry(order.versionKey,{user:{username:'owner',role:'admin'},sessionId:'s'});assert.equal(f.workflow.get(order.versionKey).status,'notification_pending');assert.equal(f.calls.pdf,1);assert.equal(f.pipeline.arrivals()[0].orderVersionKey,order.versionKey); }); + +test('recovery retains a persisted legacy key while verifying unchanged task fields',async t=>{ + const f=fixture(t),order=f.workflow.identify({arrival:a,detail:d}).order; + f.workflow.orders.delete(order.versionKey);order.versionKey='legacy-version-key';order.status='interrupted';f.workflow.orders.set(order.versionKey,order);f.store.putOrder(order); + await f.pipeline.retry(order.versionKey,{user:{username:'owner',role:'admin'},sessionId:'s'}); + assert.equal(f.workflow.get('legacy-version-key').status,'notification_pending');assert.equal(f.calls.pdf,1);assert.equal(f.workflow.listOrders().length,1); +}); + +test('retry refuses ambiguous legacy tasks even when PDF and archive are already successful',async t=>{ + const f=fixture(t);await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'s'}); + const first=f.workflow.listOrders()[0];f.workflow.update(first.versionKey,draft=>{draft.status='notification_error';}); + const duplicate={...structuredClone(first),versionKey:'legacy-second-key'};f.workflow.orders.set(duplicate.versionKey,duplicate); + await assert.rejects(()=>f.pipeline.retry(first.versionKey,{user:{username:'owner',role:'admin'},sessionId:'s'}),error=>error.code==='TASK_IDENTITY_CONFLICT'); + assert.equal(f.workflow.get(first.versionKey).status,'notification_error');assert.equal(f.calls.pdf,1);assert.equal(f.calls.archive,1); +}); test('test recipient guard rejects either a production To or Cc and cannot be disabled by config',t=>{ const {pipeline}=fixture(t);assert.throws(()=>pipeline.assertRecipients({to:['someone@company.example'],cc:[]}));assert.throws(()=>pipeline.assertRecipients({to:['2639266652@qq.com'],cc:['someone@company.example']}));pipeline.assertRecipients({to:['2639266652@qq.com'],cc:[]}); assert.throws(()=>pipeline.saveConfig({...pipeline.config(),allowedRecipients:['someone@company.example']})); }); +test('reading real notification tasks persists source evidence without exporting or sending',async t=>{ + const f=fixture(t),{BpmScanStore}=require('../src/bpm-scan-store.cjs'),scan=new BpmScanStore(path.join(f.store.dir,'scan'));try{ + f.pipeline.scanStore=scan;f.pipeline.manager.scanOrderTasks=async()=>[{...a,source:'todo-v4',arrivalDay:'2026-10-22',recordKind:'notification-task',tid:'1',pid:'2',processInstanceId:'2',processVersion:'V1'}]; + const result=await f.pipeline.scanSource('c',{user:{username:'owner',role:'operator'},sessionId:'s'});assert.equal(result.added,1);assert.equal(scan.getArrival('c','todo-v4','t').recordKind,'notification-task');assert.equal(f.calls.pdf,0);assert.equal(f.calls.mail,0); + }finally{scan.close();} +}); async function sendingFixture(t,result){ const f=fixture(t);f.pipeline.clock=()=>new Date('2026-10-22T03:00:00Z');await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'test'}); f.store.setMeta('config',{...f.pipeline.config(),enabled:true,sendEnabled:true,channelId:'mail',since:'2026-10-22T00:00:00Z'}); diff --git a/tests/order-workflow-plan.test.cjs b/tests/order-workflow-plan.test.cjs index 0abf603..471ba3d 100644 --- a/tests/order-workflow-plan.test.cjs +++ b/tests/order-workflow-plan.test.cjs @@ -9,7 +9,7 @@ const arrival={source:'portal-v4',taskId:'task-plan-1',processName:'海外运营 const rule={id:'rule-plan',enabled:true,processName:'海外运营订单评审',nodeName:'订单专员(生效)',productLine:'海外运营',templateId:'tpl-overseas',adapters:{V13:{orderNo:'order',serialNo:'serial',productCode:'product',modelFull:'full',modelShort:'short',customer:'customer',brief:{source:'arrival',path:'subject'}}}}; const detail={tid:'100001',pid:'900001',processVersion:'V13',processInstanceId:'900001',businessVersion:'BV-1',nodeName:'订单专员(生效)',fields:{order:'000123',serial:'SERIAL-EXAMPLE',product:'MODEL-EXAMPLE-001',full:'MODEL-EXAMPLE-001',short:'MODEL-EXAMPLE',customer:'示例客户'},processSteps:[{name:'订单专员(生效)',status:'处理中'}]}; -test('order version requires tid pid current order number and explicit business version',()=>{ +test('order identity retains tid pid current order number and reports upstream revision only when present',()=>{ const workflow=new OrderWorkflow();publish(workflow,rule,arrival,detail); const result=workflow.identify({arrival,detail}); assert.equal(result.order.tid,'100001'); @@ -17,7 +17,7 @@ test('order version requires tid pid current order number and explicit business assert.equal(result.order.businessVersion,'BV-1'); assert.equal(result.order.brief,'列表摘要原文'); assert.equal(result.order.businessTimeSource,'list.receivedAt'); - for(const key of ['tid','pid','businessVersion']){ + for(const key of ['tid','pid']){ const missing={...detail};delete missing[key]; assert.throws(()=>workflow.identify({arrival,detail:missing}),error=>error.code==='VERSION_MISSING'); } diff --git a/tests/order-workflow-task-identity.test.cjs b/tests/order-workflow-task-identity.test.cjs new file mode 100644 index 0000000..c1b82bc --- /dev/null +++ b/tests/order-workflow-task-identity.test.cjs @@ -0,0 +1,45 @@ +'use strict'; +const test=require('node:test');const assert=require('node:assert/strict'); +const {OrderWorkflow}=require('../src/order-workflow.cjs'); +const rule={id:'r',enabled:true,status:'published',processName:'P',nodeName:'N',productLine:'C',templateId:'tpl'}; +const mapping={orderNo:'no',serialNo:'sn',productCode:'product',modelFull:'model',modelShort:'short',customer:'customer',brief:{source:'arrival',path:'subject'}}; +const arrival={source:'portal-v4',taskId:'task-1',processName:'P',activityName:'N',subject:'原文\n保留换行',arrivedAt:'2026-10-22T01:00:00Z'}; +const detail={tid:'1',pid:'2',processName:'P',nodeName:'N',processVersion:'V1',fields:{no:'000123',sn:'S',product:'P',model:'M',short:'M',customer:'C',quantity:'10'}}; +test('a real BPM notification task can be processed without inventing a business revision',()=>{ + const w=new OrderWorkflow(),result=w.identify({arrival,detail,mapping,rule});assert.equal(result.status,'matched');assert.equal(result.order.businessVersion,null);assert.equal(result.order.versionSource,'bpm.taskId');assert.equal(result.order.brief,'原文\n保留换行'); + assert.equal(w.identify({arrival:{...arrival,connectionId:'another-authorized-connection'},detail,mapping,rule}).status,'duplicate');assert.equal(w.listOrders().length,1); +}); +test('a new BPM task is a new notification even when order number and form identifiers are unchanged',()=>{ + const w=new OrderWorkflow(),first=w.identify({arrival,detail,mapping,rule}).order,second=w.identify({arrival:{...arrival,taskId:'task-2'},detail,mapping,rule}).order;assert.notEqual(first.versionKey,second.versionKey);assert.equal(first.orderNo,second.orderNo);assert.equal(w.listOrders().length,2); +}); +test('changing a field or reported revision on the same task never creates another notification',()=>{ + const w=new OrderWorkflow();w.identify({arrival,detail,mapping,rule});assert.throws(()=>w.identify({arrival,detail:{...detail,fields:{...detail.fields,quantity:'20'}},mapping,rule}),e=>e.code==='VERSION_CONTENT_CONFLICT'); + assert.throws(()=>w.identify({arrival,detail:{...detail,businessVersion:'new-reported-value'},mapping,rule}),e=>e.code==='VERSION_CONTENT_CONFLICT');assert.equal(w.listOrders().length,1); +}); +test('an old configured revision path is optional when BPM does not supply it',()=>{ + const w=new OrderWorkflow(),o=w.identify({arrival,detail,mapping:{...mapping,businessVersion:'not-present'},rule}).order;assert.equal(o.businessVersion,null);assert.equal(o.versionSource,'bpm.taskId'); +}); + +function conflictingLegacyWorkflow(){ + const w=new OrderWorkflow(),original=w.identify({arrival,detail,mapping,rule}).order; + const first={...structuredClone(original),versionKey:'legacy-revision-a'},second={...structuredClone(original),versionKey:'legacy-revision-b'}; + const workflow=new OrderWorkflow({store:{orders:()=>[first,second]}}); + return {workflow,first,second}; +} + +test('multiple legacy versions for the same task require confirmation before any new archive',()=>{ + const {workflow:w,first}=conflictingLegacyWorkflow(); + assert.throws(()=>w.identify({arrival,detail,mapping,rule}),e=>e.code==='TASK_IDENTITY_CONFLICT'); + assert.throws(()=>w.start(first.versionKey),e=>e.code==='TASK_IDENTITY_CONFLICT'); + assert.equal(w.listOrders().length,2); +}); + +test('ambiguous legacy tasks cannot enter a new notification batch or send an already frozen batch',()=>{ + const {workflow:w,first,second}=conflictingLegacyWorkflow(); + for(const order of [first,second])w.update(order.versionKey,draft=>{draft.status='notification_pending';draft.notification={status:'pending',occurredAt:'2026-10-22T01:00:00Z',brief:'original',templateId:'tpl'};}); + assert.throws(()=>w.freezeBatches('2026-10-22T03:00:00Z',{groups:{C:{to:['2639266652@qq.com'],cc:[]}},templates:{tpl:{id:'tpl',version:1,subject:'{{产品线}}',text:'{{订单列表}}'}}}),e=>e.code==='EMPTY_BATCH'); + assert.equal(w.listBatches().length,0);assert.equal(w.get(first.versionKey).notification.status,'blocked'); + w.batches.set('old-batch',{id:'old-batch',status:'prepared',orderVersionKeys:[first.versionKey]}); + assert.throws(()=>w.markBatchSending('old-batch'),e=>e.code==='TASK_IDENTITY_CONFLICT'); + assert.equal(w.getBatch('old-batch').status,'prepared'); +}); diff --git a/tests/order-workflow-ui.test.cjs b/tests/order-workflow-ui.test.cjs index d614046..002722e 100644 --- a/tests/order-workflow-ui.test.cjs +++ b/tests/order-workflow-ui.test.cjs @@ -111,3 +111,10 @@ test('admin can restore an exhausted failed batch with a required recovery note' test('old arrivals explain that an arbitrary detail link cannot establish the order identity',{timeout:30000},async t=>{ const {page,base}=await fixture(t);await page.goto(base+'/#rules');await page.getByRole('button',{name:'编辑规则',exact:true}).click({timeout:3000});await page.getByText('历史记录若未保存 tid/pid 或权威详情链接,请先重新扫描获取来源依据,不能用任意链接绑定订单。',{exact:true}).waitFor({timeout:1000}); }); + + +test('operator can explicitly read real notification tasks without enabling processing or sending',{timeout:30000},async t=>{ + const {page,state,base}=await fixture(t,'operator');await page.goto(base+'/#order-rules');await page.getByRole('heading',{name:'分类规则',exact:true}).waitFor({timeout:3000}); + await page.getByLabel('通知任务来源连接',{exact:true}).selectOption('conn-1');await page.getByRole('button',{name:'读取通知任务',exact:true}).click(); + await page.getByText('只读采集完成',{exact:false}).waitFor({timeout:3000});assert.equal(state.calls.some(call=>call.path==='/api/order-workflow/source-scan'&&call.body.connectionId==='conn-1'),true);assert.equal(state.calls.some(call=>call.path==='/api/order-workflow/settings'),false); +}); diff --git a/web/order-workflow.js b/web/order-workflow.js index fcba41c..c803e5c 100644 --- a/web/order-workflow.js +++ b/web/order-workflow.js @@ -17,6 +17,18 @@ window.OrderWorkflowViews=(()=>{ let savedRules=result.rules||[],edit=null,check=null,busy=false,selectedArrival='',checkRevision=0;const admin=user.role==='admin',arrivals=records.arrivals||[]; container.innerHTML=`

分类规则

${admin?'':''}
分类规则决定流程到达后的产品线、模板和收件群组。保存草稿后,检查真实只读样本,再发布规则。
`; const host=container.querySelector('#workflow-rule-editor'); + if(user.role!=='viewer'){ + const sourceForm=document.createElement('form');sourceForm.className='card card-body mb-3'; + sourceForm.innerHTML=`
读取 BPM 实际通知任务,供分类样本检查使用。
`; + container.prepend(sourceForm); + sourceForm.onsubmit=async event=>{event.preventDefault();const button=sourceForm.querySelector('button');if(button.disabled)return;button.disabled=true;const status=sourceForm.querySelector('[data-source-result]'); + try{const result=await view.request('/order-workflow/source-scan',{connectionId:sourceForm.querySelector('select').value});const refreshed=await view.request('/order-workflow');if(!view.active())return; + const previous=arrivals[Number(selectedArrival)];arrivals.splice(0,arrivals.length,...(refreshed.arrivals||[]));selectedArrival=previous?String(arrivals.findIndex(row=>row.source===previous.source&&row.taskId===previous.taskId&&row.connectionId===previous.connectionId)):'';if(selectedArrival==='-1')selectedArrival=''; + const select=host.querySelector('#rule-sample');if(select){select.innerHTML=''+arrivals.map((row,index)=>``).join('');select.value=selectedArrival;} + check=null;++checkRevision;const publish=host.querySelector('#rule-publish');if(publish)publish.disabled=true;host.querySelector('#rule-check-result')?.replaceChildren();status.textContent=`只读采集完成,共 ${result.seen||0} 条通知任务。`; + }catch(error){if(view.active()&&error.name!=='AbortError')status.textContent=error.message;}finally{if(view.active())button.disabled=false;} + }; + } function renderList(){container.querySelector('#workflow-rule-list').innerHTML=`
${savedRules.map((rule,index)=>``).join('')||''}
流程 / 当前节点产品线 / 模板发布状态
${esc(rule.processName)}
${esc(rule.nodeName)}
${esc(rule.productLine)}
${esc(available.templates?.find(template=>template.id===rule.templateId)?.subject||rule.templateId)}
${rule.published||rule.status==='published'?'已发布':'草稿'}
${rule.enabled?'已启用':'已停用'}
${admin?``:''}
暂无分类规则
`;container.querySelectorAll('[data-rule-edit]').forEach(button=>button.onclick=()=>{if(!busy&&canLeave())openEditor(savedRules[Number(button.dataset.ruleEdit)]);});} function openEditor(rule){ edit=structuredClone(rule);check=null;++checkRevision;dirty=false; @@ -38,7 +50,7 @@ window.OrderWorkflowViews=(()=>{ async function orders(container,isActive=()=>true){ const view=begin(isActive),data=await view.request('/order-workflow');if(!view.active())return;const records=data.orders||[],blockedCandidates=(data.blockedArrivals||[]).filter(row=>!row.orderVersionKey&&['blocked','error','interrupted'].includes(row.status)); - container.innerHTML=`

订单任务

${records.length} 个订单版本
显示 BPM 来源、归档与通知的处理结果;缺字段和结果不明时保留具体阻断原因。
${records.map((order,index)=>``).join('')||''}
订单 / 业务版本BPM 来源 / 分类PDF / 归档通知 / 批次
${esc(order.orderNo||'待确认订单号')}
${esc(order.businessVersion||order.version||'待确认业务版本')}
${stateBadge(order.status)}
${esc(order.source)} · ${esc(order.taskId)}
${esc(order.productLine)} · ${esc(order.ruleId)}
tid=${esc(order.tid)} · pid=${esc(order.pid)}
${stateBadge(order.steps?.pdf?.status||order.pdf?.status)}
${stateBadge(order.steps?.archive?.status||order.archive?.status)}
${stateBadge(order.notification?.status||order.steps?.notification?.status)}
${esc(order.notification?.batchId||order.steps?.notification?.batchId||'—')}
暂无订单任务。已发布分类规则匹配到完整的订单版本后会在此显示。

待确认的 BPM 到达记录

${blockedCandidates.length} 条
这些记录尚未建立订单版本;请先根据阻断原因补全规则或来源依据,再重新采集。
${blockedCandidates.map((candidate,index)=>``).join("")||``}
流程 / 当前节点来源 / 任务号阻断原因
${esc(candidate.processName)}
${esc(candidate.activityName||candidate.nodeName)}
${esc(candidate.source)}
${esc(candidate.taskId)}
候选记录:${esc(candidate.id)}
${esc(candidate.error||"尚未确认")}
${esc(candidate.code||"UNKNOWN")}
${user.role!=="viewer"?``:""}
暂无阻断的候选记录
`; + container.innerHTML=`

订单任务

${records.length} 个订单任务
显示 BPM 来源、归档与通知的处理结果;缺字段和结果不明时保留具体阻断原因。
${records.map((order,index)=>``).join('')||''}
订单 / 通知任务BPM 来源 / 分类PDF / 归档通知 / 批次
${esc(order.orderNo||'待确认订单号')}
${esc(order.businessVersion||order.version||order.taskId||'—')}
${stateBadge(order.status)}
${esc(order.source)} · ${esc(order.taskId)}
${esc(order.productLine)} · ${esc(order.ruleId)}
tid=${esc(order.tid)} · pid=${esc(order.pid)}
${stateBadge(order.steps?.pdf?.status||order.pdf?.status)}
${stateBadge(order.steps?.archive?.status||order.archive?.status)}
${stateBadge(order.notification?.status||order.steps?.notification?.status)}
${esc(order.notification?.batchId||order.steps?.notification?.batchId||'—')}
暂无订单任务。已发布分类规则匹配到 BPM 通知任务后会在此显示。

待确认的 BPM 到达记录

${blockedCandidates.length} 条
这些记录尚未建立订单任务;请先根据阻断原因补全规则或来源依据,再重新采集。
${blockedCandidates.map((candidate,index)=>``).join("")||``}
流程 / 当前节点来源 / 任务号阻断原因
${esc(candidate.processName)}
${esc(candidate.activityName||candidate.nodeName)}
${esc(candidate.source)}
${esc(candidate.taskId)}
候选记录:${esc(candidate.id)}
${esc(candidate.error||"尚未确认")}
${esc(candidate.code||"UNKNOWN")}
${user.role!=="viewer"?``:""}
暂无阻断的候选记录
`; container.querySelectorAll('[data-candidate-retry]').forEach(button=>button.onclick=async()=>{if(button.disabled)return;button.disabled=true;const candidate=blockedCandidates[Number(button.dataset.candidateRetry)],message=container.querySelector('#workflow-candidate-message');try{await view.request('/order-workflow/arrivals/'+encodeURIComponent(candidate.id)+'/retry',{});if(view.active()){message.hidden=false;notice(message,'候选记录重试已提交,请刷新查看结果。','success');}}catch(error){if(view.active()&&error.name!=='AbortError'){message.hidden=false;notice(message,error.message,'danger');button.disabled=false;}}}); let detailRequest=0;container.querySelectorAll('[data-order-detail]').forEach(button=>button.onclick=async()=>{const request=++detailRequest,host=container.querySelector('#workflow-order-detail'),order=records[Number(button.dataset.orderDetail)];button.disabled=true;try{const response=await view.request('/order-workflow/order/'+encodeURIComponent(order.versionKey));if(!view.active()||request!==detailRequest)return;drawDetail(host,response.order||response);}catch(error){if(view.active()&&error.name!=='AbortError')notify(error.message,'danger');}finally{if(view.active())button.disabled=false;}}); function drawDetail(host,order){const sources=Object.entries(order.sources||{}),steps=Object.entries(order.steps||{}),retry=user.role!=='viewer'&&['detail_error','pdf_error','archive_error','notification_error','interrupted'].includes(order.status);host.innerHTML=`

订单详情 · ${esc(order.orderNo||'待确认')}

${stateBadge(order.status)} ${esc(order.processName)} · ${esc(order.nodeName)}
${order.error?`
${esc(order.error)}
`:''}

步骤与阻断原因

${steps.map(([name,step])=>`
${esc({discovery:'BPM 来源',detail:'详情采集',pdf:'PDF',archive:'SMB 归档',notification:'通知'}[name]||name)} ${stateBadge(step.status)}${step.error?`
${esc(step.error)}
`:''}${step.jobId||step.archiveId||step.path?`
${esc(step.jobId||step.archiveId||'')} ${esc(step.path||'')}
`:''}
`).join('')}

字段来源

${sources.map(([name,source])=>``).join('')}
字段来源值
${esc(name)}${esc(source.path)}${esc(source.value)}
${order.businessTime?`
业务时间:${esc(formatDate(order.businessTime))} · ${esc(order.businessTimeSource)}
`:''}${retry?'':''}
`;host.querySelector('#order-detail-close').onclick=()=>{++detailRequest;host.replaceChildren();};host.querySelector('#workflow-retry-order')?.addEventListener('click',async event=>{const button=event.currentTarget;button.disabled=true;try{await view.request('/order-workflow/orders/'+encodeURIComponent(order.versionKey)+'/retry',{});if(view.active())notice(host.querySelector('#order-detail-message'),'重试已提交,请刷新查看步骤结果。','success');}catch(error){if(view.active()&&error.name!=='AbortError')notice(host.querySelector('#order-detail-message'),error.message,'danger');}finally{if(view.active())button.disabled=false;}});}