diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 4d84c27..c9e0ace 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,6 +1,18 @@ # 开发交接(2026-10-23) -## 当前规则与本机测试状态 +## 当前:Excel规则已接入测试执行链 + +本机运行 `%LOCALAPPDATA%/OrderNotificationAutomationReleases/test-excel-import-20261023-14e48339`,代码树 `14e483398ff3d44f4f0948009e6cbac2c5033092`。原76版本保留作回退,正式服务机未操作。 + +- Excel预览后可“确认导入并应用到测试”;编辑则“保存草稿 → 应用到测试”。直接复用既有匹配、详情采集、PDF归档、批次与调度器,不增加第二套业务链。规则仍严格按Excel流程和节点,不添加节点别名。 +- 测试固定邮箱、空Cc、无附件、桌面目录、运行ID/基线及计划不变。应用不回填历史,不重做旧订单和冻结批次;有未完成的旧版本任务时拒绝切换,先完成或人工处理。正式发布路径保留。 +- 默认 `npm test` 改跑29项核心业务验收,全部通过,约74秒;旧完整测试保留为 `npm run test:full`,不再每次运行。首次全量曾因下载等待超时失败、第二轮由用户主动中止,均不计通过。导出已改用官方单文件包,保留Excel格式。 +- 更新前官方完整备份并自动验证:`%LOCALAPPDATA%/OrderNotificationAutomationBackups/before-excel-execution-20261023-151155`。更新后账号、连接、全部规则/适配器/样本、旧订单/批次/原始回执、SMTP配置/游标/发信记录逐项哈希一致。532个候选文件与对应Git树一致。 +- 实机页面已刷新,原始Excel识别15类,“确认导入并应用到测试”可用;仅预览,没有在实机确认导入或应用。本轮没有真实发信或办理BPM。自动通知仍等待真实合格订单的PDF/归档检查;缺少的流程适配与已办通知补漏仍未完成,不声称15类真实业务闭环已验收。 + +操作说明见[业务配置与Excel导入](business-configuration.md),证据见[整合验收记录](bpm-native-integration-verification-2026-10-23.md)。下文为此前原生代码切换的历史记录,进程入口以前述新版本为准。 + +## 早前原生整合切换记录(76bbac02版本) 本节为当前交接基准,下文旧日期内容仅保留历史。源码位于 Z 盘项目目录(同一 UNC 共享目录),分支为 codex/smb-storage。当前业务代码提交1848a6c,已经推送;本机运行已切到经过逐文件核对的本地副本,原工作树代码保持不动。 @@ -23,7 +35,7 @@ 更新后观察同一业务进程持续运行超过十分钟,未新增重启;295份对账线索已完成,17条真实待办读取成功,原82条到达记录的键、首见时间及来源保留。新建业务批次0,本轮没有新增真实邮件。数字是交接时快照,后台后续对账会继续更新。 -13:03/13:09 的17条实时待办均未命中Excel通知节点,这是当时待办快照,不能据此判断今天没有应通知订单。随后根据用户提供的当天邮件,在已办列表及只读流程步骤中找到三笔:两笔试产类订单已于11:24/11:25提交Excel的确切通知节点;一笔海外返工订单于11:26结束名为“订单通知书”的节点,与Excel的“订单专员(订单通知书)”不一致,等待业务确认,不擅自增加别名。严格测试运行基线为12:12,三笔都已离开通知待办。 +13:03/13:09 的17条实时待办均未命中Excel通知节点,这是当时待办快照,不能据此判断今天没有应通知订单。随后根据用户提供的当天邮件,在已办列表及只读流程步骤中找到三笔:两笔试产类订单已于11:24/11:25提交Excel的确切通知节点;一笔海外返工订单于11:26结束名为“订单通知书”的节点,与Excel的“订单专员(订单通知书)”不一致,用户已选择继续按Excel,不建立节点别名。严格测试运行基线为12:12,三笔都已离开通知待办。 当前执行器只读当前待办,历史采样只用于字段配置,缺少已办通知任务的补偿发现。已验证的 ProcessStep 只返回节点名称和办理完成时间,没有通知任务ID或节点到达时间;不能用流程实例ID、行号、完成时间构造通知任务。下一步需核实可获取原通知任务ID/到达时间的只读来源,再设计受控历史对账与持久通知快照;历史纳入和补发范围须明确,原已发送/结果不明任务仍禁止自动重演。人工邮件跨类别合并不覆盖Excel分类:这两类仍分别使用分类模板。详见[本轮整合验证](bpm-native-integration-verification-2026-10-23.md)。 diff --git a/docs/bpm-native-integration-verification-2026-10-23.md b/docs/bpm-native-integration-verification-2026-10-23.md index 8538407..b08f9a7 100644 --- a/docs/bpm-native-integration-verification-2026-10-23.md +++ b/docs/bpm-native-integration-verification-2026-10-23.md @@ -42,7 +42,7 @@ |---|---|---|---|---| | A | 试产订单评审 | 订单专员(订单通知书) | 11:25 提交 | 第15行“试产订单通知书”,流程+节点确切匹配 | | B | 中试样机制作申请 | 订单专员(订单通知书)-海外 | 11:24 提交 | 第15行“试产订单通知书”,流程+节点确切匹配 | -| C | 海外返工订单评审 | 订单通知书 | 11:26 结束 | 第2行“海外订单通知书”包含该流程,但要求“订单专员(订单通知书)”;节点不一致,未确认前保持阻断 | +| C | 海外返工订单评审 | 订单通知书 | 11:26 结束 | 第2行“海外订单通知书”包含该流程,但要求“订单专员(订单通知书)”;节点不一致,按用户决定继续严格依据Excel,不作等价映射 | 三笔列表摘要与用户邮件列出的订单号、型号及其他列示字段一致,历史详情也取得真实订单号字段。人工邮件将试产类与海外类合在“海外订单通知书”中;这不是修改Excel分类或跨类别合并模板的授权,仍按既定分类分别汇总。 @@ -50,8 +50,21 @@ 已核验的流程步骤响应包含 `RowNum`、`NodeName`、`HandlerAccount`、`FinishAt`、`SelAcount`、`Comments`,没有独立通知任务ID或节点到达时间。`TaskID`查询参数在此处指流程实例ID,不可当通知任务ID;`RowNum`不是稳定任务键,`FinishAt`不是到达时间。历史列表的 `startTime` 是流程发起时间,也不可作通知到达时间。不能把这些记录伪装成实时待办事件、重写业务时间或自动补发。 -下一阶段需要先取得可保留原通知任务ID和到达时间的只读数据来源,设计有重叠窗口的历史对账与通知快照持久化,并明确历史发现的人工处理/纳入范围;其中样本C的节点等价关系必须由业务负责人确认。该设计尚未实施,本次未改规则、执行代码、基线或发送范围。完整原始业务证据、真实订单与样本对应关系只保存在本机忽略目录 `output/business-flow-test/morning-mail-{audit,steps,local}-20261023.json`,不进入Git。 +下一阶段需要先取得可保留原通知任务ID和到达时间的只读数据来源,设计有重叠窗口的历史对账与通知快照持久化,并明确历史发现的人工处理/纳入范围;用户已选择样本C继续严格按Excel阻断,本次不建立节点等价映射。该设计尚未实施,本次未改规则、执行代码、基线或发送范围。完整原始业务证据、真实订单与样本对应关系只保存在本机忽略目录 `output/business-flow-test/morning-mail-{audit,steps,local}-20261023.json`,不进入Git。 ## 尚未验收项 15 类配置检查不代表 15 类真实业务闭环。仍缺 `零售国内返工订单更改评审` 的字段适配器;对应流程阻断。两笔历史邮件样本的字段与 BPM 历史列表一致,但没有发送时刻的通知节点证据。其余类别的实际通知到达、逐类 PDF 视觉核对、计划批次实际收件及正式 SMB 存储仍须分别验收。助手会话操作期间切换范围的已知竞争不属于本轮修复;顺序夹具通过不能证明该并发问题已解决。 + + +## Excel到执行链的最小交付 + +用户要求缩小测试并快速完成。本轮保留已有协调器、归档器与发送器,只补齐显式规则应用:Excel导入可原子保存并应用到当前受限测试;页面编辑保存后可应用。复用真实服务端字段证据,精确流程节点匹配;邮箱、Cc、附件、测试目录、运行身份和起始时间锁定。应用不启动发送、归档或历史补发。正式发布内容不改写。 + +有未冻结旧版本订单、未完成任务或缺失关联订单时拒绝应用,避免现有单类别窗口批次混入两个规则版本。已冻结旧批次通过此前批准快照校验继续完成,不重渲染、不重复入队。缺适配的流程保留明确缺项,并阻断相应订单。服务端管理员权限、草稿及运行版本检查与整次导入回滚保持。 + +默认 `npm test` / `npm run test:business` 改为29项核心验收,全部通过,耗时73956毫秒。包括原表形态与导出回导、15类逐类编辑、认证HTTP导入/应用、规则实际驱动识别、无归档不入批次、归档后分类汇总、模拟SMTP隔离投递、结果不明禁止重发、原冻结批次继续完成、重启、版本冲突、整次回滚和缺适配阻断。旧全量保留 `npm run test:full`。首次997项全量995通过/1失败/1跳过,失败是下载事件等待20秒;改用官方ExcelJS单文件包后专项通过,格式保留。第二轮全量由用户主动中止,不计通过;未用核心29项冒充全量结果。独立复审无剩余P1/P2。 + +本机更新到 `test-excel-import-20261023-14e48339`,候选532个文件逐字节核对代码树一致;依赖锁与已验证安装一致,无依赖升级。官方备份已自动验完整性,更新后13组配置与业务证据哈希全部一致。实机原Excel预览15类,应用按钮可用;未确认实际导入、未新增业务批次或发信,不办理BPM。页面证明存于本机忽略目录。 + +该交付接通规则生效与已有执行链,不等于所有真实流程已验收。已办通知原任务ID/到达时间来源、缺失流程字段适配,以及逐类真实PDF/邮件实收和正式SMB仍为独立缺口。 diff --git a/docs/business-configuration.md b/docs/business-configuration.md index 796ddcd..da4631c 100644 --- a/docs/business-configuration.md +++ b/docs/business-configuration.md @@ -1,6 +1,6 @@ -#模板 `{{日期}}` 使用订单原始 `event.receivedAt` 的北京时间日期;跨日按订单出现顺序去重,不能改用批次截止、纳入或创建日期。只有引用该变量的模板要求该时间完整;缺失阻断新冻结,不重写旧批次。 +# 业务配置与 Excel 导入 - 后续业务资料整理表 +模板 `{{日期}}` 使用订单原始 `event.receivedAt` 的北京时间日期;跨日按订单出现顺序去重,不能改用批次截止、纳入或创建日期。只有引用该变量的模板要求该时间完整;缺失阻断新冻结,不重写旧批次。 2026-10-23 当前业务权威:唯一来源文件是 `source/订单通知书邮件发送信息.xls`。系统只采用该文件原始 15 类的精确流程和精确节点;不使用“生效”别名,BOM 节点排除,海外 4 个流程只允许 `订单专员(订单通知书)`。产品线和模板 ID 由类别配置显式指定,Excel 不提供这些字段;测试产品线暂用 rule.name,并明确标为测试标签。固定 QQ、空 Cc、Desktop 目录是受控测试覆盖值,不是原 Excel 的正式目的地;正式原始目的地不提交 Git。 @@ -8,10 +8,22 @@ BPM 只读,不已阅、不审批、不保存;本轮受控测试仅归档到本机 Desktop 测试目录。发送固定为北京时间 11:00、17:00:To `2639266652@qq.com`,Cc 为空,附件为空;PDF 必须先归档但不附在邮件中。按类别、绑定模板和发送窗口分别成批;无新增不发空邮件,错过窗口不即时追赶或回填。当前服务端待办只有在新鲜提供器扫描后才能纳入带 `admittedAt` 的不可变清单,原始 `receivedAt` 不修改,冻结和发送前都要复核任务仍存在且内容新鲜。 -当前本机已切换到已核对的本地测试副本,原数据与输出路径保留,正式服务机未更新。最终全量990项:989通过、0失败、1项可选ZCode测试跳过;13:03/13:09的17条待办快照均未匹配,不代表当天没有应通知任务。当天邮件反查已确认两笔试产类订单在11:24/11:25办理Excel确切通知节点,另有一笔海外返工节点名称与Excel不同,待业务确认。当前只扫描待办,尚无已办通知任务补偿读取;历史步骤只提供完成时间而缺少通知任务ID/到达时间,不能伪造执行事件或自动补发。仍按Excel分类分批,不照抄人工邮件的跨类合并。PDF及归档运行能力待首笔合格任务实检,计划意图已启用,页面仍显示受阻。15类真实闭环未验收,零售国内返工订单更改评审仍缺适配器。详细证据和待确认项以[本轮整合验证](bpm-native-integration-verification-2026-10-23.md)为准。 +当前本机已更新为Excel规则执行桥版本,原数据与输出路径保留,正式服务机未更新。本轮核心回归29项全部通过,约74秒;此前基础整合全量990项为历史验收记录,并非本轮全量结果。13:03/13:09的17条待办快照均未匹配,不代表当天没有应通知任务。当天邮件反查已确认两笔试产类订单在11:24/11:25办理Excel确切通知节点,另有一笔海外返工节点名称与Excel不同,用户已选择继续按Excel保持阻断。当前只扫描待办,尚无已办通知任务补偿读取;历史步骤只提供完成时间而缺少通知任务ID/到达时间,不能伪造执行事件或自动补发。仍按Excel分类分批,不照抄人工邮件的跨类合并。PDF及归档运行能力待首笔合格任务实检,计划意图已启用,页面仍显示受阻。15类真实闭环未验收,零售国内返工订单更改评审仍缺适配器。详细证据和待确认项以[本轮整合验证](bpm-native-integration-verification-2026-10-23.md)为准。 不自动回填历史窗口:仅有提供器证明且已纳入不可变清单的待办,可保留到下一合法 11:00/17:00 窗口;非纳入历史任务保持 missedWindow 人工核验。已冻结 prepared 批次只有 30 分钟发送宽限,超时不得自动发送。 +## Excel 导入与规则编辑 + +在“业务设置 → 分类通知规则 → 导入 Excel”选择原始 `.xls`,或选择“下载当前规则 Excel”得到的 `.xlsx`。上传限制为2 MiB,分类表最多200行、20列;表内公式须先转成值。读取只继承明确的纵向合并单元格,不把原表下方的说明或图片当成分类行。 + +预览必须先核对每行的流程与节点配对、邮件主题、归档位置、主送/抄送和变更项,再确认导入。流程与节点按原始源表读取器相同的NFKC规则规范化全角/半角字符;不把“生效”“订单通知书”等不同名称解释成别名。原始表中多个流程、多个节点按明确列出的组合导入;如只适用部分组合,应使用导出表的“流程节点配对”逐行维护。 + +原表的“附件:PDF”文字和旧模板“附带PDF=是”不启用邮件附件,预览给出提示;当前业务始终PDF仅归档、邮件无附件。只写目录名称的行保留为待完善草稿,在规则编辑第03步选择实际存储位置。邮箱或规则内容不合格时,整次导入不可提交;分类不明确或重复必须在表内修正。导入只更新已存在的类别,优先按“类别编号”定位,原表按现有分类名称/主题定位,不猜测新增类别。 + +可仅保存草稿,也可在受限测试启用时选择“确认导入并应用到测试”,原子地保存并更新执行规则。管理员逐类编辑后,先保存,再点击“应用到测试”;新任务由现有协调器自动采集、归档及进入分类批次。刷新保留已保存值。下载当前规则保留稳定类别编号和明确流程节点配对,修改分类名称后仍可回导。另一个管理员在预览后修改规则时,提交返回版本冲突,不能部分覆盖;同一预览重复确认只提交一次。仅保存草稿不改变执行。显式应用只改变新任务使用的规则,不直接归档、创建订单批次或发送邮件,也不恢复已暂停的发送计划。 + +草稿、正式发布版本与当前测试执行版本分别保存,测试规则由同一份导入/编辑草稿生成,不另建处理器。应用时固定覆盖为既有测试邮箱、空Cc、无附件及每类桌面目录,测试基线和发送计划不变。若本类别尚有未冻结的旧版本订单或未完成任务,应用会拒绝,须先完成或人工处理,避免版本混发;已冻结的原批次保留原快照,仍可按原规则完成。缺字段适配的流程明确阻断,不用其他流程字段凑数。暂停测试后恢复普通验证/发布控件,发布仍须真实样本检查,且不会自行恢复测试发送。当前用户选择继续严格按Excel,不为海外返工流程增加节点等价映射。 + 以下“业务通知来源”字段表属于既有通用来源接口的历史资料模板,不用于上述 BPM Excel 订单工作流;通用接口的版本回退语义不用于 BPM 任务身份。 ## 存储服务器 diff --git a/docs/design-requirements.md b/docs/design-requirements.md index e3068e1..83de1b1 100644 --- a/docs/design-requirements.md +++ b/docs/design-requirements.md @@ -1,6 +1,6 @@ -#模板 `{{日期}}` 使用订单原始 `event.receivedAt` 的北京时间日期;跨日按订单出现顺序去重,不能改用批次截止、纳入或创建日期。只有引用该变量的模板要求该时间完整;缺失阻断新冻结,不重写旧批次。 +# 订单通知自动化:设计要求 - 订单通知自动化:设计要求 +模板 `{{日期}}` 使用订单原始 `event.receivedAt` 的北京时间日期;跨日按订单出现顺序去重,不能改用批次截止、纳入或创建日期。只有引用该变量的模板要求该时间完整;缺失阻断新冻结,不重写旧批次。 更新日期:2026-10-23。本文为当前设计要求入口;历史调研、旧根目录 pipeline 和阶段计划仅供追溯。业务规则调整须同步本文、实现与验收记录。 @@ -16,7 +16,7 @@ - 服务端历史待办只有在新鲜提供器扫描、精确流程/节点命中后才能纳入不可变允许清单;保存 `admittedAt`,原始 `receivedAt` 不改;冻结与发送前都必须复核当前存在和内容新鲜。 - 当前原生入口只有 `OrderExecutionCoordinator` 与 `OrderRuleDispatcher`。旧根目录 pipeline 未启动;本机已完成原生代码切换,正式服务机未更新。 -当前本机已切换到已核对的本地测试副本,原数据与输出路径保留,正式服务机未更新。最终全量990项:989通过、0失败、1项可选ZCode测试跳过;13:03/13:09的17条待办快照均未匹配,不代表当天没有应通知任务。当天邮件反查已确认两笔试产类订单在11:24/11:25办理Excel确切通知节点,另有一笔海外返工节点名称与Excel不同,待业务确认。当前只扫描待办,尚无已办通知任务补偿读取;历史步骤只提供完成时间而缺少通知任务ID/到达时间,不能伪造执行事件或自动补发。仍按Excel分类分批,不照抄人工邮件的跨类合并。PDF及归档运行能力待首笔合格任务实检,计划意图已启用,页面仍显示受阻。15类真实闭环未验收,零售国内返工订单更改评审仍缺适配器。详细证据和待确认项以[本轮整合验证](bpm-native-integration-verification-2026-10-23.md)为准。 +当前本机已更新为Excel规则执行桥版本,原数据与输出路径保留,正式服务机未更新。本轮核心回归29项全部通过,约74秒;此前基础整合全量990项为历史验收记录,并非本轮全量结果。13:03/13:09的17条待办快照均未匹配,不代表当天没有应通知任务。当天邮件反查已确认两笔试产类订单在11:24/11:25办理Excel确切通知节点,另有一笔海外返工节点名称与Excel不同,用户已选择继续按Excel保持阻断。当前只扫描待办,尚无已办通知任务补偿读取;历史步骤只提供完成时间而缺少通知任务ID/到达时间,不能伪造执行事件或自动补发。仍按Excel分类分批,不照抄人工邮件的跨类合并。PDF及归档运行能力待首笔合格任务实检,计划意图已启用,页面仍显示受阻。15类真实闭环未验收,零售国内返工订单更改评审仍缺适配器。详细证据和待确认项以[本轮整合验证](bpm-native-integration-verification-2026-10-23.md)为准。 ## 1. 产品目标与运行方式 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 b3bcd2e..1679245 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 @@ -1,12 +1,12 @@ -#模板 `{{日期}}` 使用订单原始 `event.receivedAt` 的北京时间日期;跨日按订单出现顺序去重,不能改用批次截止、纳入或创建日期。只有引用该变量的模板要求该时间完整;缺失阻断新冻结,不重写旧批次。 +# BPM 分类模板实施记录 - BPM 分类模板实施记录 +模板 `{{日期}}` 使用订单原始 `event.receivedAt` 的北京时间日期;跨日按订单出现顺序去重,不能改用批次截止、纳入或创建日期。只有引用该变量的模板要求该时间完整;缺失阻断新冻结,不重写旧批次。 用户于 2026-10-22 批准分类模板实施计划;以下 2026-10-23 权威规则覆盖早期草稿:唯一来源是 `source/订单通知书邮件发送信息.xls` 原始 15 类,严格按 Excel 流程和节点匹配;不使用“生效”别名,不含 BOM,海外 4 个流程仅 `订单专员(订单通知书)`。当前合并代码已完成本机测试切换,正式服务机未更新。 处理单位为 `source + portalSource + taskId`;缺失 revision 保持缺失,不伪造 0。旧 ID、冻结批次、已知 sent/unknown 回执保留且禁止重演。列表 `listVersion` 与表单 `formVersion` 分开,原始 `brief` 与字段证据原样保存;邮件展示层一单一行、从订单号开始,模板问候/说明/签名不变。BPM 只读,不已阅、不审批、不保存;本轮受控测试仅归档到本机 Desktop 测试目录。PDF 必须先归档,邮件固定 To `2639266652@qq.com`、Cc 为空、附件为空;按类别+绑定模板+窗口成批,11:00/17:00 北京时间,无新增不发空报,错过窗口不回填。 -当前本机已切换到已核对的本地测试副本,原数据与输出路径保留,正式服务机未更新。最终全量990项:989通过、0失败、1项可选ZCode测试跳过;13:03/13:09的17条待办快照均未匹配,不代表当天没有应通知任务。当天邮件反查已确认两笔试产类订单在11:24/11:25办理Excel确切通知节点,另有一笔海外返工节点名称与Excel不同,待业务确认。当前只扫描待办,尚无已办通知任务补偿读取;历史步骤只提供完成时间而缺少通知任务ID/到达时间,不能伪造执行事件或自动补发。仍按Excel分类分批,不照抄人工邮件的跨类合并。PDF及归档运行能力待首笔合格任务实检,计划意图已启用,页面仍显示受阻。15类真实闭环未验收,零售国内返工订单更改评审仍缺适配器。详细证据和待确认项以[本轮整合验证](bpm-native-integration-verification-2026-10-23.md)为准。既有sent/unknown、冻结内容和原始业务时间保留,BPM只读。 +当前本机已更新为Excel规则执行桥版本,原数据与输出路径保留,正式服务机未更新。本轮核心回归29项全部通过,约74秒;此前基础整合全量990项为历史验收记录,并非本轮全量结果。13:03/13:09的17条待办快照均未匹配,不代表当天没有应通知任务。当天邮件反查已确认两笔试产类订单在11:24/11:25办理Excel确切通知节点,另有一笔海外返工节点名称与Excel不同,用户已选择继续按Excel保持阻断。当前只扫描待办,尚无已办通知任务补偿读取;历史步骤只提供完成时间而缺少通知任务ID/到达时间,不能伪造执行事件或自动补发。仍按Excel分类分批,不照抄人工邮件的跨类合并。PDF及归档运行能力待首笔合格任务实检,计划意图已启用,页面仍显示受阻。15类真实闭环未验收,零售国内返工订单更改评审仍缺适配器。详细证据和待确认项以[本轮整合验证](bpm-native-integration-verification-2026-10-23.md)为准。既有sent/unknown、冻结内容和原始业务时间保留,BPM只读。 产品线和模板 ID 由类别配置显式指定,Excel 不提供这些字段;测试产品线暂用 rule.name,并明确标为测试标签。固定 QQ、空 Cc、Desktop 目录是受控测试覆盖值,不是原 Excel 的正式目的地;正式原始目的地不提交 Git。 diff --git a/docs/unattended-system-design.md b/docs/unattended-system-design.md index 1ba9d37..9b47949 100644 --- a/docs/unattended-system-design.md +++ b/docs/unattended-system-design.md @@ -8,7 +8,7 @@ 产品线和模板 ID 由类别配置显式指定,Excel 不提供这些字段;测试产品线暂用 rule.name,并明确标为测试标签。固定 QQ、空 Cc、Desktop 目录是受控测试覆盖值,不是原 Excel 的正式目的地;正式原始目的地不提交 Git。 -当前本机已切换到已核对的本地测试副本,原数据与输出路径保留,正式服务机未更新。最终全量990项:989通过、0失败、1项可选ZCode测试跳过;13:03/13:09的17条待办快照均未匹配,不代表当天没有应通知任务。当天邮件反查已确认两笔试产类订单在11:24/11:25办理Excel确切通知节点,另有一笔海外返工节点名称与Excel不同,待业务确认。当前只扫描待办,尚无已办通知任务补偿读取;历史步骤只提供完成时间而缺少通知任务ID/到达时间,不能伪造执行事件或自动补发。仍按Excel分类分批,不照抄人工邮件的跨类合并。PDF及归档运行能力待首笔合格任务实检,计划意图已启用,页面仍显示受阻。15类真实闭环未验收,零售国内返工订单更改评审仍缺适配器。详细证据和待确认项以[本轮整合验证](bpm-native-integration-verification-2026-10-23.md)为准。 +当前本机已更新为Excel规则执行桥版本,原数据与输出路径保留,正式服务机未更新。本轮核心回归29项全部通过,约74秒;此前基础整合全量990项为历史验收记录,并非本轮全量结果。13:03/13:09的17条待办快照均未匹配,不代表当天没有应通知任务。当天邮件反查已确认两笔试产类订单在11:24/11:25办理Excel确切通知节点,另有一笔海外返工节点名称与Excel不同,用户已选择继续按Excel保持阻断。当前只扫描待办,尚无已办通知任务补偿读取;历史步骤只提供完成时间而缺少通知任务ID/到达时间,不能伪造执行事件或自动补发。仍按Excel分类分批,不照抄人工邮件的跨类合并。PDF及归档运行能力待首笔合格任务实检,计划意图已启用,页面仍显示受阻。15类真实闭环未验收,零售国内返工订单更改评审仍缺适配器。详细证据和待确认项以[本轮整合验证](bpm-native-integration-verification-2026-10-23.md)为准。 ## 最终验收目标 diff --git a/package.json b/package.json index 8343017..b5dfe45 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,9 @@ "service:status": "node scripts/service.cjs status", "service:stop": "node scripts/service.cjs stop", "service:restart": "node scripts/service.cjs restart", - "test": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\"" + "test": "npm run test:business", + "test:business": "node --test --test-concurrency=1 tests/order-rules/excel-import-contract.test.cjs tests/order-rules/excel-execution-bridge.test.cjs tests/order-rules/excel-import-flow-ui.test.cjs tests/order-rules/scheduled-mail-policy.test.cjs", + "test:full": "node --test --test-concurrency=2 \"tests/**/*.test.cjs\"" }, "engines": { "node": ">=22.13" diff --git a/src/modules/order-rules/api.cjs b/src/modules/order-rules/api.cjs index 1a257a3..555bce1 100644 --- a/src/modules/order-rules/api.cjs +++ b/src/modules/order-rules/api.cjs @@ -34,7 +34,11 @@ async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,re result=orderRules.saveRestrictedTest(body,user); } else if(route==='/api/order-rules/import/preview')result=require('./import.cjs').previewImport(orderRules,body,actor); - else if(route==='/api/order-rules/import/commit')result=require('./import.cjs').commitImport(orderRules,body,actor,{mail}); + else if(route==='/api/order-rules/import/commit')result=require('./import.cjs').commitImport(orderRules,body,actor,{mail,user}); + else if(route==='/api/order-rules/restricted-test/apply'){ + for(const item of Array.isArray(body?.rules)?body.rules:[]){const record=orderRules.get('rules',item?.id);if(record)checkTemplates(mail,record.draft);} + result=orderRules.applyRestrictedDrafts(body,user); + } else if(route==='/api/order-rules/rules'){ const old=orderRules.get('rules',body?.id)?.draft; if(old)checkTemplates(mail,validateRule(body,old)); diff --git a/src/modules/order-rules/import-template.cjs b/src/modules/order-rules/import-template.cjs index 3c22e3a..0832675 100644 --- a/src/modules/order-rules/import-template.cjs +++ b/src/modules/order-rules/import-template.cjs @@ -1,6 +1,8 @@ 'use strict'; async function template(store){ - const Excel=require('exceljs'),book=new Excel.Workbook(),sheet=book.addWorksheet('分类规则'); + // This endpoint only needs the in-memory workbook API. The vendor bundle + // preserves formatting without hundreds of synchronous cold file loads. + const Excel=require('exceljs/dist/exceljs.min.js'),book=new Excel.Workbook(),sheet=book.addWorksheet('分类规则'); sheet.columns=['类别编号','分类名称','订单评审流程','电子流状态','流程节点配对','服务器存档地址','邮件命名','收件人','抄送人','附带PDF','文件名日期'].map(header=>({header,width:['收件人','流程节点配对'].includes(header)?60:28})); const dates={appDate:'申请日期',receivedAt:'接收日期',archiveDate:'归档日期'}; for(const {draft:r}of store.all('rules'))sheet.addRow([r.id,r.name,r.processNames.join('/'),r.nodeNames.join('/'),require('./scopes.cjs').scopesFor(r).map(s=>s.processName+' → '+s.nodeName).join('\n'),r.archiveDirectory,r.subjectPrefix,r.to.join('\n'),r.cc.join('\n'),r.attachPdf?'是':'否',dates[r.filenameDate]||'']); diff --git a/src/modules/order-rules/import.cjs b/src/modules/order-rules/import.cjs index f98f4d9..3184748 100644 --- a/src/modules/order-rules/import.cjs +++ b/src/modules/order-rules/import.cjs @@ -2,7 +2,9 @@ const crypto=require('node:crypto'); const {validateRule,addresses,fail}=require('./validation.cjs'); const {checkTemplates}=require('./template-validation.cjs'); -const split=value=>String(value||'').split(/[\n/+]/).map(v=>v.trim().replace(/^[“"「]|[”"」]$/g,'')).filter(Boolean); +// Match the authoritative source-workbook reader's canonical text, without +// treating different business node names as aliases. +const split=value=>String(value||'').normalize('NFKC').split(/[\n/+]/).map(v=>v.trim().replace(/^[“”"'「」]+|[“”"'「」]+$/g,'').trim()).filter(Boolean); function recipients(value){ const text=String(value||'').trim();if(!text)return [];if(!text.includes('@'))fail('收件人未识别到有效邮箱'); const parsed=require('nodemailer/lib/addressparser')(text.replace(/[,;\n]/g,',')),values=[]; @@ -26,15 +28,17 @@ function previewImport(store,input,actor){ const old=record.draft,processes=split(get('订单评审流程')),nodes=split(get('电子流状态'));if(!processes.length||!nodes.length)fail('流程名和节点名不能为空'); const prefix=subject.match(/^[【\[].+?[】\]]/)?.[0]||subject; let scopes=processes.flatMap(processName=>nodes.map(nodeName=>({processName,nodeName}))); - if(get('流程节点配对'))scopes=get('流程节点配对').split('\n').filter(v=>v.trim()).map(v=>{const pair=v.split('→').map(s=>s.trim());if(pair.length!==2||!pair.every(Boolean))fail('流程节点配对请按“流程名 → 节点名”每行一对填写');return {processName:pair[0],nodeName:pair[1]};}); + if(get('流程节点配对'))scopes=get('流程节点配对').split('\n').filter(v=>v.trim()).map(v=>{const pair=v.split('→').map(s=>s.normalize('NFKC').trim());if(pair.length!==2||!pair.every(Boolean))fail('流程节点配对请按“流程名 → 节点名”每行一对填写');return {processName:pair[0],nodeName:pair[1]};}); const candidate={...old,name:get('分类名称')||old.name,sourceRow:index+2,subjectPrefix:prefix,to:recipients(get('收件人')),scopes}; if(headers.includes('抄送人'))candidate.cc=recipients(get('抄送人')); if(headers.includes('服务器存档地址'))candidate.archiveDirectory=get('服务器存档地址'); if(headers.includes('文件名日期')){const dates={'申请日期':'appDate','接收日期':'receivedAt','归档日期':'archiveDate','':'',appDate:'appDate',receivedAt:'receivedAt',archiveDate:'archiveDate'};if(!Object.hasOwn(dates,get('文件名日期')))fail('文件名日期只支持申请日期、接收日期或归档日期');candidate.filenameDate=dates[get('文件名日期')];} - if(headers.includes('附带PDF')){const value=get('附带PDF');if(!['是','否','true','false'].includes(value))fail('附带PDF请填写是或否');candidate.attachPdf=['是','true'].includes(value);} - else if(headers.includes('邮件正文')){const value=get('邮件正文');if(/附件[::].*PDF/i.test(value))candidate.attachPdf=true;else if(/摘要信息/.test(value))candidate.attachPdf=false;else row.warnings.push('邮件正文描述未自动转换,保留原附件设置');} + if(headers.includes('附带PDF')){const value=get('附带PDF');if(!['是','否','true','false'].includes(value))fail('附带PDF请填写是或否');if(['是','true'].includes(value))row.warnings.push('PDF 仅归档,不附在通知邮件中;已忽略表内的附带PDF要求');} + else if(headers.includes('邮件正文')){const value=get('邮件正文');if(/PDF/i.test(value))row.warnings.push('PDF 仅归档,不附在通知邮件中;正文继续使用分类模板和BPM摘要');else if(!/摘要信息/.test(value))row.warnings.push('邮件正文描述未自动转换,保留原分类模板和摘要设置');} + candidate.attachPdf=false; candidate.adapterIds=[...new Set([...old.adapterIds,...store.adapters().filter(a=>a.verified&&processes.includes(a.processName)).filter(a=>!store.adapters().some(b=>b.id!==a.id&&b.verified&&b.processName===a.processName&&b.processVersion===a.processVersion)).map(a=>a.id)])]; Object.assign(candidate,validateRule(candidate,old),{version:old.version});row.candidate=candidate;row.version=old.version;row.recipientCount=candidate.to.length; + row.preview={scopes:structuredClone(candidate.scopes),subjectPrefix:candidate.subjectPrefix,archiveDirectory:candidate.archiveDirectory,to:[...candidate.to],cc:[...candidate.cc],attachPdf:false}; const labels={name:'分类名称',subjectPrefix:'邮件主题',to:'收件人',cc:'抄送人',archiveDirectory:'归档目录',attachPdf:'PDF附件',filenameDate:'文件名日期',scopes:'流程与节点',adapterIds:'BPM识别配置'}; for(const [key,label]of Object.entries(labels))if(JSON.stringify(old[key])!==JSON.stringify(candidate[key]))row.changes.push(label); if(!candidate.archiveDirectory.startsWith('\\\\'))row.warnings.push('表内仅有目录名称,请在第03步选择存储服务器和目录'); @@ -43,19 +47,21 @@ function previewImport(store,input,actor){ }catch(error){row.issues.push(error.message);} }); if(!rows.length)fail('表格没有可导入的分类行'); - const id=crypto.randomUUID(),canCommit=rows.every(r=>!r.issues.length),plan={id,actor,createdAt:store.now(),canCommit,rows}; + const test=store.restrictedTest?.(); + const id=crypto.randomUUID(),canCommit=rows.every(r=>!r.issues.length),plan={id,actor,createdAt:store.now(),canCommit,rows,...test?.enabled?{testVersion:test.version}:{}}; store.put('rule-imports',plan);return publicPlan(plan); } -function publicPlan(plan){return {id:plan.id,canCommit:plan.canCommit,rows:plan.rows.map(({candidate,...row})=>row)};} -function commitImport(store,input,actor,{mail}={}){return store.transaction(()=>{ - if(!input||Object.keys(input).some(k=>k!=='id')||typeof input.id!=='string')fail('请选择已检查的导入预览'); +function publicPlan(plan){return {id:plan.id,canCommit:plan.canCommit,...plan.testVersion!==undefined?{testVersion:plan.testVersion}:{},rows:plan.rows.map(({candidate,...row})=>row)};} +function commitImport(store,input,actor,{mail,user}={}){return store.transaction(()=>{ + if(!input||Object.keys(input).some(k=>!['id','applyToTest'].includes(k))||typeof input.id!=='string'||input.applyToTest!==undefined&&typeof input.applyToTest!=='boolean')fail('请选择已检查的导入预览'); const plan=store.get('rule-imports',input.id);if(!plan||plan.actor!==actor)fail('导入预览不存在,请重新选择文件',404); - if(plan.result)return plan.result; + if(plan.result){if(Boolean(input.applyToTest)!==Boolean(plan.result.applied))fail('此预览已按其他方式导入,请重新预览。',409);return plan.result;} if(Date.parse(store.now())-Date.parse(plan.createdAt)>30*60000)fail('导入预览已过期,请重新选择文件',409); if(!plan.canCommit)fail('请修复 Excel 中的问题后重新导入',409); const prepared=plan.rows.map(row=>{const record=store.get('rules',row.id);return {record,rule:validateRule(row.candidate,record?.draft)};}); for(const {rule}of prepared)checkTemplates(mail,rule); for(const {record,rule}of prepared){store.put('rule-history',{id:record.id+':'+record.draft.version,rule:record.draft,at:store.now(),actor});record.draft=rule;record.trialVersion=null;record.trialDemo=null;record.trialSampleId=null;store.put('rules',record);} - plan.result={id:plan.id,count:prepared.length};store.put('rule-imports',plan);store.audit(actor,'Excel 导入分类草稿',String(prepared.length)+' 类');return plan.result; + if(input.applyToTest){if(plan.testVersion===undefined)fail('此预览没有有效的测试版本,请重新预览。',409);store.applyRestrictedDrafts({version:plan.testVersion,rules:prepared.map(({record,rule})=>({id:record.id,version:rule.version}))},user);} + plan.result={id:plan.id,count:prepared.length,...input.applyToTest?{applied:true}:{}};store.put('rule-imports',plan);store.audit(actor,'Excel 导入分类草稿',String(prepared.length)+' 类');return plan.result; });} module.exports={previewImport,commitImport}; diff --git a/src/modules/order-rules/restricted-test.cjs b/src/modules/order-rules/restricted-test.cjs index cc44d89..6221466 100644 --- a/src/modules/order-rules/restricted-test.cjs +++ b/src/modules/order-rules/restricted-test.cjs @@ -29,6 +29,43 @@ function executionRule(store,record){ const run=state(store);if(!run)return record?.published||null; const rule=run.rules.find(r=>r.id===record?.id);return rule&&validRule(store,rule,run)?structuredClone(rule):null; } +function applyDrafts(store,input,actor){ + if(actor?.role!=='admin'||!actor.username)fail('仅管理员可应用测试规则。',403); + return store.transaction(()=>{ + const run=state(store); + if(!run?.enabled||!input||Object.keys(input).some(k=>!['version','rules'].includes(k))||input.version!==run.version)fail('测试配置已变化或已暂停,请刷新。',409); + if(!Array.isArray(input.rules)||!input.rules.length||input.rules.length>100||new Set(input.rules.map(r=>r?.id)).size!==input.rules.length)fail('请选择唯一的规则版本。'); + const next=structuredClone(run),adapters=store.adapters(); + for(const item of input.rules){ + if(!item||Object.keys(item).some(k=>!['id','version'].includes(k))||typeof item.id!=='string'||!/^[\w-]{1,100}$/.test(item.id)||!Number.isSafeInteger(item.version))fail('规则版本格式无效。'); + const record=store.get('rules',item.id),index=next.rules.findIndex(r=>r.id===item.id); + if(!record||record.draft.version!==item.version||index<0)fail('规则已变化或不在当前测试范围,请刷新。',409); + const draft=record.draft,binding=next.rules[index]; + if(run.rules[index].version!==draft.version){ + const unfinished=order=>order?.ruleSnapshot?.testRunId===run.id&&['normal','huizhou'].some(mode=>{const value=require('./delivery.cjs').delivery(order,mode);return value&&!value.batchId&&!['sent','ignored','unknown','not_applicable','disabled','empty'].includes(value.status);}); + const pending=store.all('orders').some(order=>order.categoryId===item.id&&unfinished(order)); + const tasks=store.all('execution-tasks').some(task=>{ + if(!task.categoryIds?.includes(item.id)||['sent','ignored'].includes(task.status))return false; + const order=task.orderId&&store.get('orders',task.orderId);return !order||unfinished(order); + }); + if(pending||tasks)fail('此类别仍有旧规则订单或未完成任务,请先完成或人工处理后再应用新版本。',409); + } + const selected=adapters.filter(a=>a.verified&&!a.reference&&draft.adapterIds.includes(a.id)&&draft.processNames.includes(a.processName)&&evidence(store,a)); + if(!selected.length)fail('规则缺少已核实的字段适配:'+draft.name,409); + const rule={...structuredClone(draft),status:'enabled',to:[run.recipient],cc:[],attachPdf:false,archiveDirectory:binding.archiveDirectory,productLine:draft.productLine||binding.productLine,testRunId:run.id,testSince:run.since,testArchiveRoot:run.archiveRoot,adapterIds:selected.map(a=>a.id),scopes:structuredClone(scopesFor(draft))}; + const covered=rule.processNames.filter(p=>selected.some(a=>a.processName===p)); + const issues=publicationIssues({...rule,processNames:covered},adapters);if(issues.length)fail(issues.join(';'),409); + assertPath(store,rule.archiveDirectory,run);next.rules[index]=rule;next.adapterHashes[rule.id]=hash(rule.adapterIds.map(id=>adapters.find(a=>a.id===id))); + } + for(let i=0;irule.processNames.filter(p=>!adapters.some(a=>rule.adapterIds.includes(a.id)&&a.processName===p)).map(processName=>({categoryId:rule.id,processName}))); + // Keep the previous approved versions for existing tasks and frozen batches. + // The current execution snapshot alone changes; identities and baseline do not. + store.put('restricted-test-history',{id:run.id+':'+run.version,value:run});next.version++; + store.put('restricted-test',{id:'main',value:next});store.audit(actor.username,'应用Excel分类到测试',input.rules.map(r=>r.id+' v'+r.version).join(',')); + return {applied:true,count:input.rules.length,test:summary(store)}; + }); +} function save(store,input,actor){ if(actor?.role!=='admin'||!actor.username)fail('仅管理员可以维护受限测试。',403); return store.transaction(()=>{ @@ -66,7 +103,11 @@ function save(store,input,actor){ function assertRule(store,rule,run=state(store)){ if(!run){if(rule?.testRunId)fail('测试配置不存在,禁止按正式规则继续执行。',409);return;} if(!run.enabled||rule?.testRunId!==run.id||rule.testArchiveRoot!==run.archiveRoot)fail('受限测试已暂停或执行快照不一致。',409); - const frozen=run.rules.find(r=>r.id===rule.id);if(frozen&&(!validRule(store,frozen,run)||hash(frozen)!==hash(rule)))fail('受限测试字段或规则快照已变化。',409); + const frozen=run.rules.find(r=>r.id===rule.id); + if(frozen?(!validRule(store,frozen,run)||hash(frozen)!==hash(rule)):state(store)?.id===run.id){ + const approved=store.all('restricted-test-history').some(row=>row.value?.id===run.id&&row.value.rules.some(previous=>previous.id===rule.id&&validRule(store,previous,row.value)&&hash(previous)===hash(rule))); + if(!approved)fail('受限测试字段或规则快照已变化。',409); + } if(rule.to?.length!==1||rule.to[0]!==run.recipient||rule.cc?.length)fail('受限测试收件人必须为固定QQ且无抄送。',409); assertPath(store,rule.archiveDirectory,run); } @@ -137,4 +178,4 @@ function admitCurrent(store,rows,actor){ return structuredClone(entries); }); } -module.exports={state,summary,save,executionRule,assertPath,assertRule,assertEvent,assertOrder,assertBatch,recordCurrentScan,admitCurrent,eventTime,orderTime,isAdmitted,eventInWindow,orderInWindow}; +module.exports={state,summary,save,applyDrafts,executionRule,assertPath,assertRule,assertEvent,assertOrder,assertBatch,recordCurrentScan,admitCurrent,eventTime,orderTime,isAdmitted,eventInWindow,orderInWindow}; diff --git a/src/modules/order-rules/store.cjs b/src/modules/order-rules/store.cjs index b5ef33c..54d9802 100644 --- a/src/modules/order-rules/store.cjs +++ b/src/modules/order-rules/store.cjs @@ -48,6 +48,7 @@ class RuleStore{ now(){return this.clock().toISOString();} restrictedTest(){return require('./restricted-test.cjs').summary(this);} saveRestrictedTest(input,actor){return require('./restricted-test.cjs').save(this,input,actor);} + applyRestrictedDrafts(input,actor){return require('./restricted-test.cjs').applyDrafts(this,input,actor);} executionRule(record){return require('./restricted-test.cjs').executionRule(this,record);} providersReady(){return ['liveTodo','pdfExport','automaticArchive'].every(key=>this.capabilities[key]===true);} adapters(){return registry.registry(this);} @@ -83,7 +84,7 @@ class RuleStore{ queryRevision(){return Number(this.db.prepare('SELECT total_changes() AS revision').get().revision);} snapshot({includeRecords=true}={}){ const adapters=this.adapters(),rules=this.all('rules').map(record=>({...record.draft,status:record.published?.status||'draft',activationVersion:record.activationVersion||0,hasDraft:!record.published||record.draft.version!==record.published.version,publishedVersion:record.published?.version||null,trialVersion:record.trialVersion,mappingIssue:record.mappingIssue||null,explanation:describeRule(record.draft),validationIssues:publicationIssues(record.draft,adapters)})); - const restrictedTest=typeof this.restrictedTest==='function'?this.restrictedTest():null;for(const rule of rules)if(restrictedTest){const active=typeof this.executionRule==='function'?this.executionRule({id:rule.id}):null;rule.testStatus=active?'enabled':'paused';} + const restrictedTest=typeof this.restrictedTest==='function'?this.restrictedTest():null;for(const rule of rules)if(restrictedTest){const active=typeof this.executionRule==='function'?this.executionRule({id:rule.id}):null;rule.testStatus=active?'enabled':'paused';rule.testVersion=active?.version||null;rule.testHasDraft=!active||active.version!==rule.version;} return {rules,restrictedTest,adapters,orders:includeRecords?this.all('orders').reverse():[],batches:includeRecords?this.all('batches').reverse():[],settings:this.settings(),audit:includeRecords?this.all('audit').slice(-100).reverse():[],capabilities:copy(this.capabilities),window:upcomingWindow(this.clock(),this.schedule(),this.calendar())}; } saveRule(input,actor){return this.transaction(()=>{ diff --git a/tests/order-rules/excel-execution-bridge.test.cjs b/tests/order-rules/excel-execution-bridge.test.cjs new file mode 100644 index 0000000..6e562db --- /dev/null +++ b/tests/order-rules/excel-execution-bridge.test.cjs @@ -0,0 +1,51 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto'); +const {RuleStore}=require('../../src/modules/order-rules/store.cjs'),{activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs'); +const {previewImport,commitImport}=require('../../src/modules/order-rules/import.cjs'),restricted=require('../../src/modules/order-rules/restricted-test.cjs'); +const admin={username:'admin',role:'admin'}; +function fixture(t){ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'excel-execution-')),desktop=path.join(dir,'Desktop'),local=path.join(desktop,'run');fs.mkdirSync(local,{recursive:true}); + const root='\\\\localhost\\'+local[0]+'$'+local.slice(2),options={desktopRoot:desktop,clock:()=>new Date('2026-10-23T01:00:00Z'),capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}};let store=new RuleStore(path.join(dir,'state'),options); + t.after(()=>{store.close();const resolved=fs.realpathSync(dir);assert.equal(path.dirname(resolved).toLowerCase(),fs.realpathSync(os.tmpdir()).toLowerCase());assert(path.basename(resolved).startsWith('excel-execution-'));fs.rmSync(resolved,{recursive:true,force:true});}); + const evidence=activateReferenceMapping(store),old=store.get('rules','bs-change').draft;store.saveRule({...old,to:['2639266652@qq.com'],cc:[],bodyTemplateId:'',archiveDirectory:root+'\\orders',filenameDate:'receivedAt'},'admin'); + store.saveRestrictedTest({version:0,enabled:true,recipient:'2639266652@qq.com',archiveRoot:root,channelId:'fixture-mail',ruleIds:['bs-change']},admin); + const event=(taskId,nodeName='Excel通知节点')=>({...evidence.sample,instanceId:'fixture-instance-'+taskId,taskId,nodeName,receivedAt:'2026-10-23T01:00:01Z'}); + const input={rows:[['类别编号','分类名称','订单评审流程','电子流状态','服务器存档地址','邮件命名','收件人'],['bs-change','备损订单更改通知书','备损订单更改评审','Excel通知节点','Excel归档分类','【备损订单更改通知书】','formal@example.test']]}; + return {get store(){return store;},root,event,input,reopen(){const clock=store.clock;store.close();store=new RuleStore(path.join(dir,'state'),{...options,clock});}}; +} +for(const outcome of ['sent','unknown'])test('Excel import drives matching, archive prerequisite, batching and isolated delivery: '+outcome,async t=>{ + const f=fixture(t),before=f.store.restrictedTest(),published=f.store.get('rules','bs-change').published; + const preview=previewImport(f.store,f.input,'admin');assert.equal(preview.testVersion,before.version); + const saved=commitImport(f.store,{id:preview.id,applyToTest:true},'admin',{user:admin});assert.equal(saved.applied,true); + assert.deepEqual(commitImport(f.store,{id:preview.id,applyToTest:true},'admin',{user:admin}),saved); + const active=f.store.executionRule(f.store.get('rules','bs-change'));assert.equal(active.scopes[0].nodeName,'Excel通知节点');assert.deepEqual(active.to,['2639266652@qq.com']);assert.deepEqual(active.cc,[]);assert.equal(active.archiveDirectory,f.root+'\\orders'); + assert.equal(f.store.restrictedTest().id,before.id);assert.equal(f.store.restrictedTest().since,before.since);assert.deepEqual(f.store.get('rules','bs-change').published,published); + const sample=f.event('new-task'),order=f.store.ingest(sample,'fixture');assert.equal(order.status,'identified',order.error);assert.equal(f.store.ingest(sample,'fixture').id,order.id); + const config=f.store.settings();f.store.saveSettings({...config,enabled:true,processingEnabled:true,channelId:'fixture-mail'},'admin'); + f.store.clock=()=>new Date('2026-10-23T03:00:00Z');assert.equal(f.store.prepare('2026-10-23T03:00:00Z','fixture').length,0); + const content=Buffer.from('%PDF-1.7 fixture');f.store.recordArchive(order.id,{archivedAt:'2026-10-23T01:01:00Z',files:[{name:'fixture.pdf',path:f.root+'\\orders\\fixture.pdf',size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}]},'fixture'); + const [batch]=f.store.prepare('2026-10-23T03:00:00Z','fixture');assert.ok(batch);assert.deepEqual(batch.attachments,[]); + const sent=[],mail={store:{channelSecret:()=>({id:'fixture-mail',version:1,name:'fixture',email:'fixture@example.test',smtp:{}}),guard(){}},exclusive:async(id,work)=>work(),clients:new Set(),smtpFactory:()=>({verify:async()=>{},sendMail:async message=>{sent.push(message);if(outcome==='unknown')throw Object.assign(Error('fixture connection lost'),{code:'ETIMEDOUT'});return {accepted:['2639266652@qq.com'],rejected:[]};},close(){}})}; + const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs'),dispatcher=new OrderRuleDispatcher({store:f.store,mail,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),clock:()=>f.store.clock(),providersReady:()=>true}); + await dispatcher.dispatch(batch,f.store.settings());assert.equal(f.store.get('batches',batch.id).status,outcome);assert.equal(sent.length,1);assert.deepEqual(sent[0].to,['2639266652@qq.com']);assert.deepEqual(sent[0].attachments,[]); + await assert.rejects(dispatcher.resend(batch.id,{version:1,idempotencyKey:'protected-result',note:'保护已发送及结果不明批次'},admin),{status:409});assert.equal(sent.length,1); +}); +test('applying edits keeps old task snapshots valid and rejects stale or unauthorized activation',t=>{ + const f=fixture(t),run=f.store.restrictedTest(),oldRule=f.store.executionRule(f.store.get('rules','bs-change')),order=f.store.ingest(f.event('old-task',oldRule.nodeNames[0]),'fixture'); + const draft=f.store.get('rules','bs-change').draft;f.store.saveRule({...draft,subjectPrefix:'【新版本】'},'admin');const next=f.store.get('rules','bs-change').draft; + const input={version:run.version,rules:[{id:next.id,version:next.version}]};assert.throws(()=>f.store.applyRestrictedDrafts(input,{username:'op',role:'operator'}),{status:403}); + assert.throws(()=>f.store.applyRestrictedDrafts(input,admin),e=>e.status===409&&/旧规则订单/.test(e.message));assert.deepEqual(f.store.restrictedTest(),run); + const content=Buffer.from('%PDF-1.7 fixture');f.store.recordArchive(order.id,{archivedAt:'2026-10-23T01:01:00Z',files:[{name:'old.pdf',path:f.root+'\\orders\\old.pdf',size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}]},'fixture'); + assert.throws(()=>f.store.applyRestrictedDrafts(input,admin),{status:409}); + f.store.saveSettings({...f.store.settings(),channelId:'fixture-mail'},'admin');f.store.clock=()=>new Date('2026-10-23T03:00:00Z');const [batch]=f.store.prepare('2026-10-23T03:00:00Z','fixture');assert.ok(batch);const before=f.store.get('orders',order.id),frozen=structuredClone(batch); + f.store.applyRestrictedDrafts(input,admin);assert.throws(()=>f.store.applyRestrictedDrafts(input,admin),{status:409});assert.deepEqual(f.store.get('orders',order.id),before);assert.deepEqual(f.store.get('batches',batch.id),frozen);assert.doesNotThrow(()=>restricted.assertRule(f.store,oldRule)); + f.reopen();assert.equal(f.store.executionRule(f.store.get('rules',next.id)).subjectPrefix,'【新版本】');assert.deepEqual(f.store.get('orders',order.id),before);assert.doesNotThrow(()=>restricted.assertRule(f.store,oldRule)); + f.store.beginSending(batch.id);f.store.finishSending(batch.id,'sent','fixture accepted');assert.equal(f.store.get('batches',batch.id).status,'sent'); +}); +test('unusable imports roll back atomically and uncovered flows remain explicitly blocked',t=>{ + const f=fixture(t),before=f.store.all('rules'),run=f.store.get('restricted-test','main'); + f.input.rows[1][2]='未配置字段的流程';const bad=previewImport(f.store,f.input,'admin');assert.throws(()=>commitImport(f.store,{id:bad.id,applyToTest:true},'admin',{user:admin}),{status:409});assert.deepEqual(f.store.all('rules'),before);assert.deepEqual(f.store.get('restricted-test','main'),run); + f.input.rows[1][2]='备损订单更改评审/未配置字段的流程';const partial=previewImport(f.store,f.input,'admin');commitImport(f.store,{id:partial.id,applyToTest:true},'admin',{user:admin}); + assert(f.store.restrictedTest().uncovered.some(row=>row.processName==='未配置字段的流程')); + const blocked=f.store.ingest({...f.event('uncovered'),processName:'未配置字段的流程'},'fixture');assert.equal(blocked.status,'blocked');assert.equal(blocked.archive,null); +}); diff --git a/tests/order-rules/excel-import-contract.test.cjs b/tests/order-rules/excel-import-contract.test.cjs new file mode 100644 index 0000000..11a5536 --- /dev/null +++ b/tests/order-rules/excel-import-contract.test.cjs @@ -0,0 +1,50 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict'); +const {seedRules}=require('../../src/modules/order-rules/catalog.cjs'); +const {previewImport,commitImport}=require('../../src/modules/order-rules/import.cjs'); +function fixture(){ + const records=new Map(seedRules().map(draft=>['rules:'+draft.id,{id:draft.id,draft,published:null}])); + const store={all:kind=>[...records].filter(([key])=>key.startsWith(kind+':')).map(([,value])=>structuredClone(value)),get:(kind,id)=>structuredClone(records.get(kind+':'+id)),put:(kind,value)=>records.set(kind+':'+value.id,structuredClone(value)),adapters:()=>[],now:()=>new Date('2026-10-23T02:00:00Z').toISOString(),audit(){},transaction(work){const before=structuredClone(records);try{return work();}catch(error){records.clear();for(const [key,value]of before)records.set(key,value);throw error;}}}; + return store; +} +function sourceRows(rule,body='BPM摘要信息'){ + return {rows:[['序号','服务器存档地址','订单评审流程','邮件命名','邮件正文','电子流状态','收件人'],[1,'测试归档',rule.processNames.join('/'),rule.subjectPrefix,body,rule.nodeNames.join('/'),'recipient@example.test']]}; +} +test('Excel scope import uses the same Unicode normalization as the authoritative source without adding node aliases',()=>{ + const store=fixture(),old=store.get('rules','processing-notice').draft,input=sourceRows(old); + input.rows[1][5]='订单专员(激活)'; + const plan=previewImport(store,input,'admin');assert.equal(plan.canCommit,true); + commitImport(store,{id:plan.id},'admin'); + assert.deepEqual(store.get('rules',old.id).draft.scopes,[{processName:'加工订单评审',nodeName:'订单专员(激活)'}]); + const overseas=store.get('rules','overseas-notice').draft,p=previewImport(store,sourceRows(overseas),'admin');commitImport(store,{id:p.id},'admin'); + assert.deepEqual(store.get('rules',overseas.id).draft.nodeNames,['订单专员(订单通知书)']); +}); +test('legacy Excel attachment descriptions and explicit yes cannot enable PDF email attachments',()=>{ + for(const explicit of [false,true]){ + const store=fixture(),old=store.get('rules','bs-change').draft,input=sourceRows(old,'附件:订单通知书PDF'); + if(explicit){input.rows[0].push('附带PDF');input.rows[1].push('是');} + const before=store.all('rules'),plan=previewImport(store,input,'admin');assert.equal(plan.canCommit,true);assert.deepEqual(store.all('rules'),before); + assert(plan.rows[0].warnings.some(message=>/PDF.*仅归档|不附.*PDF/.test(message))); + commitImport(store,{id:plan.id},'admin');assert.equal(store.get('rules',old.id).draft.attachPdf,false); + } +}); +test('import previews expose actual scopes and distribution values so administrators can verify before writing',()=>{ + const store=fixture(),old=store.get('rules','bs-change').draft,plan=previewImport(store,sourceRows(old),'admin'); + assert.deepEqual(plan.rows[0].preview.scopes,[{processName:old.processNames[0],nodeName:old.nodeNames[0]}]); + assert.deepEqual(plan.rows[0].preview.to,['recipient@example.test']);assert.equal(plan.rows[0].preview.archiveDirectory,'测试归档');assert.equal(plan.rows[0].preview.attachPdf,false); + assert.equal(plan.rows[0].candidate,undefined);assert.equal(store.get('rules',old.id).draft.version,old.version); +}); +test('exported rules can round trip all fifteen categories and keep published and restricted snapshots intact',async()=>{ + const store=fixture(),XLSX=require('xlsx'),{parse}=require('../../web/modules/order-rules/import-parser.js'); + for(const record of store.all('rules')){record.draft.to=['recipient@example.test'];record.draft.scopes=record.draft.processNames.flatMap(processName=>record.draft.nodeNames.map(nodeName=>({processName,nodeName:nodeName.normalize('NFKC')})));record.draft.nodeNames=[...new Set(record.draft.scopes.map(row=>row.nodeName))];record.published={...structuredClone(record.draft),status:'enabled'};store.put('rules',record);} + store.put('restricted-test',{id:'main',value:{id:'fixed-run',rules:store.all('rules').map(r=>r.published)}}); + const before=store.all('rules'),run=store.get('restricted-test','main'),bytes=await require('../../src/modules/order-rules/import-template.cjs').template(store),plan=previewImport(store,parse(XLSX,bytes),'admin'); + assert.equal(plan.canCommit,true);assert.equal(plan.rows.length,15);commitImport(store,{id:plan.id},'admin'); + for(const record of before){const saved=store.get('rules',record.id);assert.deepEqual(saved.draft.scopes,record.draft.scopes);assert.deepEqual(saved.published,record.published);assert.equal(saved.draft.attachPdf,false);} + assert.deepEqual(store.get('restricted-test','main'),run); +}); +test('rule exports keep readable column widths, a frozen header, filter and bold labels',async()=>{ + const bytes=await require('../../src/modules/order-rules/import-template.cjs').template(fixture()),zip=await require('jszip').loadAsync(bytes); + const sheet=await zip.file('xl/worksheets/sheet1.xml').async('string'),styles=await zip.file('xl/styles.xml').async('string'); + assert.match(sheet,/]*ySplit="1"[^>]*state="frozen"/);assert.match(sheet,/]*width="60"/);assert.match(styles,//); +}); diff --git a/tests/order-rules/excel-import-flow-ui.test.cjs b/tests/order-rules/excel-import-flow-ui.test.cjs new file mode 100644 index 0000000..561ab81 --- /dev/null +++ b/tests/order-rules/excel-import-flow-ui.test.cjs @@ -0,0 +1,71 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto'); +const {startTestDashboard,login}=require('../fixtures/dashboard-runtime.cjs'); +const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'); +async function setup(t){ + const dir=await fs.mkdtemp(path.join(os.tmpdir(),'excel-import-flow-')),runtime=await startTestDashboard({stateDir:dir,mailHistory:true}),browser=await loadPlaywright().chromium.launch(browserOptions()); + t.after(async()=>{await browser.close();await runtime.close();const resolved=await fs.realpath(dir),parent=await fs.realpath(os.tmpdir());if(path.dirname(resolved).toLowerCase()!==parent.toLowerCase()||!path.basename(resolved).startsWith('excel-import-flow-'))throw Error('Unexpected test cleanup path');await fs.rm(resolved,{recursive:true,force:true});}); + const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(10000);return {page,runtime,base:'http://127.0.0.1:'+runtime.server.address().port}; +} +test('source Excel imports fifteen editable drafts, survives reload and exports without changing execution snapshots',{timeout:120000},async t=>{ + const {page,runtime,base}=await setup(t),XLSX=require('xlsx'),originals=runtime.orderRules.all('rules'); + const published=originals[0];published.published={...published.draft,status:'enabled'};runtime.orderRules.put('rules',published); + const source=[['序号','服务器存档地址','订单评审流程','邮件命名','邮件正文','电子流状态','收件人'],...originals.map(({draft:r},i)=>[i+1,'测试归档',r.processNames.join('/'),r.subjectPrefix,'BPM摘要信息,附件:PDF',r.nodeNames.join('/'),'2639266652@qq.com']),['','','表格下方的说明不是分类规则']]; + const book=XLSX.utils.book_new();XLSX.utils.book_append_sheet(book,XLSX.utils.aoa_to_sheet(source),'订单通知书邮件信息'); + // Optional local acceptance exercises the unchanged private workbook; it is + // never copied into fixtures, logged, or submitted to a live service. + const bytes=process.env.ORDER_RULE_SOURCE_WORKBOOK?await fs.readFile(process.env.ORDER_RULE_SOURCE_WORKBOOK):XLSX.write(book,{type:'buffer',bookType:'biff8'}); + await page.goto(base+'/#order-rules');await login(page);await page.getByRole('button',{name:'导入 Excel',exact:true}).click(); + await page.locator('#rule-import-file').setInputFiles({name:'源规则.xls',mimeType:'application/vnd.ms-excel',buffer:bytes}); + const confirm=page.getByRole('button',{name:'确认导入 15 类草稿',exact:true});await confirm.waitFor();assert.equal(await confirm.isEnabled(),true); + assert.equal(await page.getByText('查看导入内容',{exact:true}).count(),15); + assert.deepEqual(runtime.orderRules.all('rules'),originals.map(r=>r.id===published.id?published:r)); + await confirm.click();await page.getByText('Excel 草稿已导入,启停状态未改变。',{exact:true}).waitFor(); + for(const {id,draft}of originals){ + await page.locator('[data-rule-id="'+id+'"]').click();await page.getByLabel('规则名称',{exact:true}).fill(draft.name+' · 验收'); + await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor(); + assert.equal(runtime.orderRules.get('rules',id).draft.name,draft.name+' · 验收');assert.equal(runtime.orderRules.get('rules',id).draft.attachPdf,false); + } + await page.reload();await page.locator('[data-rule-id="'+originals.at(-1).id+'"]').click();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),originals.at(-1).draft.name+' · 验收'); + await page.getByRole('button',{name:'导入 Excel',exact:true}).click(); + const [download]=await Promise.all([page.waitForEvent('download',{timeout:30000}),page.getByRole('link',{name:'下载当前规则 Excel',exact:true}).click({noWaitAfter:true})]); + const exported=await fs.readFile(await download.path()),roundtrip=require('../../web/modules/order-rules/import-parser.js').parse(XLSX,exported); + assert.equal(roundtrip.rows.length,16);assert.equal(download.suggestedFilename(),'分类规则.xlsx'); + await page.locator('#rule-import-file').setInputFiles({name:'分类规则.xlsx',mimeType:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',buffer:exported});await confirm.waitFor();assert.equal(await confirm.isEnabled(),true); + assert.deepEqual(runtime.orderRules.get('rules',published.id).published,published.published);assert.equal(runtime.orderRules.settings().enabled,false);assert.equal(runtime.orderRules.all('orders').length,0);assert.equal(runtime.orderRules.all('batches').length,0); +}); +test('rule editor exposes explicit test application while drafts remain editable',{timeout:60000},async t=>{ + const {page,runtime,base}=await setup(t),original=runtime.orderRules.snapshot.bind(runtime.orderRules),run={id:'fixture-run',version:1,enabled:true,ruleCount:15,readyCount:15}; + runtime.orderRules.snapshot=()=>({...original(),restrictedTest:run}); + await page.goto(base+'/#order-rules');await login(page); + await page.getByRole('button',{name:'保存草稿',exact:true}).waitFor(); + assert.match(await page.locator('#order-rules-panel').innerText(),/受限稳定性测试:15 \/ 15 类可用/); + assert.equal(await page.getByRole('button',{name:'应用到测试',exact:true}).isEnabled(),true); + assert.equal(await page.getByRole('button',{name:'保存草稿',exact:true}).isEnabled(),true); + await page.getByLabel('规则名称',{exact:true}).fill('仍可编辑的草稿');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor(); + assert.equal(await page.getByRole('button',{name:'应用到测试',exact:true}).isEnabled(),true);assert.deepEqual(run,{id:'fixture-run',version:1,enabled:true,ruleCount:15,readyCount:15}); +}); +test('import and editor application update the actual execution rule through authenticated HTTP',{timeout:60000},async t=>{ + const {page,runtime,base}=await setup(t),XLSX=require('xlsx'),{activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs'); + activateReferenceMapping(runtime.orderRules); + const desktop=path.join(os.tmpdir(),'excel-bridge-desktop-'+crypto.randomUUID()),local=path.join(desktop,'run');await fs.mkdir(local,{recursive:true});runtime.orderRules.desktopRoot=desktop; + t.after(async()=>{const resolved=await fs.realpath(desktop);assert.equal(path.dirname(resolved).toLowerCase(),(await fs.realpath(os.tmpdir())).toLowerCase());assert(path.basename(resolved).startsWith('excel-bridge-desktop-'));await fs.rm(resolved,{recursive:true,force:true});}); + const root='\\\\localhost\\'+local[0]+'$'+local.slice(2),draft=runtime.orderRules.get('rules','bs-change').draft; + runtime.orderRules.saveRule({...draft,to:['2639266652@qq.com'],cc:[],bodyTemplateId:'',archiveDirectory:root+'\\orders',filenameDate:'receivedAt'},'admin'); + const run=runtime.orderRules.saveRestrictedTest({version:0,enabled:true,recipient:'2639266652@qq.com',archiveRoot:root,channelId:'fixture-channel',ruleIds:['bs-change']},{username:'admin',role:'admin'}); + const rows=[['类别编号','分类名称','订单评审流程','电子流状态','服务器存档地址','邮件命名','收件人'],['bs-change','备损订单更改通知书','备损订单更改评审','Excel通知节点','表内目录','【备损订单更改通知书】','formal@example.test']],book=XLSX.utils.book_new();XLSX.utils.book_append_sheet(book,XLSX.utils.aoa_to_sheet(rows),'分类规则'); + await page.goto(base+'/#order-rules');await login(page);await page.getByRole('button',{name:'导入 Excel',exact:true}).click();await page.locator('#rule-import-file').setInputFiles({name:'执行规则.xlsx',mimeType:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',buffer:XLSX.write(book,{type:'buffer',bookType:'xlsx'})}); + await page.getByRole('button',{name:'确认导入并应用到测试',exact:true}).click();await page.getByText('Excel 规则已导入并应用到测试,旧订单和批次保持不变。',{exact:true}).waitFor(); + const active=()=>runtime.orderRules.executionRule(runtime.orderRules.get('rules','bs-change'));assert.equal(active().nodeNames[0],'Excel通知节点');assert.deepEqual(active().to,['2639266652@qq.com']);assert.equal(runtime.orderRules.restrictedTest().since,run.since); + await page.locator('[data-rule-id="bs-change"]').click();await page.getByLabel('邮件主题前缀',{exact:true}).fill('【编辑后的执行规则】');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();assert.notEqual(active().subjectPrefix,'【编辑后的执行规则】'); + await page.getByRole('button',{name:'应用到测试',exact:true}).click();await page.getByText('规则已应用到测试,新任务使用当前规则;旧订单和批次保持不变。',{exact:true}).waitFor();assert.equal(active().subjectPrefix,'【编辑后的执行规则】');assert.equal(runtime.orderRules.settings().enabled,false); +}); +test('paused restricted snapshots preserve their warning but restore ordinary publication controls',{timeout:60000},async t=>{ + const {page,runtime,base}=await setup(t),original=runtime.orderRules.snapshot.bind(runtime.orderRules); + const record=runtime.orderRules.get('rules','overseas-notice');record.published={...record.draft,status:'paused'};runtime.orderRules.put('rules',record); + runtime.orderRules.snapshot=()=>({...original(),restrictedTest:{id:'fixture-run',version:2,enabled:false,ruleCount:15,readyCount:0}}); + await page.goto(base+'/#order-rules');await login(page);await page.getByRole('button',{name:'保存草稿',exact:true}).waitFor(); + assert.match(await page.locator('#order-rules-panel').innerText(),/受限稳定性测试已暂停/); + assert.equal(await page.getByRole('button',{name:'发布此版本',exact:true}).isEnabled(),true); + assert.equal(await page.getByRole('button',{name:'预览迁移',exact:true}).count(),1); +}); diff --git a/web/modules/order-rules/import-view.js b/web/modules/order-rules/import-view.js index 7b420a5..ab5f91c 100644 --- a/web/modules/order-rules/import-view.js +++ b/web/modules/order-rules/import-view.js @@ -2,7 +2,7 @@ 'use strict'; function bind(container,{api,esc,active,reload,feedback,guard,mutate}){ const host=container.querySelector('#rule-import-panel'),file=container.querySelector('#rule-import-file'),open=container.querySelector('#rule-import-open');let worker,revision=0,busy=false,plan,cancelRead; - const lock=value=>{busy=value;open.disabled=value;host.querySelectorAll('[data-import-file],[data-import-close]').forEach(b=>b.disabled=value);}; + const lock=value=>{busy=value;open.disabled=value;host.querySelectorAll('[data-import-file],[data-import-close],[data-import-submit]').forEach(b=>b.disabled=value||b.hasAttribute('data-import-submit')&&!plan?.canCommit);}; const owned=request=>active()&&request===revision; open.onclick=()=>{if(busy)return;revision++;host.hidden=false;host.innerHTML='

