diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index c0dcfc2..dd90f9d 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -6,11 +6,11 @@ 15类规则草稿主送均为用户指定QQ、抄送清空,归档目录均在 `C:/Users/ABS/Desktop/订单通知稳定性测试-20261021-180837` 的分类子目录。163通道SMTP/IMAP验证通过;授权码仅由应用加密保存,不写文档或Git。一封无订单、无附件的测试邮件已被SMTP接受,尚无用户收件确认。真实PDF生成、桌面归档及大小/SHA256读回验证通过;测试文件保留供用户检查。 -31份既有字段映射重新检查后已生效,采样仍为31份(4待办、27历史)。仅“备损订单通知书”具备真实通知节点样本,已按原检查/发布契约启用;另外14类尚未发布,历史样本没有冒充通知到达或发布依据。所有惠州附加通知开关仍关闭。用户尚未回复“受限模式覆盖15类/仅运行具备真实通知样本类别”的范围问题,未实现新的受限测试模式。 +31份既有字段映射重新检查后已生效,采样仍为31份(4待办、27历史)。正式发布仍只有“备损订单通知书”;另外14类的历史样本没有冒充正式通知到达或发布依据。用户已明确选择受限测试模式,现已建立15类独立测试快照;运行规则与正式published完全分离,惠州附加通知开关仍关闭。当前有1个流程“零售国内返工订单更改评审”没有字段覆盖,测试配置保留该流程级阻塞,不放宽到未核验字段。 自动处理与自动分类发信均已开启,version=3,接收时间基线为北京时间2026-10-21 18:35:22;早于基线的历史不回放。沿用原发送计划:北京时间11:00/17:00、默认工作日并受业务日历控制;无符合条件订单不发空邮件。18:47复核原npm start后台服务running、心跳更新,订单和批次均为0;当前真实待办未命中目标通知节点,不能宣称业务邮件或15类端到端已经验收。 -普通重启会清空内存运行能力,页面可能显示“自动通知受阻”;新匹配订单会先真实采集并探测运行条件,再识别/归档。不得手工伪造ready标志。设置和目录已经验证不等于自然到达闭环已经稳定,仍需后续观察。配置、备份和证据见[本机稳定性测试记录](local-stability-test-2026-10-21.md)。本轮仅配置及文档变更,无产品代码修改。 +普通重启会清空内存运行能力,页面可能显示“自动通知受阻”;新匹配订单会先真实采集并探测运行条件,再识别/归档。不得手工伪造ready标志。受限模式只接受测试基线之后的真实todo,拒绝历史、配置采样、演示和未来时间;暂停保留快照,不切换为正式发送。设置和目录已经验证不等于自然到达闭环已经稳定,仍需后续观察。配置、备份和证据见[本机稳定性测试记录](local-stability-test-2026-10-21.md)及[受限模式验收](restricted-stability-verification-2026-10-22.md)。本轮代码已提交,本机测试服务已恢复。 ## 惠州附加通知(功能交付记录) diff --git a/docs/local-stability-test-2026-10-21.md b/docs/local-stability-test-2026-10-21.md index 8fc106b..c9bb06e 100644 --- a/docs/local-stability-test-2026-10-21.md +++ b/docs/local-stability-test-2026-10-21.md @@ -19,8 +19,9 @@ | 分类归档 | 15个分类子目录;缺少文件名日期来源的草稿设为收到时间 `receivedAt` | | 扩展归档 | 自动归档开启并建立新基线,既有历史不回放 | | 字段映射 | 31份重新检查并生效;样本仍31份,其中4待办、27历史 | -| 已启用类别 | 仅备损订单通知书 `bs-notice`,使用既有真实通知节点样本按原契约检查及发布 | -| 其余14类 | 草稿邮箱/目录已配置,缺少真实通知节点依据,尚未发布 | +| 正式发布类别 | 仅备损订单通知书 `bs-notice`,使用既有真实通知节点样本按原契约检查及发布 | +| 受限测试类别 | 15类均建立独立测试快照;仅处理测试基线后真实 `todo`,不改变正式 `published` | +| 流程级阻塞 | `domestic-change` 下的“零售国内返工订单更改评审”暂无字段覆盖,保留阻塞 | | 惠州通知 | 15类开关仍关闭,尚无惠州业务邮件验收 | | 自动开关 | `processingEnabled=true`、`enabled=true`、version=3 | | 接收基线 | 北京时间2026-10-21 18:35:22,基线之前历史不自动入队 | @@ -43,7 +44,7 @@ ## 尚待观察与确认 -当前没有新的符合条件通知到达,因此尚未验证真实新订单自动入队、分类批次冻结和业务邮件实际收件。其他14类与惠州附加通知均不属于当前已运行覆盖。用户尚未回复是否另建严格限制QQ/桌面目的地、与正式发布分开的15类受限测试模式;未实现该模式,不推定同意放宽原发布凭据。 +当前没有新的符合条件通知到达,因此尚未验证真实新订单自动入队、分类批次冻结和业务邮件实际收件。受限模式已覆盖15类快照,但“零售国内返工订单更改评审”仍因字段缺失阻塞;惠州附加通知仍关闭。测试模式与正式发布依据分开,不能把受限快照直接当作投产发布凭据。 普通服务重启会清空内存中的提供器运行能力,页面目前可能显示“自动通知受阻”。执行器会在新匹配订单实际采集后重新探测,再识别/归档;这些运行能力未持久为人工ready。后续需观察首次自然到达、断网/重启恢复、两个发送时点及实际QQ收件。SMTP结果不明继续由人工核验,禁止自动重发。 diff --git a/docs/restricted-stability-verification-2026-10-22.md b/docs/restricted-stability-verification-2026-10-22.md new file mode 100644 index 0000000..766b6fa --- /dev/null +++ b/docs/restricted-stability-verification-2026-10-22.md @@ -0,0 +1,34 @@ +# 15类受限稳定性测试验收 + +日期:2026-10-22(北京时间)。工作树为 `C:/Users/ABS/.codex/worktrees/modular-refactor/Order Notification Automation`,分支 `codex/modular-refactor`。本轮在用户确认“受限测试模式,覆盖15类”后实施;未操作服务机、未办理BPM节点、未推送合并。 + +## 运行配置 + +- 已建立受限测试运行快照,15类独立保存测试规则、字段适配证据、接收基线、固定通道和归档根目录。 +- 测试基线为2026-10-22 08:39:01(北京时间)。只接受基线之后的真实 BPM `todo`;历史、字段配置采样、演示样本、未来时间和非待办来源均拒绝。 +- 固定使用既有QQ测试收件配置和桌面稳定性测试目录,抄送为空;写文件和SMTP发送前再次检查固定边界。 +- 暂停只暂停受限快照,恢复时校验版本和字段证据;不会回落到正式规则,也不会把历史订单补发。 +- 正式 `published` 状态保持原样,当前仍只有 `bs-notice`;受限测试不产生正式发布凭据。惠州通知保持关闭。 +- 15类中有1个流程级阻塞:`domestic-change` 的“零售国内返工订单更改评审”尚无字段覆盖。该流程不会因受限模式而绕过字段映射。 + +## 实施边界 + +`restricted-test.cjs` 独立维护测试配置、快照、固定地址和适配证据摘要。RuleStore、只读执行器、归档提供器和邮件调度器在最终边界重新校验测试运行标识、QQ单收件人、桌面子目录、字段版本、基线和暂停状态。正式规则迁移在受限测试期间被拒绝;订单/批次详情显示受限测试标识。管理员可暂停/恢复,其他角色只读。 + +## 专项验证 + +- 13项受限测试通过:15类快照与正式发布隔离、历史及未来事件拒绝、15类未来真实节点匹配、重启恢复、固定目的地、路径穿越/符号链接拦截、SMTP前后边界、暂停恢复、权限、API、UI、unknown结果和禁止自动重发。 +- 23项既有批次调度测试通过;一次组合执行被长时间运行测试中断,随后拆分运行确认批次调度文件全量23项通过。 +- 完整 `npm test` 最终退出0:733项,732通过、0失败、1项可选集成跳过。此前一次组合运行的Excel偶发失败和一次执行边界超时均已单独复现定位并修复后重新通过。 +- 14个本轮修改/新增 JS/CJS 文件语法检查通过,`git diff --check` 通过。 +- `npm ci` 使用原锁文件完成;保留原有2项中危依赖审计提示,未做无关升级。 + +## 本机服务读回 + +停服后创建并验证受限模式备份,再恢复 `npm start`。只读读回确认:服务running且心跳新鲜,受限快照15类/15类可用,正式发布仍仅`bs-notice`,自动处理和自动发信仍开启,订单0、批次0。实际测试服务入口仍为 `http://127.0.0.1:18766/`。 + +配置脚本和读回结果保存在忽略目录 `output/verification`,不提交邮箱授权码、密码、业务PDF、数据库或凭据。桌面测试目录继续保留,用户可自行检查和删除。 + +## 未完成的现场闭环 + +尚无新的真实通知到达,故自然监听、首次真实订单PDF、分类冻结、SMTP最终收件仍待用户持续观察。受限测试可用于本机稳定性验证,正式投产前仍需按真实通知节点重新检查并发布;不因本轮受限快照改变正式发布门槛。 diff --git a/docs/superpowers/plans/2026-10-22-restricted-stability.md b/docs/superpowers/plans/2026-10-22-restricted-stability.md new file mode 100644 index 0000000..30af3d8 --- /dev/null +++ b/docs/superpowers/plans/2026-10-22-restricted-stability.md @@ -0,0 +1,52 @@ +# 受限稳定性测试 Implementation Plan + +> **For agentic workers:** 使用 superpowers:executing-plans,顺序实施并自审;用户已确认范围,无需重复批准,不创建子代理。 + +**Goal:** 15类以独立测试快照参与QQ/桌面受限测试,保留正式发布要求。 + +**Architecture:** `restricted-test.cjs` 管理持久配置、证据和边界;RuleStore选择实际执行快照;执行/归档/发送在最终操作处再次限制;现有页面展示模式。 + +**Tech Stack:** 原Node 22.13+、CommonJS、加密SQLite、原生页面/Tabler、node:test,不增依赖。 + +**Spec:** [已确认设计](../specs/2026-10-22-restricted-stability-design.md)。 + +## Global Constraints + +- 固定本工作树codex/modular-refactor,保留原账号及数据;BPM只读,不操作服务机、不推送合并。 +- 只处理测试基线以后真实通知;历史仅作字段依据;正式published及试运行证据不变。 +- 固定单一QQ及桌面根目录,写入/发送前验证;暂停不切换成正式模式,unknown不自动重发。 +- 日历及每日两时点、精确节点配对、冻结和受控恢复沿用;个人邮箱及凭据不进Git。 + +## 执行结果 + +2026-10-22已完成:独立测试配置、15类快照、真实todo基线过滤、执行/归档/SMTP边界、API与Tabler页面、暂停恢复和unknown保护均已实现并验收。1个流程缺少字段映射,按设计保持流程级阻塞。详细结果见[受限模式验收](../../restricted-stability-verification-2026-10-22.md)。 + +## Task 1: 独立测试配置和执行快照 + +Files: 新增 `src/modules/order-rules/restricted-test.cjs`、`tests/order-rules/restricted-test.test.cjs`;修改 `store.cjs`。 + +- [x] 使用实际临时RuleStore/服务端采样和生效映射建立测试fixture。历史证据只用于配置,旧事件不可入队,15类产生独立快照,暂停/重启保留隔离。 +- [x] 实现 `saveRestrictedTest(input,actor)`、`restrictedTest()`、`executionRule(record)`;固定recipient/archiveRoot/channelId,保存runId/since/rules/adapter证据摘要;后续仅启停。 +- [x] 在ingest、recheck、recordArchive、prepare、beginSending调用边界检查;测试快照绝不写入published。专项到绿。 + +## Task 2: 执行和外部操作边界 + +Files: 修改 `coordinator.cjs`、`dispatcher.cjs`、`storage/order-archive.cjs`;扩充上述测试。 + +- [x] 真实未来节点按测试规则执行,历史/旧时点跳过,字段更新阻塞;归档路径穿越/链接及收件篡改在外部副作用前失败。 +- [x] 执行器统一从executionRule选规则;归档probe/archive/read、SMTP前及verify后、人工重发执行持久测试边界检查,批次保留runId。 +- [x] 暂停/恢复、重启及unknown结果不会跨模式或重复发信。 + +## Task 3: API和页面 + +Files: 修改 `api.cjs`、`view.js`、规则及订单/批次展示;新增专项API/UI测试。 + +- [x] 管理员维护/其他角色只读、版本冲突、固定目的地修改拒绝、页面状态准确。 +- [x] 新增管理员POST `/api/order-rules/restricted-test`;发送设置显示固定配置与暂停/恢复按钮,复用禁重及生命周期。分类及业务记录展示独立测试标识。 +- [x] 检查页面刷新、暂停/恢复失败状态及窄屏内容;专项到绿。 + +## Task 4: 交付和本机配置 + +- [x] 停服完整备份并verify;以原锁文件npm ci,执行专项、核心批次回归、修改文件语法/文档链接/差异/私有文件检查,自审跨模块边界。 +- [x] 提交代码,使用受控本地操作读取现有QQ/桌面/通道生成15类测试配置;恢复原npm start,自动处理和发信保持开启,基线设为本次测试启用时间。 +- [x] 核对服务running、15类快照、正式发布仍仅原类别、原数据及固定目的地;补充HANDOFF和验收记录,不重复发诊断邮件。 diff --git a/docs/superpowers/specs/2026-10-22-restricted-stability-design.md b/docs/superpowers/specs/2026-10-22-restricted-stability-design.md new file mode 100644 index 0000000..0f4b915 --- /dev/null +++ b/docs/superpowers/specs/2026-10-22-restricted-stability-design.md @@ -0,0 +1,17 @@ +# 15类受限稳定性测试 + +用户于2026-10-22明确选择此前提出的受限测试方案,授权本机实施、验收和更新。只处理今后真实通知,邮件固定为指定QQ,归档限定既有桌面目录。BPM只读,不操作服务机,不推送合并。 + +## 行为 + +新增独立加密测试配置及规则快照,不改写 `published`、正式试运行或发布凭据。激活时复用已生效且有服务端采样依据的字段映射,历史仅用于字段检查,不伪造通知节点或到达。每类至少一个已验证版本才可启用;未覆盖流程保持阻塞。15类沿用原精确流程/节点配对、模板、附件、11:00/17:00及业务日历逻辑,惠州保持现有关闭设置。 + +首次启用生成独立runId和当前接收基线。测试运行只接受source=todo、非配置采样、非演示、收到时间不早于基线的实际采集事件。暂停保留快照、固定地址及原基线,恢复不建立历史补发。停用测试不会自动落回正式发送;切换投产由后续明确操作及真实发布检查处理。 + +收件仅允许一个QQ邮箱且无抄送,首次激活后不可在原测试配置中改变。归档根目录必须是当前Windows用户桌面的现有子目录,通过localhost管理共享映射,拒绝越界、路径穿越和符号链接越界。每个测试规则、订单和冻结批次保留runId及固定边界;写文件/回执、冻结/发信、人工补发均再次校验,修改草稿、配置或旧批次不能绕过。结果不明继续禁止自动重发。 + +发送设置显示测试运行状态、覆盖数、固定QQ/目录、起始时间,管理员可暂停/恢复,其他角色只读。分类列表显示测试启用与正式发布状态的区别;订单/批次详情显示受限测试标识。首次启动使用受控本地配置操作,不把个人邮箱写进Git。 + +## 实现和验收 + +独立模块负责测试配置验证、快照、运行规则选择和边界校验。原执行器及归档/发送提供器调用该模块;普通模式保持原契约。测试覆盖历史证据与正式发布隔离、15类快照、未来真实事件、重启/暂停、字段变化、QQ和桌面边界、并发配置变化、unknown恢复、管理员权限及页面状态。专项和全量通过后提交;更新前停服备份验证,保留原账号/密钥/数据,运行后只读核对。不为验收发送重复诊断邮件或办理BPM。 diff --git a/src/modules/order-execution/coordinator.cjs b/src/modules/order-execution/coordinator.cjs index b32cf46..591857c 100644 --- a/src/modules/order-execution/coordinator.cjs +++ b/src/modules/order-execution/coordinator.cjs @@ -51,7 +51,7 @@ class OrderExecutionCoordinator{ if(!snapshot||snapshot.processVersion!==sample.processVersion||!Array.isArray(snapshot.fields))throw Error('采集样本流程版本或实际字段证据不一致。'); } async checkArchivedRuntime(task,order,connection,principal){ - const published=this.store.get('rules',order.ruleSnapshot?.id)?.published; + const published=this.store.executionRule(this.store.get('rules',order.ruleSnapshot?.id)); if(published?.status!=='enabled')return; try{ if(!order.archive?.files?.length||typeof this.archive.read!=='function')throw Error('持久归档缺少可读回的文件证据。'); @@ -167,7 +167,9 @@ class OrderExecutionCoordinator{ this.store.transaction(()=>{ for(const row of rows){ if(row.source!=='todo')continue; - const rules=this.store.all('rules').map(r=>r.published?.status==='enabled'?r.published:r.draft).filter(rule=>matchesScope(rule,row)); + const testing=require('../order-rules/restricted-test.cjs').state(this.store); + if(testing&&(row.source!=='todo'||row.configurationOnly||Date.parse(row.receivedAt)this.store.executionRule(r)||(!testing?r.draft:null)).filter(rule=>rule&&matchesScope(rule,row)); if(!rules.length)continue; const id=hash([connection.id,row.source,String(row.instanceId),String(row.taskId),String(row.revision)]); let task=this.store.get('execution-tasks',id); @@ -254,7 +256,7 @@ class OrderExecutionCoordinator{ const captured=this.store.recordCapture({sample,snapshot,taskId:task.id});task.sampleId=captured.id;task.step='identify';this.persist(task); } const captured=this.store.get('capture-samples',task.sampleId);let order; - await this.refreshCapabilities(this.store.all('rules').find(r=>task.categoryIds.includes(r.id))?.published); + await this.refreshCapabilities(this.store.executionRule(this.store.all('rules').find(r=>task.categoryIds.includes(r.id)))); if(task.orderId){order=this.store.get('orders',task.orderId);if(order?.status==='blocked'&&!order.archive)try{order=this.store.recheck(order.id,{note:'重新扫描使用当前已核验规则'},principal.user.username);}catch(error){task.status='blocked';task.error=error.message;this.persist(task);await this.exception(task,connection,false);return;}} if(!order){order=this.store.ingest(captured.sample,principal.user.username);task.orderId=order.id;} Object.assign(task,this.store.get('execution-tasks',task.id)); diff --git a/src/modules/order-rules/api.cjs b/src/modules/order-rules/api.cjs index 21fb33f..1a257a3 100644 --- a/src/modules/order-rules/api.cjs +++ b/src/modules/order-rules/api.cjs @@ -29,7 +29,11 @@ async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,re } if(user.role!=='admin')fail('仅管理员可维护规则、批次与发送设置。',403); let result; - if(route==='/api/order-rules/import/preview')result=require('./import.cjs').previewImport(orderRules,body,actor); + if(route==='/api/order-rules/restricted-test'){ + if(body?.enabled){const channelId=orderRules.restrictedTest()?.channelId||body.channelId;if(!mail?.store.publicChannel(channelId)?.state.smtp)fail('请先验证测试发件邮箱SMTP。',409);for(const record of orderRules.all('rules'))if(!body.ruleIds||body.ruleIds.includes(record.id))checkTemplates(mail,orderRules.executionRule(record)||record.draft);} + 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/rules'){ const old=orderRules.get('rules',body?.id)?.draft; diff --git a/src/modules/order-rules/dispatcher.cjs b/src/modules/order-rules/dispatcher.cjs index b8ee5ff..3bad083 100644 --- a/src/modules/order-rules/dispatcher.cjs +++ b/src/modules/order-rules/dispatcher.cjs @@ -69,6 +69,7 @@ class OrderRuleDispatcher{ async dispatch(batch,config,{manual=false}={}){ let transport,sending=false; try{ + require('./restricted-test.cjs').assertBatch(this.store,batch,config); if(batch.channelId&&batch.channelId!==config.channelId){ this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。');return; } @@ -85,6 +86,7 @@ class OrderRuleDispatcher{ if(manual?this.stopped||!this.providersReady()||!this.store.providersReady():!this.ready()||this.store.settings().channelId!==config.channelId)throw Error('发送已暂停或配置已变更。'); if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>1800000)throw Error('冻结发送队列超过30分钟。'); this.mail.store.guard(channel.id,channel.version); + require('./restricted-test.cjs').assertBatch(this.store,batch,config); this.store.beginSending(batch.id,{manual});sending=true; const result=await transport.sendMail({from:{address:channel.email,name:channel.name},to:[...batch.to],cc:[...batch.cc],subject:batch.subject,text:batch.text,html:batch.html,attachments,messageId:`<${batch.id}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true}); const accepted=new Set((result?.accepted||[]).map(address=>String(address.address||address).toLowerCase())); @@ -107,6 +109,7 @@ class OrderRuleDispatcher{ const replay=record=>{if(record.inputHash!==inputHash)fail('此幂等标识已用于不同的补发请求。',409);return this.store.get('batches',record.batchId);}; const prior=this.store.get('resend-requests',requestId);if(prior)return replay(prior); const original=this.store.get('batches',id);if(!original)fail('批次不存在。',404); + require('./restricted-test.cjs').assertBatch(this.store,original,{...this.store.settings(),channelId:original.channelId}); if(!original.channelId)fail('原批次未冻结发件邮箱,不能补发。',409); const operation=this.mail.exclusive(original.channelId,async()=>{ const previous=this.store.get('resend-requests',requestId);if(previous)return replay(previous); diff --git a/src/modules/order-rules/migrations.cjs b/src/modules/order-rules/migrations.cjs index 267d314..64b4828 100644 --- a/src/modules/order-rules/migrations.cjs +++ b/src/modules/order-rules/migrations.cjs @@ -56,6 +56,7 @@ function synchronizeTasks(store,order){ } } function preview(store,id,input){ + if(require('./restricted-test.cjs').state(store))fail('受限测试期间不能向正式规则迁移订单,投产须另行检查。',409); validate(input); const rule=store.get('rules',id)?.published; if(!rule||rule.status!=='enabled'||input.version!==rule.version){ diff --git a/src/modules/order-rules/query.cjs b/src/modules/order-rules/query.cjs index 13a3369..15f9046 100644 --- a/src/modules/order-rules/query.cjs +++ b/src/modules/order-rules/query.cjs @@ -38,7 +38,7 @@ function taskEvidence(task,context,user){ } function orderRow(order,task){ const event=identity(order?.event||task?.row); - return {...event,...pick(order,['id','status','categoryId','error','reason','batchId','createdAt','updatedAt','orderNo','receivedAt']),...(order?{notifications:notifications(order)}:{}), + return {...event,...pick(order,['id','status','categoryId','error','reason','batchId','createdAt','updatedAt','orderNo','receivedAt']),...(order?{notifications:notifications(order),...(order.ruleSnapshot?.testRunId?{testRunId:order.ruleSnapshot.testRunId}:{})}:{}), id:order?.id||'task:'+task.id,connectionId:order?.sample?.connectionId||event.connectionId||task?.connectionId, error:task?.error||order?.error,executionTaskId:task?.id,executionStatus:task?.status,exceptionId:task?.exceptionId,orderNo:order?.orderNo||event.orderNo||event.serialNum||event.taskId, categoryId:order?.categoryId||task?.categoryIds?.[0]||'',status:task&&['failed','blocked','unknown','capturing','archiving'].includes(task.status)?task.status:order?.status||task?.status}; @@ -77,7 +77,7 @@ function publicRevision(context,user){ } function queryOrders(context,input,user){return page(visibleOrders(context,user),filters(input,'orders'),publicRevision(context,user));} function batchRow(context,batch){ - return {...pick(batch,['id','version','categoryId','subject','status','error','createdAt','windowStart','windowEnd','cutoff','orderNos']),notificationMode:modeOf(batch),windowStart:batch.windowStart||batch.window?.start,windowEnd:batch.windowEnd||batch.window?.end||batch.cutoff,orderCount:batch.orderIds?.length||0,connectionIds:[...new Set((batch.orderIds||[]).map(id=>{const o=context.orderRules.get('orders',id);return o?.sample?.connectionId||o?.event?.connectionId||o?.connectionId;}).filter(Boolean))]}; + return {...pick(batch,['id','version','categoryId','subject','status','error','createdAt','windowStart','windowEnd','cutoff','orderNos','testRunId']),notificationMode:modeOf(batch),windowStart:batch.windowStart||batch.window?.start,windowEnd:batch.windowEnd||batch.window?.end||batch.cutoff,orderCount:batch.orderIds?.length||0,connectionIds:[...new Set((batch.orderIds||[]).map(id=>{const o=context.orderRules.get('orders',id);return o?.sample?.connectionId||o?.event?.connectionId||o?.connectionId;}).filter(Boolean))]}; } function queryBatches(context,input,user){ const f=filters(input,'batches'),data=records(context.orderRules); diff --git a/src/modules/order-rules/restricted-test.cjs b/src/modules/order-rules/restricted-test.cjs new file mode 100644 index 0000000..63598fe --- /dev/null +++ b/src/modules/order-rules/restricted-test.cjs @@ -0,0 +1,82 @@ +'use strict'; +const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto'); +const {fail,publicationIssues,addresses}=require('./validation.cjs'); +const {scopesFor}=require('./scopes.cjs'); +const canonical=v=>Array.isArray(v)?v.map(canonical):v&&typeof v==='object'?Object.fromEntries(Object.keys(v).sort().map(k=>[k,canonical(v[k])])):v; +const hash=v=>crypto.createHash('sha256').update(JSON.stringify(canonical(v))).digest('hex'); +const state=store=>typeof store?.get==='function'?store.get('restricted-test','main')?.value||null:null; +function localPath(unc){ + if(typeof unc!=='string'||/[\x00-\x1f/:]/.test(unc)||!/^\\\\localhost\\[a-z]\$\\/i.test(unc)||unc.split('\\').some(p=>p==='.'||p==='..'||/[. ]$/.test(p)))fail('受限测试仅允许当前用户桌面的localhost共享子目录。',409); + return unc[12]+':\\'+unc.slice(15); +} +function inside(root,target){const relative=path.win32.relative(root,target);return !relative.startsWith('..')&&!path.win32.isAbsolute(relative);} +function realAncestor(target){let current=target;while(!fs.existsSync(current)){const parent=path.dirname(current);if(parent===current)fail('受限测试目录不可访问。',409);current=parent;}return fs.realpathSync(current);} +function assertPath(store,directory,run=state(store)){ + if(!run)return; + const root=localPath(run.archiveRoot),target=localPath(directory); + if(!inside(root,target)||!inside(fs.realpathSync(root),realAncestor(target)))fail('受限测试归档超出固定桌面目录。',409); +} +function evidence(store,adapter){ + const captured=store.get('capture-samples',adapter.sampleId||''); + if(!captured||captured.provenance!=='server-provider'||captured.sample?.demo||captured.evidenceHash!==adapter.evidenceHash||captured.processName!==adapter.processName||captured.processVersion!==adapter.processVersion)return false; + const result=require('./field-mappings.cjs').evaluateMapping(store,{...adapter,version:adapter.version},captured,{relatedRules:[]}); + return result.valid; +} +function summary(store){const run=state(store);if(!run)return null;return {id:run.id,version:run.version,enabled:run.enabled,recipient:run.recipient,archiveRoot:run.archiveRoot,channelId:run.channelId,since:run.since,ruleCount:run.rules.length,readyCount:run.rules.filter(r=>validRule(store,r,run)).length,uncovered:run.uncovered};} +function validRule(store,rule,run){return run.enabled&&hash(rule.adapterIds.map(id=>store.adapters().find(a=>a.id===id)))===run.adapterHashes[rule.id];} +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 save(store,input,actor){ + if(actor?.role!=='admin'||!actor.username)fail('仅管理员可以维护受限测试。',403); + return store.transaction(()=>{ + const old=state(store),keys=['version','enabled','recipient','archiveRoot','channelId','ruleIds']; + if(!input||Object.keys(input).some(k=>!keys.includes(k))||typeof input.enabled!=='boolean'||input.version!==(old?.version||0))fail('受限测试配置已变化,请刷新。',409); + if(old){ + for(const key of ['recipient','archiveRoot','channelId'])if(input[key]!==undefined&&input[key]!==old[key])fail('受限测试目的地已固定,不能通过启停修改。',409); + if(input.ruleIds&&hash([...input.ruleIds].sort())!==hash(old.rules.map(r=>r.id).sort()))fail('受限测试类别已固定。',409); + const next={...old,enabled:input.enabled,version:old.version+1}; + if(next.enabled){assertPath(store,next.archiveRoot,next);if(next.rules.some(r=>!validRule(store,r,next)))fail('测试字段配置已变化,需要重新核验,不能直接恢复。',409);} + store.put('restricted-test',{id:'main',value:next});store.audit(actor.username,next.enabled?'恢复受限测试':'暂停受限测试',next.id);return summary(store); + } + if(!input.enabled)fail('尚未建立受限测试配置。',409); + const [recipient]=addresses([input.recipient]);if(!/^[\w.!#$%&'*+\/=?^`{|}~-]+@qq\.com$/i.test(recipient))fail('受限测试只允许一个QQ收件箱。',409); + const local=localPath(input.archiveRoot),desktop=store.desktopRoot; + if(!fs.existsSync(local)||!fs.statSync(local).isDirectory()||!inside(desktop,local)||path.win32.relative(desktop,local)===''||!inside(fs.realpathSync(desktop),fs.realpathSync(local)))fail('请选择当前用户桌面内已有的测试子目录。',409); + if(typeof input.channelId!=='string'||!input.channelId||input.channelId.length>100)fail('请选择已验证的测试发件通道。',409); + if(!Array.isArray(input.ruleIds)||!input.ruleIds.length||new Set(input.ruleIds).size!==input.ruleIds.length)fail('请选择测试类别。',409); + const run={id:crypto.randomUUID(),version:1,enabled:true,recipient,archiveRoot:input.archiveRoot,channelId:input.channelId,since:store.now(),rules:[],uncovered:[],adapterHashes:{}}; + for(const id of input.ruleIds){ + const record=store.get('rules',id);if(!record)fail('测试类别不存在。',409); + const draft=record.draft,adapters=store.adapters().filter(a=>a.verified&&!a.reference&&draft.adapterIds.includes(a.id)&&evidence(store,a)); + const covered=draft.processNames.filter(p=>adapters.some(a=>a.processName===p)); + run.uncovered.push(...draft.processNames.filter(p=>!covered.includes(p)).map(processName=>({categoryId:id,processName}))); + const rule={...structuredClone(draft),processNames:covered,scopes:scopesFor(draft).filter(s=>covered.includes(s.processName)),adapterIds:adapters.map(a=>a.id),status:'enabled',testRunId:run.id,testSince:run.since,testArchiveRoot:run.archiveRoot}; + if(!covered.length||!rule.scopes.length)fail('类别缺少已验证的真实字段证据:'+draft.name,409); + assertRule(store,rule,run); + const issues=publicationIssues(rule,adapters);if(issues.length)fail(issues.join(';'),409); + if(run.rules.some(r=>require('./scopes.cjs').scopesOverlap(r,rule)))fail('测试类别存在流程节点冲突。',409); + run.rules.push(rule);run.adapterHashes[id]=hash(rule.adapterIds.map(id=>store.adapters().find(a=>a.id===id))); + } + store.put('restricted-test',{id:'main',value:run});store.audit(actor.username,'建立受限测试',run.id+' '+run.rules.length+'类');return summary(store); + }); +} +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); + if(rule.to?.length!==1||rule.to[0]!==run.recipient||rule.cc?.length)fail('受限测试收件人必须为固定QQ且无抄送。',409); + assertPath(store,rule.archiveDirectory,run); +} +function assertEvent(store,sample){const run=state(store);if(!run)return; + if(!run.enabled||sample?.demo||sample?.source!=='todo'||sample.configurationOnly||!Number.isFinite(Date.parse(sample.receivedAt))||Date.parse(sample.receivedAt)Date.parse(store.now())+60000)fail('受限测试只处理启用基线之后新到达的真实待办通知。',409); +} +function assertOrder(store,order){assertRule(store,order?.ruleSnapshot);if(state(store)||order?.ruleSnapshot?.testRunId){assertEvent(store,order.sample||order.event);for(const file of order.archive?.files||[])assertPath(store,file.path);}} +function assertBatch(store,batch,config){ + const run=state(store);if(!run&&!batch.ruleSnapshot?.testRunId)return; + assertRule(store,batch.ruleSnapshot,run);if(batch.testRunId!==run.id||batch.channelId!==run.channelId||config.channelId!==run.channelId||batch.to?.length!==1||batch.to[0]!==run.recipient||batch.cc?.length)fail('受限测试批次目的地与固定配置不一致。',409); + for(const file of batch.attachments||[])assertPath(store,file.path,run); + for(const id of batch.orderIds||[]){const order=store.get('orders',id);if(!order)fail('测试批次订单不存在。',409);assertOrder(store,order);} +} +module.exports={state,summary,save,executionRule,assertPath,assertRule,assertEvent,assertOrder,assertBatch}; diff --git a/src/modules/order-rules/store.cjs b/src/modules/order-rules/store.cjs index d370673..dcff328 100644 --- a/src/modules/order-rules/store.cjs +++ b/src/modules/order-rules/store.cjs @@ -15,7 +15,8 @@ const copy=value=>structuredClone(value); const BASE_CAPABILITIES={liveTodo:false,pdfExport:false,automaticArchive:false}; function validDate(value){return typeof value==='string'&&/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)&&Number.isFinite(Date.parse(value));} class RuleStore{ - constructor(dir,{clock=()=>new Date(),capabilities={},seedOverrides=[],schedule=()=>({times:['11:00','17:00'],weekends:false}),calendar=()=>[]}={}){ + constructor(dir,{clock=()=>new Date(),capabilities={},seedOverrides=[],schedule=()=>({times:['11:00','17:00'],weekends:false}),calendar=()=>[],desktopRoot=path.join(require('node:os').homedir(),'Desktop')}={}){ + this.desktopRoot=desktopRoot; this.clock=clock;this.schedule=schedule;this.calendar=calendar;this.capabilities={...BASE_CAPABILITIES,...capabilities}; try{ fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')}); @@ -43,6 +44,9 @@ class RuleStore{ }catch(error){try{this.db?.close();}catch{}this.vault?.destroy();throw error;} } 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);} + 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);} fields(){return registry.fields(this);} @@ -64,6 +68,7 @@ class RuleStore{ settings(){const {id,...settings}=this.get('settings','main');return {...settings,processingEnabled:settings.processingEnabled??settings.enabled,processingSince:settings.processingSince??null};} saveSettings(input,actor){return this.transaction(()=>{ const old=this.settings(); + const testing=this.restrictedTest();if(testing&&input?.channelId!==testing.channelId)fail('受限测试发件通道已固定。',409); if(!input||Object.keys(input).some(k=>!['version','enabled','processingEnabled','processingSince','channelId','maxMessageBytes'].includes(k))||input.version!==old.version)fail('设置已变化,请刷新。',409); if(typeof input.enabled!=='boolean'||typeof input.channelId!=='string'||input.channelId.length>100||!Number.isInteger(input.maxMessageBytes)||input.maxMessageBytes<1024||input.maxMessageBytes>100*1024*1024)fail('邮箱或邮件大小限制无效。'); if(input.enabled&&(!this.providersReady()||!input.channelId))fail('待办接入、PDF 导出与自动归档尚未全部联调,暂不能启用自动发送。',409); @@ -74,7 +79,8 @@ 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)})); - return {rules,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())}; + 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';} + 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(()=>{ const record=this.get('rules',input?.id);if(!record)fail('规则不存在。',404); @@ -88,6 +94,7 @@ class RuleStore{ return result; } publish(id,input,actor){return this.transaction(()=>{ + if(this.restrictedTest()?.enabled)fail('受限测试运行期间不能发布正式分类规则;请先暂停测试并重新检查真实通知。',409); const record=this.get('rules',id);if(!record)fail('规则不存在。',404); if(input?.version!==record.draft.version)fail('规则已变化,请刷新。',409); const issues=publicationIssues(record.draft,this.adapters()); @@ -119,12 +126,13 @@ class RuleStore{ record.published.status='enabled';record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);this.audit(actor,'启用已发布规则',id+' v'+record.published.version);return this.snapshot().rules.find(r=>r.id===id); });} matchingPublications(sample){ - const rules=this.all('rules').filter(r=>r.published).map(r=>r.published); + const rules=this.all('rules').map(r=>this.executionRule(r)).filter(Boolean); const enabled=rules.filter(r=>r.status==='enabled'); const hasEnabledMatch=enabled.some(r=>matchesScope(r,sample)); return hasEnabledMatch?enabled:rules; } ingest(sample,actor){return this.transaction(()=>{ + require('./restricted-test.cjs').assertEvent(this,sample); if(sample?.demo)fail('演示样本仅用于试运行,不能创建正式任务。'); if(!sample||['connectionId','source','instanceId','taskId','revision'].some(k=>!['string','number'].includes(typeof sample[k])||!String(sample[k]).trim()||String(sample[k]).length>250))fail('缺少来源、流程实例、任务及业务修订标识。'); sample=copy(sample);for(const key of ['connectionId','source','instanceId','taskId','revision'])sample[key]=String(sample[key]).trim(); @@ -134,6 +142,7 @@ class RuleStore{ const active=this.matchingPublications(sample); const result=previewMatch(active,this.adapters(),sample),rule=active.find(r=>r.id===result.ruleId); const ready=this.providersReady(),enabled=rule?.status==='enabled'; + if(rule)require('./restricted-test.cjs').assertRule(this,rule); const order={id,sourceHash,event:result.event||copy(sample),sample:copy(sample),ruleSnapshot:rule?copy(rule):null,categoryId:result.categoryId||rule?.categoryId||'',status:result.valid&&ready&&enabled?'identified':'blocked',error:result.valid?(!enabled?'该类别规则已暂停。':ready?null:'待办接入、PDF 导出和自动归档待联调。'):result.issues.join(';'),ingestedAt:this.now(),updatedAt:this.now(),archive:null,batchId:null,trace:result}; order.notifications={huizhou:initialNotification(rule,order.event)}; const window=upcomingWindow(this.clock(),this.schedule(),this.calendar()); @@ -145,6 +154,7 @@ class RuleStore{ recordArchive(id,evidence,actor,expected){return this.transaction(()=>{ if(!this.capabilities.automaticArchive)fail('自动归档接入待联调。',409); const order=this.get('orders',id);if(!order)fail('订单任务不存在。',404); + require('./restricted-test.cjs').assertOrder(this,{...order,archive:evidence}); const stale=expected&&!require('./migrations.cjs').archiveContextMatches(this,order,expected); if(!stale){ if(!['identified','preparing'].includes(order.status))fail('当前状态不允许记录归档结果。',409); @@ -178,6 +188,7 @@ class RuleStore{ if(!order||order.blockedByBatchId||require('./migrations.cjs').frozen(this,order)||!['blocked','identified','preparing','archived','pending'].includes(order.status))fail('仅未进入批次的待处理订单可以重新识别。',409); const published=this.matchingPublications(order.sample); const result=previewMatch(published,this.adapters(),order.sample),rule=published.find(r=>r.id===result.ruleId); + require('./restricted-test.cjs').assertEvent(this,order.sample);if(rule)require('./restricted-test.cjs').assertRule(this,rule); if(!result.valid||rule?.status!=='enabled')fail(result.issues.join(';')||'对应规则尚未启用。',409); order.event=result.event;order.ruleSnapshot=copy(rule);order.categoryId=rule.categoryId;order.trace=result; if(order.notifications)order.notifications.huizhou=initialNotification(rule,order.event); @@ -237,7 +248,7 @@ class RuleStore{ const blockers=this.discoveryBlockers(cutoff); const resultId=(category,mode)=>category+':'+cutoff+(mode==='normal'?'':':'+mode); const existingBatch=(category,mode)=>this.all('batches').find(b=>b.categoryId===category&&modeOf(b)===mode&&Date.parse(b.cutoff)===Date.parse(cutoff)&&!(b.status==='cancelled'&&b.resolution?.resolution==='retry')); - for(const record of this.all('rules').filter(r=>r.published?.status==='enabled'))for(const mode of record.published.huizhouEnabled===true?['normal','huizhou']:['normal']){const categoryId=record.published.categoryId,existing=existingBatch(categoryId,mode);this.put('window-results',{id:resultId(categoryId,mode),categoryId,notificationMode:mode,cutoff,status:existing?'frozen':blockers.length?'blocked':'empty',batchId:existing?.id||null,error:blockers.join(';')||null,updatedAt:this.now()});} + for(const rule of this.all('rules').map(r=>this.executionRule(r)).filter(r=>r?.status==='enabled'))for(const mode of rule.huizhouEnabled===true?['normal','huizhou']:['normal']){const categoryId=rule.categoryId,existing=existingBatch(categoryId,mode);this.put('window-results',{id:resultId(categoryId,mode),categoryId,notificationMode:mode,cutoff,status:existing?'frozen':blockers.length?'blocked':'empty',batchId:existing?.id||null,error:blockers.join(';')||null,updatedAt:this.now()});} if(blockers.length)return []; const grouped=new Map(),batches=[]; for(const order of this.all('orders'))for(const mode of ['normal','huizhou']){ @@ -256,17 +267,19 @@ class RuleStore{ // companion after repairing a Hui-only blocker. Historical freezes stay closed. const normal=mode==='huizhou'&&existingBatch(rule.categoryId,'normal'); if(normal&&normal.huizhouPlanned!==true)continue; - const published=this.get('rules',rule.id)?.published; + const published=this.executionRule(this.get('rules',rule.id)); let error=!published||published.status!=='enabled'?'该类别规则已暂停。':null; if(!error&&published.version!==rule.version)error='本类别订单规则版本已过期,请应用当前已发布规则后处理。'; if(!error&&this.categoryIncomplete(rule.categoryId,window))error='本类别存在未完成的采集、归档或核验任务。'; if(!error&&mode==='huizhou'&&orders.some(o=>delivery(o,mode).issues?.length))error=orders.flatMap(o=>delivery(o,mode).issues||[]).join(';'); if(!error&&orders.some(o=>mode==='normal'?o.status!=='pending':!o.archive||!['pending','batched','sent','unknown'].includes(o.status)))error='本类别存在字段、文件或归档尚未准备完成的订单。'; let snapshot; - if(!error)try{const selected=ordersForMode(orders,mode);snapshot=buildBatch(rule,selected,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window,notificationMode:mode});snapshot=applyBodyTemplate(snapshot,this.templateResolver?.(rule.categoryId,rule,mode),selected,this.settings().maxMessageBytes);}catch(cause){error=cause.message;} + if(!error)try{for(const order of orders)require('./restricted-test.cjs').assertOrder(this,order);const selected=ordersForMode(orders,mode);snapshot=buildBatch(rule,selected,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window,notificationMode:mode});snapshot=applyBodyTemplate(snapshot,this.templateResolver?.(rule.categoryId,rule,mode),selected,this.settings().maxMessageBytes);}catch(cause){error=cause.message;} const key=resultId(rule.categoryId,mode); if(error){this.put('window-results',{id:key,categoryId:rule.categoryId,notificationMode:mode,cutoff,status:'blocked',error,updatedAt:this.now()});this.recordIssue('build:'+key,{component:'rules',notificationMode:mode,error,cutoff,categoryId:rule.categoryId,orderIds:orders.map(o=>o.id)});for(const original of orders){const order=this.get('orders',original.id);updateDelivery(order,mode,{error,...(mode==='huizhou'?{status:'blocked'}:{})});this.put('orders',order);}continue;} const batch={...snapshot,id:crypto.randomUUID(),version:1,status:'prepared',createdAt:this.now(),ruleSnapshot:copy(rule),channelId:this.settings().channelId,error:null}; + if(rule.testRunId)batch.testRunId=rule.testRunId; + require('./restricted-test.cjs').assertBatch(this,batch,this.settings()); if(mode==='normal')batch.huizhouPlanned=rule.huizhouEnabled===true&&orders.some(order=>!!order.notifications?.huizhou); this.put('batches',batch);this.put('window-results',{id:key,categoryId:rule.categoryId,notificationMode:mode,cutoff,status:'frozen',batchId:batch.id,updatedAt:this.now()}); const issue=this.get('business-issues','build:'+key);if(issue)this.put('business-issues',{...issue,status:'awaiting_verification',updatedAt:this.now()}); @@ -279,7 +292,8 @@ class RuleStore{ releaseBatchOrders(batch){for(const id of batch.orderIds){const order=this.get('orders',id),mode=modeOf(batch);if(delivery(order,mode)?.batchId===batch.id){updateDelivery(order,mode,{batchId:null});this.put('orders',order);}}} beginSending(id,{manual=false}={}){return this.transaction(()=>{ const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404); - if(!(manual&&batch.manual)&&this.get('rules',batch.ruleSnapshot.id)?.published?.status!=='enabled')fail('该类别规则已暂停,批次不能进入发送。',409); + require('./restricted-test.cjs').assertBatch(this,batch,this.settings()); + if(!(manual&&batch.manual)&&this.executionRule(this.get('rules',batch.ruleSnapshot.id))?.status!=='enabled')fail('该类别规则已暂停,批次不能进入发送。',409); if(this.batchIncomplete(batch)||!(manual&&batch.manual)&&this.discoveryBlockers(batch.cutoff).length)throw Object.assign(Error('待办扫描或类别订单尚不完整,等待完整扫描与恢复。'),{status:409,code:'DISCOVERY_INCOMPLETE'}); const orders=batch.orderIds.map(oid=>this.get('orders',oid)); if(this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&task.runtimeCheck?.status==='blocked'))fail('已归档订单的运行条件复核未通过,批次不能进入发送。',409); diff --git a/src/modules/storage/order-archive.cjs b/src/modules/storage/order-archive.cjs index df9afe2..57b3b18 100644 --- a/src/modules/storage/order-archive.cjs +++ b/src/modules/storage/order-archive.cjs @@ -5,6 +5,7 @@ const crypto=require('node:crypto'); const {segments,inside}=require('./files.cjs'); const {renderSnapshot}=require('../pdf/exporter.cjs'); const {archiveFilename}=require('./order-filename.cjs'); +const restricted=require('../order-rules/restricted-test.cjs'); const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])):value; const fingerprint=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex'); const fail=message=>Object.assign(new Error(message),{status:409}); @@ -21,6 +22,7 @@ class OrderArchiveProvider{ constructor({storage,outputDir,renderer=renderSnapshot,clock=()=>new Date(),journal}={}){this.storage=storage;this.outputDir=path.resolve(outputDir,'order-execution');this.renderer=renderer;this.clock=clock;this.last=null;this.probes=new Map();this.journal=journal;this.supportsRecovery=!!journal;} capabilities(){return {automaticArchive:!!this.last?.success,pdfExport:!!this.last?.success,checkedAt:this.last?.at,message:this.last?.message||'尚无经过实际生成和共享目录读回校验的订单归档。'};} async probe(rule){ + if(this.journal)restricted.assertRule(this.journal,rule); const key=fingerprint(rule.archiveDirectory),cached=this.probes.get(key);if(cached&&+this.clock()-Date.parse(cached.checkedAt)<300000)return cached; let temporary; try{ @@ -34,6 +36,7 @@ class OrderArchiveProvider{ } async archive(input){try{return await this.performArchive(input);}catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}} async performArchive({order,rule,snapshot,taskId}){ + if(this.journal){restricted.assertRule(this.journal,rule);restricted.assertOrder(this.journal,order);} const identity=taskId||order.id,generation=order.archiveGeneration||1,id=identity+':g'+generation; let previous=this.journal?.get('archive-intents',id); const legacy=generation===1&&!previous&&this.journal?.get('archive-intents',identity); @@ -57,6 +60,7 @@ class OrderArchiveProvider{ const intent=previous||{id,archiveGeneration:generation,outputFingerprint,sourceHash:order.sourceHash,chosen:new Date(chosen).toISOString(),directory:rule.archiveDirectory,filename,localPath:file,sha256:digest,size:local.length}; if(id&&this.journal&&!previous)this.journal.put('archive-intents',intent); if(previous?.evidence){const bytes=await this.read(previous.evidence.files[0]);if(bytes.length!==local.length||crypto.createHash('sha256').update(bytes).digest('hex')!==digest)throw fail('已归档文件读回校验失败。');this.last={success:true,at:this.clock().toISOString(),message:'已归档文件再次读回核验通过。'};return previous.evidence;} + if(this.journal){restricted.assertRule(this.journal,rule);restricted.assertPath(this.journal,path.win32.join('\\\\'+target.server.host,target.server.share,...segments(target.server.directory),...segments(target.relative)));} const receipt=await this.storage.run(target.server.id,async(server,signal)=>{ const saved=await this.storage.operation(server,'archive',[file,intent.filename,target.relative],signal); const check=await this.storage.operation(server,'readFile',[saved.relativePath],signal),bytes=Buffer.from(check.bytes); @@ -68,6 +72,7 @@ class OrderArchiveProvider{ }catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;} } async read(file){ + if(this.journal)restricted.assertPath(this.journal,file.path); const directory=path.win32.dirname(file.path),target=targetFor(this.storage,directory); const result=await this.storage.readFile(target.server.id,[target.relative,path.win32.basename(file.path)].filter(Boolean).join('/'));return Buffer.from(result.bytes); } diff --git a/tests/order-rules/restricted-test-ui.test.cjs b/tests/order-rules/restricted-test-ui.test.cjs new file mode 100644 index 0000000..8594ac2 --- /dev/null +++ b/tests/order-rules/restricted-test-ui.test.cjs @@ -0,0 +1,17 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs/promises'),path=require('node:path'); +const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs'); +async function setup(t,role='admin'){ + const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage({viewport:{width:390,height:844}});page.setDefaultTimeout(5000);await page.setContent('
'); + await page.addScriptTag({content:await fs.readFile(path.resolve('web/modules/order-notifications/view.js'),'utf8')}); + await page.evaluate(async role=>{window.active=true;window.calls=[];window.PageLifecycle={onDispose:()=>{},guard:fn=>fn(),dirty:()=>false};window.run={id:'run-1',version:2,enabled:true,recipient:'test@qq.com',archiveRoot:'\\\\localhost\\C$\\Users\\test\\Desktop\\run',since:'2026-10-22T01:00:00Z',ruleCount:15,readyCount:15,uncovered:[]};window.OrderNotificationViews.configure({user:{role},esc:v=>String(v??'').replaceAll('<','<'),formatDate:v=>v||'—',api:async(url,body)=>{if(body){calls.push({url,body});return new Promise((resolve,reject)=>{window.finish=()=>resolve({...run,version:3,enabled:false});window.fail=()=>reject(Error('保存失败'));});}return url==='/mail'?{channels:[]}:{settings:{version:1,enabled:true,processingEnabled:true},restrictedTest:run};}});await OrderNotificationViews.render(document.querySelector('#root'),()=>active,'settings');},role);return page; +} +test('settings shows fixed restricted scope and pause is single-flight with failure recovery',async t=>{ + const page=await setup(t);assert.match(await page.locator('main').innerText(),/受限稳定性测试/);assert.match(await page.locator('main').innerText(),/15/);assert.match(await page.locator('main').innerText(),/test@qq.com/); + const button=page.getByRole('button',{name:'暂停测试',exact:true});await button.click();assert.equal(await button.isDisabled(),true);await page.evaluate(()=>fail());await page.getByText('保存失败',{exact:true}).waitFor();assert.equal(await button.isEnabled(),true); + await button.click();await page.evaluate(()=>finish());await page.getByRole('button',{name:'恢复测试',exact:true}).waitFor(); + assert.deepEqual(await page.evaluate(()=>calls.map(c=>c.body)),[{version:2,enabled:false},{version:2,enabled:false}]);assert.equal(await page.locator('input[value="test@qq.com"]').count(),0); +}); +test('readonly members see restricted scope without an enable or pause action',async t=>{ + const page=await setup(t,'viewer');assert.match(await page.locator('main').innerText(),/受限稳定性测试/);assert.equal(await page.getByRole('button',{name:'暂停测试',exact:true}).count(),0); +}); diff --git a/tests/order-rules/restricted-test.test.cjs b/tests/order-rules/restricted-test.test.cjs new file mode 100644 index 0000000..1bcf138 --- /dev/null +++ b/tests/order-rules/restricted-test.test.cjs @@ -0,0 +1,115 @@ +'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'); +const {activateFieldMapping}=require('../fixtures/activate-field-mapping.cjs'); +const admin={username:'admin',role:'admin'}; +function fixture(t,{all=false}={}){ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'restricted-test-')),desktop=path.join(dir,'Desktop'),local=path.join(desktop,'run');fs.mkdirSync(local,{recursive:true}); + const root='\\\\localhost\\'+local[0]+'$'+local.slice(2),options={clock:()=>new Date('2026-10-22T01:00:00Z'),capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true},desktopRoot:desktop}; + let store=new RuleStore(path.join(dir,'state'),options);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});}); + const ids=all?store.all('rules').map(r=>r.id):['bs-change'];let sample; + for(const id of ids){const rule=store.get('rules',id).draft; + sample={connectionId:'c1',source:'history',configurationOnly:true,timestampType:'process-start',instanceId:'history-'+id,taskId:'h-'+id,revision:'1',processName:rule.processNames[0],processVersion:'test-1',nodeName:'历史节点',receivedAt:'2026-10-21T01:00:00Z',serialNum:'S-'+id,title:'订单号:123456 客户简称:测试客户',fields:{order:'123456'}}; + const captured=store.recordCapture({sample,snapshot:{processVersion:'test-1',fields:[{path:'order',label:'订单号',value:'123456'}]},taskId:sample.taskId}); + const active=activateFieldMapping(store,{sampleId:captured.id,processName:sample.processName,processVersion:sample.processVersion,fields:{orderNo:'order'}},admin); + const current=store.get('rules',id).draft; + store.saveRule({...current,adapterIds:[active.id],to:['test@qq.com'],cc:[],archiveDirectory:root+'\\'+id,filenameDate:'receivedAt'},'admin'); + } + const input=()=>({version:store.restrictedTest()?.version||0,enabled:true,recipient:'test@qq.com',archiveRoot:root,channelId:'test-channel',ruleIds:ids}); + return {get store(){return store;},root,local,desktop,sample,ids,input,reopen(){store.close();store=new RuleStore(path.join(dir,'state'),options);},future(patch={}){const r=store.get('rules','bs-change').draft;return {...sample,processName:r.processNames[0],nodeName:r.nodeNames[0],source:'todo',configurationOnly:false,timestampType:'received',instanceId:'live-1',taskId:'live-1',receivedAt:'2026-10-22T01:00:01Z',...patch};}}; +} +test('history prepares 15 independent test snapshots without granting formal publication',t=>{ + const f=fixture(t,{all:true}),before=f.store.all('rules').map(r=>[r.id,r.published,r.trialSampleId]); + const run=f.store.saveRestrictedTest(f.input(),admin); + assert.equal(run.enabled,true);assert.equal(run.ruleCount,15);assert.equal(run.since,'2026-10-22T01:00:00.000Z'); + assert.deepEqual(f.store.all('rules').map(r=>[r.id,r.published,r.trialSampleId]),before); + for(const record of f.store.all('rules')){const rule=f.store.executionRule(record);assert.equal(rule.testRunId,run.id);assert.deepEqual(rule.to,['test@qq.com']);assert.deepEqual(rule.cc,[]);} + const record=f.store.get('rules','bs-change');assert.throws(()=>f.store.publish(record.id,{version:record.draft.version},'admin'),{status:409}); +}); +test('restricted ingest refuses history, configuration-only, future dates and pre-baseline arrivals',t=>{ + const f=fixture(t);f.store.saveRestrictedTest(f.input(),admin); + for(const patch of [{source:'history'},{configurationOnly:true},{receivedAt:'2026-10-22T00:59:59Z'},{receivedAt:'2026-10-23T01:00:00Z'}])assert.throws(()=>f.store.ingest(f.future(patch),'admin'),{status:409}); + const order=f.store.ingest(f.future({receivedAt:'2026-10-22T01:00:00Z'}),'admin');assert.equal(order.status,'identified',order.error);assert.ok(order.ruleSnapshot.testRunId);assert.equal(f.store.all('orders').length,1); +}); +test('test state survives restart, pauses without falling back to publication and locks destinations',t=>{ + const f=fixture(t),sample=f.future({receivedAt:'2026-10-22T01:00:00Z'}),captured=f.store.recordCapture({sample,taskId:'formal-fixture',snapshot:{processVersion:sample.processVersion,fields:[{path:'order',value:'123456'}]}}); + assert.equal(f.store.capturedPreview(captured.id).valid,true);f.store.publish('bs-change',{version:f.store.get('rules','bs-change').draft.version},'admin'); + const published=f.store.get('rules','bs-change').published,run=f.store.saveRestrictedTest(f.input(),admin);f.reopen();assert.equal(f.store.restrictedTest().id,run.id); + for(const patch of [{recipient:'other@qq.com'},{archiveRoot:f.root+'\\other'},{channelId:'other'}])assert.throws(()=>f.store.saveRestrictedTest({...f.input(),...patch},admin),{status:409}); + const paused=f.store.saveRestrictedTest({version:run.version,enabled:false},admin);assert.equal(paused.enabled,false);assert.equal(f.store.executionRule(f.store.get('rules','bs-change')),null); + assert.throws(()=>f.store.ingest(f.future(),'admin'),{status:409}); + const resumed=f.store.saveRestrictedTest({version:paused.version,enabled:true},admin);assert.equal(resumed.since,run.since);assert.equal(resumed.id,run.id); + assert.throws(()=>f.store.saveRestrictedTest({version:run.version,enabled:false},admin),{status:409}); + assert.deepEqual(f.store.get('rules','bs-change').published,published); + assert.throws(()=>f.store.previewMigration('bs-change',{version:published.version,idempotencyKey:'restricted-migration',note:'验证测试隔离迁移'}),{status:409}); +}); +test('all 15 classes ingest future real events through their original exact node pairs',t=>{ + const f=fixture(t,{all:true});f.store.saveRestrictedTest(f.input(),admin); + for(const record of f.store.all('rules')){const r=f.store.executionRule(record),scope=r.scopes[0],sample={...f.sample,...scope,source:'todo',configurationOnly:false,timestampType:'received',receivedAt:'2026-10-22T01:00:00Z',instanceId:'live-'+r.id,taskId:'live-'+r.id};const order=f.store.ingest(sample,'admin');assert.equal(order.status,'identified',r.id+': '+order.error);assert.equal(order.categoryId,r.id);} + assert.equal(f.store.all('orders').length,15); +}); +test('test configuration checks admin role, QQ, Desktop path and active mapping evidence',t=>{ + const f=fixture(t); + assert.throws(()=>f.store.saveRestrictedTest(f.input(),{username:'op',role:'operator'}),{status:403}); + for(const patch of [{recipient:'test@example.test'},{archiveRoot:'\\\\nas\\orders'},{archiveRoot:f.root+'\\..\\..\\elsewhere'}])assert.throws(()=>f.store.saveRestrictedTest({...f.input(),...patch},admin)); + const adapter=f.store.adapters().find(a=>a.verified&&!a.reference);f.store.put('field-adapters',{...adapter,evidenceHash:'changed'}); + assert.throws(()=>f.store.saveRestrictedTest(f.input(),admin),{status:409}); +}); +test('frozen test rule ignores draft edits but stops when its mapping evidence changes',t=>{ + const f=fixture(t);f.store.saveRestrictedTest(f.input(),admin);const record=f.store.get('rules','bs-change'); + f.store.saveRule({...record.draft,to:['elsewhere@example.test'],archiveDirectory:'\\\\nas\\orders'},'admin'); + assert.deepEqual(f.store.executionRule(f.store.get('rules','bs-change')).to,['test@qq.com']); + const adapter=f.store.adapters().find(a=>a.verified&&!a.reference);f.store.put('field-adapters',{...adapter,version:adapter.version+1}); + assert.equal(f.store.executionRule(f.store.get('rules','bs-change')),null); +}); +test('archive provider blocks outside and symlink targets before rendering or writing',async t=>{ + const f=fixture(t);f.store.saveRestrictedTest(f.input(),admin);const rule=f.store.executionRule(f.store.get('rules','bs-change')); + const {OrderArchiveProvider}=require('../../src/modules/storage/order-archive.cjs');let rendered=0; + const archive=new OrderArchiveProvider({journal:f.store,storage:{},outputDir:f.local,renderer:async()=>{rendered++;throw Error('renderer should never run');}}); + await assert.rejects(archive.archive({order:{id:'o',event:{}},rule:{...rule,archiveDirectory:'\\\\nas\\orders'},snapshot:{}}),{status:409});assert.equal(rendered,0); + const outside=fs.mkdtempSync(path.join(os.tmpdir(),'restricted-outside-'));t.after(()=>fs.rmSync(outside,{recursive:true,force:true})); + fs.symlinkSync(outside,path.join(f.local,'escape'),'junction'); + await assert.rejects(archive.probe({...rule,archiveDirectory:f.root+'\\escape'}),{status:409});assert.equal(rendered,0); +}); +test('dispatcher prevents changed recipients and paused tests at the actual SMTP boundary',async t=>{ + const f=fixture(t);const run=f.store.saveRestrictedTest(f.input(),admin),order=f.store.ingest(f.future(),'admin'); + const content=Buffer.from('%PDF-1.7 test'),file={name:'order.pdf',path:f.root+'\\bs-change\\order.pdf',size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}; + f.store.recordArchive(order.id,{archivedAt:f.store.now(),files:[file]},'admin'); + const settings=f.store.get('settings','main');f.store.put('settings',{...settings,channelId:'test-channel',enabled:true,processingEnabled:true}); + f.store.clock=()=>new Date('2026-10-22T03:00:00Z');const [batch]=f.store.prepare('2026-10-22T03:00:00Z','admin');assert.ok(batch); + const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');let sends=0,checks=0; + const mail={clients:new Set(),store:{channelSecret:()=>({id:'test-channel',version:1,email:'sender@example.test',smtp:{}}),guard:()=>{}},smtpFactory:()=>({verify:async()=>{checks++;f.store.saveRestrictedTest({version:run.version,enabled:false},admin);},sendMail:async()=>{sends++;return {accepted:['test@qq.com']};}})}; + const dispatcher=new OrderRuleDispatcher({store:f.store,mail,settings:()=>({}),clock:f.store.clock,providersReady:()=>true,attachmentReader:async()=>content}); + await dispatcher.dispatch({...batch,to:['outside@example.test']},f.store.settings());assert.equal(checks,0);assert.equal(sends,0); + // Use a new reservation for the asynchronous pause case, preserving normal transitions. + f.store.put('batches',batch);const reserved=f.store.get('orders',order.id);reserved.status='batched';reserved.batchId=batch.id;f.store.put('orders',reserved); + await dispatcher.dispatch(batch,f.store.settings());assert.equal(checks,1);assert.equal(sends,0);assert.equal(f.store.get('batches',batch.id).status,'failed'); +}); +test('execution scans only post-baseline matching todo nodes and archives using test snapshots',async t=>{ + const f=fixture(t);f.store.saveRestrictedTest(f.input(),admin);let captures=0,exports=0; + const connection={id:'c1',owner:'admin',status:'connected'},row=f.future(),principal={user:admin,sessionId:'s'}; + const provider={scan:async()=>[{...row,taskId:'old',receivedAt:'2026-10-22T00:59:59Z'},{...row,taskId:'history',source:'history'},{...row,taskId:'wrong',nodeName:'人工审批'},row],capabilities:()=>({liveTodo:true,pdfExport:true}),capture:async()=>{captures++;return {sample:row,snapshot:{processVersion:row.processVersion,fields:[{path:'order',value:'123456'}]}};}}; + const archive={probe:async rule=>{assert.ok(rule.testRunId);return {pdfExport:true,automaticArchive:true};},archive:async({rule})=>{exports++;assert.deepEqual(rule.to,['test@qq.com']);return {archivedAt:f.store.now(),files:[{path:rule.archiveDirectory+'\\one.pdf',name:'one.pdf',kind:'pdf',size:1,sha256:'a'.repeat(64)}]};}}; + const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs'); + const execution=new OrderExecutionCoordinator({store:f.store,workspace:{getConnection:()=>connection,snapshot:()=>({connections:[connection]})},provider,archive,clock:f.store.clock});t.after(()=>execution.stop()); + await execution.scan({connectionId:'c1',idempotencyKey:'test-future'},principal); + assert.equal(captures,1);assert.equal(exports,1);assert.equal(f.store.all('orders')[0]?.status,'pending');assert.equal(f.store.all('execution-tasks').length,1); +}); +test('restricted API permits only administrators and retains fixed destinations on versioned pause',async t=>{ + const f=fixture(t),{orderRuleApi}=require('../../src/modules/order-rules/api.cjs');let result; + const call=(user,body)=>orderRuleApi({orderRules:f.store,workspace:{record:()=>{}},mail:{store:{publicChannel:()=>({state:{smtp:true}}),categoryTemplate:()=>null}},user,route:'/api/order-rules/restricted-test',method:'POST',body,reply:(status,value)=>{assert.equal(status,200);result=value;}}); + for(const role of ['viewer','operator'])await assert.rejects(call({username:role,role},f.input()),{status:403}); + await call(admin,f.input());assert.equal(result.ruleCount,1); + await call(admin,{version:result.version,enabled:false});assert.equal(result.enabled,false);assert.equal(result.recipient,'test@qq.com'); +}); +test('uncertain SMTP outcome stays unknown across test restart and cannot be resent automatically',async t=>{ + const f=fixture(t);f.store.saveRestrictedTest(f.input(),admin);const order=f.store.ingest(f.future(),'admin'),content=Buffer.from('%PDF-1.7 test'); + f.store.recordArchive(order.id,{archivedAt:f.store.now(),files:[{name:'one.pdf',path:f.root+'\\bs-change\\one.pdf',size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}]},'admin'); + const settings=f.store.get('settings','main');f.store.put('settings',{...settings,enabled:true,channelId:'test-channel'});f.store.clock=()=>new Date('2026-10-22T03:00:00Z');const [batch]=f.store.prepare('2026-10-22T03:00:00Z','admin'); + const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');let sent=0; + const mail={clients:new Set(),exclusive:async(_,fn)=>fn(),store:{channelSecret:()=>({id:'test-channel',version:1,email:'sender@example.test',smtp:{}}),guard:()=>{}},smtpFactory:()=>({verify:async()=>{},sendMail:async message=>{assert.deepEqual(message.to,['test@qq.com']);assert.deepEqual(message.cc,[]);sent++;throw Error('connection lost after DATA');}})}; + const sender=()=>new OrderRuleDispatcher({store:f.store,mail,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),clock:f.store.clock,providersReady:()=>true,attachmentReader:async()=>content}); + await sender().dispatch(batch,f.store.settings());assert.equal(f.store.get('batches',batch.id).status,'unknown'); + f.reopen();assert.equal(f.store.get('batches',batch.id).status,'unknown');await sender().tick();assert.equal(sent,1); + await assert.rejects(sender().resend(batch.id,{version:f.store.get('batches',batch.id).version,idempotencyKey:'unknown-retry',note:'不得重发待核实邮件'},admin),{status:409});assert.equal(sent,1); +}); diff --git a/web/modules/order-notifications/detail.js b/web/modules/order-notifications/detail.js index bd2c180..10ad48c 100644 --- a/web/modules/order-notifications/detail.js +++ b/web/modules/order-notifications/detail.js @@ -18,7 +18,7 @@ window.BusinessRecordDetail=(()=>{ async function load(kind,id,trigger){ const request=++revision;controller?.abort();controller=new AbortController();panel.show('