从 Excel 导入分类规则

支持原始“订单通知书邮件发送信息.xls”和下载的分类模板。先检查变化,确认后保存为草稿;不改变已启用版本,也不会发信。

下载当前规则 Excel
';host.querySelector('[data-import-file]').onclick=()=>{file.value='';file.click();};host.querySelector('[data-import-close]').onclick=()=>{revision++;worker?.terminate();host.hidden=true;};}; file.onchange=async()=>{ @@ -11,8 +11,11 @@ const bytes=await selected.arrayBuffer();if(!owned(request))return;worker?.terminate();worker=new Worker('/order-rules-import-worker.js'); const parsed=await new Promise((resolve,reject)=>{const timeout=setTimeout(()=>{worker.terminate();reject(Error('Excel 读取超时,请精简表格后重试。'));},10000);cancelRead=()=>{clearTimeout(timeout);reject(Error('页面已离开'));};worker.onmessage=e=>{clearTimeout(timeout);cancelRead=null;e.data.error?reject(Error(e.data.error)):resolve(e.data.data);};worker.onerror=()=>{clearTimeout(timeout);cancelRead=null;reject(Error('Excel 读取失败,请检查文件或刷新重试。'));};worker.postMessage(bytes,[bytes]);}); if(!owned(request))return;plan=await api('/order-rules/import/preview',parsed);if(!owned(request))return; - result.innerHTML=`
识别到 ${plan.rows.length} 类。${plan.canCommit?'请核对下面的变化,再确认导入。':'有需要修复的行,请修改 Excel 后重新选择文件。'}
${plan.rows.map(r=>``).join('')}
Excel 行 / 分类变更检查结果
${esc(r.sourceRow)} · ${esc(r.name||'未识别类别')}${esc(r.changes.join('、')||'内容无变化')}${r.recipientCount!==undefined?`
主送 ${esc(r.recipientCount)} 人
`:''}
${r.issues.map(v=>`
${esc(v)}
`).join('')}${r.warnings.map(v=>`
${esc(v)}
`).join('')}${!r.issues.length&&!r.warnings.length?'可导入':''}
`; - result.querySelector('#rule-import-confirm').onclick=event=>{if(busy)return;const button=event.currentTarget;guard(()=>mutate(async()=>{if(!owned(request)||busy)return;lock(true);button.disabled=true;try{const saved=await api('/order-rules/import/commit',{id:plan.id});if(!owned(request))return;result.innerHTML='
已导入 '+saved.count+' 类草稿。请逐类检查识别结果,再发布启用。
';await window.PageLifecycle.afterSave(reload,'Excel 草稿已导入,启停状态未改变。',feedback,active);}catch(error){if(owned(request)){feedback(error.message,'danger');if(button.isConnected)button.disabled=false;}}finally{if(owned(request))lock(false);}}));}; + result.innerHTML=`
识别到 ${plan.rows.length} 类。${plan.canCommit?'请核对下面的变化,再确认导入。':'有需要修复的行,请修改 Excel 后重新选择文件。'}
${plan.rows.map(r=>``).join('')}
Excel 行 / 分类变更检查结果
${esc(r.sourceRow)} · ${esc(r.name||'未识别类别')}${esc(r.changes.join('、')||'内容无变化')}${r.recipientCount!==undefined?`
主送 ${esc(r.recipientCount)} 人
`:''}${r.preview?`
查看导入内容
${r.preview.scopes.map(s=>`
${esc(s.processName)} → ${esc(s.nodeName)}
`).join('')}
主题:${esc(r.preview.subjectPrefix)}
归档:${esc(r.preview.archiveDirectory||'待配置')}
收件人:${esc(r.preview.to.join(';')||'未配置')}
抄送人:${esc(r.preview.cc.join(';')||'无')}
PDF 仅归档,邮件不附附件
`:''}
${r.issues.map(v=>`
${esc(v)}
`).join('')}${r.warnings.map(v=>`
${esc(v)}
`).join('')}${!r.issues.length&&!r.warnings.length?'可导入':''}
`; + const confirm=result.querySelector('#rule-import-confirm');confirm.dataset.importSubmit=''; + if(plan.testVersion!==undefined){confirm.className='btn';confirm.insertAdjacentHTML('beforebegin','');result.insertAdjacentHTML('beforeend','

应用后新任务按Excel规则执行;测试邮箱、归档目录和发送时间保持不变,旧订单和批次不重做。

');} + const commit=apply=>event=>{if(busy)return;const button=event.currentTarget;guard(()=>mutate(async()=>{if(!owned(request)||busy)return;lock(true);button.disabled=true;try{const saved=await api('/order-rules/import/commit',{id:plan.id,...apply?{applyToTest:true}:{}});if(!owned(request))return;const message=saved.applied?'Excel 规则已导入并应用到测试,旧订单和批次保持不变。':'Excel 草稿已导入,启停状态未改变。';result.innerHTML='
已处理 '+saved.count+' 类:'+(saved.applied?'已应用到测试。':'已保存草稿。')+'可在下方选择分类继续编辑。
';await window.PageLifecycle.afterSave(reload,message,feedback,active);}catch(error){if(owned(request)){feedback(error.message,'danger');if(button.isConnected)button.disabled=false;}}finally{if(owned(request))lock(false);}}));}; + confirm.onclick=commit(false);const apply=result.querySelector('#rule-import-apply');if(apply)apply.onclick=commit(true); }catch(error){if(owned(request)){result.textContent=error.message;result.className='mt-3 text-danger';}}finally{worker?.terminate();if(owned(request))lock(false);} }; return {dispose(){revision++;cancelRead?.();worker?.terminate();}}; diff --git a/web/modules/order-rules/view.js b/web/modules/order-rules/view.js index 5a26087..ceda61e 100644 --- a/web/modules/order-rules/view.js +++ b/web/modules/order-rules/view.js @@ -15,18 +15,18 @@ const optional=(path,kind)=>api(path).catch(error=>({error:{kind,message:error.message}})); const [snapshot,catalog,mail,bindings,storage,connections]=await Promise.all([api('/order-rules?view=summary'),optional('/order-rules/fields?view=directory','fields'),optional('/mail','mail'),optional('/mail/templates/categories','mail'),optional('/storage','storage'),admin?optional('/workspace','connections'):Promise.resolve({connections:[]})]); if(!isActive()||request!==revision)return false; - data={connections:connections.connections||[],rules:snapshot.rules||[],adapters:snapshot.adapters||[],samples:catalog.samples||[],fieldProcesses:catalog.processes||[],catalogError:catalog.error?.message,resources:{templates:mail.templates||[],bindings:bindings.bindings||[],servers:storage.servers||[],errors:[mail.error,bindings.error,storage.error].filter(Boolean)}};dirty=false;draw();return true; + data={connections:connections.connections||[],rules:snapshot.rules||[],restrictedTest:snapshot.restrictedTest||null,adapters:snapshot.adapters||[],samples:catalog.samples||[],fieldProcesses:catalog.processes||[],catalogError:catalog.error?.message,resources:{templates:mail.templates||[],bindings:bindings.bindings||[],servers:storage.servers||[],errors:[mail.error,bindings.error,storage.error].filter(Boolean)}};dirty=false;draw();return true; } function draw(){ unregister?.();resourceController?.dispose();scopeController?.dispose();++trialRevision; if(!data.rules.length){panel.innerHTML=`
${empty('暂无分类规则,请先导入经确认的 Excel 分类。')}
`;return;} - const rule=data.rules.find(r=>r.id===selectedId)||data.rules[0];selectedId=rule.id; + const rule=data.rules.find(r=>r.id===selectedId)||data.rules[0],restrictedActive=data.restrictedTest?.enabled===true;selectedId=rule.id; const sourcesFor=value=>data.samples.filter(c=>c.provenance==='server-provider'&&c.sample?.demo!==true&&c.sample?.source!=='history'&&(value.processNames||[]).includes(c.processName)).map(c=>({id:'capture:'+c.id,sampleId:c.id,label:(c.sample.serialNum||'待办订单')+' · '+c.processName+' · '+formatDate(c.sample.receivedAt),processName:c.processName,sample:c.sample})); let sources=sourcesFor(rule); const recognition=(data.catalogError?`
订单读取失败:${esc(data.catalogError)}。请刷新重试,或到订单执行检查 BPM 连接。
`:'')+window.OrderRulePreview.panel(sources,{esc,operator}); panel.innerHTML=`
分类规则

${esc(rule.name)}

草稿 v${esc(rule.version)} · 已发布 ${esc(rule.publishedVersion?'v'+rule.publishedVersion:'无')} · Excel 行 ${esc(rule.sourceRow??'—')}
${window.OrderRuleEditor.render(rule,data.adapters,{esc,admin,resources:data.resources,recognition})}
`; - if(data.restrictedTest)panel.insertAdjacentHTML('afterbegin','
受限稳定性测试:'+Number(data.restrictedTest.readyCount)+' / '+Number(data.restrictedTest.ruleCount)+' 类可用。测试使用独立快照,保存草稿不改变正在运行的测试。查看测试设置
'); - if(admin&&rule.publishedVersion&&!data.restrictedTest){ + if(data.restrictedTest)panel.insertAdjacentHTML('afterbegin','
'+(restrictedActive?'受限稳定性测试:'+Number(data.restrictedTest.readyCount)+' / '+Number(data.restrictedTest.ruleCount)+' 类可用。保存后点击“应用到测试”,新任务使用新规则;旧订单和批次保持原快照。':'受限稳定性测试已暂停。可继续维护、验证和发布草稿;这些操作不会恢复测试发送。')+(data.restrictedTest.uncovered?.length?'另有 '+Number(data.restrictedTest.uncovered.length)+' 个流程缺少字段适配,对应订单不会自动归档或发送。':'')+'查看测试设置
'); + if(admin&&rule.publishedVersion&&!restrictedActive){ const migration=document.createElement('section');migration.className='card mt-3'; migration.innerHTML='

将未冻结订单迁移到已发布版本

仅当前已发布版本。冻结、发送及结果不确定订单不改写;输出变化会要求新代归档。

'; panel.querySelector('.rule-editor-column').append(migration); @@ -39,6 +39,7 @@ }); } const form=panel.querySelector('#order-rule-editor'),owned=()=>isActive()&&panel.querySelector('#order-rule-editor')===form; + if(admin&&restrictedActive){form.querySelector('#order-rule-publish').textContent='应用到测试';panel.querySelector('#rule-version-state').textContent='草稿 v'+rule.version+' · 当前测试 '+(rule.testVersion?'v'+rule.testVersion:'未应用')+' · Excel 行 '+(rule.sourceRow??'—');} const read=()=>window.OrderRuleEditor.read(form,rule,data.adapters);let baseline; function coverage(){ const value=read(),missing=value.processNames.filter(p=>!data.adapters.some(a=>a.processName===p&&a.verified&&!a.reference&&value.adapterIds.includes(a.id))); @@ -51,7 +52,7 @@ panel.querySelector('#order-rule-explanation').textContent=window.OrderRuleEditor.describe(read()); panel.querySelector('#order-rule-dirty').textContent=dirty?'有未保存的修改。保存后请重新检查识别结果,再发布。':''; panel.querySelector('#order-rule-preview-result').innerHTML='

配置已变化,请重新检查。

'; - const publish=panel.querySelector('#order-rule-publish');if(publish)publish.disabled=dirty||saving||!!data.restrictedTest;coverage();refreshSources(); + const publish=panel.querySelector('#order-rule-publish');if(publish)publish.disabled=dirty||saving;coverage();refreshSources(); } const catalog=[...data.rules.flatMap(window.OrderRuleScopes.scopesFor).filter(s=>!/历史查看|未提供办理节点/.test(s.nodeName)),...data.samples.filter(c=>c.sample?.source==='todo').map(c=>({processName:c.processName,nodeName:c.sample?.nodeName})).filter(r=>r.nodeName&&!/历史查看|未提供办理节点/.test(r.nodeName))]; scopeController=window.OrderRuleScopes.bind(panel.querySelector('#rule-scopes'),{catalog,esc,admin,onChange:changed}); @@ -63,7 +64,7 @@ async function mutate(work){ if(saving||!owned())return false;saving=true;form.setAttribute('aria-busy','true'); const locked=[...panel.querySelectorAll('input,select,textarea,button'),container.querySelector('#rule-import-open')].filter(e=>e&&!e.disabled);locked.forEach(e=>e.disabled=true); - try{return await work();}finally{saving=false;form.removeAttribute('aria-busy');if(form.isConnected){locked.forEach(e=>{if(e.isConnected)e.disabled=false;});const publish=form.querySelector('#order-rule-publish');if(publish)publish.disabled=dirty||!!data.restrictedTest;}const open=container.querySelector('#rule-import-open');if(open?.isConnected)open.disabled=false;} + try{return await work();}finally{saving=false;form.removeAttribute('aria-busy');if(form.isConnected){locked.forEach(e=>{if(e.isConnected)e.disabled=false;});const publish=form.querySelector('#order-rule-publish');if(publish)publish.disabled=dirty;}const open=container.querySelector('#rule-import-open');if(open?.isConnected)open.disabled=false;} } refreshCurrent=()=>mutate(reload);mutationCurrent=mutate; async function save(){ @@ -73,7 +74,7 @@ unregister=window.PageLifecycle.register({dirty:()=>owned()&&dirty,save:admin?save:null}); if(admin){ form.onkeydown=event=>{if(event.key==='Enter'&&event.target.tagName==='INPUT'&&event.target.closest('#rule-scopes'))event.preventDefault();};form.oninput=form.onchange=event=>{if(!['rule-scope-search','order-rule-sample-source','rule-storage-server','rule-storage-folder'].includes(event.target.id))changed();};form.onsubmit=event=>{event.preventDefault();return save();}; - panel.querySelector('#order-rule-publish').onclick=event=>action(event.currentTarget,async()=>{if(dirty||saving)throw Error('请先保存当前修改,再检查识别结果并发布。');return mutate(async()=>{await api('/order-rules/rules/'+encodeURIComponent(rule.id)+'/publish',{version:rule.version});if(!owned())return;await window.PageLifecycle.afterSave(reload,'规则版本已发布。自动执行仍由全局设置与接入状态控制。',feedback,isActive);});}); + panel.querySelector('#order-rule-publish').onclick=event=>action(event.currentTarget,async()=>{if(dirty||saving)throw Error('请先保存当前修改,再应用或发布。');return mutate(async()=>{if(restrictedActive)await api('/order-rules/restricted-test/apply',{version:data.restrictedTest.version,rules:[{id:rule.id,version:rule.version}]});else await api('/order-rules/rules/'+encodeURIComponent(rule.id)+'/publish',{version:rule.version});if(!owned())return;await window.PageLifecycle.afterSave(reload,restrictedActive?'规则已应用到测试,新任务使用当前规则;旧订单和批次保持不变。':'规则版本已发布。自动执行仍由全局设置与接入状态控制。',feedback,isActive);});}); } if(operator)panel.querySelector('#order-rule-preview').onclick=event=>action(event.currentTarget,async()=>{ if(saving||!form.reportValidity())return;const request=++trialRevision,evidence=sources.find(a=>a.id===source.value);if(!evidence)throw Error('请选择已采集的真实 BPM 订单。');