正在加载详情…

',trigger); try{const d=await api('/order-rules/'+kind+'/'+encodeURIComponent(id),undefined,{signal:controller.signal});if(!isActive()||request!==revision)return; - panel.show(kind==='orders'?orderBody(d):batchBody(d),trigger); + panel.show((d.testRunId?'
受限稳定性测试 · 固定QQ收件箱/桌面归档
':'')+(kind==='orders'?orderBody(d):batchBody(d)),trigger); container.querySelectorAll('[data-business-action]').forEach(form=>form.onsubmit=async event=>{ event.preventDefault();const button=form.querySelector('button'),notice=form.querySelector('[role=alert]');if(button.disabled)return; const action=form.dataset.businessAction,t=d.executionTask,body={version:t&&['revision','retry'].includes(action)?t.version:d.version,note:form.elements.note.value}; diff --git a/web/modules/order-notifications/records.js b/web/modules/order-notifications/records.js index cb12581..0b9ea46 100644 --- a/web/modules/order-notifications/records.js +++ b/web/modules/order-notifications/records.js @@ -9,7 +9,7 @@ window.BusinessRecordViews=(()=>{ const input=(name,label,type='text')=>``; container.innerHTML=`

${kind==='orders'?'订单中心':'邮件批次'}

${input('q','搜索订单 / 标识 / 主题')}
${select('categoryId','类别')}
${select('connectionId','来源连接')}
${kind==='batches'?`
`:''}
${input('from',kind==='batches'?'窗口截止日期从(北京时间)':'接收日期从(北京时间)','date')}
${input('to',kind==='batches'?'窗口截止日期至':'接收日期至','date')}
${window.RecordUi.footer}
${kind==='orders'&&user.role!=='viewer'?'

扫描并处理订单

读取授权待办、采集真实字段、生成 PDF 并归档;BPM 节点由人工办理。邮件按独立开关和批次调度发送。

':''}`; let table;const detail=window.BusinessRecordDetail.mount(container,{...options,onChanged:()=>{const error=container.querySelector('[data-record-error]');error.hidden=false;error.textContent='业务状态已变化,请刷新记录核对。';}}); - function draw(data){const host=container.querySelector('[data-arrival-list]');host.innerHTML=`
${data.items.map((row,index)=>``).join('')||''}
${kind==='orders'?'订单 / 类别':'主题 / 类别'}状态与原因接收 / 创建时间详情
${esc(row.orderNo||row.subject||row.id)}
${esc(catalogs.categories.get(row.categoryId)||row.categoryId||'未分类')}
${kind==='batches'?''+(row.notificationMode==='huizhou'?'惠州通知':'普通通知')+'':''}
${esc(labels[row.status]||row.status)}${kind==='orders'&&row.notifications?['normal','huizhou'].map(mode=>{const notice=row.notifications[mode];return notice?'
'+(mode==='huizhou'?'惠州通知':'普通通知')+':'+esc(labels[notice.status]||notice.status)+'
'+esc(notice.error||'')+'
'+(notice.issues?.length?'
'+notice.issues.map(esc).join(';')+'
':'')+'
':'';}).join(''):''}
${esc(row.error||row.reason||'')}
${esc(formatDate(row.receivedAt||row.createdAt))}
暂无匹配记录
`;host.querySelectorAll('[data-business-detail]').forEach(button=>button.onclick=()=>detail.open(kind,data.items[Number(button.dataset.businessDetail)].id,button));} + function draw(data){const host=container.querySelector('[data-arrival-list]');host.innerHTML=`
${data.items.map((row,index)=>``).join('')||''}
${kind==='orders'?'订单 / 类别':'主题 / 类别'}状态与原因接收 / 创建时间详情
${esc(row.orderNo||row.subject||row.id)}
${esc(catalogs.categories.get(row.categoryId)||row.categoryId||'未分类')}
${row.testRunId?'受限测试':''}${kind==='batches'?''+(row.notificationMode==='huizhou'?'惠州通知':'普通通知')+'':''}
${esc(labels[row.status]||row.status)}${kind==='orders'&&row.notifications?['normal','huizhou'].map(mode=>{const notice=row.notifications[mode];return notice?'
'+(mode==='huizhou'?'惠州通知':'普通通知')+':'+esc(labels[notice.status]||notice.status)+'
'+esc(notice.error||'')+'
'+(notice.issues?.length?'
'+notice.issues.map(esc).join(';')+'
':'')+'
':'';}).join(''):''}
${esc(row.error||row.reason||'')}
${esc(formatDate(row.receivedAt||row.createdAt))}
暂无匹配记录
`;host.querySelectorAll('[data-business-detail]').forEach(button=>button.onclick=()=>detail.open(kind,data.items[Number(button.dataset.businessDetail)].id,button));} const names=Object.keys(filters).filter(k=>!['page','pageSize'].includes(k)); table=window.RecordTable.mount({view,container,isActive,api,endpoint:'/order-rules/'+kind,render:draw,readDraft:()=>Object.fromEntries(names.map(k=>[k,container.querySelector('[name="'+k+'"]').value.trim()])),writeDraft(next){for(const k of names)container.querySelector('[name="'+k+'"]').value=next[k];}}); const workspaceRead=api('/workspace'); diff --git a/web/modules/order-notifications/view.js b/web/modules/order-notifications/view.js index e1c9fa7..897b67e 100644 --- a/web/modules/order-notifications/view.js +++ b/web/modules/order-notifications/view.js @@ -18,6 +18,16 @@ window.OrderNotificationViews=(()=>{ const {api,esc,user,formatDate}=helpers,config=data.settings,admin=user.role==='admin',mail=await api('/mail').catch(error=>({channels:[],error:error.message}));if(!isActive())return; container.innerHTML=`

处理与邮件设置

${mail.error?'
邮箱目录读取失败:'+esc(mail.error)+'。请刷新重试。
':''}

启用时建立接收时间基线,早于基线的未处理历史不会自动入队。无需先启用邮件。当前启用基线:${esc(formatDate(config.processingSince))}。

两个开关独立暂停。邮箱、类别与归档条件未通过时,服务端拒绝启用邮件。

${admin?'':''}
`; const form=container.querySelector('form');if(admin)form.onsubmit=async event=>{event.preventDefault();const button=form.querySelector('button');button.disabled=true;try{if(mail.error)throw Error('邮箱目录读取失败,请刷新后再保存。');const saved=await api('/order-rules/settings',{version:config.version,processingEnabled:form.elements.processingEnabled.checked,enabled:form.elements.enabled.checked,channelId:form.elements.channelId.value,maxMessageBytes:Math.round(Number(form.elements.maxSize.value)*1048576)});if(isActive()){Object.assign(config,saved);form.querySelector('[role=alert]').textContent='设置已保存。';}}catch(error){if(isActive())form.querySelector('[role=alert]').textContent=error.message;}finally{if(button.isConnected)button.disabled=false;}}; + if(data.restrictedTest){ + form.elements.channelId.disabled=true; + const card=document.createElement('section');card.className='card settings-width mb-3';container.prepend(card); + let run=data.restrictedTest; + function drawTest(){ + card.innerHTML=`

受限稳定性测试

${run.enabled?'测试运行中':'测试已暂停'}

覆盖 ${Number(run.ruleCount)} 类,当前可用 ${Number(run.readyCount)} 类。正式投产须重新检查并发布。

固定收件箱
${esc(run.recipient)}
桌面归档目录
${esc(run.archiveRoot)}
测试接收基线
${esc(formatDate(run.since))}

仅处理基线后的真实通知;暂停保留测试模式,不切换为正式发送。收件箱、目录与发件通道已固定。

${run.uncovered?.length?`

${run.uncovered.length} 个流程尚无可用字段版本,继续阻塞。

`:''}
${admin?``:''}`; + const button=card.querySelector('button');if(button)button.onclick=async()=>{if(button.disabled)return;button.disabled=true;try{const saved=await api('/order-rules/restricted-test',{version:run.version,enabled:!run.enabled});if(isActive()&&card.isConnected){run=saved;drawTest();}}catch(error){if(isActive()&&card.isConnected)card.querySelector('[role=alert]').textContent=error.message;}finally{if(button.isConnected)button.disabled=false;}}; + } + drawTest(); + } } return {configure:options=>{helpers=options;},render}; })(); diff --git a/web/modules/order-rules/view.js b/web/modules/order-rules/view.js index 7d25e4c..5a26087 100644 --- a/web/modules/order-rules/view.js +++ b/web/modules/order-rules/view.js @@ -24,8 +24,9 @@ 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(admin&&rule.publishedVersion){ + 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){ const migration=document.createElement('section');migration.className='card mt-3'; migration.innerHTML='

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

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

'; panel.querySelector('.rule-editor-column').append(migration); @@ -50,7 +51,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;coverage();refreshSources(); + const publish=panel.querySelector('#order-rule-publish');if(publish)publish.disabled=dirty||saving||!!data.restrictedTest;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}); @@ -62,7 +63,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;}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||!!data.restrictedTest;}const open=container.querySelector('#rule-import-open');if(open?.isConnected)open.disabled=false;} } refreshCurrent=()=>mutate(reload);mutationCurrent=mutate; async function save(){ @@ -82,7 +83,7 @@ }); function drawList(){ const filtered=data.rules.filter(r=>(r.name+' '+r.categoryId).toLocaleLowerCase().includes(query.toLocaleLowerCase())&&(filter==='all'||filter==='needs'&&r.validationIssues?.length||filter==='draft'&&r.hasDraft||filter==='published'&&r.status==='enabled'||filter==='paused'&&r.status==='paused')); - panel.querySelector('#rule-category-list').innerHTML=filtered.map(r=>`
${r.status==='enabled'?'已启用':r.status==='paused'?'已暂停':'未启用'}
`).join('')||'

没有符合条件的类别,请调整搜索或筛选。

'; + panel.querySelector('#rule-category-list').innerHTML=filtered.map(r=>`
${r.testStatus?(r.testStatus==='enabled'?'受限测试中':'测试已暂停'):(r.status==='enabled'?'已启用':r.status==='paused'?'已暂停':'未启用')}
`).join('')||'

没有符合条件的类别,请调整搜索或筛选。

'; panel.querySelectorAll('[data-rule-id]').forEach(button=>button.onclick=()=>{if(button.dataset.ruleId===selectedId||saving)return;window.PageLifecycle.guard(()=>{dirty=false;selectedId=button.dataset.ruleId;draw();});}); switchCurrent=async id=>{const current=data.rules.find(r=>r.id===id);if(!current.publishedVersion){dirty=false;selectedId=id;draw();feedback('此分类尚未发布。请先保存草稿,在第04步检查真实订单,再发布启用。','warning');return;}await mutate(async()=>{try{const op=current.status==='enabled'?'pause':'resume';await api('/order-rules/rules/'+encodeURIComponent(id)+'/'+op,{version:current.version,publishedVersion:current.publishedVersion,activationVersion:current.activationVersion||0});if(!isActive())return;await window.PageLifecycle.afterSave(reload,op==='pause'?'此规则已暂停。':'已启用已发布版本,未发布草稿保持不变。',feedback,isActive);}catch(error){if(isActive())feedback(error.message,'danger');}});}; panel.querySelectorAll('[data-rule-toggle]').forEach(toggle=>toggle.onchange=()=>{const id=toggle.dataset.ruleToggle;toggle.checked=data.rules.find(r=>r.id===id).status==='enabled';if(!admin||saving)return;window.PageLifecycle.guard(()=>switchCurrent(id));});