diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index 359009f..8572e7a 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -1,5 +1,20 @@ # 开发交接(2026-10-18) +## 2026-10-22:分类模板通知代码增量 + +当前分支仍为 `codex/smb-storage`。本次按业务负责人明确提供的 BPM 匹配与分类模板计划开发,入口见 [实施与验收记录](superpowers/plans/2026-10-22-bpm-category-template-implementation.md)。本节优先于下文早期“未实施”的说明;不代表已部署或已完成真实业务验收。 + +- 分类规则按流程 + 当前节点精确匹配,表单版本只用于选择显式字段适配器。产品线、模板和收件组由分类指定,草稿经服务器采集的真实只读样本检查后才可发布。 +- 订单版本必须具备 `tid + pid + 当前订单号 + 业务版本`;不再用流程实例号代替缺失业务版本。同一版本的字段变化会阻断。列表摘要保留原始换行,节点时间缺失时保留 `list.receivedAt` 来源标记。 +- 新增受保护的 `OrderPipeline`,复用现有 PDF 导出器、SMB 归档和邮件通道。归档回执含路径、字节数和 SHA-256;归档失败不创建通知事件,重试不重做成功 PDF。 +- 通知事件进入既有通知库,但标识为订单工作流管理,通用通知调度器不会重复处理。批次按分类、规则版本、模板和窗口冻结;PDF 不进附件;SMTP 部分拒收和结果不明均为 `unknown`,重启不自动重发。 +- 新页面入口为 `#order-center`、`#mail-batches`、`#order-rules`(兼容 `#rules`),不重复放顶部导航;展示候选阻断、步骤证据、模板版本及核验记录。 +- **新订单链路的自动处理和发送默认关闭,本轮未启用、未更新运行服务。** 测试收件人硬限制为指定隔离邮箱。原工作台账号、业务文件和数据库未迁移。 + +真实环境尚须核对 V13 页面所需只读接口、流程步骤结构和业务版本字段。详情读取只放行经过限制的表单 GET 和静态资源,不为页面初始化而放开不明 POST/动作接口。历史到达记录没有明确详情链接或 `tid/pid` 时,必须重新取得权威关联,不能把另一张同流程订单的链接拼到该记录。 + +本次另修复全量回归发现的 Windows 中文快捷方式路径问题:使用 `IShellLinkW/IPersistFile`,保留既有登录启动行为,没有实际安装或修改当前服务自启动。 + ## 接续分支与运行 仓库:`https://git.simgreek.com/simgreek/order-notification-automation.git`。 diff --git a/docs/business-configuration.md b/docs/business-configuration.md index 9f3d83d..303ad37 100644 --- a/docs/business-configuration.md +++ b/docs/business-configuration.md @@ -1,5 +1,7 @@ # 后续业务资料整理表 +2026-10-22:BPM 订单来源使用 [分类模板实施规则](superpowers/plans/2026-10-22-bpm-category-template-implementation.md)。流程 + 节点决定分类,表单版本选择字段适配器,产品线和模板由分类明确指定,业务版本不可缺省。下文“版本留空取摘要”等说明仅适用于既有通用来源接口,不适用于 BPM 订单工作流。 + 本轮交付通用配置能力。下面的信息整理完成后,可在工作台录入并联调,不需要把服务器地址或产业接口人写进源码。 ## 存储服务器 diff --git a/docs/design-requirements.md b/docs/design-requirements.md index 4c36ac6..8674541 100644 --- a/docs/design-requirements.md +++ b/docs/design-requirements.md @@ -2,6 +2,8 @@ 更新日期:2026-10-18。本文为当前设计要求入口;与早期调研或阶段计划冲突时,以本文及对应模块最新设计为准。业务规则的调整需要同步本文、实现与验收记录。继续开发先读 [交接说明](HANDOFF.md)。 +2026-10-22 增补:业务负责人已明确提供并授权实施 [BPM 分类模板计划](superpowers/plans/2026-10-22-bpm-category-template-implementation.md)。该链路以分类规则指定产品线、邮件模板及收件组,版本适配器精确对应表单版本;PDF/SMB 归档成功是创建通知事件的前置条件,归档与通知仍分别保存状态。此约束替代下文早期“PDF 归档不影响通知”和按产业独立猜模板的描述;归档完成不代表邮件完成,也不直接绕过分类、版本、收件组及发送窗口检查。自动处理、PDF 自动执行和自动发送在真实业务验收前保持关闭。 + ## 1. 产品目标与运行方式 团队成员在各自电脑访问同一台常驻服务器,通过 Web 管理 BPM 连接、流程到达记录、业务日历、异常、邮件模板和收件群组。正式工作台使用真实持久数据,不预置演示账号或虚构订单,不提供默认管理员密码。 diff --git a/docs/superpowers/plans/2026-10-22-bpm-category-template-implementation.md b/docs/superpowers/plans/2026-10-22-bpm-category-template-implementation.md new file mode 100644 index 0000000..d6c2117 --- /dev/null +++ b/docs/superpowers/plans/2026-10-22-bpm-category-template-implementation.md @@ -0,0 +1,47 @@ +# BPM 分类模板实施记录 + +用户于 2026-10-22 明确批准会话中的“BPM 订单匹配与分类模板通知实施计划”。该计划替代此前设计草稿的停止实施状态,不代表业务自动运行或真实发送已获本轮启用授权。 + +## 顺序与验收 + +1. 只读详情适配器:复用托管会话,限制 BPM 域名/读取请求;明确 tid/pid、表单版本和字段证据;不办理流程。 +2. 分类配置:精确流程+当前节点;版本只选适配器;产品线、PDF 模板、邮件模板、收件组、通知类型、批次方式、启停;真实样本检查后发布。 +3. 统一任务:复用 OrderWorkflow/Store,版本键 tid+pid+当前订单号+业务版本;缺失阻断;步骤证据独立持久化和恢复。 +4. PDF/SMB:复用现有生成及存储服务;成功步骤不重做;归档失败阻断通知。 +5. 模板通知:按分类+模板+窗口分批;四个变量;冻结版本/正文/收件人;附件固定为空;仅隔离测试邮箱。 +6. 页面记录与恢复:订单和批次可追溯;viewer 只读;发送结果 unknown 禁止自动重发,管理员核验。 + +每阶段先失败测试后实现;最终 npm ci、全量测试、专项验收、代码审查、只提交代码与脱敏文档。不得提交业务 PDF、会话、凭据和本地设计草稿;不更新服务机,不开启自动处理/发信。 + +## 已实现的代码边界 + +| 模块 | 行为 | +|---|---| +| `bpm-order-detail.cjs` | 验证详情来源、唯一 tid/pid、表单路径和版本;复用托管会话,只读取可见绑定字段和流程步骤;阻止写请求和越域跳转 | +| `order-workflow.cjs` / Store | 草稿/样本检查/发布;精确匹配;版本幂等和字段冲突;步骤状态及原子批次/订单更新;中断恢复 | +| `order-pipeline.cjs` | 默认关闭的执行器;PDF、文件归档回执、通知桥接、窗口调度和发送结果核验;只重试失败步骤 | +| `order-template-bridge.cjs` | 渲染产品线、订单号、日期、订单列表四变量,保留原始换行;冻结模板和渲染结果,附件为空 | +| 工作台 | 分类配置、真实记录样本检查、订单步骤/字段证据、候选采集恢复、邮件批次和管理员核验 | + +原有 BPM 列表存储继续按连接、来源、任务标识去重;同一任务重新扫描或规则版本变化会重新检查详情,业务版本键决定是否产生新任务。同一版本即使非邮件映射字段发生变化,也必须人工核实版本,不能重做新内容 PDF。 + +当前节点没有独立进入时间时,使用列表收到时间,保存 `list.receivedAt`。业务版本只接受明确采集值或经确认的字段适配路径,不以 tid、pid、标题、型号或内容摘要填补。 + +## 发送与恢复约定 + +- 同分类、同模板、同规则版本、同发送窗口汇总,分类不同或规则/产品线修订后分别冻结,防止旧订单使用新产品线标题。 +- 冻结批次保存模板版本、原始模板快照、渲染后的主题/纯文本/HTML、To/Cc 和订单版本键;发送前再次限制测试收件人与空附件。 +- 邮箱正被收信/检查占用时保留当前窗口,不提前消耗;`next_window` 对错过窗口保留待发记录,`skip` 标记覆盖所有已错过窗口的待发记录,留待人工处理;空批次不发。 +- 归档失败保留成功 PDF;通知桥接失败保留成功归档。恢复前核对版本和全部可见字段,不把新版本快照用于旧任务。 +- `sending` 重启后原子转为 `unknown`,同时更新关联订单;unknown 必须管理员填写核验依据。SMTP 检查明确失败有次数上限,耗尽后仍能人工核验或重新入队。 +- 输出结果不明的 PDF 保持阻断,须人工核查输出记录,不能为追求成功状态重复生成。 + +## 隔离验证与真实验收分界 + +专项测试包括字段/版本冲突、草稿发布门槛、来源链接关联、写请求阻断、归档失败后重试、通知镜像队列所有权、模板冻结、分类分批、收件人限制、SMTP 部分拒收/不明结果、邮箱互斥、错过窗口与恢复、页面生命周期及角色。 + +新增 HTTP/浏览器集成测试使用临时状态目录、随机端口、虚构 BPM 详情、实际 PDF 渲染和本地 `FileArea` 归档,验证 SHA-256、通知队列、幂等与页面字段证据。它不调用真实 BPM/SMTP/SMB,自动处理和发送均关闭。测试结束关闭临时服务并删除测试目录。 + +真实 V13 表单仍需现场只读验收。尤其须确认页面需要的字段读取接口及流程步骤表结构、业务版本权威字段、列表与详情的 tid/pid 关联。未确认时检查返回阻断,不能绕过检查发布或启用自动处理;不能把本次隔离测试称作真实业务闭环验收。 + +运行数据库、日志、截图、临时导出文件和测试报告不进入 Git;本地旧设计草稿保持在工作区,单独排除提交。 diff --git a/docs/verification.md b/docs/verification.md index 55d6ec6..deacad9 100644 --- a/docs/verification.md +++ b/docs/verification.md @@ -127,3 +127,16 @@ - 实机管理命令执行一次业务重启:守护 PID 47552 保持,业务 PID 从 62420 变为 59864;双端口检查通过,恢复计数为 1。使用临时测试会话验证重启后原会话仍可访问;测试会话随后撤销,没有修改账号密码。 - 正式首页 HTTP 200;真实浏览器系统健康页显示守护正常、登录自启启用,脚本错误为空。摘要 `output/verification/service-health-live.json`;隔离截图 `service-health-desktop.png`,正式页截图 `service-health-live.png`,均留在本机忽略目录。页面 390 px 无横向溢出,断线时保留旧值并更新连接中断提示,恢复后可继续刷新。 - 健康模块显示最近保存/观测结果,不等同实时外网连通性;未配置邮箱明确显示未配置。没有以健康展示触发 SMB 写入、BPM 登录或真实业务邮件发送。守护恢复遵循现有邮件 unknown 核验与任务中断规则。 + +## BPM 分类模板订单链路(2026-10-22) + +- 依据用户明确批准的实施计划,完成只读详情读取、草稿/样本检查/发布、显式订单版本、PDF/归档依赖、通知队列桥接、分类模板批次、SMTP 不明结果恢复及订单/批次页面。新自动处理和发信默认关闭,本轮没有启用、更新运行服务或操作服务机。 +- 已执行 `npm ci`,锁定依赖安装完成;最终执行 `npm test -- --test-concurrency=1`,共 243 项,242 通过、0 失败、1 跳过,耗时约 651 秒。跳过的是需要本机官方 ZCode 运行包的可选集成测试。完整本机日志:`output/implementation/final-full-test.log`。 +- 初次并发全量出现 6 项失败:页面可选模块的离页判断、订单/批次重启一致性旧断言、Windows 中文快捷方式路径,以及 3 个 Windows 加密子进程故障。前 3 项已修复;3 个加密用例单独复测及最终串行全量均通过。没有将初次失败算作通过。 +- 新 HTTP/真实浏览器隔离测试走实际服务启动、登录权限、分类规则发布、实际 PDF 排版、StorageService/FileArea 文件归档和 SHA-256、通知队列关联与版本幂等;外部 BPM 详情和 SMTP 传输由测试边界替代,归档限定临时本地目录,关闭自动执行,测试后删除临时状态和文件。 +- 只读页面测试覆盖明确 xdatabind、隐藏原订单排除、密码字段排除、首个隐藏字段的就绪等待、流程步骤核对、唯一详情参数和写请求/越域拦截。业务版本缺失不回退,不猜 tid/pid 关联。 +- 恢复测试与独立审查修复了 PDF/归档执行状态漏落盘、订单插入到候选关联之间的中断、候选永久去重、分类修订合批、发送窗口被占用消耗、跨日错过窗口及部分拒收。发送中重启后原子转为 unknown,必须人工核验;管理员可恢复明确 SMTP 失败批次。 +- 原生 Windows 自启测试使用临时中文及带空格目录验证 IShellLinkW/IPersistFile 创建、读取、启动隔离脚本及移除,并保留外来快捷方式保护;没有修改当前用户真实的登录启动项。 +- 31 个新增或变更 JS/CJS 文件语法检查、Git 差异空白检查通过;人工复核凭据扫描命中,均为 CSS 选择器或测试虚构密码。提交中不含业务 PDF、EML、会话、数据库、密钥、日志及旧本地设计草稿。 +- 独立代码审查及修复复核未留下已确认的 P0/P1/P2 问题。报告位于忽略目录 `output/implementation/pipeline-review.md`。 +- 验收边界:没有进行真实 BPM V13 / 210 SMB / 163 收件联调。仍需核实 V13 的权威业务版本字段、列表详情关联及页面初始化所需只读接口;当前采集器不为兼容页面而放开未知 POST。隔离测试通过不代表完整真实业务闭环验收。 diff --git a/src/bpm-list-client.cjs b/src/bpm-list-client.cjs index ec3e306..a4a6110 100644 --- a/src/bpm-list-client.cjs +++ b/src/bpm-list-client.cjs @@ -3,11 +3,12 @@ const sanitize=require('sanitize-html'); const {loadPlaywright}=require('./runtime.cjs'); const fail=(message,status=502)=>Object.assign(new Error(message),{status}); const SOURCES=[['portal-v8','bpm/worklist/informlist'],['portal-v4','skyworth/todo/v2/workflow/get_process_of_inform_v4']]; -function plain(value,max=8000){ - const text=sanitize(String(value??''),{allowedTags:[],allowedAttributes:{}}).replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(m,key)=>{ +function plain(value,max=8000,preserveLines=false){ + const input=preserveLines?String(value??'').replace(//gi,'\n'):String(value??''); + const text=sanitize(input,{allowedTags:[],allowedAttributes:{}}).replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi,(m,key)=>{ if(key[0]==='#'){const n=key[1].toLowerCase()==='x'?parseInt(key.slice(2),16):+key.slice(1);return n>0&&n<=0x10ffff?String.fromCodePoint(n):'';} return {amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:' '}[key.toLowerCase()]; - });return text.replace(/\s+/g,' ').trim().slice(0,max); + });return (preserveLines?text:text.replace(/\s+/g,' ').trim()).slice(0,max); } function normalizeArrival(row,source){ if(!row||typeof row!=='object'||!['string','number'].includes(typeof row.taskId)||!String(row.taskId)||String(row.taskId).length>200)throw fail('BPM 列表缺少有效的任务标识。'); @@ -18,7 +19,9 @@ function normalizeArrival(row,source){ const date=new Date(/(?:Z|[+-]\d{2}:\d{2})$/.test(raw)?raw:raw+'+08:00'); if(Number.isNaN(+date))throw fail('BPM 流程到达时间无效。'); const arrivedAt=date.toISOString(),arrivalDay=new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(date); - return {source,taskId:String(row.taskId),serialNum:plain(row.serialNum,250),processName:plain(row.processName,250),activityName:plain(row.activityName,250),subject:plain(row.processInstanceSubject),initiator:plain(row.processInstanceInitiatorShortName||row.processInstanceInitiator,250),arrivedAt,arrivalDay}; + let detailUrl;if(typeof row.detailUrl==='string'){try{require('./bpm-order-detail.cjs').parseDetailUrl(row.detailUrl);detailUrl=row.detailUrl;}catch{}} + const identity={};for(const key of ['tid','pid'])if(['string','number'].includes(typeof row[key])&&/^\d{1,30}$/.test(String(row[key])))identity[key]=String(row[key]); + return {source,taskId:String(row.taskId),serialNum:plain(row.serialNum,250),processName:plain(row.processName,250),activityName:plain(row.activityName,250),subject:plain(row.processInstanceSubject,20000,true),initiator:plain(row.processInstanceInitiatorShortName||row.processInstanceInitiator,250),arrivedAt,arrivalDay,...identity,...(detailUrl?{detailUrl}:{})}; } class BpmListClient{ constructor({baseURL='https://bpmn.skyworthdigital.com/',pageSize=100,allowLocal=false}={}){ diff --git a/src/bpm-order-detail.cjs b/src/bpm-order-detail.cjs new file mode 100644 index 0000000..9e52eb5 --- /dev/null +++ b/src/bpm-order-detail.cjs @@ -0,0 +1,59 @@ +'use strict'; +const crypto=require('node:crypto'); +const {loadPlaywright,browserOptions}=require('./runtime.cjs'); +const fail=(message,status=409)=>{throw Object.assign(new Error(message),{status});}; +function parseDetailUrl(value){ + let url;try{url=new URL(value);}catch{fail('BPM 详情地址无效。');} + if(url.origin!=='https://bpm.skyworthdigital.com'||url.username||url.password||url.hash||!url.pathname.startsWith('/YZSoft/Forms/XForm/'))fail('BPM 详情地址不受支持。',403); + if([...url.searchParams.keys()].some(key=>!['tid','pid'].includes(key))||['tid','pid'].some(key=>url.searchParams.getAll(key).length!==1))fail('BPM 详情 tid/pid 参数必须唯一,不能包含办理动作。'); + const tid=url.searchParams.get('tid'),pid=url.searchParams.get('pid');if(!/^\d{1,30}$/.test(tid||'')||!/^\d{1,30}$/.test(pid||''))fail('BPM 详情缺少有效 tid/pid。'); + const pathname=decodeURIComponent(url.pathname),match=pathname.match(/\/([^/]+?)(V\d+)\.aspx$/i);if(!match)fail('BPM 详情缺少可识别的表单版本。'); + return {tid,pid,processVersion:match[2].toUpperCase(),processName:match[1]}; +} +function allowDetailRequest(value,method,target,navigation=false){ + try{const url=new URL(value),detail=new URL(target);if(method!=='GET'||url.origin!==detail.origin||url.username||url.password)return false; + if(navigation)return url.href===detail.href; + return !url.search&&/\.(?:js|css|png|jpg|jpeg|gif|svg|woff2?|ttf|ico)$/i.test(url.pathname)&&!/(?:approve|fulfill|markread|upload|delete)/i.test(url.pathname); + }catch{return false;} +} +function readDetailDocument(){ + const source=document.querySelector('form');if(!source)throw Error('BPM 详情表单未就绪。'); + const visible=element=>{for(let node=element;node;node=node.parentElement){const style=getComputedStyle(node);if(node.hidden||['hidden','password','file'].includes(node.type)||style.display==='none'||['hidden','collapse'].includes(style.visibility))return false;}return true;}; + const value=element=>element instanceof HTMLSelectElement?[...element.selectedOptions].map(option=>option.textContent).join('、'):['checkbox','radio'].includes(element.type)?(element.checked?element.value:''):'value'in element?element.value:element.innerText; + const elements=[...source.querySelectorAll('[xdatabind],[data-xdatabind],[data-bind]')].filter(visible).map(element=>({binding:element.getAttribute('xdatabind')||element.getAttribute('data-xdatabind')||element.getAttribute('data-bind'),value:value(element)})); + const processSteps=[]; + for(const table of document.querySelectorAll('table')){ + const rows=[...table.rows],header=rows.find(row=>[...row.cells].some(cell=>/^(节点|环节|步骤|活动名称|节点名称)$/.test(cell.textContent.trim()))&&[...row.cells].some(cell=>/^(状态|处理状态)$/.test(cell.textContent.trim())));if(!header)continue; + const labels=[...header.cells].map(cell=>cell.textContent.trim()),ni=labels.findIndex(label=>/^(节点|环节|步骤|活动名称|节点名称)$/.test(label)),si=labels.findIndex(label=>/^(状态|处理状态)$/.test(label)); + for(const row of rows.slice(rows.indexOf(header)+1)){const name=row.cells[ni]?.textContent.trim(),status=row.cells[si]?.textContent.trim();if(name&&status)processSteps.push({name,status});} + } + const copy=source.cloneNode(true),originals=[source,...source.querySelectorAll('*')],copies=[copy,...copy.querySelectorAll('*')]; + for(let i=originals.length-1;i>=0;i--){const original=originals[i],target=copies[i];if(!visible(original)||['SCRIPT','IFRAME','OBJECT','EMBED','BUTTON','LINK','META'].includes(original.tagName)||['hidden','password','file','submit','button','reset'].includes(original.type)||original.getAttribute('printout')==='false'){target.remove();continue;}if(['INPUT','TEXTAREA','SELECT'].includes(original.tagName)){const span=document.createElement('span');span.textContent=value(original);span.style.whiteSpace='pre-wrap';target.replaceWith(span);}else for(const attr of [...target.attributes])if(/^on/i.test(attr.name)||['action','srcdoc','srcset','formaction','value'].includes(attr.name))target.removeAttribute(attr.name);} + copy.querySelectorAll('#taskCommentForm,#TaskCommentCount').forEach(node=>node.remove()); + const styles=[];for(const sheet of document.styleSheets)try{styles.push([...sheet.cssRules].map(rule=>rule.cssText).join('\n'));}catch{} + return {elements,processSteps,snapshot:{html:copy.outerHTML,styles,width:1264,images:[]}}; +} +function extractFieldSnapshot(input){ + if(!input||!Array.isArray(input.elements)||!Array.isArray(input.processSteps)||!input.processName||!input.nodeName||!input.processInstanceId)fail('BPM 详情缺少流程实例或字段证据。'); + const fields={};for(const element of input.elements){if(!element||typeof element.binding!=='string'||!element.binding.trim())continue;if(fields[element.binding]!==undefined&&String(fields[element.binding])!==String(element.value??''))fail('BPM 详情字段存在多个不同值。');fields[element.binding]=element.value??'';} + if(!Object.keys(fields).length)fail('BPM 详情没有可用字段证据。');return {readOnly:true,processName:input.processName,nodeName:input.nodeName,processVersion:input.processVersion||'',processInstanceId:input.processInstanceId,fields,processSteps:structuredClone(input.processSteps)}; +} +async function captureDetail({storageState,sessionStorage={},detailUrl,processName,nodeName,browserFactory=()=>loadPlaywright().chromium.launch(browserOptions()),timeout=20000}){ + const identity=parseDetailUrl(detailUrl);if(!storageState)fail('BPM 会话需要续登。',401);if(processName&&identity.processName!==processName)fail('列表流程名称与详情表单不一致。'); + const browser=await browserFactory();let context; + try{ + context=await browser.newContext({storageState,serviceWorkers:'block',acceptDownloads:false,permissions:[]});const blocked=[]; + await context.route('**/*',async route=>{try{const request=route.request();if(!allowDetailRequest(request.url(),request.method(),detailUrl,request.isNavigationRequest())){blocked.push({method:request.method(),path:new URL(request.url()).pathname});return await route.abort();}const response=await route.fetch({maxRedirects:0,timeout});if(response.status()>=300&&response.status()<400)return await route.abort();return await route.fulfill({response});}catch{await route.abort().catch(()=>{});}}); + if(context.routeWebSocket)await context.routeWebSocket(/.*/,socket=>socket.close()); + await context.addInitScript(({sessions})=>{for(const [key,value] of Object.entries(sessions[location.origin]||{}))sessionStorage.setItem(key,value);document.addEventListener('submit',event=>event.preventDefault(),true);},{sessions:sessionStorage}); + const page=await context.newPage();page.on('dialog',dialog=>dialog.dismiss().catch(()=>{}));page.on('download',download=>download.cancel().catch(()=>{})); + const response=await page.goto(detailUrl,{waitUntil:'domcontentloaded',timeout});if(!response||response.status()!==200||page.url()!==new URL(detailUrl).href)fail('BPM 详情需要授权会话或页面未就绪。',401); + await page.locator('form [xdatabind]:visible,form [data-xdatabind]:visible').first().waitFor({state:'visible',timeout}); + const raw=await page.evaluate(readDetailDocument),steps=raw.processSteps,current=[...new Set(steps.filter(step=>['处理中','running','active'].includes(step.status)).map(step=>step.name))]; + if(current.length!==1||!nodeName||current[0]!==nodeName)fail('流程步骤未能唯一确认当前节点,详情采集已阻断。'); + const detail=extractFieldSnapshot({...raw,processName:identity.processName,nodeName:current[0],processVersion:identity.processVersion,processInstanceId:identity.pid}); + const capturedAt=new Date().toISOString(),evidenceHash=crypto.createHash('sha256').update(JSON.stringify(detail)).digest('hex'); + return {...identity,detail:{...detail,tid:identity.tid,pid:identity.pid,capturedAt,evidenceHash},snapshot:raw.snapshot,capturedAt,evidenceHash,blockedRequests:blocked}; + }catch(error){if(error.status)throw error;fail('BPM 详情读取未完成,可能需要登录或尚未批准页面所需的只读数据接口。',502);}finally{await context?.close().catch(()=>{});await browser.close().catch(()=>{});} +} +module.exports={parseDetailUrl,extractFieldSnapshot,captureDetail,allowDetailRequest,readDetailDocument}; diff --git a/src/bpm-scan-store.cjs b/src/bpm-scan-store.cjs index 335e6cb..d23c76c 100644 --- a/src/bpm-scan-store.cjs +++ b/src/bpm-scan-store.cjs @@ -22,6 +22,8 @@ class BpmScanStore{ fail(id,message){this.db.prepare('UPDATE runs SET status=?,finished_at=?,message=? WHERE id=?').run('error',new Date().toISOString(),message,id);this.prune();} prune(){this.db.exec("DELETE FROM runs WHERE status!='running' AND id NOT IN(SELECT id FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 200)");} status(){return {config:this.config(),total:this.db.prepare('SELECT COUNT(*) n FROM arrivals').get().n,runs:this.db.prepare('SELECT id,connection_id AS connectionId,actor,started_at AS startedAt,finished_at AS finishedAt,status,seen,added,message FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 30').all()};} + getArrival(connectionId,source,taskId){const row=this.db.prepare('SELECT connection_id AS connectionId,value,first_seen AS firstSeenAt FROM arrivals WHERE connection_id=? AND source=? AND task_id=?').get(connectionId,source,taskId);if(!row)return null;const {value,...metadata}=row;return {...JSON.parse(value),...metadata};} + recent({since='',limit=500}={}){return this.db.prepare('SELECT connection_id AS connectionId,value,first_seen AS firstSeenAt,last_seen AS lastSeenAt FROM arrivals WHERE first_seen>=? ORDER BY first_seen DESC,task_id LIMIT ?').all(since,limit).map(({value,...metadata})=>({...JSON.parse(value),...metadata}));} list({connectionId='',q='',before='',days=7}={}){ if(typeof q!=='string'||q.length>200||typeof connectionId!=='string'||connectionId.length>200||typeof before!=='string'||(before&&!/^\d{4}-\d{2}-\d{2}$/.test(before))||!Number.isInteger(days)||days<1||days>31)throw invalid('查询条件无效。'); const conditions=[],args=[];if(connectionId){conditions.push('connection_id=?');args.push(connectionId);}if(q){conditions.push("value LIKE ? ESCAPE '\\'");args.push('%'+q.replace(/[\\%_]/g,'\\$&')+'%');} diff --git a/src/bpm-session-manager.cjs b/src/bpm-session-manager.cjs index e88521f..03f4ee6 100644 --- a/src/bpm-session-manager.cjs +++ b/src/bpm-session-manager.cjs @@ -175,6 +175,16 @@ class BpmSessionManager { if(renewed.status!=='connected')throw error(renewed.checks?.portal?.message||'请在 BPM 连接中完成登录。',401); return query(); } + async captureOrderDetail(connection,principal,arrival){ + return this.run(connection?.id,async()=>{ + this.authorize(connection,principal); + if(this.sessions.has(connection.id))throw error('此连接正在登录窗口中使用,请关闭后采集详情。',409); + const saved=await this.vault().read(connection.id); + const {captureDetail}=require('./bpm-order-detail.cjs'); + const result=await captureDetail({storageState:saved?.storageState,sessionStorage:saved?.sessionStorage,detailUrl:arrival.detailUrl,processName:arrival.processName,nodeName:arrival.activityName}); + this.authorize(connection,principal);return result; + }); + } authorize(connection, principal) { if (!connection || typeof connection.id !== 'string' || !connection.id || connection.id.length > 200) throw error('连接标识无效。'); if (!principal?.sessionId || !principal.user || !['admin','operator'].includes(principal.user.role) || (principal.user.role !== 'admin' && connection.owner !== principal.user.username)) throw error('只有连接负责人或管理员可以操作。',403); diff --git a/src/dashboard.cjs b/src/dashboard.cjs index 9e1844f..b13981f 100644 --- a/src/dashboard.cjs +++ b/src/dashboard.cjs @@ -14,7 +14,7 @@ const {SessionStore,SESSION_MS}=require('./dashboard-sessions.cjs'); const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address); const publicJob=({path:ignored,...job})=>({...job,downloadable:job.status==='success'}); -function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,storage,notifications,workflow,assistant,health,watchdog,trustedProxy=false}) { +function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,storage,notifications,workflow,pipeline,assistant,health,watchdog,trustedProxy=false}) { const sessions=new SessionStore(path.dirname(store.file));const failures=new Map(); const sessionCookieName=previewUserId?'order_preview_session':'order_session'; const sessionCookiePattern=new RegExp('(?:^|;\\s*)'+sessionCookieName+'=([a-f0-9]{64})(?:;|$)'); @@ -26,6 +26,7 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma '/bpm.js':{path:path.join(webRoot,'bpm.js'),type:'text/javascript'}, '/mail.js':{path:path.join(webRoot,'mail.js'),type:'text/javascript'}, '/orders.js':{path:path.join(webRoot,'orders.js'),type:'text/javascript'}, + '/order-workflow.js':{path:path.join(webRoot,'order-workflow.js'),type:'text/javascript'}, '/storage.js':{path:path.join(webRoot,'storage.js'),type:'text/javascript'}, '/storage-preview.html':{path:path.join(webRoot,'storage-preview.html'),type:'text/html',preview:true}, '/storage-preview.js':{path:path.join(webRoot,'storage-preview.js'),type:'text/javascript',preview:true}, @@ -104,7 +105,7 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma if(await bpmScanApi({scanner,workspace,user,sessionId:token,url,route,method:request.method,body,reply}))return; if(await storageApi({storage,workspace,user,url,route,method:request.method,body,request,response,reply,trustedProxy}))return; if(await notificationApi({notifications,workspace,user,route,method:request.method,body,reply}))return; - if(await orderWorkflowApi({workflow,user,route,method:request.method,body,reply}))return; + if(await orderWorkflowApi({workflow,pipeline,workspace,user,sessionId:token,route,method:request.method,body,reply}))return; if(await assistantApi({assistant,workspace,user,sessionId:token,route,method:request.method,body,request,reply,trustedProxy}))return; if(workspaceApi({workspace,store,user,route,method:request.method,body,reply,bpmSessions}))return; if(route==='/api/overview' && request.method==='GET') { diff --git a/src/notifications.cjs b/src/notifications.cjs index b06c584..02f5c2d 100644 --- a/src/notifications.cjs +++ b/src/notifications.cjs @@ -18,6 +18,7 @@ class NotificationStore{ this.db.prepare('INSERT OR IGNORE INTO settings VALUES(1,?)').run(JSON.stringify({version:1,enabled:false,sourceKey:crypto.randomUUID(),sourceName:'业务来源',channelId:'',fieldMap:DEFAULT_MAP,maxAttempts:3})); if(!this.db.prepare('PRAGMA table_info(items)').all().some(c=>c.name==='industry')){this.db.exec("ALTER TABLE items ADD COLUMN industry TEXT NOT NULL DEFAULT ''");for(const row of this.db.prepare('SELECT id,payload FROM items').all())this.db.prepare('UPDATE items SET industry=? WHERE id=?').run(this.decode(row.id,row.payload).industry,row.id);} this.db.exec('CREATE INDEX IF NOT EXISTS notification_pending ON items(status,industry,attempts)'); + if(!this.db.prepare('PRAGMA table_info(items)').all().some(c=>c.name==='owner'))this.db.exec("ALTER TABLE items ADD COLUMN owner TEXT NOT NULL DEFAULT 'generic'"); } transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(e){this.db.exec('ROLLBACK');throw e;}} encode(id,data){try{return this.vault.encode(id,data);}catch{fail('通知内容加密不可用,请联系管理员。',503);}} @@ -26,11 +27,12 @@ class NotificationStore{ saveSettings(input){const old=this.settings();if(!input||Object.keys(input).some(k=>!['version','enabled','sourceKey','sourceName','channelId','fieldMap','maxAttempts'].includes(k)))fail('通知配置无效。');if(input.version!==old.version)fail('通知配置已被修改,请刷新。',409);if(typeof input.enabled!=='boolean'||typeof input.sourceName!=='string'||!input.sourceName.trim()||input.sourceName.length>80||typeof input.channelId!=='string'||input.channelId.length>100||!Number.isInteger(input.maxAttempts)||input.maxAttempts<1||input.maxAttempts>10)fail('请检查来源、邮箱和尝试次数(1–10)。');if(input.sourceKey&&input.sourceKey!==old.sourceKey)fail('来源标识不能更改。');const saved={...input,sourceKey:old.sourceKey,sourceName:input.sourceName.trim(),fieldMap:validateMap(input.fieldMap),version:old.version+1};this.db.prepare('UPDATE settings SET value=? WHERE id=1').run(JSON.stringify(saved));return saved;} scheduleState(){const row=this.db.prepare("SELECT value FROM metadata WHERE key='schedule'").get();return row?JSON.parse(row.value):null;} setSchedule(value){this.db.prepare("INSERT INTO metadata VALUES('schedule',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(JSON.stringify(value));} - ingest(event){const id=hash([event.sourceKey,event.sourceId,event.sourceVersion,event.industry].join('\0')),old=this.db.prepare('SELECT * FROM items WHERE id=?').get(id);if(old){const value=this.decode(id,old.payload);if(value.brief!==event.brief||value.subject!==event.subject)fail('同一通知版本的内容已变化,请核实来源版本。',409);return this.item(old);}this.db.prepare('INSERT INTO items(id,payload,status,created_at,industry) VALUES(?,?,?,?,?)').run(id,this.encode(id,event),'pending',new Date().toISOString(),event.industry);return this.item(this.db.prepare('SELECT * FROM items WHERE id=?').get(id));} + ingest(event){const id=hash([event.sourceKey,event.sourceId,event.sourceVersion,event.industry].join('\0')),old=this.db.prepare('SELECT * FROM items WHERE id=?').get(id);if(old){const value=this.decode(id,old.payload);if(value.brief!==event.brief||value.subject!==event.subject)fail('同一通知版本的内容已变化,请核实来源版本。',409);return this.item(old);}this.db.prepare('INSERT INTO items(id,payload,status,created_at,industry,owner) VALUES(?,?,?,?,?,?)').run(id,this.encode(id,event),'pending',new Date().toISOString(),event.industry,event.owner==='order-workflow'?'order-workflow':'generic');return this.item(this.db.prepare('SELECT * FROM items WHERE id=?').get(id));} item({payload,...row}){return {...this.decode(row.id,payload),...row};} items(){return this.db.prepare('SELECT * FROM items ORDER BY rowid DESC LIMIT 100').all().map(r=>this.item(r));} - pending(attempts,industries){if(!industries.length)return [];return this.db.prepare("SELECT * FROM items WHERE status IN('pending','blocked') AND attempts AND industry IN("+industries.map(()=>'?').join(',')+") ORDER BY rowid LIMIT 200").all(attempts,...industries).map(r=>this.item(r));} - blockUnmapped(industries){this.db.prepare("UPDATE items SET status='blocked',error='此产业尚未配置接口人收件组。' WHERE status IN('pending','blocked')"+(industries.length?' AND industry NOT IN('+industries.map(()=>'?').join(',')+')':'')).run(...industries);} + pending(attempts,industries){if(!industries.length)return [];return this.db.prepare("SELECT * FROM items WHERE owner='generic' AND status IN('pending','blocked') AND attempts AND industry IN("+industries.map(()=>'?').join(',')+") ORDER BY rowid LIMIT 200").all(attempts,...industries).map(r=>this.item(r));} + blockUnmapped(industries){this.db.prepare("UPDATE items SET status='blocked',error='此产业尚未配置接口人收件组。' WHERE owner='generic' AND status IN('pending','blocked')"+(industries.length?' AND industry NOT IN('+industries.map(()=>'?').join(',')+')':'')).run(...industries);} + syncOrder(order){const id=hash(['order-workflow',order.versionKey,order.businessVersion,order.productLine].join('\0'));this.db.prepare("UPDATE items SET status=?,error=?,batch_id=? WHERE id=? AND owner='order-workflow'").run(order.notification?.status||order.status,order.notification?.error||null,order.notification?.batchId||null,id);} block(id,message){this.db.prepare("UPDATE items SET status='blocked',error=? WHERE id=? AND status IN('pending','blocked')").run(message,id);} prepare(items,snapshot){return this.transaction(()=>{const id=crypto.randomUUID();this.db.prepare('INSERT INTO batches VALUES(?,?,?,?,?)').run(id,'prepared',this.encode(id,snapshot),null,new Date().toISOString());for(const item of items){const result=this.db.prepare("UPDATE items SET status='reserved',attempts=attempts+1,error=NULL,batch_id=? WHERE id=? AND status IN('pending','blocked')").run(id,item.id);if(!result.changes)fail('通知队列已变化,请重试。',409);}return id;});} mark(id,status,message=null){this.transaction(()=>{this.db.prepare('UPDATE batches SET status=?,error=? WHERE id=?').run(status,message,id);if(status!=='sending')this.db.prepare('UPDATE items SET status=?,error=? WHERE batch_id=?').run(status==='failed'?'pending':status,message,id);});} @@ -43,6 +45,8 @@ class NotificationService{ map(data){if(!data||typeof data!=='object'||Array.isArray(data))fail('通知来源必须是 JSON 对象。');const config=this.store.settings(),raw=Object.fromEntries(Object.entries(config.fieldMap).map(([key,p])=>[key,valueAt(data,p)]));if(!['string','number'].includes(typeof raw.id)||!String(raw.id).trim()||String(raw.id).length>200||/[\x00-\x1f]/.test(String(raw.id))||typeof raw.industry!=='string'||!raw.industry.trim()||raw.industry.length>100||/[\x00-\x1f]/.test(raw.industry)||typeof raw.brief!=='string'||!raw.brief.trim()||raw.brief.length>20000)fail('通知 ID、产业和简要说明不能为空,正文最多 20000 字。');if(raw.subject!==undefined&&(typeof raw.subject!=='string'||raw.subject.length>300||/[\r\n\x00]/.test(raw.subject)))fail('通知标题最多 300 字,不能包含换行。');if(raw.version!==undefined&&(!['string','number'].includes(typeof raw.version)||String(raw.version).length>200||/[\x00-\x1f]/.test(String(raw.version))))fail('来源版本无效。');if(raw.occurredAt!==undefined&&(typeof raw.occurredAt!=='string'||!Number.isFinite(Date.parse(raw.occurredAt))))fail('业务时间无效。');return {source:config.sourceName,sourceKey:config.sourceKey,sourceId:String(raw.id).trim(),sourceVersion:raw.version===undefined||raw.version===''?hash(raw.brief):String(raw.version),industry:raw.industry.trim(),brief:raw.brief,subject:raw.subject||raw.industry.trim()+'业务通知',occurredAt:raw.occurredAt||this.clock().toISOString()};} preview(data){try{const event=this.map(data),group=this.settings().groups.find(g=>g.productLine===event.industry);return {valid:!!group,event,to:group?.to||[],cc:group?.cc||[],issues:group?[]:['此产业尚未配置接口人收件组。']};}catch(e){if(!e.status)throw e;return {valid:false,issues:[e.message]};}} ingest(data){return this.store.ingest(this.map(data));} + ingestOrder(order){if(order?.steps?.archive?.status!=='success'||!order.archive?.archiveId||!order.versionKey||!order.businessVersion||!order.templateId||!order.ruleId||!order.productLine||!order.brief)fail('订单通知必须有成功归档及已确认的订单版本证据。',409);return this.store.ingest({owner:'order-workflow',source:order.source,sourceKey:'order-workflow',sourceId:order.versionKey,sourceVersion:order.businessVersion,industry:order.productLine,brief:order.brief,subject:order.subject,occurredAt:order.businessTime,orderVersionKey:order.versionKey,ruleId:order.ruleId,templateId:order.templateId});} + syncOrder(order){this.store.syncOrder(order);} saveSettings(input){if(this.running)fail('通知正在发送,请稍后修改配置。',409);if(input?.enabled){const c=this.mail.store.publicChannel(input.channelId);if(!c.state.smtp)fail('请先验证发件邮箱的 SMTP 连接。',409);if(!this.settings().groups.length)fail('请先配置产业接口人收件组。',409);}const old=this.store.settings(),saved=this.store.saveSettings(input);if(saved.enabled&&!old.enabled)this.resetSchedule(this.clock());return saved;} resetSchedule(now){const schedule=this.settings().schedule,calendar=this.calendar();const state={signature:JSON.stringify([schedule,calendar]),next:nextSlots(schedule,now,1,calendar)[0]};this.store.setSchedule(state);return state;} tick(now=this.clock()){ diff --git a/src/order-pipeline.cjs b/src/order-pipeline.cjs new file mode 100644 index 0000000..2034adf --- /dev/null +++ b/src/order-pipeline.cjs @@ -0,0 +1,201 @@ +'use strict'; +const crypto=require('node:crypto'); +const {renderSnapshot}=require('./exporter.cjs'); +const {nextSlots,dayPolicy}=require('./schedule.cjs'); +const {parseDetailUrl}=require('./bpm-order-detail.cjs'); +const {OrderWorkflow}=require('./order-workflow.cjs'); +const TEST_RECIPIENT='2639266652@qq.com'; +const fail=(message,status=409)=>Object.assign(new Error(message),{status}); +const idFor=arrival=>crypto.createHash('sha256').update(JSON.stringify([arrival.connectionId,arrival.source,arrival.taskId])).digest('hex'); +const DEFAULTS={version:1,enabled:false,sendEnabled:false,channelId:'',serverId:'',since:null,maxAttempts:3}; +function latestElapsedSlot(now,schedule,calendar){ + const shifted=new Date(+now+8*3600000),midnight=Date.UTC(shifted.getUTCFullYear(),shifted.getUTCMonth(),shifted.getUTCDate()); + for(let offset=0;offset<370;offset++){ + const day=midnight-offset*86400000;if(!dayPolicy(new Date(day).toISOString().slice(0,10),schedule,calendar).send)continue; + for(const time of [...schedule.times].sort().reverse()){const [hour,minute]=time.split(':').map(Number),slot=day+(hour*60+minute)*60000-8*3600000;if(slot<=+now)return slot;} + } + return null; +} + +class OrderPipeline{ + constructor({workflow,store,scanStore,workspace,manager,jobs,storage,mail,notifications,settings,calendar=()=>[],outputDir,render=renderSnapshot,clock=()=>new Date()}){ + Object.assign(this,{workflow,store,scanStore,workspace,manager,jobs,storage,mail,notifications,settings,calendar,outputDir,render,clock});this.pending=new Map();this.stopped=false;this.sending=null;this.principal={sessionId:'order-pipeline:'+crypto.randomUUID(),user:{username:'订单任务',role:'admin'}}; + } + config(){return {...DEFAULTS,...this.store.meta('config',{})};} + saveConfig(input){ + const old=this.config();if(!input||Object.keys(input).some(key=>!Object.hasOwn(DEFAULTS,key))||input.version!==old.version)throw fail('订单运行配置已变化或包含无效参数。'); + if(typeof input.enabled!=='boolean'||typeof input.sendEnabled!=='boolean'||!Number.isInteger(input.maxAttempts)||input.maxAttempts<1||input.maxAttempts>10||typeof input.channelId!=='string'||typeof input.serverId!=='string')throw fail('订单运行配置无效。'); + if(this.pending.size||this.sending)throw fail('订单任务正在运行,请稍后修改配置。'); + if(input.enabled){if(!this.workflow.rules().some(rule=>rule.enabled&&rule.status==='published'))throw fail('请先通过真实只读样本检查并发布分类规则。');if(!input.serverId)throw fail('请选择归档服务器。');const server=this.storage.store.publicServer(input.serverId);if(!server.enabled||!server.state.writable)throw fail('归档服务器未启用或未通过读写检查。');} + if(input.sendEnabled){if(!input.enabled||!input.channelId)throw fail('请先启用订单处理并指定发件邮箱。');const channel=this.mail.store.publicChannel(input.channelId);if(!channel.state.smtp)throw fail('请先验证 SMTP。');for(const group of this.settings().groups)this.assertRecipients(group);} + const saved={...input,version:old.version+1,since:input.enabled?(old.enabled?old.since:this.clock().toISOString()):old.since};this.store.setMeta('config',saved);this.store.setMeta('schedule',null);return saved; + } + assertRecipients(group){if(!Array.isArray(group?.to)||!group.to.length||!Array.isArray(group.cc)||[...group.to,...group.cc].some(address=>typeof address!=='string'||address.toLowerCase()!==TEST_RECIPIENT))throw fail('受限测试期间 To/Cc 只允许隔离测试邮箱。');} + authorize(arrival,principal){const connection=this.workspace.getConnection(arrival.connectionId);if(connection.status==='disabled'||!principal?.sessionId||!['admin','operator'].includes(principal.user?.role)||(principal.user.role!=='admin'&&connection.owner!==principal.user.username))throw fail('只有连接负责人或管理员可以读取和处理此订单。',403);return connection;} + arrivals(){return this.store.candidates();} + options(){return {templates:this.mail.store.templates(),groups:this.settings().groups,connections:this.workspace.snapshot?.().connections?.map(({id,name})=>({id,name}))||[],adapters:{}};} + async checkRule(ruleId,input,principal){ + const arrival=this.scanStore.getArrival(input.connectionId,input.source,input.taskId);if(!arrival)throw fail('所选 BPM 到达记录不存在。',404);this.authorize(arrival,principal); + this.workflow.invalidateCheck(ruleId); + if(input.detailUrl){ + const provided=parseDetailUrl(input.detailUrl),stored=arrival.detailUrl?parseDetailUrl(arrival.detailUrl):null; + if(stored?(provided.tid!==stored.tid||provided.pid!==stored.pid||provided.processVersion!==stored.processVersion||provided.processName!==stored.processName):(String(arrival.tid||'')!==provided.tid||String(arrival.pid||'')!==provided.pid||provided.processName!==arrival.processName))throw fail('详情链接与到达记录缺少同一订单的关联证据,请重新扫描带有明确 tid/pid 的记录。'); + arrival.detailUrl=input.detailUrl; + } + if(!arrival.detailUrl)throw fail('到达记录没有真实详情链接,请提供该订单的 BPM 详情链接;不能猜测 tid/pid。'); + const captured=await this.manager.captureOrderDetail(this.workspace.getConnection(arrival.connectionId),principal,arrival); + const result=this.workflow.checkRule(ruleId,{arrival,detail:captured.detail,provenance:'bpm-readonly'}); + if(result.valid)this.store.setMeta('check:'+result.checkId,{ruleId,version:result.version,arrivalKey:idFor(arrival),evidenceHash:result.evidenceHash}); + return result; + } + publishRule(id,input){ + const check=this.store.meta('check:'+input.checkId);if(!check||check.ruleId!==id||check.version!==input.version)throw fail('缺少当前规则的服务器样本检查证据。'); + const rule=this.workflow.getRule(id),template=this.mail.store.template(rule.templateId);if(template.status!=='active')throw fail('分类绑定模板尚未确认生效。');if(rule.pdfTemplateId!=='bpm-snapshot-v1')throw fail('不支持此 PDF 模板。'); + const group=this.settings().groups.find(group=>group.productLine===(rule.recipientGroupId||rule.productLine));this.assertRecipients(group); + return this.workflow.publishRule(id,input); + } + async process(arrival,principal=this.principal){ + const id=idFor(arrival);if(this.pending.has(id))return this.pending.get(id);if(this.stopped)throw fail('订单服务正在停止。'); + const task=this.processOne(arrival,principal).finally(()=>this.pending.delete(id));this.pending.set(id,task);return task; + } + async processOne(arrival,principal){ + const candidate={id:idFor(arrival),...structuredClone(arrival),status:'capturing',ruleRevision:this.workflow.rules().map(rule=>[rule.id,rule.version,rule.status]),updatedAt:this.clock().toISOString()};let order; + try{ + const connection=this.authorize(arrival,principal);this.store.putCandidate(candidate); + if(!arrival.detailUrl)throw fail('缺少已核实的 BPM 详情链接。'); + const capture=await this.manager.captureOrderDetail(connection,principal,arrival); + const identified=this.workflow.identify({arrival,detail:capture.detail});order=identified.order; + if(identified.status==='duplicate'){ + if(['archive_error','pdf_error','notification_error','interrupted'].includes(order.status)){ + order=order.steps.archive?.status==='success'?this.workflow.update(order.versionKey,draft=>{draft.status='archived';}):this.workflow.start(order.versionKey); + if(order.status==='detail_capturing')order=this.workflow.markDetailReady(order.versionKey,{capturedAt:capture.capturedAt,evidenceHash:capture.evidenceHash}); + candidate.orderVersionKey=order.versionKey;candidate.snapshot=capture.snapshot;this.store.putCandidate(candidate);return await this.execute(order,capture.snapshot,principal,candidate); + } + if(['identified','detail_ready','pdf_success','archived'].includes(order.status)){ + if(order.status==='identified'){this.workflow.start(order.versionKey);order=this.workflow.markDetailReady(order.versionKey,{capturedAt:capture.capturedAt,evidenceHash:capture.evidenceHash});} + candidate.orderVersionKey=order.versionKey;candidate.snapshot=capture.snapshot;this.store.putCandidate(candidate);return await this.execute(order,capture.snapshot,principal,candidate); + } + candidate.status='duplicate';candidate.orderVersionKey=order.versionKey;this.store.putCandidate(candidate);return order; + } + candidate.orderVersionKey=order.versionKey;candidate.snapshot=capture.snapshot;this.store.putCandidate(candidate); + order=this.workflow.start(order.versionKey);order=this.workflow.markDetailReady(order.versionKey,{capturedAt:capture.capturedAt,evidenceHash:capture.evidenceHash||capture.detail.evidenceHash}); + return await this.execute(order,capture.snapshot,principal,candidate); + }catch(error){candidate.status='blocked';candidate.error=error.status?error.message:'详情或规则读取失败,请检查连接和采集记录。';candidate.code=error.code||'DETAIL_FAILED';this.store.putCandidate(candidate);return {status:'blocked',candidate};} + } + async execute(input,snapshot,principal,candidate){ + let order=input; + try{ + if(order.steps.pdf?.status!=='success'){ + const jobId='order-'+order.versionKey,existing=this.jobs.jobs().find(job=>job.jobId===jobId); + if(existing?.status==='success'){order=this.workflow.markPdfSuccess(order.versionKey,{jobId,...existing});} + else{ + if(existing&&['running','interrupted'].includes(existing.status))throw fail('上次 PDF 结果未确认,请核查输出记录,禁止重复生成。'); + if(!snapshot)throw fail('缺少已采集的 PDF 快照。'); + order=this.workflow.beginPdf(order.versionKey); + const field=order.sources.orderNo.path.replace(/^detail\./,''); + const pdfSnapshot={...snapshot,metadata:{order:order.orderNo,project:order.productCode,model:order.modelShort,serial:order.serialNo},...(/^OFR_(?:LSCP|BS|KD|WY)_Applicant\.OrderNum$/.test(field)?{bpmOrder:{field,value:order.orderNo}}:{})}; + this.jobs.recordJob({jobId,status:'running',metadata:pdfSnapshot.metadata,orderVersionKey:order.versionKey}); + let result;try{result=await this.render(pdfSnapshot,{outputDir:this.outputDir});}catch(error){this.jobs.recordJob({jobId,status:'error',error:'订单 PDF 生成失败。'});throw error;} + this.jobs.recordJob({jobId,status:'success',...result,metadata:pdfSnapshot.metadata,orderVersionKey:order.versionKey,...(pdfSnapshot.bpmOrder?{bpmOrder:pdfSnapshot.bpmOrder}:{})});order=this.workflow.markPdfSuccess(order.versionKey,{jobId,...result}); + } + } + if(order.steps.archive?.status!=='success'){ + const serverId=this.config().serverId||this.storage.store.settings().serverId;if(!serverId)throw fail('尚未指定归档服务器。'); + order=this.workflow.beginArchive(order.versionKey); + const receipt=await this.storage.archive(serverId,order.pdf.jobId,'',principal.user.username); + if(!receipt?.id||!receipt.sha256||!receipt.bytes||!receipt.relativePath)throw fail('归档服务没有返回完整文件校验回执。'); + order=this.workflow.markArchiveSuccess(order.versionKey,{archiveId:receipt.id,serverId,path:receipt.relativePath,bytes:receipt.bytes,sha256:receipt.sha256}); + } + if(!order.notification){const event=this.notifications?.ingestOrder(order);order=this.workflow.createNotification(order.versionKey);if(event)order=this.workflow.update(order.versionKey,draft=>{draft.notification.eventId=event.id;});} + candidate.status='processed';candidate.orderVersionKey=order.versionKey;delete candidate.snapshot;delete candidate.error;this.store.putCandidate(candidate);return order; + }catch(error){ + const current=this.workflow.get(order.versionKey),message=error.status?error.message:current.steps.archive?.status==='success'?'归档已成功,通知入队失败。':current.steps.pdf?.status==='success'?'SMB 归档失败,通知已阻断。':'PDF 未完成,通知已阻断。'; + if(current.steps.pdf?.status==='success'&¤t.steps.archive?.status!=='success')this.workflow.markArchiveError(order.versionKey,message);else if(current.steps.pdf?.status!=='success')this.workflow.markPdfError(order.versionKey,message); + if(current.steps.archive?.status==='success')this.workflow.update(order.versionKey,draft=>{draft.status='notification_error';draft.error=message;draft.steps.notification={status:'error',error:message};}); + candidate.status='error';candidate.error=message;candidate.orderVersionKey=order.versionKey;this.store.putCandidate(candidate);return this.workflow.get(order.versionKey); + } + } + async retry(key,principal){ + const order=this.workflow.get(key);if(!order)throw fail('订单版本不存在。',404);this.authorize(order.arrival,principal); + const candidate=this.arrivals().find(row=>row.orderVersionKey===key)||{id:idFor(order.arrival),...structuredClone(order.arrival),orderVersionKey:key,status:'recovering'}; + if(this.pending.has(candidate.id))throw fail('订单任务正在运行。');if(!['archive_error','pdf_error','detail_error','notification_error','interrupted'].includes(order.status))throw fail('只能重试明确失败或中断的步骤。'); + const task=(async()=>{ + if(!candidate.snapshot&&order.steps.pdf?.status!=='success'){ + const capture=await this.manager.captureOrderDetail(this.workspace.getConnection(order.arrival.connectionId),principal,order.arrival); + const preview=new OrderWorkflow({clock:this.clock}).identify({arrival:order.arrival,detail:capture.detail,rule:order.ruleSnapshot,mapping:order.ruleSnapshot.adapters[capture.detail.processVersion]}); + if(preview.order.versionKey!==key||JSON.stringify(preview.order.sources)!==JSON.stringify(order.sources)||JSON.stringify(preview.order.detailSnapshot.fields)!==JSON.stringify(order.detailSnapshot.fields))throw fail('恢复采集的业务版本或字段已变化,原任务不能使用新内容的 PDF。'); + candidate.snapshot=capture.snapshot;this.store.putCandidate(candidate); + } + let current=order.status==='notification_error'||order.steps.archive?.status==='success'?this.workflow.update(key,draft=>{draft.status='archived';}):this.workflow.start(key);if(current.status==='detail_capturing')current=this.workflow.markDetailReady(key,order.detailEvidence||{});return this.execute(current,candidate.snapshot,principal,candidate); + })().finally(()=>this.pending.delete(candidate.id));this.pending.set(candidate.id,task);return task; + } + async retryArrival(id,principal){ + const candidate=this.arrivals().find(row=>row.id===id);if(!candidate)throw fail('候选记录不存在。',404);this.authorize(candidate,principal); + if(candidate.orderVersionKey)return this.retry(candidate.orderVersionKey,principal); + if(!['blocked','error'].includes(candidate.status))throw fail('只能重试失败或阻断的候选记录。'); + const arrival=this.scanStore.getArrival(candidate.connectionId,candidate.source,candidate.taskId);if(!arrival)throw fail('原始 BPM 到达记录不存在。');return this.process(arrival,principal); + } + async tick(){ + if(this.stopped||this.ticking)return;this.ticking=this.perform().finally(()=>{this.ticking=null;});return this.ticking; + } + async perform(){ + const config=this.config();if(!config.enabled)return;const seen=new Map(this.arrivals().map(row=>[row.id,row])); + if(dayPolicy(this.clock(),this.settings().schedule,this.calendar()).scan)for(const arrival of this.scanStore.recent({since:config.since||this.clock().toISOString(),limit:10000})){ + if(this.stopped)break;if(!Number.isFinite(Date.parse(arrival.arrivedAt))||Date.parse(arrival.arrivedAt)[rule.id,rule.version,rule.status])); + const changed=!old||JSON.stringify(old.ruleRevision)!==revision||old.lastSeenAt!==arrival.lastSeenAt||old.arrivedAt!==arrival.arrivedAt||old.subject!==arrival.subject; + if(changed&&this.workflow.rules().some(rule=>rule.enabled&&rule.status==='published'&&rule.processName===arrival.processName&&rule.nodeName===arrival.activityName))await this.process(arrival); + } + for(const order of this.workflow.listOrders().filter(order=>order.status==='interrupted')){if(this.stopped)break;try{await this.retry(order.versionKey,this.principal);}catch{}} + if(config.sendEnabled)await this.sendDue(); + for(const order of this.workflow.listOrders())if(order.notification)this.notifications?.syncOrder(order); + } + start(){if(!this.timer){this.timer=setInterval(()=>this.tick().catch(()=>{}),15000);this.timer.unref?.();}} + async stop(){this.stopped=true;clearInterval(this.timer);await this.ticking;await Promise.allSettled([...this.pending.values()]);if(this.sending)await this.sending;} + resetSchedule(now=this.clock()){ + const schedule=this.settings().schedule,calendar=this.calendar(),state={signature:JSON.stringify([schedule,calendar]),next:nextSlots(schedule,now,1,calendar)[0]};this.store.setMeta('schedule',state);return state; + } + async sendDue(){ + if(this.stopped||this.sending||!this.config().sendEnabled)return; + this.sending=this.performSend().finally(()=>{this.sending=null;});return this.sending; + } + async performSend(){ + const now=this.clock(),config=this.config(),settings=this.settings(),calendar=this.calendar(),signature=JSON.stringify([settings.schedule,calendar]),state=this.store.meta('schedule'); + if(!config.enabled||!config.sendEnabled)return; + if(!state||state.signature!==signature){this.resetSchedule(now);return;} + if(!state.next||Date.parse(state.next)>+now)return; + const due=Date.parse(state.next); + // A late service does not retroactively execute a send window. Pending events + // remain for next_window; skip explicitly retains an operator-visible record. + if(+now-due>60000){ + const lastDue=latestElapsedSlot(now,settings.schedule,calendar)||due; + if(settings.schedule.missed==='skip')for(const order of this.workflow.listOrders().filter(order=>['notification_pending','blocked'].includes(order.status)&&order.notification&&Date.parse(order.businessTime)<=lastDue))this.workflow.update(order.versionKey,draft=>{draft.status='skipped';draft.notification.status='skipped';draft.notification.error='服务错过发送窗口,等待人工处理。';draft.steps.notification={status:'skipped',error:draft.notification.error};}); + this.resetSchedule(now); + return; + } + if(!dayPolicy(now,settings.schedule,calendar).send){this.resetSchedule(now);return;} + const groups={};for(const group of settings.groups){try{this.assertRecipients(group);groups[group.productLine]=group;}catch{}} + const templates={};for(const template of this.mail.store.templates().filter(template=>template.status==='active'))templates[template.id]=this.mail.store.template(template.id); + try{this.workflow.freezeBatches(new Date(due).toISOString(),{groups,templates});}catch(error){if(error.code!=='EMPTY_BATCH')throw error;} + const pending=this.workflow.listBatches().filter(batch=>['prepared','failed'].includes(batch.status)&&(batch.attempts||0){ + this.resetSchedule(now); + for(const batch of pending){ + if(this.stopped||!this.config().sendEnabled)break;let transport,sending=false; + try{ + this.assertRecipients(batch);if(batch.attachments?.length)throw fail('订单邮件附件必须为空。'); + const channel=this.mail.store.channelSecret(config.channelId);transport=this.mail.smtpFactory(channel.smtp);await transport.verify();this.mail.store.guard(channel.id,channel.version); + this.assertRecipients(batch);this.workflow.markBatchSending(batch.id);sending=true; + const receipt=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((receipt.accepted||[]).map(address=>String(address.address||address).toLowerCase())); + if(receipt.rejected?.length||[...batch.to,...batch.cc].some(address=>!accepted.has(address.toLowerCase())))this.workflow.markBatchUnknown(batch.id,'部分收件人未被 SMTP 接受,必须人工核验,禁止自动重发。'); + else this.workflow.markBatchSent(batch.id); + }catch{ + if(sending)this.workflow.markBatchUnknown(batch.id,'SMTP 发送结果不明,必须人工核验,禁止自动重发。'); + else this.workflow.markBatchFailed(batch.id,'SMTP 检查失败或隔离收件人校验失败;达到上限后需人工处理。'); + }finally{transport?.close?.();} + } + }).catch(error=>{if(error.status!==409)throw error;}); + } +} +module.exports={OrderPipeline,TEST_RECIPIENT}; diff --git a/src/order-template-bridge.cjs b/src/order-template-bridge.cjs new file mode 100644 index 0000000..02408c5 --- /dev/null +++ b/src/order-template-bridge.cjs @@ -0,0 +1,18 @@ +'use strict'; +const {renderTemplate}=require('./mail-parser.cjs'); +const fail=(message)=>{throw Object.assign(new Error(message),{status:409});}; +function buildTemplateValues({productLine,orders,date}){ + if(typeof productLine!=='string'||!productLine.trim())fail('分类规则没有产品线。'); + if(!Array.isArray(orders)||!orders.length)fail('模板批次没有订单。'); + if(typeof date!=='string'||!date.trim())fail('模板批次没有业务日期。'); + const orderNumbers=orders.map(order=>String(order.orderNo||'').trim());if(orderNumbers.some(value=>!value))fail('模板批次存在缺少订单号的订单。'); + const orderList=orders.map(order=>String(order.brief||'')).join('\n\n');if(!orderList.trim())fail('模板批次没有简要说明原文。'); + return {'产品线':productLine.trim(),'订单号':orderNumbers.join('、'),'日期':date.trim(),'订单列表':orderList}; +} +function renderOrderTemplate(template,input){ + if(!template||typeof template.id!=='string'||!Number.isInteger(template.version))fail('分类模板快照无效。'); + if(Array.isArray(template.attachments)&&template.attachments.length)fail('业务通知模板不能包含 PDF 或其他附件。'); + const values=buildTemplateValues(input),rendered=renderTemplate({...template,attachments:[]},values); + return {...rendered,templateId:template.id,templateVersion:template.version,attachments:[]}; +} +module.exports={buildTemplateValues,renderOrderTemplate}; diff --git a/src/order-workflow-api.cjs b/src/order-workflow-api.cjs index d2cf179..c64fec7 100644 --- a/src/order-workflow-api.cjs +++ b/src/order-workflow-api.cjs @@ -1,29 +1,40 @@ 'use strict'; const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});}; -const keys=(body,allowed)=>{if(!body||typeof body!=='object'||Object.keys(body).some(key=>!allowed.includes(key)))fail('订单流程参数无效。');}; -async function orderWorkflowApi({workflow,user,route,method,body,reply}){ - if(!route.startsWith('/api/order-workflow'))return false; +const keys=(body,allowed)=>{if(!body||typeof body!=='object'||Array.isArray(body)||Object.keys(body).some(key=>!allowed.includes(key)))fail('订单流程参数无效。');}; +async function orderWorkflowApi({workflow,pipeline,workspace,user,sessionId,route,method,body,reply}){ + if(!/^\/api\/order-workflow(?:\/|$)/.test(route))return false; if(!workflow)fail('订单流程服务未启动。',503); - if(route==='/api/order-workflow'&&method==='GET'){reply(200,{orders:workflow.listOrders(),batches:workflow.listBatches()});return true;} - if(user?.role==='viewer')fail('只读成员不能操作订单流程。',403); + const admin=()=>{if(user?.role!=='admin')fail('仅管理员可以维护分类规则或核验发信结果。',403);}; + const service=()=>{if(!pipeline)fail('订单任务执行服务未启动。',503);return pipeline;}; + const audit=(action,detail)=>workspace?.record(user,action,detail); + if(route==='/api/order-workflow'&&method==='GET'){const candidates=pipeline?.arrivals().map(({snapshot,...value})=>value)||[],arrivals=pipeline?.scanStore?.recent?.()||[];reply(200,{orders:workflow.listOrders(),batches:workflow.listBatches(),arrivals,blockedArrivals:candidates,settings:pipeline?.config()||{enabled:false,sendEnabled:false}});return true;} + if(route==='/api/order-workflow/rules'&&method==='GET'){reply(200,{rules:workflow.rules()});return true;} + if(route==='/api/order-workflow/options'&&method==='GET'){reply(200,service().options());return true;} + const orderRoute=/^\/api\/order-workflow\/order\/([^/]+)$/.exec(route); + if(orderRoute&&method==='GET'){const order=workflow.get(decodeURIComponent(orderRoute[1]));if(!order)fail('订单版本不存在。',404);reply(200,order);return true;} + if(user?.role==='viewer'||!['admin','operator'].includes(user?.role))fail('只读成员不能操作订单流程。',403); if(method!=='POST')fail('没有找到此订单流程操作。',404); - if(route==='/api/order-workflow/identify'){ - keys(body,['provenance','arrival','detail','mapping','rule']);if(body.provenance!=='bpm-readonly')fail('订单详情必须来自授权 BPM 只读采集。',409); - const result=workflow.identify(body);reply(200,result);return true; + if(route==='/api/order-workflow/rules'){ + admin();keys(body,['id','version','enabled','processName','nodeName','productLine','templateId','pdfTemplateId','notificationType','batchMode','recipientGroup','recipientGroupId','adapters']); + if(Object.hasOwn(body,'recipientGroup'))fail('请绑定已保存的收件组,不能在分类中注入邮箱地址。'); + const result=workflow.saveRule(body);audit('保存分类规则草稿',result.id);reply(200,result);return true; } - const step=/^\/api\/order-workflow\/orders\/([^/]+)\/(start|detail-ready|pdf-success|pdf-error|archive-success|archive-error|notification)$/.exec(route); - if(step){const id=decodeURIComponent(step[1]);const action=step[2];let result; - if(action==='start'){keys(body,[]);result=workflow.start(id);} - else if(action==='detail-ready'){keys(body,['evidence']);result=workflow.markDetailReady(id,body.evidence||{});} - else if(action==='pdf-success'){keys(body,['jobId']);result=workflow.markPdfSuccess(id,{jobId:body.jobId});} - else if(action==='pdf-error'){keys(body,['message']);result=workflow.markPdfError(id,body.message);} - else if(action==='archive-success'){keys(body,['archiveId','path']);result=workflow.markArchiveSuccess(id,{archiveId:body.archiveId,path:body.path});} - else if(action==='archive-error'){keys(body,['message']);result=workflow.markArchiveError(id,body.message);} - else {keys(body,['productLine','brief','subject','occurredAt']);result=workflow.createNotification(id,body);} + const ruleAction=/^\/api\/order-workflow\/rules\/([^/]+)\/(check|publish)$/.exec(route); + if(ruleAction){ + admin();const id=decodeURIComponent(ruleAction[1]);let result; + if(ruleAction[2]==='check'){keys(body,['connectionId','source','taskId','detailUrl']);result=await service().checkRule(id,body,{user,sessionId});audit('只读检查分类规则样本',id);} + else{keys(body,['version','checkId']);result=service().publishRule(id,body);audit('发布分类规则',id);} reply(200,result);return true; } - const batch=/^\/api\/order-workflow\/batches\/([^/]+)\/(freeze|unknown|retry)$/.exec(route); - if(batch){const id=decodeURIComponent(batch[1]);if(batch[2]==='freeze'){keys(body,['cutoff','mode','groups']);reply(200,workflow.freezeBatch(body.cutoff,{mode:body.mode,groups:body.groups}));return true;}if(batch[2]==='unknown'){keys(body,['message']);reply(200,workflow.markBatchUnknown(id,body.message));return true;}if(!workflow.canAutoRetry(id))fail('结果不明批次必须先人工核验,不能自动重发。',409);reply(200,{ok:true});return true;} - fail('没有找到此订单流程操作。',404); + if(route==='/api/order-workflow/settings'){admin();const result=service().saveConfig(body);audit('保存订单任务运行设置',result.enabled?'启用':'暂停');reply(200,result);return true;} + const retry=/^\/api\/order-workflow\/orders\/([^/]+)\/retry$/.exec(route); + if(retry){keys(body,[]);const id=decodeURIComponent(retry[1]);reply(200,await service().retry(id,{user,sessionId}));audit('重试失败订单步骤',id);return true;} + const retryArrival=/^\/api\/order-workflow\/arrivals\/([^/]+)\/retry$/.exec(route); + if(retryArrival){keys(body,[]);const id=decodeURIComponent(retryArrival[1]);reply(200,await service().retryArrival(id,{user,sessionId}));audit('重试候选订单采集',id);return true;} + const resolve=/^\/api\/order-workflow\/batches\/([^/]+)\/resolve$/.exec(route); + if(resolve){admin();keys(body,['resolution','note']);if(pipeline?.sending)fail('邮件发送中,请稍后核验。',409);const id=decodeURIComponent(resolve[1]);reply(200,workflow.resolveBatch(id,body,user.username));audit('核验订单邮件发送结果',id);return true;} + // Execution evidence is generated by server services. An HTTP provenance label + // or a caller-supplied job/archive ID never establishes a successful step. + fail('该订单流程操作不接受客户端执行证据。',409); } module.exports={orderWorkflowApi}; diff --git a/src/order-workflow-store.cjs b/src/order-workflow-store.cjs index c7d8eb8..acab12d 100644 --- a/src/order-workflow-store.cjs +++ b/src/order-workflow-store.cjs @@ -2,16 +2,35 @@ const fs=require('node:fs');const path=require('node:path');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('./bpm-vault.cjs'); const fail=(message,status=409)=>Object.assign(new Error(message),{status}); class OrderWorkflowStore{ - constructor(dir){this.dir=path.resolve(dir);fs.mkdirSync(this.dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(this.dir,'secrets')});this.db=new DatabaseSync(path.join(this.dir,'workflow.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON; + constructor(dir,{vault=null}={}){this.dir=path.resolve(dir);fs.mkdirSync(this.dir,{recursive:true});this.vault=vault||new BpmVault({stateDir:path.join(this.dir,'secrets')});this.db=new DatabaseSync(path.join(this.dir,'workflow.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON; CREATE TABLE IF NOT EXISTS orders(version_key TEXT PRIMARY KEY,order_no TEXT NOT NULL,status TEXT NOT NULL,payload BLOB NOT NULL,updated_at TEXT NOT NULL); - CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY,status TEXT NOT NULL,payload BLOB NOT NULL,updated_at TEXT NOT NULL);`);for(const row of this.db.prepare("SELECT id,payload FROM batches WHERE status='sending'").all()){const batch=this.vault.decode('batch:'+row.id,row.payload);batch.status='unknown';batch.error='服务重启,发送结果需要核实。';this.putBatch(batch);}} + CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY,status TEXT NOT NULL,payload BLOB NOT NULL,updated_at TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS rules(id TEXT PRIMARY KEY,payload BLOB NOT NULL,updated_at TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS candidates(id TEXT PRIMARY KEY,payload BLOB NOT NULL,updated_at TEXT NOT NULL); + CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);`); + for(const row of this.db.prepare("SELECT id,payload FROM batches WHERE status IN('sending','unknown')").all()){ + const batch=this.vault.decode('batch:'+row.id,row.payload);batch.status='unknown';batch.error||='服务重启,发送结果需要核实。'; + const orders=(batch.orderVersionKeys||[]).map(key=>this.getOrder(key)).filter(Boolean); + for(const order of orders){order.status='unknown';order.notification={...order.notification,status:'unknown',batchId:batch.id};order.steps={...order.steps,notification:{status:'unknown',batchId:batch.id,error:batch.error}};} + this.putGraph(orders,[batch]); + } + for(const order of this.orders())if(['identified','detail_capturing','detail_ready','pdf_pending','pdf_success','archive_pending','archived'].includes(order.status)){order.status='interrupted';order.error='服务重启,恢复时检查已完成步骤。';this.putOrder(order);} + } now(){return new Date().toISOString();} + putGraph(orders,batches){this.db.exec('BEGIN IMMEDIATE');try{orders.forEach(order=>this.putOrder(order));batches.forEach(batch=>this.putBatch(batch));this.db.exec('COMMIT');}catch(error){this.db.exec('ROLLBACK');throw error;}} putOrder(order){if(!order||typeof order.versionKey!=='string'||!order.versionKey)throw fail('订单版本键无效。',400);const value=structuredClone({...order,updatedAt:order.updatedAt||this.now()});this.db.prepare('INSERT INTO orders(version_key,order_no,status,payload,updated_at) VALUES(?,?,?,?,?) ON CONFLICT(version_key) DO UPDATE SET order_no=excluded.order_no,status=excluded.status,payload=excluded.payload,updated_at=excluded.updated_at').run(value.versionKey,String(value.orderNo||''),String(value.status||'unknown'),this.vault.encode('order:'+value.versionKey,value),value.updatedAt);return value;} getOrder(versionKey){const row=this.db.prepare('SELECT version_key,payload FROM orders WHERE version_key=?').get(versionKey);return row?this.vault.decode('order:'+row.version_key,row.payload):null;} orders(){return this.db.prepare('SELECT version_key,payload FROM orders ORDER BY updated_at DESC').all().map(row=>this.vault.decode('order:'+row.version_key,row.payload));} putBatch(batch){if(!batch||typeof batch.id!=='string'||!batch.id)throw fail('批次标识无效。',400);const value=structuredClone({...batch,updatedAt:batch.updatedAt||this.now()});this.db.prepare('INSERT INTO batches(id,status,payload,updated_at) VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET status=excluded.status,payload=excluded.payload,updated_at=excluded.updated_at').run(value.id,String(value.status||'unknown'),this.vault.encode('batch:'+value.id,value),value.updatedAt);return value;} getBatch(id){const row=this.db.prepare('SELECT id,payload FROM batches WHERE id=?').get(id);return row?this.vault.decode('batch:'+row.id,row.payload):null;} batches(){return this.db.prepare('SELECT id,payload FROM batches ORDER BY updated_at DESC').all().map(row=>this.vault.decode('batch:'+row.id,row.payload));} + putRule(rule){if(!rule||typeof rule.id!=='string'||!rule.id)throw fail('分类规则标识无效。',400);const value=structuredClone(rule);this.db.prepare('INSERT INTO rules(id,payload,updated_at) VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload,updated_at=excluded.updated_at').run(value.id,this.vault.encode('rule:'+value.id,value),this.now());return value;} + getRule(id){const row=this.db.prepare('SELECT id,payload FROM rules WHERE id=?').get(id);return row?this.vault.decode('rule:'+row.id,row.payload):null;} + rules(){return this.db.prepare('SELECT id,payload FROM rules ORDER BY updated_at DESC').all().map(row=>this.vault.decode('rule:'+row.id,row.payload));} + meta(key,fallback=null){const row=this.db.prepare('SELECT value FROM metadata WHERE key=?').get(key);return row?JSON.parse(row.value):fallback;} + setMeta(key,value){this.db.prepare('INSERT INTO metadata VALUES(?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key,JSON.stringify(value));return value;} + putCandidate(value){this.db.prepare('INSERT INTO candidates VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET payload=excluded.payload,updated_at=excluded.updated_at').run(value.id,this.vault.encode('candidate:'+value.id,value),this.now());return value;} + candidates(){return this.db.prepare('SELECT id,payload FROM candidates ORDER BY updated_at DESC').all().map(row=>this.vault.decode('candidate:'+row.id,row.payload));} close(){this.db.close();this.vault.destroy();} } module.exports={OrderWorkflowStore}; diff --git a/src/order-workflow.cjs b/src/order-workflow.cjs index 868cf05..45f96d4 100644 --- a/src/order-workflow.cjs +++ b/src/order-workflow.cjs @@ -1,6 +1,7 @@ 'use strict'; const crypto=require('node:crypto'); +const {renderOrderTemplate}=require('./order-template-bridge.cjs'); class OrderWorkflowError extends Error{ constructor(code,message){super(message);this.name='OrderWorkflowError';this.code=code;this.status=409;} @@ -9,75 +10,132 @@ class OrderWorkflowError extends Error{ const clone=value=>structuredClone(value); const hash=value=>crypto.createHash('sha256').update(String(value)).digest('hex'); const present=value=>value!==undefined&&value!==null&&(typeof value!=='string'||value.trim()!==''); +const text=value=>String(value??'').trim(); -function readCandidate(fields,path){ - const paths=Array.isArray(path)?path:[path]; - if(!paths.length||paths.some(p=>typeof p!=='string'||!p.trim()))throw new OrderWorkflowError('MISSING_FIELD','字段映射路径不能为空。'); - const values=paths.map(item=>({path:item,value:fields?.[item]})).filter(item=>present(item.value)); - if(!values.length)throw new OrderWorkflowError('MISSING_FIELD','缺少字段:'+paths.join('、')); +function candidateValues(source,spec){ + const paths=Array.isArray(spec)?spec:[spec]; + if(!paths.length||paths.some(path=>typeof path!=='string'&&!(path&&typeof path==='object'&&typeof path.path==='string'))){throw new OrderWorkflowError('MISSING_FIELD','字段映射路径不能为空。');} + return paths.map(item=>{ + const descriptor=typeof item==='string'?{source:'detail',path:item}:item; + const origin=descriptor.source||descriptor.from||'detail'; + if(!['detail','arrival','list'].includes(origin)||!descriptor.path.trim())throw new OrderWorkflowError('MISSING_FIELD','字段来源或路径无效。'); + const value=origin==='arrival'||origin==='list'?source.arrival?.[descriptor.path]:source.detail?.fields?.[descriptor.path]; + if(present(value)&&!['string','number'].includes(typeof value))throw new OrderWorkflowError('AMBIGUOUS_FIELD','业务字段必须为单一文本或数值:'+descriptor.path); + return {path:`${origin}.${descriptor.path}`,value}; + }).filter(item=>present(item.value)); +} + +function readCandidate(source,spec,label='字段'){ + const values=candidateValues(source,spec); + if(!values.length){ + const paths=(Array.isArray(spec)?spec:[spec]).map(item=>typeof item==='string'?item:item?.path||'').filter(Boolean); + throw new OrderWorkflowError('MISSING_FIELD','缺少字段'+(label?`(${label})`:'')+':'+paths.join('、')); + } const distinct=new Map(values.map(item=>[JSON.stringify(item.value),item])); - if(distinct.size>1)throw new OrderWorkflowError('AMBIGUOUS_FIELD','字段存在多个不同候选值:'+paths.join('、')); + if(distinct.size>1)throw new OrderWorkflowError('AMBIGUOUS_FIELD','字段存在多个不同候选值:'+values.map(item=>item.path).join('、')); return values[0]; } +function nodeNames(steps){return (Array.isArray(steps)?steps:[]).map(step=>text(step?.name||step?.nodeName||step?.activityName||step?.text)).filter(Boolean);} + function exactRule(arrival,detail,rule){ if(!rule||rule.enabled!==true)throw new OrderWorkflowError('RULE_BLOCKED','订单规则未启用。'); - if(rule.processName!==arrival.processName||rule.processName!==detail.processName&&detail.processName!==undefined)throw new OrderWorkflowError('PROCESS_CONFLICT','流程名称与已确认规则不一致。'); - if(rule.processVersion&&String(rule.processVersion)!==String(detail.processVersion))throw new OrderWorkflowError('FORM_VERSION_CONFLICT','表单版本与已确认规则不一致。'); - if(rule.nodeName&&rule.nodeName!==detail.nodeName)throw new OrderWorkflowError('NODE_CONFLICT','当前节点与已确认规则不一致。'); + if(rule.processName!==arrival.processName||(detail.processName!==undefined&&rule.processName!==detail.processName))throw new OrderWorkflowError('PROCESS_CONFLICT','流程名称与已确认规则不一致。'); + const arrivalNode=text(arrival.activityName),detailNode=text(detail.nodeName); + if((arrivalNode&&arrivalNode!==rule.nodeName)||(detailNode&&detailNode!==rule.nodeName)||(arrivalNode&&detailNode&&arrivalNode!==detailNode))throw new OrderWorkflowError('NODE_CONFLICT','当前节点与已确认规则不一致。'); + const observed=nodeNames(detail.processSteps);if(observed.length&&!observed.includes(rule.nodeName))throw new OrderWorkflowError('NODE_CONFLICT','流程步骤证据中没有当前节点。'); + const current=nodeNames((detail.processSteps||[]).filter(step=>['处理中','running','active'].includes(step.status)));if(current.length&&(new Set(current).size!==1||current[0]!==rule.nodeName))throw new OrderWorkflowError('NODE_CONFLICT','流程步骤当前办理节点与列表不一致。'); } +function dateOnly(value){const date=new Date(value);if(Number.isNaN(+date))return text(value);return new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(date);} + class OrderWorkflow{ - constructor({clock=()=>new Date(),schedule={times:['11:00','17:00'],timezone:'Asia/Shanghai'},store=null}={}){this.clock=clock;this.schedule=schedule;this.store=store;this.orders=new Map((store?.orders?.()||[]).map(order=>[order.versionKey,order]));this.batches=new Map((store?.batches?.()||[]).map(batch=>[batch.id,batch]));} - persistOrder(order){this.store?.putOrder?.(order);} - persistBatch(batch){this.store?.putBatch?.(batch);} - identify({arrival,detail,mapping,rule}){ - if(!arrival?.source||!arrival.taskId)throw new OrderWorkflowError('SOURCE_ID_MISSING','缺少 BPM 来源和任务号。'); - if(!detail||typeof detail.fields!=='object')throw new OrderWorkflowError('DETAIL_MISSING','缺少订单详情字段。'); - exactRule(arrival,detail,rule); - const orderNo=readCandidate(detail.fields,mapping.orderNo),serialNo=readCandidate(detail.fields,mapping.serialNo); - const productCode=readCandidate(detail.fields,mapping.productCode),modelFull=readCandidate(detail.fields,mapping.modelFull); - const modelShort=readCandidate(detail.fields,mapping.modelShort),customer=readCandidate(detail.fields,mapping.customer); - const brief=readCandidate(detail.fields,mapping.brief); - const productLine=Object.hasOwn(mapping,'productLine')?readCandidate(detail.fields,mapping.productLine):rule.productLinePath?readCandidate(detail.fields,rule.productLinePath):null; - if(!detail.processInstanceId)throw new OrderWorkflowError('VERSION_MISSING','缺少流程实例或业务版本标识。'); - const version=String(detail.businessVersion||detail.processInstanceId); - const versionKey=hash([arrival.source,arrival.taskId,detail.processInstanceId,version].join('\0')); - const order={ - id:hash([arrival.source,orderNo.value].join('\0')),versionKey,orderNo: String(orderNo.value).trim(),version, - source:arrival.source,taskId:String(arrival.taskId),processName:arrival.processName,processVersion:String(detail.processVersion||''), - nodeName:detail.nodeName||arrival.activityName||'',serialNo:String(serialNo.value),productCode:String(productCode.value), - modelFull:String(modelFull.value),modelShort:String(modelShort.value),customer:String(customer.value), - productLine:productLine?String(productLine.value):null,brief:String(brief.value),subject:String(detail.subject||arrival.subject||''), - businessTime:detail.businessTime||null,sourceRevision:detail.sourceRevision||detail.processInstanceId, - sources:{orderNo,serialNo,productCode,modelFull,modelShort,customer,brief,...(productLine?{productLine}:{})}, - ruleId:rule.id,status:'identified',createdAt:this.clock().toISOString(),updatedAt:this.clock().toISOString(), - }; - const existing=this.orders.get(versionKey);if(existing)return {status:'duplicate',order:clone(existing)}; - this.orders.set(versionKey,order);this.persistOrder(order);return {status:'matched',order:clone(order)}; + constructor({clock=()=>new Date(),schedule={times:['11:00','17:00'],timezone:'Asia/Shanghai'},store=null}={}){ + this.clock=clock;this.schedule=schedule;this.store=store;this.orders=new Map((store?.orders?.()||[]).map(order=>[order.versionKey,order]));this.batches=new Map((store?.batches?.()||[]).map(batch=>[batch.id,batch]));this.ruleMap=new Map((store?.rules?.()||[]).map(rule=>[rule.id,rule])); } - get(versionKey){const order=this.orders.get(versionKey);return order?clone(order):null;} - listOrders(){return [...this.orders.values()].map(clone);} - update(versionKey,work){const order=this.orders.get(versionKey);if(!order)throw new OrderWorkflowError('ORDER_NOT_FOUND','订单版本不存在。');const result=work(order);order.updatedAt=this.clock().toISOString();this.persistOrder(order);return result||clone(order);} - transition(versionKey,from,to){return this.update(versionKey,order=>{if(order.status!==from)throw new OrderWorkflowError('INVALID_STATE',`订单状态 ${order.status} 不能转为 ${to}。`);order.status=to;});} - start(versionKey){return this.update(versionKey,order=>{if(!['identified','detail_error','pdf_error','archive_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前订单不能开始处理。');order.status='detail_capturing';});} - markDetailReady(versionKey,detailEvidence={}){return this.update(versionKey,order=>{if(order.status!=='detail_capturing')throw new OrderWorkflowError('INVALID_STATE','详情尚未处于采集状态。');order.detailEvidence=clone(detailEvidence);order.status='detail_ready';});} - markPdfSuccess(versionKey,pdf){return this.update(versionKey,order=>{if(order.status!=='detail_ready')throw new OrderWorkflowError('INVALID_STATE','详情未准备好,不能记录 PDF。');if(!pdf?.jobId)throw new OrderWorkflowError('PDF_EVIDENCE_MISSING','缺少 PDF 任务证据。');order.pdf=clone(pdf);order.status='pdf_success';});} - markPdfError(versionKey,message){return this.update(versionKey,order=>{if(!['detail_ready','pdf_pending','detail_capturing'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能记录 PDF 失败。');order.error=String(message);order.status='pdf_error';});} - markArchiveSuccess(versionKey,archive){return this.update(versionKey,order=>{if(order.status!=='pdf_success')throw new OrderWorkflowError('INVALID_STATE','PDF 未成功,不能记录归档。');if(!archive?.archiveId)throw new OrderWorkflowError('ARCHIVE_EVIDENCE_MISSING','缺少 SMB 归档回执。');order.archive=clone(archive);order.status='archived';});} - markArchiveError(versionKey,message){return this.update(versionKey,order=>{if(order.status!=='pdf_success')throw new OrderWorkflowError('INVALID_STATE','当前状态不能记录归档失败。');order.error=String(message);order.status='archive_error';});} - createNotification(versionKey,input){return this.update(versionKey,order=>{if(order.status!=='archived')throw new OrderWorkflowError('ARCHIVE_REQUIRED','归档未成功,不能创建通知事件。');for(const key of ['productLine','brief','subject','occurredAt'])if(!present(input?.[key]))throw new OrderWorkflowError('NOTIFICATION_FIELD_MISSING','通知字段未确认:'+key);order.notification={...clone(input),orderVersionKey:versionKey,createdAt:this.clock().toISOString(),status:'pending'};order.status='notification_pending';});} - freezeBatch(cutoff,{mode='product_line',groups={}}={}){ - const candidates=[...this.orders.values()].filter(order=>order.status==='notification_pending'&&order.notification?.status==='pending'); - const grouped=new Map();for(const order of candidates){const key=mode==='order'?order.versionKey:order.notification.productLine;const group=groups[order.notification.productLine];if(!group?.to?.length){order.notification.status='blocked';order.notification.error='产业/产品线没有已确认的收件组。';order.status='blocked';continue;}if(!grouped.has(key))grouped.set(key,{group,orders:[]});grouped.get(key).orders.push(order);} - const [key,selected]=grouped.entries().next().value||[];if(!selected)throw new OrderWorkflowError('EMPTY_BATCH','当前发送窗口没有待发通知。'); - const batch={id:crypto.randomUUID(),status:'prepared',cutoff,mode,productLine:key,to:[...selected.group.to],cc:[...(selected.group.cc||[])],orderVersionKeys:selected.orders.map(order=>order.versionKey),subject:selected.orders.map(order=>order.notification.subject).join('、'),text:selected.orders.map(order=>order.notification.brief).join('\n\n'),attachments:[]}; - this.batches.set(batch.id,batch);this.persistBatch(batch);for(const order of selected.orders){order.notification.status='reserved';order.notification.batchId=batch.id;order.status='batched';this.persistOrder(order);}return clone(batch); + persistOrder(order){this.store?.putOrder?.(order);}persistBatch(batch){this.store?.putBatch?.(batch);} + saveRule(rule){ + if(!rule||typeof rule.id!=='string'||!rule.id||typeof rule.processName!=='string'||!rule.processName.trim()||typeof rule.nodeName!=='string'||!rule.nodeName.trim()||typeof rule.productLine!=='string'||!rule.productLine.trim()||typeof rule.templateId!=='string'||!rule.templateId.trim()||!rule.adapters||typeof rule.adapters!=='object'||Array.isArray(rule.adapters))throw new OrderWorkflowError('RULE_INVALID','分类规则缺少流程、节点、产品线、模板或版本适配器。'); + for(const [version,mapping] of Object.entries(rule.adapters))if(!version.trim()||!mapping||typeof mapping!=='object'||Array.isArray(mapping))throw new OrderWorkflowError('RULE_INVALID','字段适配器版本无效。'); + const old=this.ruleMap.get(rule.id);if(old&&rule.version!==old.version)throw new OrderWorkflowError('RULE_VERSION_CONFLICT','分类规则已被修改,请刷新后保存。'); + const value={batchMode:'category_template',notificationType:'order',pdfTemplateId:'bpm-snapshot-v1',...clone(rule),version:(old?.version||0)+1,status:'draft',check:null,enabled:rule.enabled!==false,processName:rule.processName.trim(),nodeName:rule.nodeName.trim(),productLine:rule.productLine.trim(),templateId:rule.templateId.trim()}; + if(!['category_template','product_line','order'].includes(value.batchMode))throw new OrderWorkflowError('RULE_INVALID','批次模式无效。'); + this.store?.putRule?.(value);this.ruleMap.set(value.id,value);return clone(value); } - getBatch(id){const batch=this.batches.get(id);return batch?clone(batch):null;} - listBatches(){return [...this.batches.values()].map(clone);} - markBatchUnknown(id,message){const batch=this.batches.get(id);if(!batch)throw new OrderWorkflowError('BATCH_NOT_FOUND','批次不存在。');batch.status='unknown';batch.error=String(message);this.persistBatch(batch);return clone(batch);} + checkRule(id,{arrival,detail,provenance}){ + const rule=this.getRule(id);if(!rule)throw new OrderWorkflowError('RULE_NOT_FOUND','分类规则不存在。');if(provenance!=='bpm-readonly'||detail?.readOnly===false)throw new OrderWorkflowError('DETAIL_PROVENANCE','只能使用服务器只读采集的 BPM 样本。'); + rule.check=null;this.store?.putRule?.(rule);this.ruleMap.set(id,rule); + try{const preview=new OrderWorkflow({clock:this.clock});preview.identify({arrival,detail,rule:{...rule,enabled:true},mapping:rule.adapters[String(detail.processVersion)]});} + catch(error){return {valid:false,issues:[{code:error.code||'SAMPLE_INVALID',message:error.message}],sample:{processName:arrival.processName,nodeName:detail.nodeName,processVersion:detail.processVersion,fields:clone(detail.fields),tid:detail.tid,pid:detail.pid}};} + const check={checkId:crypto.randomUUID(),version:rule.version,checkedAt:this.clock().toISOString(),evidenceHash:hash(JSON.stringify({arrival,detail}))};rule.check=check;this.store?.putRule?.(rule);this.ruleMap.set(id,rule);return {valid:true,issues:[],...check,sample:{processName:arrival.processName,nodeName:detail.nodeName,processVersion:detail.processVersion,fields:clone(detail.fields),tid:detail.tid,pid:detail.pid}}; + } + publishRule(id,{version,checkId}){ + const rule=this.getRule(id);if(!rule||rule.version!==version||rule.check?.version!==version||!checkId||rule.check?.checkId!==checkId)throw new OrderWorkflowError('RULE_CHECK_REQUIRED','必须对当前版本执行真实只读样本检查后发布。'); + if(rule.enabled&&[...this.ruleMap.values()].some(old=>old.id!==id&&old.status==='published'&&old.enabled&&old.processName===rule.processName&&old.nodeName===rule.nodeName))throw new OrderWorkflowError('RULE_CONFLICT','同一流程和节点已有发布规则。'); + rule.status='published';rule.publishedAt=this.clock().toISOString();this.store?.putRule?.(rule);this.ruleMap.set(id,rule);return clone(rule); + } + invalidateCheck(id){const rule=this.getRule(id);if(!rule)throw new OrderWorkflowError('RULE_NOT_FOUND','分类规则不存在。');rule.check=null;this.store?.putRule?.(rule);this.ruleMap.set(id,rule);} + getRule(id){const rule=this.ruleMap.get(id);return rule?clone(rule):null;}rules(){return [...this.ruleMap.values()].map(clone);} + resolveRule(arrival,detail){ + const node=text(arrival?.activityName||detail?.nodeName);if(arrival?.activityName&&detail?.nodeName&&arrival.activityName!==detail.nodeName)throw new OrderWorkflowError('NODE_CONFLICT','列表当前节点与详情节点不一致。'); + const candidates=[...this.ruleMap.values()].filter(rule=>rule.enabled===true&&rule.status==='published'&&rule.processName===arrival?.processName&&rule.nodeName===node);if(candidates.length!==1)throw new OrderWorkflowError(candidates.length?'RULE_CONFLICT':'RULE_UNMATCHED',candidates.length?'流程和节点命中多个分类规则。':'流程和节点没有命中已发布分类规则。'); + const rule=candidates[0],mapping=rule.adapters?.[String(detail?.processVersion||'')];if(!mapping)throw new OrderWorkflowError('ADAPTER_MISSING','当前表单版本没有字段适配器:'+String(detail?.processVersion||''));return {rule,mapping}; + } + identify(input){ + let {arrival,detail,mapping,rule}=input||{};if(!arrival?.source||!present(arrival.taskId))throw new OrderWorkflowError('SOURCE_ID_MISSING','缺少 BPM 来源和任务号。');if(!detail||typeof detail.fields!=='object'||Array.isArray(detail.fields))throw new OrderWorkflowError('DETAIL_MISSING','缺少订单详情字段。'); + if(!rule){const resolved=this.resolveRule(arrival,detail);rule=resolved.rule;mapping=resolved.mapping;}else if(!mapping&&rule.adapters?.[String(detail.processVersion||'')])mapping=rule.adapters[String(detail.processVersion)];if(!mapping)throw new OrderWorkflowError('ADAPTER_MISSING','当前表单版本没有字段适配器。');exactRule(arrival,detail,rule); + const mappedVersion=mapping.businessVersion?readCandidate({arrival,detail},mapping.businessVersion,'业务版本'):null; + const businessVersion=mappedVersion?.value??detail.businessVersion; + if(!present(detail.tid)||!present(detail.pid)||!present(businessVersion)||![detail.tid,detail.pid,businessVersion].every(value=>['string','number'].includes(typeof value)))throw new OrderWorkflowError('VERSION_MISSING','缺少 tid、pid 或明确的业务版本标识。');if(!present(detail.processVersion))throw new OrderWorkflowError('FORM_VERSION_MISSING','缺少表单版本。'); + const source={arrival,detail},orderNo=readCandidate(source,mapping.orderNo,'订单号'),serialNo=readCandidate(source,mapping.serialNo,'流水号'),productCode=readCandidate(source,mapping.productCode,'产品编号'),modelFull=readCandidate(source,mapping.modelFull,'完整型号'),modelShort=readCandidate(source,mapping.modelShort,'短型号'),customer=readCandidate(source,mapping.customer,'客户'),brief=readCandidate(source,mapping.brief,'简要说明'); + if(!present(rule.productLine))throw new OrderWorkflowError('RULE_INVALID','分类规则必须指定产品线。'); + const productLine={path:'rule.productLine',value:rule.productLine},version=String(businessVersion),currentOrderNo=text(orderNo.value),tid=String(detail.tid),pid=String(detail.pid),versionKey=hash(JSON.stringify([tid,pid,currentOrderNo,version])); + const businessTime=detail.businessTime||arrival.arrivedAt||arrival.receivedAt||null,businessTimeSource=detail.businessTime?'detail.businessTime':businessTime?'list.receivedAt':null;if(!businessTime)throw new OrderWorkflowError('BUSINESS_TIME_MISSING','缺少业务时间和列表收到时间。');const now=this.clock().toISOString(); + const order={id:hash([arrival.source,currentOrderNo].join('\0')),versionKey,version,businessVersion:version,tid,pid,orderNo:currentOrderNo,source:arrival.source,taskId:String(arrival.taskId),processName:arrival.processName,processVersion:String(detail.processVersion),nodeName:detail.nodeName||arrival.activityName||'',serialNo:text(serialNo.value),productCode:text(productCode.value),modelFull:text(modelFull.value),modelShort:text(modelShort.value),customer:text(customer.value),productLine:productLine.value,brief:String(brief.value),subject:String(detail.subject||arrival.subject||''),businessTime,businessTimeSource,sourceRevision:detail.sourceRevision||version,sources:{orderNo,serialNo,productCode,modelFull,modelShort,customer,brief,productLine},ruleId:rule.id,templateId:rule.templateId||null,status:'identified',steps:{discovery:{status:'success',source:'bpm-readonly'},detail:{status:'pending'},pdf:{status:'pending'},archive:{status:'pending'},notification:{status:'pending'}},createdAt:now,updatedAt:now}; + order.ruleSnapshot=clone(rule);order.detailSnapshot=clone(detail);order.arrival=clone(arrival);order.sources.businessVersion=mappedVersion||{path:'detail.businessVersion',value:version}; + const existing=this.orders.get(versionKey);if(existing){if(existing.ruleId!==order.ruleId||existing.brief!==order.brief||JSON.stringify(existing.sources)!==JSON.stringify(order.sources)||JSON.stringify(existing.detailSnapshot?.fields)!==JSON.stringify(detail.fields))throw new OrderWorkflowError('VERSION_CONTENT_CONFLICT','同一订单版本的分类或字段证据已变化,请人工确认业务版本。');return {status:'duplicate',order:clone(existing)};}this.persistOrder(order);this.orders.set(versionKey,order);return {status:'matched',order:clone(order)}; + } + get(versionKey){const order=this.orders.get(versionKey);return order?clone(order):null;}listOrders(){return [...this.orders.values()].map(clone);} + update(versionKey,work){const saved=this.orders.get(versionKey);if(!saved)throw new OrderWorkflowError('ORDER_NOT_FOUND','订单版本不存在。');const order=clone(saved);order.steps||={};work(order);order.updatedAt=this.clock().toISOString();this.persistOrder(order);this.orders.set(versionKey,order);return clone(order);} + start(versionKey){return this.update(versionKey,order=>{if(!['identified','detail_error','pdf_error','archive_error','interrupted'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前订单不能开始处理。');if(order.steps.pdf?.status==='success'){order.status='pdf_success';return;}if(order.steps.detail?.status==='success'){order.status='detail_ready';return;}order.status='detail_capturing';order.steps.detail={status:'running',startedAt:this.clock().toISOString()};});} + markDetailReady(versionKey,detailEvidence={}){return this.update(versionKey,order=>{if(!['detail_capturing','detail_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','详情尚未处于采集状态。');order.detailEvidence=clone(detailEvidence);order.steps.detail={status:'success',...clone(detailEvidence)};order.status='detail_ready';});} + beginPdf(versionKey){return this.update(versionKey,order=>{if(!['detail_ready','pdf_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能生成 PDF。');order.status='pdf_pending';order.steps.pdf={status:'running',startedAt:this.clock().toISOString()};});} + beginArchive(versionKey){return this.update(versionKey,order=>{if(order.steps.pdf?.status!=='success'||!['pdf_success','archive_error'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能归档。');order.status='archive_pending';order.steps.archive={status:'running',startedAt:this.clock().toISOString()};});} + markPdfSuccess(versionKey,pdf){return this.update(versionKey,order=>{if(!['detail_ready','pdf_error','pdf_pending'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','详情未准备好,不能记录 PDF。');if(!pdf?.jobId)throw new OrderWorkflowError('PDF_EVIDENCE_MISSING','缺少 PDF 任务证据。');order.pdf=clone(pdf);order.steps.pdf={status:'success',...clone(pdf)};order.status='pdf_success';});} + markPdfError(versionKey,message){return this.update(versionKey,order=>{if(!['detail_ready','pdf_pending','detail_capturing'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能记录 PDF 失败。');order.error=String(message);order.steps.pdf={status:'error',error:String(message)};order.status='pdf_error';});} + markArchiveSuccess(versionKey,archive){return this.update(versionKey,order=>{if(!['pdf_success','archive_error','archive_pending'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','PDF 未成功,不能记录归档。');if(!archive?.archiveId)throw new OrderWorkflowError('ARCHIVE_EVIDENCE_MISSING','缺少 SMB 归档回执。');order.archive=clone(archive);order.steps.archive={status:'success',...clone(archive)};order.status='archived';});} + markArchiveError(versionKey,message){return this.update(versionKey,order=>{if(!['pdf_success','archive_pending'].includes(order.status))throw new OrderWorkflowError('INVALID_STATE','当前状态不能记录归档失败。');order.error=String(message);order.steps.archive={status:'error',error:String(message)};order.status='archive_error';});} + createNotification(versionKey,input){return this.update(versionKey,order=>{if(order.status!=='archived')throw new OrderWorkflowError('ARCHIVE_REQUIRED','归档未成功,不能创建通知事件。');const data=input||{productLine:order.productLine,templateId:order.templateId,brief:order.brief,subject:order.subject,occurredAt:order.businessTime};data.templateId||=order.templateId;for(const key of ['productLine','templateId','brief','subject','occurredAt'])if(!present(data[key]))throw new OrderWorkflowError('NOTIFICATION_FIELD_MISSING','通知字段未确认:'+key);order.notification={...clone(data),orderVersionKey:versionKey,createdAt:this.clock().toISOString(),status:'pending'};order.steps.notification={status:'pending'};order.status='notification_pending';});} + freezeBatches(cutoff,{mode='product_line',groups={},templates={}}={}){ + if(!Number.isFinite(Date.parse(cutoff)))throw new OrderWorkflowError('WINDOW_INVALID','发送窗口无效。'); + const candidates=[...this.orders.values()].filter(order=>['notification_pending','blocked'].includes(order.status)&&['pending','blocked'].includes(order.notification?.status)&&Date.parse(order.notification.occurredAt)<=Date.parse(cutoff)).map(clone),grouped=new Map(); + const block=(order,message)=>{order.notification.status='blocked';order.notification.error=message;order.steps.notification={status:'blocked',error:message};order.status='blocked';}; + for(const order of candidates){ + const notification=order.notification,productLine=order.productLine,templateId=order.templateId,rule=order.ruleSnapshot||{}; + const group=groups[rule.recipientGroupId||productLine]; + if(!Array.isArray(group?.to)||!group.to.length){block(order,'分类规则没有已确认的收件组。');continue;} + const template=templates[templateId];if(!template){block(order,'分类规则绑定的邮件模板未加载。');continue;} + const key=JSON.stringify([order.ruleId,rule.version,productLine,templateId,rule.batchMode==='order'||mode==='order'?order.versionKey:'',group.to,group.cc||[]]); + if(!grouped.has(key))grouped.set(key,{ruleId:order.ruleId,productLine,templateId,group,template,orders:[]});grouped.get(key).orders.push(order); + } + const batches=[]; + for(const selected of grouped.values()){ + const orders=selected.orders,date=[...new Set(orders.map(order=>dateOnly(order.businessTime)))].join('、');let rendered; + try{rendered=renderOrderTemplate(selected.template,{productLine:selected.productLine,orders,date});}catch(error){orders.forEach(order=>block(order,error.message));continue;} + const batch={id:crypto.randomUUID(),status:'prepared',cutoff,mode,ruleId:selected.ruleId,productLine:selected.productLine,templateId:selected.templateId,templateVersion:rendered.templateVersion,templateSnapshot:{id:selected.template.id,version:selected.template.version,subject:selected.template.subject,text:selected.template.text,html:selected.template.html},to:[...selected.group.to],cc:[...(selected.group.cc||[])],orderVersionKeys:orders.map(order=>order.versionKey),subject:rendered.subject,text:rendered.text,html:rendered.html,attachments:[],attempts:0,createdAt:this.clock().toISOString()}; + for(const order of orders){order.notification.status='reserved';order.notification.batchId=batch.id;delete order.notification.error;order.steps.notification={status:'batched',batchId:batch.id};order.status='batched';}batches.push(batch); + } + this.saveGraph(candidates,batches); + if(!batches.length)throw new OrderWorkflowError('EMPTY_BATCH','当前发送窗口没有待发通知。');return batches.map(clone); + } + saveGraph(orders,batches){if(this.store?.putGraph)this.store.putGraph(orders,batches);else {orders.forEach(order=>this.persistOrder(order));batches.forEach(batch=>this.persistBatch(batch));}orders.forEach(order=>this.orders.set(order.versionKey,order));batches.forEach(batch=>this.batches.set(batch.id,batch));} + freezeBatch(cutoff,options={}){return this.freezeBatches(cutoff,options)[0];} + getBatch(id){const batch=this.batches.get(id);return batch?clone(batch):null;}listBatches(){return [...this.batches.values()].map(clone);} + markBatchSending(id){return this.updateBatch(id,'sending');}markBatchSent(id){return this.updateBatch(id,'sent');}markBatchFailed(id,message){return this.updateBatch(id,'failed',message);} + updateBatch(id,status,error=null){const saved=this.batches.get(id);if(!saved)throw new OrderWorkflowError('BATCH_NOT_FOUND','批次不存在。');const allowed={prepared:['sending','failed'],sending:['sent','unknown'],failed:['sending','failed'],unknown:[]};if(!allowed[saved.status]?.includes(status))throw new OrderWorkflowError('INVALID_BATCH_STATE','当前批次不能执行此操作。');const batch={...clone(saved),status,error,updatedAt:this.clock().toISOString()};if(status==='sending'||status==='failed')batch.attempts=(batch.attempts||0)+1;const orders=batch.orderVersionKeys.map(key=>this.get(key)).filter(Boolean);for(const order of orders){order.status=status==='failed'?'batched':status;order.notification.status=status;order.steps.notification={status,batchId:id,...(error?{error}:{})};}this.saveGraph(orders,[batch]);return clone(batch);} + markBatchUnknown(id,message){return this.updateBatch(id,'unknown',String(message));} + resolveBatch(id,{resolution,note},actor){const saved=this.getBatch(id);if(!saved||!['unknown','failed'].includes(saved.status))throw new OrderWorkflowError('RESOLUTION_INVALID','只能核验结果不明或明确失败的批次。');if(!['sent','retry'].includes(resolution)||typeof note!=='string'||note.trim().length<5)throw new OrderWorkflowError('RESOLUTION_INVALID','请填写至少 5 字的核验依据。');const batch={...saved,status:resolution==='sent'?'sent':'prepared',resolution,verification:{actor,note:note.trim(),at:this.clock().toISOString()}};if(resolution==='retry')batch.attempts=0;const orders=batch.orderVersionKeys.map(key=>this.get(key)).filter(Boolean);for(const order of orders){order.status=resolution==='sent'?'sent':'batched';order.notification.status=resolution==='sent'?'sent':'reserved';order.steps.notification={status:order.status,batchId:id};}this.saveGraph(orders,[batch]);return clone(batch);} canAutoRetry(id){const batch=this.batches.get(id);return !!batch&&batch.status==='failed';} } -module.exports={OrderWorkflow,OrderWorkflowError}; +module.exports={OrderWorkflow,OrderWorkflowError,readCandidate}; diff --git a/src/server.cjs b/src/server.cjs index 24e5d3d..6252f86 100644 --- a/src/server.cjs +++ b/src/server.cjs @@ -23,6 +23,7 @@ const { StorageService } = require('./storage-service.cjs'); const { NotificationStore, NotificationService } = require('./notifications.cjs'); const { OrderWorkflowStore } = require('./order-workflow-store.cjs'); const { OrderWorkflow } = require('./order-workflow.cjs'); +const { OrderPipeline } = require('./order-pipeline.cjs'); function createServer(options) { let busy = false; @@ -118,7 +119,7 @@ async function main(options = {}) { const custodian=new BpmCustodian({workspace,manager:bpmSessions}); let server; let dashboard; - let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,workflowStore,workflow,assistantStore,assistant,health; + let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,workflowStore,workflow,pipeline,assistantStore,assistant,health; try { mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore}); mailStore.migrateLegacy(store.settings().templates); @@ -126,16 +127,18 @@ async function main(options = {}) { storageStore=new StorageStore(path.join(stateDir,'storage'));storage=new StorageService({store:storageStore,jobs:store,outputDir}); notificationStore=new NotificationStore(path.join(stateDir,'notifications'));notifications=new NotificationService({store:notificationStore,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides}); workflowStore=new OrderWorkflowStore(path.join(stateDir,'order-workflow'));workflow=new OrderWorkflow({store:workflowStore,schedule:store.settings().schedule}); + pipeline=new OrderPipeline({workflow,store:workflowStore,scanStore,workspace,manager:bpmSessions,jobs:store,storage,mail,notifications,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides,outputDir}); assistantStore=new AssistantStore(path.join(stateDir,'assistant'));assistantStore.recover();assistant=new AssistantService({store:assistantStore,runtime:new ZcodeRuntime({stateDir:path.join(stateDir,'assistant','runtime')}),dashboard:store,workspace,scanner,storage}); health=new RuntimeHealth({stateDir,startedAt,instanceId:watchdog.instanceId,workspace,scanner,storage,mail}); await bpmSessions.migrateAccounts(workspace.snapshot().connections); workspace.markSessionChecksPending(); server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage,watchdog}); - dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,storage,notifications,workflow,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true}); + dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,storage,notifications,workflow,pipeline,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true}); await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();scanner.start();notifications.start(); health.start(); + pipeline.start(); } - catch(error){health?.close();if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await assistant?.stop();assistantStore?.close();await notifications?.stop();notificationStore?.close();workflowStore?.close();await storage?.stop();storageStore?.close();await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;} + catch(error){health?.close();if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await pipeline?.stop();await assistant?.stop();assistantStore?.close();await notifications?.stop();notificationStore?.close();workflowStore?.close();await storage?.stop();storageStore?.close();await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;} if(!options.quiet){ console.log('订单通知中心已启动。\nWeb 工作台支持业务日历、异常待办与转交、BPM 连接管理。\n在 Chrome 订单页仍可点击扩展中的“导出当前订单”。'); console.log(`首次使用:Chrome 扩展管理 → 开发者模式 → 加载已解压的扩展程序\n选择目录:${installedExtension}\n输出目录:${outputDir}\n本地服务:http://127.0.0.1:${port}`); @@ -145,6 +148,7 @@ async function main(options = {}) { let stopping; const stop=()=>stopping ||= (async()=>{ health.close(); + await pipeline.stop(); await assistant.stop();await notifications.stop();await storage.stop();await scanner.stop();await mail.stop();await custodian.stop();await bpmSessions.shutdown(); await Promise.all([dashboard,server].map(socket=>new Promise((resolve,reject)=>socket.close(error=>error?reject(error):resolve())))); workspace.close(); @@ -155,7 +159,7 @@ async function main(options = {}) { workflowStore.close(); assistantStore.close(); })(); - return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,workflow,assistant,health,stop}; + return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,workflow,pipeline,assistant,health,stop}; } if (require.main === module) main().then(app=>{ const stop=()=>app.stop().then(()=>process.exit(0),()=>process.exit(1)); diff --git a/src/windows-shortcut.cs b/src/windows-shortcut.cs new file mode 100644 index 0000000..1745b1a --- /dev/null +++ b/src/windows-shortcut.cs @@ -0,0 +1,57 @@ +using System; +using System.Text; +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.ComTypes; + +// WScript.Shell's shortcut wrapper truncates non-ANSI paths on some Windows +// installations. IShellLinkW and IPersistFile retain UTF-16 paths end to end. +[ComImport, Guid("00021401-0000-0000-C000-000000000046")] +internal class OrderShellLink { } + +[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")] +internal interface IOrderShellLinkW { + void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int length, IntPtr findData, uint flags); + void GetIDList(out IntPtr list); + void SetIDList(IntPtr list); + void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder description, int length); + void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string description); + void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder directory, int length); + void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string directory); + void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder arguments, int length); + void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string arguments); + void GetHotkey(out short hotkey); + void SetHotkey(short hotkey); + void GetShowCmd(out int command); + void SetShowCmd(int command); + void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int length, out int index); + void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string path, int index); + void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string path, uint reserved); + void Resolve(IntPtr window, uint flags); + void SetPath([MarshalAs(UnmanagedType.LPWStr)] string path); +} + +public static class OrderShortcut { + public static void Save(string file, string target, string arguments, string directory) { + object instance = new OrderShellLink(); + try { + var link = (IOrderShellLinkW)instance; + link.SetPath(target); + link.SetArguments(arguments); + link.SetWorkingDirectory(directory); + link.SetDescription("Order workspace service supervisor"); + ((IPersistFile)instance).Save(file, true); + } finally { Marshal.FinalReleaseComObject(instance); } + } + public static string[] Read(string file) { + object instance = new OrderShellLink(); + try { + ((IPersistFile)instance).Load(file, 0); + var link = (IOrderShellLinkW)instance; + var target = new StringBuilder(32768); + var arguments = new StringBuilder(32768); + link.GetPath(target, target.Capacity, IntPtr.Zero, 4); + link.GetArguments(arguments, arguments.Capacity); + return new string[] { target.ToString(), arguments.ToString() }; + } finally { Marshal.FinalReleaseComObject(instance); } + } +} diff --git a/src/windows-startup.cjs b/src/windows-startup.cjs index a44bad1..fd3b97f 100644 --- a/src/windows-startup.cjs +++ b/src/windows-startup.cjs @@ -1,15 +1,19 @@ 'use strict'; const fs=require('node:fs'),path=require('node:path'),{execFileSync}=require('node:child_process'),{SupervisorStore}=require('./supervisor-store.cjs'); -function powershell(script,data){return execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command','$ErrorActionPreference="Stop"; [Console]::InputEncoding=New-Object System.Text.UTF8Encoding; [Console]::OutputEncoding=New-Object System.Text.UTF8Encoding; '+script],{input:JSON.stringify(data),encoding:'utf8',windowsHide:true,timeout:15000,stdio:['pipe','pipe','pipe']}).trim();} +function powershell(script,data){ + const source=fs.readFileSync(path.join(__dirname,'windows-shortcut.cs'),'utf8'); + const prefix="$ErrorActionPreference=\"Stop\"; [Console]::InputEncoding=New-Object System.Text.UTF8Encoding; [Console]::OutputEncoding=New-Object System.Text.UTF8Encoding; Add-Type -TypeDefinition @'\n"+source+"\n'@\n"; + return execFileSync('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-Command',prefix+script],{input:JSON.stringify(data),encoding:'utf8',windowsHide:true,timeout:15000,stdio:['pipe','pipe','pipe']}).trim(); +} function locations({stateDir,startupDir}){ if(process.platform!=='win32')throw Error('登录自启动仅支持 Windows。'); const root=path.resolve(startupDir||path.join(process.env.APPDATA,'Microsoft','Windows','Start Menu','Programs','Startup')); return {linkPath:path.join(root,'OrderNotificationAutomation.lnk'),launcherPath:path.join(path.resolve(stateDir),'supervisor','logon-launch.vbs'),wscript:path.join(process.env.SystemRoot,'System32','wscript.exe')}; } -function readShortcut(file){const raw=powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; $s=(New-Object -ComObject WScript.Shell).CreateShortcut($d.file); @{target=$s.TargetPath;args=$s.Arguments}|ConvertTo-Json -Compress',{file});return JSON.parse(raw);} +function readShortcut(file){const raw=powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; $s=[OrderShortcut]::Read($d.file); @{target=$s[0];args=$s[1]}|ConvertTo-Json -Compress',{file});return JSON.parse(raw);} function ownedShortcut(paths){if(!fs.existsSync(paths.linkPath))return true;const old=readShortcut(paths.linkPath);return path.resolve(old.target).toLowerCase()===path.resolve(paths.wscript).toLowerCase()&&old.args==='//B "'+paths.launcherPath+'"';} function removeFile(file){try{fs.unlinkSync(file);}catch(e){if(e.code!=='ENOENT')throw e;}if(fs.existsSync(file))throw Error('无法确认自启动文件已移除。');} -function writeShortcut({paths,projectRoot}){powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; $s=(New-Object -ComObject WScript.Shell).CreateShortcut($d.link); $s.TargetPath=$d.target; $s.Arguments=$d.args; $s.WorkingDirectory=$d.cwd; $s.Description="Order workspace service supervisor"; $s.Save()',{link:paths.linkPath,target:paths.wscript,args:'//B "'+paths.launcherPath+'"',cwd:path.resolve(projectRoot)});} +function writeShortcut({paths,projectRoot}){powershell('$d=[Console]::In.ReadToEnd()|ConvertFrom-Json; [OrderShortcut]::Save($d.link,$d.target,$d.args,$d.cwd)',{link:paths.linkPath,target:paths.wscript,args:'//B "'+paths.launcherPath+'"',cwd:path.resolve(projectRoot)});} function installAutostart({stateDir,projectRoot=path.resolve(__dirname,'..'),nodePath=process.execPath,startupDir,shortcutWriter=writeShortcut}={}){ const paths=locations({stateDir,startupDir}),store=new SupervisorStore(stateDir); try{ diff --git a/tests/bpm-detail-readonly.test.cjs b/tests/bpm-detail-readonly.test.cjs new file mode 100644 index 0000000..6dceb87 --- /dev/null +++ b/tests/bpm-detail-readonly.test.cjs @@ -0,0 +1,26 @@ +'use strict'; +const test=require('node:test');const assert=require('node:assert/strict'); +const {loadPlaywright,browserOptions}=require('../src/runtime.cjs'); +const {readDetailDocument,allowDetailRequest,parseDetailUrl,captureDetail}=require('../src/bpm-order-detail.cjs'); +test('BPM detail request policy blocks actions, uploads, redirects and other hosts',()=>{ + const url='https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/海外运营订单评审V13.aspx?tid=1&pid=2'; + assert.equal(allowDetailRequest(url,'GET',url,true),true); + assert.equal(allowDetailRequest(url,'POST',url,true),false); + assert.equal(allowDetailRequest('https://bpm.skyworthdigital.com/ASHX/Approve.ashx?method=read','GET',url,false),false); + assert.equal(allowDetailRequest('https://evil.example/x.js','GET',url,false),false); + assert.equal(allowDetailRequest(url+'&action=approve','GET',url,true),false); + assert.throws(()=>parseDetailUrl(url+'&tid=3')); +}); +test('capture waits for a visible binding even when the first bound field is hidden',async t=>{ + const http=require('node:http'),server=http.createServer((req,res)=>{res.setHeader('Content-Type','text/html; charset=utf-8');res.end('000123节点状态N处理中');});await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve));t.after(()=>new Promise(resolve=>server.close(resolve))); + const browserFactory=async()=>{const browser=await loadPlaywright().chromium.launch(browserOptions());return {close:()=>browser.close(),newContext:async options=>{const context=await browser.newContext(options),route=context.route.bind(context);context.route=async(pattern,handler)=>route(pattern,request=>handler({request:()=>request.request(),fetch:options=>request.fetch({...options,url:'http://127.0.0.1:'+server.address().port}),fulfill:options=>request.fulfill(options),abort:()=>request.abort()}));return context;}};}; + const result=await captureDetail({storageState:{cookies:[],origins:[]},detailUrl:'https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/PV1.aspx?tid=1&pid=2',processName:'P',nodeName:'N',browserFactory,timeout:1500}); + assert.equal(result.detail.fields['OFR_WY_Applicant.OrderNum'],'000123');assert.equal(result.detail.tid,'1');assert.equal(result.detail.readOnly,true);assert.equal(result.detail.businessVersion,undefined);assert.match(result.evidenceHash,/^[a-f0-9]{64}$/); +}); +test('read-only DOM extraction uses visible explicit xdatabind spans and never hidden originals',async t=>{ + const browser=await loadPlaywright().chromium.launch(browserOptions());t.after(()=>browser.close());const page=await browser.newPage(); + await page.setContent(`000123A\nB节点状态订单专员(生效)处理中审批`); + const data=await page.evaluate(readDetailDocument); + assert.equal(data.elements.find(x=>x.binding==='OFR_WY_Applicant.OrderNum').value,'000123');assert.equal(data.elements.some(x=>x.binding==='secret'),false); + assert.equal(data.processSteps[0].name,'订单专员(生效)');assert.equal(data.processSteps[0].status,'处理中');assert.doesNotMatch(data.snapshot.html,/NEVER|999999|onclick|{ + assert.deepEqual(parseDetailUrl(url),{tid:'100001',pid:'900001',processVersion:'V13',processName:'海外运营订单评审'}); + assert.throws(()=>parseDetailUrl('https://evil.example/form.aspx?tid=1&pid=2'),/不受支持/); + assert.throws(()=>parseDetailUrl(url.replace('tid=100001','tid=abc')),/tid\/pid/); +}); +test('field snapshot reads explicit DOM binding names and preserves process steps read-only',()=>{ + const result=extractFieldSnapshot({elements:[ + {binding:'OFR_WY_Applicant.OrderNum',value:'000123',disabled:false}, + {binding:'OFR_WY_BInfo.ProductModel',value:'MODEL-EXAMPLE-002',disabled:false}, + {binding:'OFR_WY_BInfo.CustomerName',value:'CUSTOMER-EXAMPLE',disabled:true}, + {binding:'OFR_WY_Applicant.OrderChangeContent',value:'摘要原文',disabled:false}, + ],processSteps:[{name:'订单专员(生效)',status:'处理中',at:null}],processName:'海外运营订单评审',nodeName:'订单专员(生效)',processVersion:'V13',processInstanceId:'900001'}); + assert.equal(result.fields['OFR_WY_Applicant.OrderNum'],'000123');assert.equal(result.fields['OFR_WY_BInfo.CustomerName'],'CUSTOMER-EXAMPLE');assert.equal(result.processSteps[0].status,'处理中');assert.equal(result.readOnly,true); +}); +test('missing process instance or bound fields is explicit',()=>{ + assert.throws(()=>extractFieldSnapshot({elements:[],processSteps:[],processName:'海外运营订单评审',nodeName:'订单专员(生效)',processVersion:'V13'}),/流程实例|字段/); +}); diff --git a/tests/bpm-runtime.test.cjs b/tests/bpm-runtime.test.cjs index 1c91133..ee5f342 100644 --- a/tests/bpm-runtime.test.cjs +++ b/tests/bpm-runtime.test.cjs @@ -15,6 +15,9 @@ test('formal runtime wires BPM sessions and preserves users across restart',asyn t.after(async()=>{if(app)await app.stop();fs.rmSync(stateDir,{recursive:true,force:true});}); const config={port:await freePort(),dashboard:{host:'127.0.0.1',port:await freePort()}}; app=await main({stateDir,config,quiet:true}); + assert.ok(app.pipeline,'runtime must wire the guarded order pipeline'); + assert.equal(app.pipeline.config().enabled,false); + assert.equal(app.pipeline.config().sendEnabled,false); const base=`http://127.0.0.1:${config.dashboard.port}`; const post=(route,body,cookie)=>fetch(base+route,{method:'POST',headers:{Origin:base,'Content-Type':'application/json',...(cookie?{Cookie:cookie}:{})},body:JSON.stringify(body)}); const bootstrap=await post('/api/bootstrap',{username:'runtime-admin',password:'Runtime-test-password-123'}); diff --git a/tests/bpm-scan.test.cjs b/tests/bpm-scan.test.cjs index 5f7d6c1..c5268da 100644 --- a/tests/bpm-scan.test.cjs +++ b/tests/bpm-scan.test.cjs @@ -4,6 +4,11 @@ const {BpmScanStore}=require('../src/bpm-scan-store.cjs'); const {BpmScanner}=require('../src/bpm-scanner.cjs'); const {BpmSessionManager}=require('../src/bpm-session-manager.cjs'); const row=(id,date='2026-10-15T16:33:58')=>({taskId:id,serialNum:'SN-'+id,processName:'订单评审',activityName:'知会',startTime:date,processInstanceSubject:'订单号:123 & 456',processInstanceInitiatorShortName:'甲'}); +test('list summary preserves raw line breaks and explicit detail references only',()=>{ + const value=normalizeArrival({...row('line'),processInstanceSubject:' 第一行\r\n第二行第三行 ',detailUrl:'https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/PV1.aspx?tid=1&pid=2'},'portal-v4'); + assert.equal(value.subject,' 第一行\r\n第二行\n第三行 ');assert.match(value.detailUrl,/tid=1&pid=2/); + assert.equal(normalizeArrival({...row('no-ref'),pid:'2'},'portal-v4').detailUrl,undefined); +}); test('arrival uses received time in Shanghai, strips HTML, never substitutes scan time',()=>{ const a=normalizeArrival(row('1'),'portal-v4');assert.equal(a.arrivalDay,'2026-10-15');assert.equal(a.arrivedAt,'2026-10-15T08:33:58.000Z');assert.equal(a.subject,'订单号:123 & 456'); assert.equal(normalizeArrival(row('2','2026-10-15T18:30:00Z'),'portal-v8').arrivalDay,'2026-10-16'); diff --git a/tests/order-notification-bridge.test.cjs b/tests/order-notification-bridge.test.cjs new file mode 100644 index 0000000..77fcf3b --- /dev/null +++ b/tests/order-notification-bridge.test.cjs @@ -0,0 +1,10 @@ +'use strict'; +const test=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path'); +const {NotificationStore,NotificationService}=require('../src/notifications.cjs'); +test('order bridge rejects unarchived evidence and generic dispatcher cannot pick up order managed events',t=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-bridge-')),store=new NotificationStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});const service=new NotificationService({store,mail:{},settings:()=>({groups:[]})}); + const order={versionKey:'order-v1',businessVersion:'v1',orderNo:'000123',source:'portal-v4',taskId:'t',productLine:'L',brief:'原文\n第二行',subject:'原文\n第二行',businessTime:'2026-10-22T01:00:00Z',ruleId:'r',templateId:'tpl',steps:{archive:{status:'error'}}}; + assert.throws(()=>service.ingestOrder(order));const ready={...order,archive:{archiveId:'a'},steps:{archive:{status:'success'}}}; + const first=service.ingestOrder(ready),again=service.ingestOrder(ready);assert.equal(first.id,again.id);assert.equal(store.items()[0].brief,order.brief);assert.equal(store.pending(3,['L']).length,0); + service.syncOrder({...ready,status:'unknown',notification:{status:'unknown',batchId:'b'}});assert.equal(store.items()[0].status,'unknown');assert.equal(store.items()[0].batch_id,'b'); +}); diff --git a/tests/order-pipeline-http.test.cjs b/tests/order-pipeline-http.test.cjs new file mode 100644 index 0000000..61da13c --- /dev/null +++ b/tests/order-pipeline-http.test.cjs @@ -0,0 +1,83 @@ +'use strict'; +const test=require('node:test'); +const assert=require('node:assert/strict'); +const crypto=require('node:crypto'); +const fs=require('node:fs/promises'); +const net=require('node:net'); +const os=require('node:os'); +const path=require('node:path'); +const {main}=require('../src/server.cjs'); +const {FileArea}=require('../src/storage-files.cjs'); +const {loadPlaywright,browserOptions}=require('../src/runtime.cjs'); + +async function unusedPort(){ + const server=net.createServer();await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve);}); + const port=server.address().port;await new Promise((resolve,reject)=>server.close(error=>error?reject(error):resolve()));return port; +} + +test('isolated main integrates authenticated rule publication, real PDF/local archive and order browser evidence',{timeout:120000},async t=>{ + const temporary=await fs.mkdtemp(path.join(os.tmpdir(),'order-pipeline-http-')); + let app,browser;const smtp={verified:0,sent:0},captured=[]; + t.after(async()=>{ + await browser?.close(); + app?.dashboard.closeAllConnections();app?.server.closeAllConnections(); + await app?.stop(); + await fs.rm(temporary,{recursive:true,force:true}); + }); + const bridgePort=await unusedPort();let dashboardPort=await unusedPort();while(dashboardPort===bridgePort)dashboardPort=await unusedPort(); + app=await main({stateDir:path.join(temporary,'state'),quiet:true,config:{port:bridgePort,outputDir:path.join(temporary,'pdf'),dashboard:{port:dashboardPort,host:'127.0.0.1'}}}); + const base='http://127.0.0.1:'+dashboardPort,password='Isolated-http-password-123'; + const call=async(route,body,cookie)=>{ + const response=await fetch(base+route,{method:body===undefined?'GET':'POST',headers:{...(body===undefined?{}:{Origin:base,'Content-Type':'application/json'}),...(cookie?{Cookie:cookie}:{})},body:body===undefined?undefined:JSON.stringify(body)}); + const text=await response.text();let data;try{data=JSON.parse(text);}catch{data={text};}return {status:response.status,data,cookie:response.headers.get('set-cookie')?.split(';')[0]}; + }; + const expect=async(route,body,cookie,status=200)=>{const result=await call(route,body,cookie);assert.equal(result.status,status,route+': '+JSON.stringify(result.data));return result;}; + assert.equal((await call('/api/order-workflow')).status,401); + const bootstrap=await expect('/api/bootstrap',{username:'admin',password},undefined,201),adminCookie=bootstrap.cookie; + await expect('/api/users',{username:'operator',password,role:'operator'},adminCookie,201); + await expect('/api/users',{username:'viewer',password,role:'viewer'},adminCookie,201); + const operatorCookie=(await expect('/api/login',{username:'operator',password})).cookie; + const viewerCookie=(await expect('/api/login',{username:'viewer',password})).cookie; + app.scanner.store.saveConfig({enabled:false,intervalMinutes:5}); + const connection=(await expect('/api/connections',{name:'HTTP 隔离 BPM 来源',owner:'operator'},adminCookie,201)).data; + const arrival={source:'portal-v4',taskId:'http-test-task-1',processName:'隔离海外订单评审',activityName:'订单专员(生效)',subject:'隔离订单简要说明第一行\n第二行保留原文',arrivedAt:'2026-10-22T01:00:00.000Z',arrivalDay:'2026-10-22',detailUrl:'https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/HttpFixtureV13.aspx?tid=900100&pid=900200'}; + app.scanner.store.complete(app.scanner.store.begin(connection.id,'隔离测试'),connection.id,[arrival]); + const storedArrival=app.scanner.store.getArrival(connection.id,arrival.source,arrival.taskId); + assert.equal(storedArrival.detailUrl,arrival.detailUrl); + const fields={'OFR_WY_Applicant.OrderNum':'000321','OFR_WY_Applicant.SN':'HTTP-SERIAL-1','OFR_WY_Applicant.Revision':'HTTP-BV-1','OFR_WY_BInfo.ProductNum':'HTTP-PRODUCT','OFR_WY_BInfo.ProductModel':'HTTP-MODEL-FULL','OFR_WY_BInfo.ProductModelNEW':'HTTP-MODEL','OFR_WY_BInfo.CustomerName':'HTTP 客户'}; + app.bpmSessions.captureOrderDetail=async(actualConnection,principal,actualArrival)=>{ + assert.equal(actualConnection.id,connection.id);assert.equal(actualArrival.taskId,arrival.taskId);assert.equal(actualArrival.detailUrl,arrival.detailUrl);assert.ok(principal.sessionId);captured.push(actualArrival.taskId); + return {detail:{readOnly:true,tid:'900100',pid:'900200',processName:arrival.processName,nodeName:arrival.activityName,processVersion:'V13',fields:structuredClone(fields),processSteps:[{name:arrival.activityName,status:'处理中'}]},capturedAt:'2026-10-22T01:01:00.000Z',evidenceHash:crypto.createHash('sha256').update(JSON.stringify(fields)).digest('hex'),snapshot:{html:'隔离测试订单订单号000321产品HTTP-PRODUCT',styles:[]}}; + }; + const localArchive=path.join(temporary,'archive');await fs.mkdir(localArchive);const area=new FileArea(localArchive); + app.storage.client.area=async()=>area; + const server=app.storage.store.saveServer({name:'HTTP 隔离本地归档',host:'archive.example.test',share:'fixture',directory:'',authMode:'windows',enabled:true}); + await app.storage.check(server.id); + const channel=app.mail.store.saveChannel({name:'HTTP 隔离发件箱',email:'sender@example.test',enabled:false,senders:['author@example.test'],smtp:{host:'smtp.example.test',port:465,security:'tls',user:'sender@example.test',password:'Synthetic-smtp-password'},imap:{host:'imap.example.test',port:993,security:'tls',user:'sender@example.test',password:'Synthetic-imap-password'}}); + app.mail.smtpFactory=()=>({async verify(){smtp.verified++;},async sendMail(){smtp.sent++;return {accepted:['2639266652@qq.com'],rejected:[]};},close(){}}); + const draft=app.mail.store.ingest(channel.id,'fixture',1,{subject:'{{产品线}} {{订单号}}',scope:'HTTP 隔离产品线',text:'{{日期}}\n{{订单列表}}',html:'{{订单列表}}',sender:'author@example.test',messageId:'',attachments:[],notes:[]},Buffer.alloc(0),channel.version); + const template=app.mail.store.confirm(draft.id,{version:draft.version,subject:'{{产品线}} {{订单号}}',scope:'HTTP 隔离产品线',useText:false},'admin'); + assert.equal(template.status,'active');assert.equal(app.mail.store.source(template.id).length,0); + const settings=(await expect('/api/settings',undefined,adminCookie)).data; + await expect('/api/settings',{version:settings.version,groups:[{productLine:'HTTP 隔离产品线',to:['2639266652@qq.com'],cc:[]}]},adminCookie); + const runtimeConfig=app.pipeline.config();await expect('/api/order-workflow/settings',{...runtimeConfig,serverId:server.id,channelId:channel.id,enabled:false,sendEnabled:false},adminCookie); + const rule={id:'http-category-rule',enabled:true,processName:arrival.processName,nodeName:arrival.activityName,productLine:'HTTP 隔离产品线',templateId:template.id,pdfTemplateId:'bpm-snapshot-v1',recipientGroupId:'HTTP 隔离产品线',notificationType:'order',batchMode:'category_template',adapters:{V13:{orderNo:'OFR_WY_Applicant.OrderNum',serialNo:'OFR_WY_Applicant.SN',businessVersion:'OFR_WY_Applicant.Revision',productCode:'OFR_WY_BInfo.ProductNum',modelFull:'OFR_WY_BInfo.ProductModel',modelShort:'OFR_WY_BInfo.ProductModelNEW',customer:'OFR_WY_BInfo.CustomerName',brief:{source:'arrival',path:'subject'}}}}; + await expect('/api/order-workflow/rules',rule,viewerCookie,403); + const saved=(await expect('/api/order-workflow/rules',rule,adminCookie)).data;assert.equal(saved.status,'draft'); + const checked=(await expect('/api/order-workflow/rules/'+rule.id+'/check',{connectionId:connection.id,source:arrival.source,taskId:arrival.taskId},adminCookie)).data;assert.equal(checked.valid,true,JSON.stringify(checked.issues));assert.equal(checked.sample.fields['OFR_WY_Applicant.OrderNum'],'000321'); + await expect('/api/order-workflow/rules/'+rule.id+'/publish',{version:saved.version,checkId:checked.checkId},operatorCookie,403); + const published=(await expect('/api/order-workflow/rules/'+rule.id+'/publish',{version:saved.version,checkId:checked.checkId},adminCookie)).data;assert.equal(published.status,'published'); + assert.equal(app.workflow.listOrders().length,0);assert.equal(app.pipeline.config().enabled,false);assert.equal(app.pipeline.config().sendEnabled,false);assert.equal(smtp.sent,0); + const order=await app.pipeline.process(storedArrival,{user:bootstrap.data.user,sessionId:'explicit-isolated-pipeline-test'}); + assert.equal(order.status,'notification_pending',JSON.stringify(order));assert.equal(order.businessVersion,'HTTP-BV-1');assert.equal(order.steps.pdf.status,'success');assert.equal(order.steps.archive.status,'success');assert.equal(order.brief,arrival.subject); + const receipt=app.storage.store.archives().find(record=>record.id===order.archive.archiveId);assert.equal(receipt.status,'success');assert.match(receipt.relativePath,/^000321\//); + const archivedBytes=await fs.readFile(path.join(localArchive,...receipt.relativePath.split('/')));assert.equal(archivedBytes.subarray(0,5).toString(),'%PDF-');assert.equal(archivedBytes.length,receipt.bytes);assert.equal(crypto.createHash('sha256').update(archivedBytes).digest('hex'),receipt.sha256);assert.equal(order.archive.sha256,receipt.sha256); + const mirror=app.notifications.store.items().find(item=>item.orderVersionKey===order.versionKey);assert.ok(mirror);assert.equal(mirror.status,'pending');assert.equal(mirror.owner,'order-workflow');assert.equal(mirror.brief,arrival.subject);assert.equal(mirror.templateId,template.id); + const before=await fs.readdir(path.join(localArchive,'000321'));await app.pipeline.process(storedArrival,{user:bootstrap.data.user,sessionId:'duplicate-isolated-test'});assert.deepEqual(await fs.readdir(path.join(localArchive,'000321')),before);assert.equal(app.workflow.listOrders().length,1);assert.equal(app.notifications.store.items().filter(item=>item.owner==='order-workflow').length,1); + assert.equal(captured.length,3);assert.equal(smtp.sent,0);assert.equal(smtp.verified,0); + browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage({viewport:{width:1280,height:900}}),pageErrors=[];page.on('pageerror',error=>pageErrors.push(error.message)); + await page.goto(base+'/#order-center');await page.getByLabel('账号',{exact:true}).fill('admin');await page.getByLabel('密码',{exact:true}).fill(password);await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('heading',{name:'订单任务',exact:true}).waitFor();await page.locator('#content tbody tr').filter({hasText:'000321'}).first().waitFor();await page.getByRole('button',{name:'查看详情',exact:true}).click();await page.getByText('detail.OFR_WY_Applicant.OrderNum',{exact:true}).waitFor();await page.getByText('list.receivedAt',{exact:false}).waitFor();assert.deepEqual(pageErrors,[]); + const viewerPage=await browser.newPage();await viewerPage.goto(base+'/#order-rules');await viewerPage.getByLabel('账号',{exact:true}).fill('viewer');await viewerPage.getByLabel('密码',{exact:true}).fill(password);await viewerPage.getByRole('button',{name:'登录',exact:true}).click();await viewerPage.getByRole('heading',{name:'分类规则',exact:true}).waitFor();assert.equal(await viewerPage.getByRole('button',{name:'新增分类规则',exact:true}).count(),0);assert.equal(await viewerPage.getByRole('button',{name:'编辑规则',exact:true}).count(),0); + const summary=(await expect('/api/order-workflow',undefined,viewerCookie)).data;assert.equal(summary.orders[0].versionKey,order.versionKey);assert.equal(summary.settings.sendEnabled,false);assert.equal(summary.batches.length,0); + assert.equal(smtp.sent,0);assert.equal(app.scanner.store.config().enabled,false); +}); diff --git a/tests/order-pipeline.test.cjs b/tests/order-pipeline.test.cjs new file mode 100644 index 0000000..5af9d3c --- /dev/null +++ b/tests/order-pipeline.test.cjs @@ -0,0 +1,71 @@ +'use strict'; +const test=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path'); +const {OrderWorkflow}=require('../src/order-workflow.cjs');const {OrderWorkflowStore}=require('../src/order-workflow-store.cjs'); +const {OrderPipeline}=require('../src/order-pipeline.cjs'); +const vault=()=>({encode:(id,value)=>Buffer.from(JSON.stringify(value)),decode:(id,value)=>JSON.parse(Buffer.from(value).toString()),destroy(){}}); +const a={connectionId:'c',source:'portal-v4',taskId:'t',processName:'P',activityName:'N',subject:'原文\n第二行',arrivedAt:'2026-10-22T01:00:00Z',detailUrl:'https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/PV1.aspx?tid=1&pid=2'}; +const d={readOnly:true,tid:'1',pid:'2',businessVersion:'revision-1',processName:'P',nodeName:'N',processVersion:'V1',fields:{no:'000123',sn:'sn',p:'p',m:'m',s:'s',c:'c'},processSteps:[{name:'N',status:'处理中'}]}; +const rule={id:'r',enabled:true,processName:'P',nodeName:'N',productLine:'Line',templateId:'tpl',recipientGroupId:'Line',adapters:{V1:{orderNo:'no',serialNo:'sn',productCode:'p',modelFull:'m',modelShort:'s',customer:'c',brief:{source:'arrival',path:'subject'}}}}; +function fixture(t,{archiveFails=false}={}){ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-pipeline-')),store=new OrderWorkflowStore(dir,{vault:vault()});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});const workflow=new OrderWorkflow({store});const saved=workflow.saveRule(rule),check=workflow.checkRule('r',{arrival:a,detail:d,provenance:'bpm-readonly'});workflow.publishRule('r',{version:saved.version,checkId:check.checkId}); + const calls={detail:0,pdf:0,archive:0,mail:0};const jobsList=[]; + const deps={workflow,store,scanStore:{getArrival:()=>structuredClone(a),recent:()=>[structuredClone(a)]},workspace:{getConnection:()=>({id:'c',status:'connected',owner:'owner'}),record(){}},manager:{captureOrderDetail:async()=>{calls.detail++;return {detail:d,snapshot:{html:'PDF',styles:[]},capturedAt:'2026-10-22T01:01:00Z'};}},jobs:{jobs:()=>jobsList,recordJob:job=>{const old=jobsList.findIndex(j=>j.jobId===job.jobId);if(old>=0)jobsList.splice(old,1);jobsList.push(job);return job;}},storage:{archive:async()=>{calls.archive++;if(archiveFails&&calls.archive===1)throw Error('SMB offline');return {id:'archive',relativePath:'000123/x.pdf',bytes:7,sha256:'a'.repeat(64)};},store:{settings:()=>({serverId:'server'}),archives:()=>[]}},render:async()=>{calls.pdf++;return {path:path.join(dir,'x.pdf'),filename:'x.pdf',bytes:7};},outputDir:dir,mail:{store:{templates:()=>[{id:'tpl',status:'active',version:1}],template:()=>({id:'tpl',status:'active',version:1,subject:'{{产品线}}',text:'{{订单列表}}',attachments:[]}),channels:()=>[]}},settings:()=>({groups:[{productLine:'Line',to:['2639266652@qq.com'],cc:[]}],schedule:{times:['11:00','17:00'],weekends:true,timezone:'Asia/Shanghai',missed:'next_window'}})}; + const pipeline=new OrderPipeline(deps);return {pipeline,store,workflow,calls}; +} +test('pipeline remains inert by default and server-owned sample checks cannot send or export',async t=>{ + const f=fixture(t);await f.pipeline.tick();assert.equal(f.calls.detail,0);assert.equal(f.calls.pdf,0);assert.equal(f.pipeline.config().enabled,false);assert.equal(f.pipeline.config().sendEnabled,false); + await f.pipeline.checkRule('r',{connectionId:'c',source:'portal-v4',taskId:'t'},{user:{username:'owner',role:'admin'},sessionId:'test'});assert.equal(f.calls.detail,1);assert.equal(f.calls.pdf,0); +}); +test('archive failure creates no notification and retry reuses successful PDF',async t=>{ + const f=fixture(t,{archiveFails:true});await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'test'});let order=f.workflow.listOrders()[0];assert.equal(order.status,'archive_error');assert.equal(order.notification,undefined);assert.equal(f.calls.pdf,1); + await f.pipeline.retry(order.versionKey,{user:{username:'owner',role:'operator'},sessionId:'test'});order=f.workflow.get(order.versionKey);assert.equal(order.status,'notification_pending');assert.equal(f.calls.pdf,1);assert.equal(f.calls.detail,1);assert.equal(f.calls.archive,2); +}); +test('missing business version creates a persistent blocked candidate without generating a PDF',async t=>{ + const f=fixture(t);f.pipeline.manager.captureOrderDetail=async()=>({detail:{...d,businessVersion:undefined}});await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'test'});assert.equal(f.workflow.listOrders().length,0);assert.equal(f.pipeline.arrivals()[0].status,'blocked');assert.match(f.pipeline.arrivals()[0].error,/业务版本/);assert.equal(f.calls.pdf,0); +}); +test('sample URL cannot splice another order into a stored arrival even if flow and node match',async t=>{ + const f=fixture(t);await assert.rejects(()=>f.pipeline.checkRule('r',{connectionId:'c',source:'portal-v4',taskId:'t',detailUrl:a.detailUrl.replace('tid=1','tid=77')},{user:{username:'owner',role:'admin'},sessionId:'s'}),/关联|不一致/);assert.equal(f.calls.detail,0); + f.pipeline.scanStore.getArrival=()=>({...a,detailUrl:undefined});await assert.rejects(()=>f.pipeline.checkRule('r',{connectionId:'c',source:'portal-v4',taskId:'t',detailUrl:a.detailUrl},{user:{username:'owner',role:'admin'},sessionId:'s'}),/关联|重新扫描/);assert.equal(f.calls.detail,0); +}); +test('PDF and SMB running state is durable before external calls',async t=>{ + const f=fixture(t);f.pipeline.render=async()=>{assert.equal(f.store.orders()[0].status,'pdf_pending');return {path:'x.pdf',filename:'x.pdf',bytes:7};};f.pipeline.storage.archive=async()=>{assert.equal(f.store.orders()[0].status,'archive_pending');return {id:'a',relativePath:'000123/x.pdf',bytes:7,sha256:'a'.repeat(64)};}; + await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'s'});assert.equal(f.workflow.listOrders()[0].status,'notification_pending'); +}); +test('a failed detail candidate can recover after login repair without inventing an order',async t=>{ + const f=fixture(t),capture=f.pipeline.manager.captureOrderDetail;f.pipeline.manager.captureOrderDetail=async()=>{throw Object.assign(Error('需要续登'),{status:401});};await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'s'});const candidate=f.pipeline.arrivals()[0];assert.equal(candidate.status,'blocked'); + f.pipeline.manager.captureOrderDetail=capture;await f.pipeline.retryArrival(candidate.id,{user:{username:'owner',role:'operator'},sessionId:'s'});assert.equal(f.workflow.listOrders()[0].status,'notification_pending'); +}); +test('recovery reconstructs an arrival link after a crash between order insert and candidate update',async t=>{ + const f=fixture(t),order=f.workflow.identify({arrival:a,detail:d}).order;f.workflow.start(order.versionKey);f.workflow.markDetailReady(order.versionKey);f.workflow.update(order.versionKey,draft=>{draft.status='interrupted';}); + await f.pipeline.retry(order.versionKey,{user:{username:'owner',role:'admin'},sessionId:'s'});assert.equal(f.workflow.get(order.versionKey).status,'notification_pending');assert.equal(f.calls.pdf,1);assert.equal(f.pipeline.arrivals()[0].orderVersionKey,order.versionKey); +}); +test('test recipient guard rejects either a production To or Cc and cannot be disabled by config',t=>{ + const {pipeline}=fixture(t);assert.throws(()=>pipeline.assertRecipients({to:['someone@company.example'],cc:[]}));assert.throws(()=>pipeline.assertRecipients({to:['2639266652@qq.com'],cc:['someone@company.example']}));pipeline.assertRecipients({to:['2639266652@qq.com'],cc:[]}); + assert.throws(()=>pipeline.saveConfig({...pipeline.config(),allowedRecipients:['someone@company.example']})); +}); +async function sendingFixture(t,result){ + const f=fixture(t);f.pipeline.clock=()=>new Date('2026-10-22T03:00:00Z');await f.pipeline.process(a,{user:{username:'owner',role:'admin'},sessionId:'test'}); + f.store.setMeta('config',{...f.pipeline.config(),enabled:true,sendEnabled:true,channelId:'mail',since:'2026-10-22T00:00:00Z'}); + f.store.setMeta('schedule',{signature:JSON.stringify([f.pipeline.settings().schedule,[]]),next:'2026-10-22T03:00:00Z'}); + f.pipeline.mail.exclusive=async(id,work)=>work();f.pipeline.mail.store.channelSecret=()=>({id:'mail',version:1,email:'sender@example.test',name:'sender',smtp:{}});f.pipeline.mail.store.guard=()=>{}; + f.pipeline.mail.smtpFactory=()=>({verify:async()=>{},sendMail:async message=>{f.calls.mail++;assert.deepEqual(message.to,['2639266652@qq.com']);assert.deepEqual(message.attachments,[]);assert.match(message.text,/原文\n第二行/);return typeof result==='function'?result(message):result;},close(){}}); + return f; +} +test('scheduled sender freezes category template then records accepted result without PDF attachment',async t=>{ + const f=await sendingFixture(t,{accepted:['2639266652@qq.com'],rejected:[]});await f.pipeline.sendDue();assert.equal(f.calls.mail,1);assert.equal(f.workflow.listBatches()[0].status,'sent');assert.equal(f.workflow.listBatches()[0].templateVersion,1);await f.pipeline.sendDue();assert.equal(f.calls.mail,1); +}); +test('partial rejection and send exceptions become unknown and never auto resend',async t=>{ + for(const result of [{accepted:[],rejected:['2639266652@qq.com']},()=>{throw Error('SMTP lost');}]){ + const f=await sendingFixture(t,result);await f.pipeline.sendDue();assert.equal(f.workflow.listBatches()[0].status,'unknown');f.store.setMeta('schedule',{signature:JSON.stringify([f.pipeline.settings().schedule,[]]),next:'2026-10-22T03:00:00Z'});await f.pipeline.sendDue();assert.equal(f.calls.mail,1); + } +}); +test('missed next-window keeps pending notifications rather than sending immediately on restart',async t=>{ + const f=await sendingFixture(t,{accepted:['2639266652@qq.com'],rejected:[]});f.pipeline.clock=()=>new Date('2026-10-22T04:00:00Z');await f.pipeline.sendDue();assert.equal(f.calls.mail,0);assert.equal(f.workflow.listOrders()[0].status,'notification_pending');assert.equal(f.store.meta('schedule').next,'2026-10-22T09:00:00.000Z'); +}); +test('busy mailbox does not consume the due order notification window',async t=>{ + const f=await sendingFixture(t,{accepted:['2639266652@qq.com'],rejected:[]});const exclusive=f.pipeline.mail.exclusive;f.pipeline.mail.exclusive=async()=>{throw Object.assign(Error('busy'),{status:409});};await f.pipeline.sendDue();assert.equal(f.store.meta('schedule').next,'2026-10-22T03:00:00Z');assert.equal(f.calls.mail,0); + f.pipeline.mail.exclusive=exclusive;await f.pipeline.sendDue();assert.equal(f.calls.mail,1); +}); +test('skip handles all elapsed send slots across a multi-day shutdown',async t=>{ + const f=await sendingFixture(t,{accepted:['2639266652@qq.com'],rejected:[]});f.pipeline.settings=()=>({groups:[{productLine:'Line',to:['2639266652@qq.com'],cc:[]}],schedule:{times:['11:00','17:00'],weekends:true,timezone:'Asia/Shanghai',missed:'skip'}});f.pipeline.clock=()=>new Date('2026-10-23T04:00:00Z');f.store.setMeta('schedule',{signature:JSON.stringify([f.pipeline.settings().schedule,[]]),next:'2026-10-21T03:00:00Z'});await f.pipeline.sendDue();assert.equal(f.calls.mail,0);assert.equal(f.workflow.listOrders()[0].status,'skipped'); +}); diff --git a/tests/order-rule-resolver.test.cjs b/tests/order-rule-resolver.test.cjs new file mode 100644 index 0000000..8254e8e --- /dev/null +++ b/tests/order-rule-resolver.test.cjs @@ -0,0 +1,20 @@ +'use strict'; +const test=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path'); +const {OrderWorkflow}=require('../src/order-workflow.cjs');const {OrderWorkflowStore}=require('../src/order-workflow-store.cjs'); + +function publish(workflow,rule,arrival,detail){const saved=workflow.saveRule(rule),check=workflow.checkRule(saved.id,{arrival,detail,provenance:'bpm-readonly'});assert.equal(check.valid,true,JSON.stringify(check.issues));return workflow.publishRule(saved.id,{version:saved.version,checkId:check.checkId});} +const testVault=()=>({encode:(id,value)=>Buffer.from(JSON.stringify(value)),decode:(id,value)=>JSON.parse(Buffer.from(value).toString('utf8')),destroy(){}}); +const arrival={source:'portal-v4',taskId:'task-1',processName:'海外运营订单评审',activityName:'订单专员(生效)',arrivedAt:'2026-10-22T01:00:00.000Z',subject:'产品线摘要'}; +const detail={tid:'test-tid-1',pid:'pid-1',businessVersion:'business-1',processInstanceId:'pid-1',processVersion:'V13',nodeName:'订单专员(生效)',fields:{order:'000123',serial:'S1',product:'P1',full:'M1',short:'M1',customer:'C1',brief:'列表摘要'}}; +const rule={id:'overseas-normal',enabled:true,processName:'海外运营订单评审',nodeName:'订单专员(生效)',productLine:'海外运营',templateId:'tpl-1',adapters:{V13:{orderNo:'order',serialNo:'serial',productCode:'product',modelFull:'full',modelShort:'short',customer:'customer',brief:'brief'}}}; +test('resolver matches process and node, then selects the exact form-version adapter',()=>{ + const workflow=new OrderWorkflow();publish(workflow,rule,arrival,detail);const result=workflow.identify({arrival,detail});assert.equal(result.status,'matched');assert.equal(result.order.ruleId,rule.id);assert.equal(result.order.productLine,'海外运营');assert.equal(result.order.templateId,'tpl-1'); +}); +test('missing version adapter and process/node conflicts remain blocked',()=>{ + const workflow=new OrderWorkflow();publish(workflow,rule,arrival,detail);assert.throws(()=>workflow.identify({arrival,detail:{...detail,processVersion:'V12'}}),e=>e.code==='ADAPTER_MISSING');assert.throws(()=>workflow.identify({arrival:{...arrival,activityName:'其他节点'},detail}),e=>e.code==='NODE_CONFLICT'); + const second={...rule,id:'overseas-conflict'};const draft=workflow.saveRule(second),checked=workflow.checkRule(draft.id,{arrival,detail,provenance:'bpm-readonly'});assert.throws(()=>workflow.publishRule(draft.id,{version:draft.version,checkId:checked.checkId}),e=>e.code==='RULE_CONFLICT'); +}); +test('rules and selected adapter survive workflow-store restart',t=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-rule-store-')),vault=testVault();let store=new OrderWorkflowStore(dir,{vault});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});}); + let workflow=new OrderWorkflow({store});publish(workflow,rule,arrival,detail);store.close();store=new OrderWorkflowStore(dir,{vault});workflow=new OrderWorkflow({store});assert.equal(workflow.rules().length,1);assert.equal(workflow.getRule(rule.id).adapters.V13.orderNo,'order'); +}); diff --git a/tests/order-template-bridge.test.cjs b/tests/order-template-bridge.test.cjs new file mode 100644 index 0000000..4d0dcff --- /dev/null +++ b/tests/order-template-bridge.test.cjs @@ -0,0 +1,11 @@ +'use strict'; +const test=require('node:test');const assert=require('node:assert/strict'); +const {buildTemplateValues,renderOrderTemplate}=require('../src/order-template-bridge.cjs'); +test('template bridge renders category values and keeps PDF out of attachments',()=>{ + const result=renderOrderTemplate({id:'tpl-1',version:3,subject:'{{产品线}} {{订单号}}',text:'{{日期}}\n{{订单列表}}',html:'{{订单列表}}',attachments:[]},{productLine:'海外运营',orders:[{orderNo:'000123',brief:'第一行\n第二行'},{orderNo:'000124',brief:'第二单'}],date:'2026-10-22'}); + assert.equal(result.subject,'海外运营 000123、000124');assert.match(result.text,/第一行\n第二行/);assert.match(result.text,/第二单/);assert.equal(result.attachments.length,0);assert.equal(result.templateId,'tpl-1');assert.equal(result.templateVersion,3); +}); +test('template bridge rejects PDF attachments and missing source values',()=>{ + assert.throws(()=>renderOrderTemplate({id:'tpl',version:1,subject:'x',text:'{{订单号}}',attachments:[{filename:'x.pdf'}]},{productLine:'P',orders:[],date:'2026-10-22'}),/附件/); + assert.throws(()=>buildTemplateValues({productLine:'',orders:[],date:'2026-10-22'}),/产品线/); +}); diff --git a/tests/order-workflow-api-safety.test.cjs b/tests/order-workflow-api-safety.test.cjs new file mode 100644 index 0000000..2ddec95 --- /dev/null +++ b/tests/order-workflow-api-safety.test.cjs @@ -0,0 +1,20 @@ +'use strict'; +const test=require('node:test');const assert=require('node:assert/strict');const {orderWorkflowApi}=require('../src/order-workflow-api.cjs'); +const user={username:'admin',role:'admin'}; +async function request(route,body,{role='admin',pipeline,workflow}={}){let result;await orderWorkflowApi({user:{...user,role},sessionId:'s',route,method:body===undefined?'GET':'POST',body,pipeline,workflow:workflow||{},reply:(status,value)=>result={status,value}});return result;} +test('HTTP cannot forge BPM provenance, PDF success, SMB success, or caller-owned batches',async()=>{ + for(const [route,body] of [['/api/order-workflow/identify',{provenance:'bpm-readonly',detail:{}}],['/api/order-workflow/orders/o/pdf-success',{jobId:'forged'}],['/api/order-workflow/orders/o/archive-success',{archiveId:'forged'}],['/api/order-workflow/batches/b/freeze',{groups:{},templates:{}}]])await assert.rejects(()=>request(route,body),error=>[403,404,409].includes(error.status)); +}); +test('sample check only accepts a persisted arrival reference and verifies configuration admin role',async()=>{ + const pipeline={checkRule:async(id,input,principal)=>({valid:true,checkId:'c',id,input,actor:principal.user.username})}; + const ok=await request('/api/order-workflow/rules/r/check',{connectionId:'c',source:'v4',taskId:'t'},{pipeline});assert.equal(ok.value.checkId,'c'); + await assert.rejects(()=>request('/api/order-workflow/rules/r/check',{connectionId:'c',source:'v4',taskId:'t',detail:{forged:true}},{pipeline}),error=>error.status===400); + await assert.rejects(()=>request('/api/order-workflow/rules/r/check',{connectionId:'c',source:'v4',taskId:'t'},{role:'operator',pipeline}),error=>error.status===403); +}); +test('viewer can inspect workflow and cannot retry or resolve and unknown requires admin evidence',async()=>{ + const workflow={listOrders:()=>[],listBatches:()=>[],resolveBatch:()=>({status:'sent'})},pipeline={arrivals:()=>[],config:()=>({enabled:false}),retry:async()=>({status:'archived'})}; + assert.equal((await request('/api/order-workflow',undefined,{role:'viewer',workflow,pipeline})).status,200); + await assert.rejects(()=>request('/api/order-workflow/orders/o/retry',{},{role:'viewer',workflow,pipeline}),error=>error.status===403); + await assert.rejects(()=>request('/api/order-workflow/batches/b/resolve',{resolution:'retry',note:'已核验邮件记录'},{role:'operator',workflow,pipeline}),error=>error.status===403); + assert.equal((await request('/api/order-workflow/batches/b/resolve',{resolution:'sent',note:'已核验邮件记录'},{workflow,pipeline})).value.status,'sent'); +}); diff --git a/tests/order-workflow-api.test.cjs b/tests/order-workflow-api.test.cjs index 63ea754..b33e82f 100644 --- a/tests/order-workflow-api.test.cjs +++ b/tests/order-workflow-api.test.cjs @@ -1,15 +1,15 @@ 'use strict'; const test=require('node:test');const assert=require('node:assert/strict'); -const {orderWorkflowApi}=require('../src/order-workflow-api.cjs'); -function call({user={username:'operator',role:'operator'},route,method='POST',body}){let result;return {run:()=>orderWorkflowApi({workflow:{orders:()=>[],batches:()=>[],identify:()=>({status:'matched',order:{versionKey:'v1',status:'identified'}}),start:()=>{},markDetailReady:()=>{},markPdfSuccess:()=>{},markArchiveSuccess:()=>{},createNotification:()=>{},freezeBatch:()=>({id:'b1',status:'prepared'}),get:()=>({versionKey:'v1',status:'identified'}),getBatch:()=>({id:'b1',status:'unknown'}),markBatchUnknown:()=>({id:'b1',status:'unknown'}),canAutoRetry:()=>false},user,route,method,body,reply:(status,value)=>{result={status,value};}}),get:()=>result};} -test('workflow API keeps BPM source provenance explicit and prevents viewer writes',async()=>{ - const input={provenance:'bpm-readonly',arrival:{source:'portal-v4',taskId:'task'},detail:{fields:{},processInstanceId:'i'},mapping:{},rule:{}}; - const denied=call({user:{username:'viewer',role:'viewer'},route:'/api/order-workflow/identify',body:input});await assert.rejects(denied.run(),e=>e.status===403); - const accepted=call({route:'/api/order-workflow/identify',body:input});await accepted.run();assert.equal(accepted.get().status,200);assert.equal(accepted.get().value.status,'matched'); - const forged=call({route:'/api/order-workflow/identify',body:{...input,provenance:'client'} });await assert.rejects(forged.run(),e=>e.status===409); +const {orderWorkflowApi}=require('../src/order-workflow-api.cjs');const {OrderWorkflow}=require('../src/order-workflow.cjs'); +const rule={id:'r',enabled:false,processName:'流程',nodeName:'节点',productLine:'L',templateId:'tpl',pdfTemplateId:'bpm-snapshot-v1',recipientGroupId:'L',notificationType:'order',batchMode:'category_template',adapters:{V13:{orderNo:'order'}}}; +async function call(user,body,workflow=new OrderWorkflow()){let result;await orderWorkflowApi({workflow,user,route:'/api/order-workflow/rules',method:'POST',body,reply:(status,value)=>result={status,value}});return result;} +test('only admins save category bindings and edits preserve optimistic version checks',async()=>{ + const workflow=new OrderWorkflow();await assert.rejects(()=>call({role:'operator'},rule,workflow),e=>e.status===403);await assert.rejects(()=>call({role:'viewer'},rule,workflow),e=>e.status===403); + const first=await call({role:'admin'},rule,workflow);assert.equal(first.value.status,'draft');assert.equal(first.value.pdfTemplateId,'bpm-snapshot-v1');assert.equal(first.value.recipientGroupId,'L'); + await assert.rejects(()=>call({role:'admin'},rule,workflow),e=>e.code==='RULE_VERSION_CONFLICT'); + const saved=await call({role:'admin'},{...rule,version:first.value.version,templateId:'tpl2'},workflow);assert.equal(saved.value.version,2); }); -test('workflow API exposes independent step actions and blocks automatic retry of unknown batch',async()=>{ - const step=call({route:'/api/order-workflow/orders/v1/start',body:{}});await step.run();assert.equal(step.get().status,200); - const unknown=call({route:'/api/order-workflow/batches/b1/unknown',body:{message:'SMTP connection lost'}});await unknown.run();assert.equal(unknown.get().value.status,'unknown'); - const retry=call({route:'/api/order-workflow/batches/b1/retry',body:{}});await assert.rejects(retry.run(),e=>e.status===409); +test('category configuration cannot inject raw recipient addresses or a published status',async()=>{ + await assert.rejects(()=>call({role:'admin'},{...rule,recipientGroup:{to:['other@example.test']}}),e=>e.status===400); + await assert.rejects(()=>call({role:'admin'},{...rule,status:'published'}),e=>e.status===400); }); diff --git a/tests/order-workflow-plan.test.cjs b/tests/order-workflow-plan.test.cjs new file mode 100644 index 0000000..0abf603 --- /dev/null +++ b/tests/order-workflow-plan.test.cjs @@ -0,0 +1,60 @@ +'use strict'; +const test=require('node:test'); +const assert=require('node:assert/strict'); +const {OrderWorkflow}=require('../src/order-workflow.cjs'); + + +function publish(workflow,rule,arrival,detail){const saved=workflow.saveRule(rule),check=workflow.checkRule(saved.id,{arrival,detail,provenance:'bpm-readonly'});assert.equal(check.valid,true,JSON.stringify(check.issues));return workflow.publishRule(saved.id,{version:saved.version,checkId:check.checkId});} +const arrival={source:'portal-v4',taskId:'task-plan-1',processName:'海外运营订单评审',activityName:'订单专员(生效)',arrivedAt:'2026-10-22T01:00:00.000Z',subject:'列表摘要原文'}; +const rule={id:'rule-plan',enabled:true,processName:'海外运营订单评审',nodeName:'订单专员(生效)',productLine:'海外运营',templateId:'tpl-overseas',adapters:{V13:{orderNo:'order',serialNo:'serial',productCode:'product',modelFull:'full',modelShort:'short',customer:'customer',brief:{source:'arrival',path:'subject'}}}}; +const detail={tid:'100001',pid:'900001',processVersion:'V13',processInstanceId:'900001',businessVersion:'BV-1',nodeName:'订单专员(生效)',fields:{order:'000123',serial:'SERIAL-EXAMPLE',product:'MODEL-EXAMPLE-001',full:'MODEL-EXAMPLE-001',short:'MODEL-EXAMPLE',customer:'示例客户'},processSteps:[{name:'订单专员(生效)',status:'处理中'}]}; + +test('order version requires tid pid current order number and explicit business version',()=>{ + const workflow=new OrderWorkflow();publish(workflow,rule,arrival,detail); + const result=workflow.identify({arrival,detail}); + assert.equal(result.order.tid,'100001'); + assert.equal(result.order.pid,'900001'); + assert.equal(result.order.businessVersion,'BV-1'); + assert.equal(result.order.brief,'列表摘要原文'); + assert.equal(result.order.businessTimeSource,'list.receivedAt'); + for(const key of ['tid','pid','businessVersion']){ + const missing={...detail};delete missing[key]; + assert.throws(()=>workflow.identify({arrival,detail:missing}),error=>error.code==='VERSION_MISSING'); + } +}); + +test('workflow blocks a process step snapshot that disagrees with the current node',()=>{ + const workflow=new OrderWorkflow();publish(workflow,rule,arrival,detail); + assert.throws(()=>workflow.identify({arrival,detail:{...detail,processSteps:[{name:'其他节点',status:'处理中'}]}}),error=>error.code==='NODE_CONFLICT'); +}); + +function ready(workflow,taskId,businessVersion,productLine='海外运营',templateId='tpl-overseas'){ + const order=workflow.identify({arrival:{...arrival,taskId},detail:{...detail,businessVersion}}).order; + workflow.start(order.versionKey);workflow.markDetailReady(order.versionKey,{capturedAt:'2026-10-22T01:01:00.000Z'});workflow.markPdfSuccess(order.versionKey,{jobId:'pdf-'+taskId});workflow.markArchiveSuccess(order.versionKey,{archiveId:'archive-'+taskId,path:'/test/'+taskId+'.pdf'});workflow.createNotification(order.versionKey,{productLine,templateId,brief:order.brief,subject:'通知标题',occurredAt:order.businessTime}); + return order; +} + +test('freezeBatches groups by category and template and freezes the template snapshot',()=>{ + const workflow=new OrderWorkflow();publish(workflow,rule,arrival,detail); + const first=ready(workflow,'task-a','BV-A'); + const second=ready(workflow,'task-b','BV-B'); + const batches=workflow.freezeBatches('2026-10-22T03:00:00.000Z',{groups:{'海外运营':{to:['test@example.test'],cc:['cc@example.test']}},templates:{'tpl-overseas':{id:'tpl-overseas',version:4,subject:'{{产品线}} {{订单号}}',text:'{{日期}}\\n{{订单列表}}',attachments:[]}}}); + assert.equal(batches.length,1); + assert.deepEqual(batches[0].orderVersionKeys,[first.versionKey,second.versionKey]); + assert.equal(batches[0].templateVersion,4); + assert.equal(batches[0].text.includes('列表摘要原文'),true); + assert.deepEqual(batches[0].attachments,[]); + assert.deepEqual(batches[0].to,['test@example.test']); +}); + +test('freezeBatches blocks missing recipients and keeps unrelated categories separate',()=>{ + const workflow=new OrderWorkflow();publish(workflow,rule,arrival,detail); + ready(workflow,'task-c','BV-C','海外运营','tpl-overseas'); + const otherRule={...rule,id:'rule-other',processName:'国内订单评审',nodeName:'订单专员',productLine:'国内',templateId:'tpl-domestic',adapters:{V13:rule.adapters.V13}}; + publish(workflow,otherRule,{...arrival,processName:otherRule.processName,activityName:otherRule.nodeName},{...detail,nodeName:otherRule.nodeName,processSteps:[{name:otherRule.nodeName,status:'处理中'}]}); + const otherArrival={...arrival,taskId:'task-d',processName:'国内订单评审',activityName:'订单专员'}; + const otherDetail={...detail,nodeName:'订单专员',businessVersion:'BV-D',processSteps:[{name:'订单专员',status:'处理中'}]}; + const other=workflow.identify({arrival:otherArrival,detail:otherDetail}).order;workflow.start(other.versionKey);workflow.markDetailReady(other.versionKey);workflow.markPdfSuccess(other.versionKey,{jobId:'pdf-d'});workflow.markArchiveSuccess(other.versionKey,{archiveId:'archive-d'});workflow.createNotification(other.versionKey,{productLine:'国内',templateId:'tpl-domestic',brief:other.brief,subject:'国内',occurredAt:other.businessTime}); + const batches=workflow.freezeBatches('2026-10-22T03:00:00.000Z',{groups:{'海外运营':{to:['test@example.test'],cc:[]}},templates:{'tpl-overseas':{id:'tpl-overseas',version:1,subject:'x',text:'x',attachments:[]},'tpl-domestic':{id:'tpl-domestic',version:1,subject:'x',text:'x',attachments:[]}}}); + assert.equal(batches.length,1);assert.equal(workflow.get(other.versionKey).status,'blocked'); +}); diff --git a/tests/order-workflow-safety.test.cjs b/tests/order-workflow-safety.test.cjs new file mode 100644 index 0000000..d4f77d4 --- /dev/null +++ b/tests/order-workflow-safety.test.cjs @@ -0,0 +1,37 @@ +'use strict'; +const test=require('node:test');const assert=require('node:assert/strict'); +const {OrderWorkflow}=require('../src/order-workflow.cjs'); +const base={id:'r',version:0,enabled:true,processName:'P',nodeName:'N',productLine:'Line',templateId:'tpl',recipientGroupId:'Line',adapters:{V1:{orderNo:'no',serialNo:'sn',productCode:'p',modelFull:'m',modelShort:'s',customer:'c',brief:{source:'arrival',path:'subject'}}}}; +const arrival={source:'v4',taskId:'a',processName:'P',activityName:'N',arrivedAt:'2026-10-22T01:00:00Z',subject:' first\nsecond '}; +const detail={tid:'1',pid:'2',businessVersion:'rev1',processName:'P',nodeName:'N',processVersion:'V1',fields:{no:'000123',sn:'s',p:'p',m:'m',s:'s',c:'c'},processSteps:[{name:'N',status:'处理中'}]}; +test('saved category stays a draft until checked against server-owned read-only evidence',()=>{ + const w=new OrderWorkflow();const r=w.saveRule(base);assert.equal(r.status,'draft');assert.equal(r.version,1); + assert.throws(()=>w.publishRule(r.id,{version:r.version,checkId:'forged'}),e=>e.code==='RULE_CHECK_REQUIRED'); + const checked=w.checkRule(r.id,{arrival,detail,provenance:'bpm-readonly'});assert.equal(checked.valid,true); + const published=w.publishRule(r.id,{version:r.version,checkId:checked.checkId});assert.equal(published.status,'published'); + assert.equal(w.identify({arrival,detail}).order.brief,' first\nsecond '); + const changed=w.saveRule({...published,productLine:'Changed'});assert.equal(changed.status,'draft'); + assert.throws(()=>w.publishRule(r.id,{version:changed.version,checkId:checked.checkId}),e=>e.code==='RULE_CHECK_REQUIRED'); +}); +test('optimistic rule edits and disabled duplicate drafts cannot overwrite or claim a published match',()=>{ + const w=new OrderWorkflow();const r=w.saveRule(base);assert.throws(()=>w.saveRule({...base,version:0}),e=>e.code==='RULE_VERSION_CONFLICT'); + w.saveRule({...base,id:'disabled',enabled:false}); + assert.throws(()=>w.identify({arrival,detail}),e=>e.code==='RULE_UNMATCHED'); + assert.equal(w.getRule(r.id).version,1); +}); +test('matching uses the category id even for two categories with identical product line and template',()=>{ + const w=new OrderWorkflow();let r=w.saveRule(base);let c=w.checkRule(r.id,{arrival,detail,provenance:'bpm-readonly'});w.publishRule(r.id,{version:r.version,checkId:c.checkId}); + const orders=[]; + for(let i=0;i<2;i++){ + const a={...arrival,taskId:'a'+i,processName:i?'Other':'P'};const d={...detail,tid:String(i+1),processName:a.processName}; + if(i){r=w.saveRule({...base,id:'other',processName:'Other'});c=w.checkRule(r.id,{arrival:a,detail:d,provenance:'bpm-readonly'});w.publishRule(r.id,{version:r.version,checkId:c.checkId});} + const o=w.identify({arrival:a,detail:d}).order;w.start(o.versionKey);w.markDetailReady(o.versionKey);w.markPdfSuccess(o.versionKey,{jobId:'p'+i});w.markArchiveSuccess(o.versionKey,{archiveId:'s'+i});w.createNotification(o.versionKey);orders.push(o); + } + const batches=w.freezeBatches('2026-10-22T03:00:00Z',{groups:{Line:{to:['2639266652@qq.com'],cc:[]}},templates:{tpl:{id:'tpl',status:'active',version:1,subject:'x',text:'{{订单列表}}',attachments:[]}}}); + assert.equal(batches.length,2);assert.notEqual(batches[0].ruleId,batches[1].ruleId); +}); +test('failed archive retries skip detail and PDF and sender cannot turn prepared straight into sent',()=>{ + const w=new OrderWorkflow();w.saveRule(base);const o=w.identify({arrival,detail,rule:{...base,status:'published'},mapping:base.adapters.V1}).order; + w.start(o.versionKey);w.markDetailReady(o.versionKey);w.markPdfSuccess(o.versionKey,{jobId:'pdf'});w.markArchiveError(o.versionKey,'offline'); + const next=w.start(o.versionKey);assert.equal(next.steps.pdf.status,'success');assert.equal(next.status,'pdf_success'); +}); diff --git a/tests/order-workflow-store.test.cjs b/tests/order-workflow-store.test.cjs index 3f413c6..76ff89e 100644 --- a/tests/order-workflow-store.test.cjs +++ b/tests/order-workflow-store.test.cjs @@ -1,13 +1,17 @@ 'use strict'; const test=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs');const os=require('node:os');const path=require('node:path'); const {OrderWorkflowStore}=require('../src/order-workflow-store.cjs'); +const testVault=()=>({encode:(id,value)=>Buffer.from(JSON.stringify(value)),decode:(id,value)=>JSON.parse(Buffer.from(value).toString('utf8')),destroy(){}}); test('workflow store persists order versions, step evidence and batches across restart',t=>{ - const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-workflow-store-'));let store=new OrderWorkflowStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});}); + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-workflow-store-')),vault=testVault();let store=new OrderWorkflowStore(dir,{vault});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});}); store.putOrder({versionKey:'v1',orderNo:'ORD-1',status:'archive_error',steps:{detail:{status:'success'},pdf:{status:'success'},archive:{status:'error',error:'SMB unavailable'}}}); store.putBatch({id:'b1',status:'unknown',orderVersionKeys:['v1'],to:['test@example.test'],cc:[]}); - store.close();store=new OrderWorkflowStore(dir);assert.equal(store.getOrder('v1').status,'archive_error');assert.equal(store.getOrder('v1').steps.archive.error,'SMB unavailable');assert.equal(store.getBatch('b1').status,'unknown');assert.deepEqual(store.getBatch('b1').orderVersionKeys,['v1']); + store.close();store=new OrderWorkflowStore(dir,{vault});assert.equal(store.getOrder('v1').status,'unknown');assert.equal(store.getOrder('v1').steps.archive.error,'SMB unavailable');assert.equal(store.getBatch('b1').status,'unknown');assert.deepEqual(store.getBatch('b1').orderVersionKeys,['v1']); }); test('workflow store restart converts sending batch to unknown without replaying it',t=>{ - const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-workflow-restart-'));let store=new OrderWorkflowStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});}); - store.putBatch({id:'b1',status:'sending',orderVersionKeys:['v1'],to:['test@example.test'],cc:[]});store.close();store=new OrderWorkflowStore(dir);assert.equal(store.getBatch('b1').status,'unknown');assert.equal(store.getBatch('b1').error,'服务重启,发送结果需要核实。'); + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'order-workflow-restart-')),vault=testVault();let store=new OrderWorkflowStore(dir,{vault});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});}); + store.putBatch({id:'b1',status:'sending',orderVersionKeys:['v1'],to:['test@example.test'],cc:[]});store.close();store=new OrderWorkflowStore(dir,{vault});assert.equal(store.getBatch('b1').status,'unknown');assert.equal(store.getBatch('b1').error,'服务重启,发送结果需要核实。'); +}); +test('restart reconciles both sending batch and linked order atomically',t=>{ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'workflow-recovery-')),vault=testVault();let store=new OrderWorkflowStore(dir,{vault});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});store.putOrder({versionKey:'v',orderNo:'000123',status:'sending',notification:{status:'sending',batchId:'b'},steps:{notification:{status:'sending'}}});store.putBatch({id:'b',status:'sending',orderVersionKeys:['v']});store.close();store=new OrderWorkflowStore(dir,{vault});assert.equal(store.getBatch('b').status,'unknown');assert.equal(store.getOrder('v').status,'unknown');assert.equal(store.getOrder('v').steps.notification.status,'unknown'); }); diff --git a/tests/order-workflow-ui.test.cjs b/tests/order-workflow-ui.test.cjs new file mode 100644 index 0000000..d614046 --- /dev/null +++ b/tests/order-workflow-ui.test.cjs @@ -0,0 +1,113 @@ +'use strict'; +const test=require('node:test');const assert=require('node:assert/strict');const fs=require('node:fs/promises');const http=require('node:http');const path=require('node:path'); +const {loadPlaywright,browserOptions}=require('../src/runtime.cjs'); +const rule={id:'r1',version:1,enabled:true,processName:'海外运营订单评审',nodeName:'订单专员(生效)',productLine:'海外运营',templateId:'tpl-1',pdfTemplateId:'bpm-snapshot-v1',notificationType:'order',batchMode:'product_line',recipientGroupId:'海外运营',adapters:{V13:{orderNo:'OrderNum',brief:{source:'arrival',path:'subject'}}},published:false}; +const arrival={connectionId:'conn-1',source:'portal-v4',taskId:'test-task-1',processName:'海外运营订单评审',activityName:'订单专员(生效)',subject:'订单说明'}; +const order={versionKey:'version-1',orderNo:'TEST-001',businessVersion:'B1',tid:'tid-1',pid:'pid-1',source:'portal-v4',taskId:'test-task-1',ruleId:'r1',productLine:'海外运营',processName:'海外运营订单评审',nodeName:'订单专员(生效)',status:'archive_error',sources:{orderNo:{path:'detail.OrderNum',value:'TEST-001'}},steps:{detail:{status:'success'},pdf:{status:'success'},archive:{status:'error',error:'共享不可用'},notification:{status:'pending'}},pdf:{jobId:'pdf-1'},error:'共享不可用'}; +async function fixture(t,role='admin'){ + const state={rules:[structuredClone(rule)],orders:[structuredClone(order)],batches:[{id:'batch-1',status:'unknown',templateId:'tpl-1',templateVersion:3,orderVersionKeys:['version-1'],to:['test@example.test'],cc:['copy@example.test'],subject:'测试主题',text:'订单说明',error:'结果需要核验'}],arrivals:[arrival],blockedArrivals:[],calls:[],checkValid:true,slowCheck:false}; + const server=http.createServer(async(req,res)=>{try{let file=req.url==='/'?'web/index.html':req.url.startsWith('/vendor/')?null:'web'+req.url;if(file&& !file.includes('..')){const value=await fs.readFile(path.resolve(__dirname,'..',file));res.setHeader('content-type',file.endsWith('.js')?'text/javascript':'text/html');res.end(value);}else{res.statusCode=404;res.end();}}catch{res.statusCode=404;res.end();}}); + await new Promise(r=>server.listen(0,'127.0.0.1',r));const browser=await loadPlaywright().chromium.launch(browserOptions()),page=await browser.newPage(); + t.after(async()=>{await browser.close();await new Promise(r=>server.close(r));}); + await page.route('**/api/**',async route=>{ + const request=route.request(),url=new URL(request.url()),body=request.postDataJSON();state.calls.push({path:url.pathname,body});let data; + if(url.pathname==='/api/bootstrap/status')data={required:false};else if(url.pathname==='/api/me')data={user:{id:'u-'+role,username:role,role}}; + else if(url.pathname==='/api/order-workflow/rules'&&request.method()==='GET')data={rules:state.rules}; + else if(url.pathname==='/api/order-workflow/options')data={templates:[{id:'tpl-1',subject:'海外模板',version:3,status:'active'}],groups:[{productLine:'海外运营',to:['test@example.test'],cc:[]}],connections:[{id:'conn-1',name:'测试连接'}],adapters:{V13:rule.adapters.V13}}; + else if(url.pathname==='/api/order-workflow')data={orders:state.orders,batches:state.batches,arrivals:state.arrivals,blockedArrivals:state.blockedArrivals,settings:{enabled:false,sendEnabled:false}}; + else if(url.pathname==='/api/order-workflow/rules'&&request.method()==='POST'){data={...body,version:(body.version||0)+1};state.rules=[data];} + else if(url.pathname.endsWith('/check')){if(state.slowCheck)await new Promise(r=>setTimeout(r,350));data={valid:state.checkValid,issues:state.checkValid?[]:['缺少业务版本'],checkId:'check-1',sample:{processName:rule.processName,nodeName:rule.nodeName,processVersion:'V13',fields:{OrderNum:'TEST-001'},tid:'tid-1',pid:'pid-1'}};} + else if(url.pathname.endsWith('/publish')){data={...state.rules[0],published:true,version:state.rules[0].version+1};state.rules=[data];} + else if(url.pathname==='/api/order-workflow/order/version-1')data=state.orders[0]; + else if(url.pathname.endsWith('/retry')){data={ok:true};} + else if(url.pathname.endsWith('/resolve')){data={ok:true};state.batches[0].status='resolved_sent';} + else data={}; + await route.fulfill({status:200,contentType:'application/json',body:JSON.stringify(data)}); + }); + return {page,state,base:'http://127.0.0.1:'+server.address().port}; +} + +test('classification page saves a draft, checks a real arrival and publishes only a successful unchanged check',{timeout:30000},async t=>{ + const {page,state,base}=await fixture(t);await page.goto(base+'/#order-rules'); + await page.getByRole('heading',{name:'分类规则',exact:true}).waitFor({timeout:3000}); + await page.getByRole('button',{name:'编辑规则',exact:true}).click(); + assert.equal(await page.locator('#rule-adapter-details').getAttribute('open'),null); + 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}).isDisabled(),true); + await page.getByLabel('真实 BPM 到达记录',{exact:true}).selectOption('0'); + state.slowCheck=true;await page.getByRole('button',{name:'检查只读样本',exact:true}).click(); + assert.equal(await page.getByRole('button',{name:'检查只读样本',exact:true}).isDisabled(),true); + await page.getByText('样本检查通过,可以发布当前草稿。',{exact:true}).waitFor(); + await page.getByRole('button',{name:'发布规则',exact:true}).click(); + await page.getByText('规则已发布。',{exact:true}).waitFor(); + assert.equal(state.calls.filter(c=>c.path.endsWith('/check')).length,1); + assert.deepEqual(state.calls.find(c=>c.path.endsWith('/publish')).body,{version:2,checkId:'check-1'}); +}); + +test('viewer sees order field evidence and frozen batch recipients but has no write actions or duplicate page tabs',{timeout:30000},async t=>{ + const {page,state,base}=await fixture(t,'viewer');await page.goto(base+'/#order-center'); + await page.getByRole('heading',{name:'订单任务',exact:true}).waitFor({timeout:3000}); + assert.equal(await page.locator('#content a[href="#mail-batches"]').count(),0); + await page.getByRole('button',{name:'查看详情',exact:true}).click();await page.getByText('detail.OrderNum',{exact:true}).waitFor(); + assert.equal(await page.getByRole('button',{name:'重试失败步骤',exact:true}).count(),0); + await page.locator('aside a[href="#mail-batches"]').click();await page.getByRole('heading',{name:'邮件批次',exact:true,level:2}).waitFor(); + await page.getByText('test@example.test',{exact:true}).waitFor();await page.getByText('copy@example.test',{exact:true}).waitFor();await page.getByText('tpl-1 · v3',{exact:true}).waitFor(); + assert.equal(await page.getByRole('button',{name:'保存核验结果',exact:true}).count(),0); + await page.locator('aside a[href="#rules"]').click();await page.getByRole('heading',{name:'分类规则',exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'新增分类规则',exact:true}).count(),0); + assert.equal(state.calls.filter(c=>c.body).length,0); +}); + +test('admin must record unknown batch evidence and business strings render as text',{timeout:30000},async t=>{ + const {page,state,base}=await fixture(t);state.batches[0].subject='';await page.goto(base+'/#mail-batches');await page.getByRole('heading',{name:'邮件批次',exact:true,level:2}).waitFor({timeout:3000}); + assert.equal(await page.locator('#content img').count(),0);await page.getByRole('button',{name:'保存核验结果',exact:true}).click();assert.equal(state.calls.some(c=>c.path.endsWith('/resolve')),false); + await page.getByLabel('核验依据',{exact:true}).fill('已查询测试邮箱并确认收到');await page.getByRole('button',{name:'保存核验结果',exact:true}).click();await page.getByText('核验结果已保存。',{exact:true}).waitFor(); + const calls=state.calls.filter(c=>c.path.endsWith('/resolve'));assert.equal(calls.length,1);assert.deepEqual(calls[0].body,{resolution:'sent',note:'已查询测试邮箱并确认收到'}); +}); + +test('leaving a slow sample check prevents its response from replacing the order center',{timeout:30000},async t=>{ + const {page,state,base}=await fixture(t);state.slowCheck=true;await page.goto(base+'/#rules');await page.getByRole('button',{name:'编辑规则',exact:true}).click({timeout:3000});await page.getByLabel('真实 BPM 到达记录',{exact:true}).selectOption('0');await page.getByRole('button',{name:'检查只读样本',exact:true}).click();await page.locator('aside a[href="#order-center"]').click();await page.getByRole('heading',{name:'订单任务',exact:true}).waitFor();await page.waitForTimeout(450);assert.equal(await page.getByText('样本检查通过,可以发布当前草稿。',{exact:true}).count(),0); +}); + +test('admin can provide an actual detail link when an older arrival has no stored link',{timeout:30000},async t=>{ + const {page,state,base}=await fixture(t);await page.goto(base+'/#rules');await page.getByRole('button',{name:'编辑规则',exact:true}).click({timeout:3000});await page.getByLabel('真实 BPM 到达记录',{exact:true}).selectOption('0'); + const detailUrl='https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/TestV13.aspx?tid=101&pid=202';await page.getByLabel('BPM 详情链接(旧记录补充)',{exact:true}).fill(detailUrl,{timeout:1000});await page.getByRole('button',{name:'检查只读样本',exact:true}).click();await page.getByText('样本检查通过,可以发布当前草稿。',{exact:true}).waitFor(); + assert.equal(state.calls.find(c=>c.path.endsWith('/check')).body.detailUrl,detailUrl); +}); + +test('a new classification can adopt process and node from an existing BPM arrival',{timeout:30000},async t=>{ + const {page,base}=await fixture(t);await page.goto(base+'/#rules');await page.getByRole('button',{name:'新增分类规则',exact:true}).click({timeout:3000});await page.getByLabel('真实 BPM 到达记录',{exact:true}).selectOption('0');assert.equal(await page.getByLabel('流程名称',{exact:true}).inputValue(),rule.processName);assert.equal(await page.getByLabel('当前节点',{exact:true}).inputValue(),rule.nodeName); +}); + +test('changing the sample link during a slow check invalidates its response',{timeout:30000},async t=>{ + const {page,state,base}=await fixture(t);state.slowCheck=true;await page.goto(base+'/#rules');await page.getByRole('button',{name:'编辑规则',exact:true}).click({timeout:3000});await page.getByLabel('真实 BPM 到达记录',{exact:true}).selectOption('0');await page.getByRole('button',{name:'检查只读样本',exact:true}).click();await page.getByLabel('BPM 详情链接(旧记录补充)',{exact:true}).fill('https://bpm.skyworthdigital.com/YZSoft/Forms/XForm/TestV13.aspx?tid=303&pid=404');await page.waitForTimeout(500);assert.equal(await page.getByRole('button',{name:'发布规则',exact:true}).isDisabled(),true);assert.equal(await page.getByText('样本检查通过,可以发布当前草稿。',{exact:true}).count(),0); +}); + +test('failed sample cannot publish and edits invalidate a successful sample check',{timeout:30000},async t=>{ + const {page,state,base}=await fixture(t);await page.goto(base+'/#rules');await page.getByRole('button',{name:'编辑规则',exact:true}).click({timeout:3000});await page.getByLabel('真实 BPM 到达记录',{exact:true}).selectOption('0');state.checkValid=false; + await page.getByRole('button',{name:'检查只读样本',exact:true}).click();await page.getByText('缺少业务版本',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'发布规则',exact:true}).isDisabled(),true); + state.checkValid=true;await page.getByRole('button',{name:'检查只读样本',exact:true}).click();await page.getByText('样本检查通过,可以发布当前草稿。',{exact:true}).waitFor();await page.getByLabel('当前节点',{exact:true}).fill('其他节点');assert.equal(await page.getByRole('button',{name:'发布规则',exact:true}).isDisabled(),true); +}); + +test('operator can recover a blocked candidate before an order version exists',{timeout:30000},async t=>{ + const {page,state,base}=await fixture(t,'operator');state.orders=[];state.blockedArrivals=[{...arrival,id:'candidate-1',status:'blocked',error:'缺少明确业务版本',code:'VERSION_MISSING'}];await page.goto(base+'/#order-center');await page.getByRole('heading',{name:'待确认的 BPM 到达记录',exact:true}).waitFor({timeout:3000}); + await page.getByText('VERSION_MISSING',{exact:true}).waitFor();await page.getByText('缺少明确业务版本',{exact:true}).waitFor();await page.getByRole('button',{name:'重新采集候选记录',exact:true}).click();await page.getByText('候选记录重试已提交,请刷新查看结果。',{exact:true}).waitFor();assert.deepEqual(state.calls.find(c=>c.path==='/api/order-workflow/arrivals/candidate-1/retry').body,{}); +}); + +test('viewer can inspect blocked candidates without a recovery action',{timeout:30000},async t=>{ + const {page,state,base}=await fixture(t,'viewer');state.blockedArrivals=[{...arrival,id:'candidate-1',status:'blocked',error:'缺少字段',code:'MISSING_FIELD'}];await page.goto(base+'/#order-center');await page.getByText('MISSING_FIELD',{exact:true}).waitFor({timeout:3000});assert.equal(await page.getByRole('button',{name:'重新采集候选记录',exact:true}).count(),0); +}); + +test('notification failures are retryable but a blocked order needs manual correction',{timeout:30000},async t=>{ + const {page,state,base}=await fixture(t,'operator');state.orders[0].status='notification_error';await page.goto(base+'/#order-center');await page.getByRole('button',{name:'查看详情',exact:true}).click({timeout:3000});await page.getByRole('button',{name:'重试失败步骤',exact:true}).click({timeout:1000});await page.getByText('重试已提交,请刷新查看步骤结果。',{exact:true}).waitFor();assert.equal(state.calls.filter(c=>c.path==='/api/order-workflow/orders/version-1/retry').length,1); + state.orders[0].status='blocked';await page.reload();await page.getByRole('button',{name:'查看详情',exact:true}).click();await page.getByText('detail.OrderNum',{exact:true}).waitFor();assert.equal(await page.getByRole('button',{name:'重试失败步骤',exact:true}).count(),0); +}); + +test('admin can restore an exhausted failed batch with a required recovery note',{timeout:30000},async t=>{ + const {page,state,base}=await fixture(t);state.batches[0].status='failed';state.batches[0].error='SMTP 检查次数已耗尽';await page.goto(base+'/#mail-batches');await page.getByRole('button',{name:'保存核验结果',exact:true}).click({timeout:1500});assert.equal(state.calls.some(c=>c.path.endsWith('/resolve')),false);await page.getByLabel('核验结果',{exact:true}).selectOption('retry');await page.getByLabel('核验依据',{exact:true}).fill('已修复 SMTP 配置并完成连接检查');await page.getByRole('button',{name:'保存核验结果',exact:true}).click();await page.getByText('核验结果已保存。',{exact:true}).waitFor();assert.equal(state.calls.find(c=>c.path.endsWith('/resolve')).body.resolution,'retry'); +}); + +test('old arrivals explain that an arbitrary detail link cannot establish the order identity',{timeout:30000},async t=>{ + const {page,base}=await fixture(t);await page.goto(base+'/#rules');await page.getByRole('button',{name:'编辑规则',exact:true}).click({timeout:3000});await page.getByText('历史记录若未保存 tid/pid 或权威详情链接,请先重新扫描获取来源依据,不能用任意链接绑定订单。',{exact:true}).waitFor({timeout:1000}); +}); diff --git a/tests/order-workflow.test.cjs b/tests/order-workflow.test.cjs index 1716e52..c7f5665 100644 --- a/tests/order-workflow.test.cjs +++ b/tests/order-workflow.test.cjs @@ -8,6 +8,7 @@ const baseArrival={ arrivedAt:'2026-10-15T08:33:58.000Z',arrivalDay:'2026-10-15',subject:'脱敏订单标题', }; const baseDetail={ + tid:'test-tid',pid:'test-pid',businessVersion:'business-1', processInstanceId:'instance-315288',processVersion:'V7',nodeName:'订单专员(订单通知书)', fields:{ 'OFR_WY_Applicant.OrderNum':'ORD-REDACTED', @@ -26,18 +27,18 @@ const mapping={ brief:'OFR_WY_Applicant.OrderChangeContent', }; const rule={id:'overseas-change-v7',processName:'海外运营订单更改评审',processVersion:'V7',nodeName:'订单专员(订单通知书)', - productLinePath:'OFR_WY_BInfo.ProductNum',notificationType:'change',enabled:true}; + productLine:'PRODUCT-REDACTED',templateId:'tpl-test',notificationType:'change',enabled:true}; test('real-order mapping requires explicit paths and keeps source evidence',()=>{ const workflow=new OrderWorkflow({clock:()=>new Date('2026-10-22T01:00:00Z')}); const result=workflow.identify({arrival:baseArrival,detail:baseDetail,mapping,rule}); assert.equal(result.status,'matched'); assert.equal(result.order.orderNo,'ORD-REDACTED'); - assert.equal(result.order.version,'instance-315288'); + assert.equal(result.order.version,'business-1'); assert.equal(result.order.productLine,'PRODUCT-REDACTED'); assert.equal(result.order.brief,baseDetail.brief); - assert.equal(result.order.sources.orderNo.path,mapping.orderNo); - assert.equal(result.order.sources.brief.path,mapping.brief); + assert.equal(result.order.sources.orderNo.path,'detail.'+mapping.orderNo); + assert.equal(result.order.sources.brief.path,'detail.'+mapping.brief); }); test('missing or conflicting explicit fields block identification without guessing',()=>{ @@ -46,7 +47,7 @@ test('missing or conflicting explicit fields block identification without guessi assert.throws(()=>workflow.identify({arrival:baseArrival,detail:missing,mapping,rule}),e=>e.code==='MISSING_FIELD'); const conflicting={...baseDetail,fields:{...baseDetail.fields,otherOrder:'DIFFERENT'}}; assert.throws(()=>workflow.identify({arrival:baseArrival,detail:conflicting,mapping:{...mapping,orderNo:['OFR_WY_Applicant.OrderNum','otherOrder']},rule}),e=>e.code==='AMBIGUOUS_FIELD'); - assert.throws(()=>workflow.identify({arrival:baseArrival,detail:baseDetail,mapping:{...mapping,productLine:''},rule}),e=>e.code==='MISSING_FIELD'); + assert.equal(workflow.identify({arrival:baseArrival,detail:baseDetail,mapping:{...mapping,productLine:''},rule}).order.productLine,rule.productLine); }); test('order version is idempotent and changed BPM revision creates a new version',()=>{ @@ -54,7 +55,7 @@ test('order version is idempotent and changed BPM revision creates a new version const first=workflow.identify({arrival:baseArrival,detail:baseDetail,mapping,rule}).order; const same=workflow.identify({arrival:{...baseArrival,subject:'different list title'},detail:baseDetail,mapping,rule}).order; assert.equal(first.versionKey,same.versionKey); - const changed=workflow.identify({arrival:{...baseArrival,taskId:'task-315288-r2'},detail:{...baseDetail,processInstanceId:'instance-315288-r2'},mapping,rule}).order; + const changed=workflow.identify({arrival:{...baseArrival,taskId:'task-315288-r2'},detail:{...baseDetail,pid:'pid-r2',businessVersion:'business-2',processInstanceId:'instance-315288-r2'},mapping,rule}).order; assert.notEqual(first.versionKey,changed.versionKey); assert.equal(first.orderNo,changed.orderNo); }); @@ -63,9 +64,9 @@ test('state transitions keep PDF archive and notification independent and block const workflow=new OrderWorkflow(); const order=workflow.identify({arrival:baseArrival,detail:baseDetail,mapping,rule}).order; workflow.start(order.versionKey);workflow.markDetailReady(order.versionKey);workflow.markPdfSuccess(order.versionKey,{jobId:'pdf-1'});workflow.markArchiveSuccess(order.versionKey,{archiveId:'archive-1',path:'\\\\210\\orders\\ORD-REDACTED\\file.pdf'}); - workflow.createNotification(order.versionKey,{productLine:order.productLine,brief:order.brief,subject:order.subject,occurredAt:order.businessTime}); + workflow.createNotification(order.versionKey,{templateId:'tpl-test',productLine:order.productLine,brief:order.brief,subject:order.subject,occurredAt:order.businessTime}); assert.equal(workflow.get(order.versionKey).status,'notification_pending'); - const failed=workflow.identify({arrival:{...baseArrival,taskId:'task-failed'},detail:{...baseDetail,processInstanceId:'instance-failed'},mapping,rule}).order; + const failed=workflow.identify({arrival:{...baseArrival,taskId:'task-failed'},detail:{...baseDetail,pid:'pid-failed',processInstanceId:'instance-failed'},mapping,rule}).order; workflow.start(failed.versionKey);workflow.markDetailReady(failed.versionKey);workflow.markPdfSuccess(failed.versionKey,{jobId:'pdf-2'});workflow.markArchiveError(failed.versionKey,'SMB unavailable'); assert.throws(()=>workflow.createNotification(failed.versionKey,{productLine:failed.productLine,brief:failed.brief,subject:failed.subject,occurredAt:failed.businessTime}),e=>e.code==='ARCHIVE_REQUIRED'); assert.equal(workflow.get(failed.versionKey).status,'archive_error'); @@ -73,10 +74,10 @@ test('state transitions keep PDF archive and notification independent and block test('batches group only confirmed product lines and unknown sends never auto-retry',()=>{ const workflow=new OrderWorkflow({schedule:{times:['11:00','17:00'],timezone:'Asia/Shanghai'}}); - const order=workflow.identify({arrival:baseArrival,detail:baseDetail,mapping,rule}).order;workflow.start(order.versionKey);workflow.markDetailReady(order.versionKey);workflow.markPdfSuccess(order.versionKey,{jobId:'pdf'});workflow.markArchiveSuccess(order.versionKey,{archiveId:'a'});workflow.createNotification(order.versionKey,{productLine:'PRODUCT-REDACTED',brief:'正文',subject:'标题',occurredAt:'2026-10-22T00:30:00.000Z'}); - const missing=workflow.identify({arrival:{...baseArrival,taskId:'task-2'},detail:{...baseDetail,processInstanceId:'instance-2'},mapping,rule}).order;workflow.start(missing.versionKey);workflow.markDetailReady(missing.versionKey);workflow.markPdfSuccess(missing.versionKey,{jobId:'pdf2'});workflow.markArchiveSuccess(missing.versionKey,{archiveId:'a2'});workflow.createNotification(missing.versionKey,{productLine:'UNMAPPED',brief:'正文2',subject:'标题2',occurredAt:'2026-10-22T00:30:00.000Z'}); - const batch=workflow.freezeBatch('2026-10-22T03:00:00.000Z',{mode:'product_line',groups:{'PRODUCT-REDACTED':{to:['test@example.test'],cc:[]}}}); + const order=workflow.identify({arrival:baseArrival,detail:baseDetail,mapping,rule}).order;workflow.start(order.versionKey);workflow.markDetailReady(order.versionKey);workflow.markPdfSuccess(order.versionKey,{jobId:'pdf'});workflow.markArchiveSuccess(order.versionKey,{archiveId:'a'});workflow.createNotification(order.versionKey,{templateId:'tpl-test',productLine:'PRODUCT-REDACTED',brief:'正文',subject:'标题',occurredAt:'2026-10-22T00:30:00.000Z'}); + const missing=workflow.identify({arrival:{...baseArrival,taskId:'task-2'},detail:{...baseDetail,pid:'pid-2',processInstanceId:'instance-2'},mapping,rule:{...rule,id:'missing-group',productLine:'UNMAPPED'}}).order;workflow.start(missing.versionKey);workflow.markDetailReady(missing.versionKey);workflow.markPdfSuccess(missing.versionKey,{jobId:'pdf2'});workflow.markArchiveSuccess(missing.versionKey,{archiveId:'a2'});workflow.createNotification(missing.versionKey,{templateId:'tpl-test',productLine:'UNMAPPED',brief:'正文2',subject:'标题2',occurredAt:'2026-10-22T00:30:00.000Z'}); + const batch=workflow.freezeBatch('2026-10-22T03:00:00.000Z',{mode:'product_line',templates:{'tpl-test':{id:'tpl-test',version:1,subject:'标题',text:'{{订单列表}}',attachments:[]}},groups:{'PRODUCT-REDACTED':{to:['test@example.test'],cc:[]}}}); assert.equal(batch.status,'prepared');assert.deepEqual(batch.to,['test@example.test']);assert.equal(batch.orderVersionKeys.length,1); assert.equal(workflow.get(missing.versionKey).status,'blocked');assert.throws(()=>workflow.freezeBatch('2026-10-22T03:00:00.000Z',{mode:'product_line',groups:{},}),e=>e.code==='EMPTY_BATCH'); - workflow.markBatchUnknown(batch.id,'SMTP connection lost');assert.equal(workflow.getBatch(batch.id).status,'unknown');assert.equal(workflow.canAutoRetry(batch.id),false); + workflow.markBatchSending(batch.id);workflow.markBatchUnknown(batch.id,'SMTP connection lost');assert.equal(workflow.getBatch(batch.id).status,'unknown');assert.equal(workflow.canAutoRetry(batch.id),false); }); diff --git a/web/app.js b/web/app.js index d23c30f..b7b185b 100644 --- a/web/app.js +++ b/web/app.js @@ -6,6 +6,8 @@ const roles={admin:'管理员',operator:'操作员',viewer:'只读成员'}; const statusMap={running:['处理中','blue'],success:['已完成','green'],error:['失败','red'],interrupted:['已中断','orange']}; let currentUser=null,settings=null,currentView='overview',overview=null,refreshTimer=null,viewGeneration=0; const views={health:['系统健康','查看服务守护、登录自启和各模块最近检查结果'],assistant:['ZCode 助手','对话查询运行状态、分析异常与执行受控恢复'],storage:['存储服务器','配置 SMB 共享目录、检查连接与管理 PDF 归档'],notifications:['业务通知','配置来源字段、产业接口人与通知队列'],overview:['工作总览','团队工作一目了然,每一次协作都有记录'],calendar:['业务日历','按公司实际安排设置工作日、休息日与暂停日期'],exceptions:['异常待办','认领、转交和跟进异常'],bpm:['BPM 连接','管理连接及负责人'],supervisor:['运行监管','配置负责人、通知方式与重试上限'],records:['订单与导出记录','查询已经采集的订单,下载已完成的 PDF'],rules:['订单匹配规则','管理订单筛选和匹配条件'],schedule:['发送计划','设置每日两个发送时间和批次整理方式'],templates:['模板与收件群组','预览确认发信模板,维护产品线收件群组'],mail:['邮箱管理','维护托管邮箱、模板收信与连接状态'],connections:['服务接入','查看各个环节的接入情况'],users:['团队账号','为局域网内的同事分配访问权限'],audit:['操作记录','查看配置变更和导出任务的处理记录']}; +views['order-center']=['订单中心','按订单版本查看 BPM、PDF、归档与通知步骤']; +views['mail-batches']=['邮件批次','查看分类模板批次、冻结收件人与发送结果']; async function api(route,body,{signal}={}) { const response=await fetch('/api'+route,{signal,credentials:'same-origin',keepalive:route.endsWith('/login/close'),method:body===undefined?'GET':'POST',headers:body?{'Content-Type':'application/json'}:{},body:body?JSON.stringify(body):undefined}); const result=await response.json(); @@ -19,10 +21,10 @@ function notify(message,type='success') { function badge(status){const [label,color]=statusMap[status] || ['待处理','secondary'];return `${label}`;} function navItem(id,symbol){return `${symbol}${views[id][0]}`;} function shell() { - root.innerHTML=`自动处理未启用${esc(currentUser.username)}${roles[currentUser.role]}退出订单通知自动化刷新数据`; - document.querySelector('#logout').onclick=async()=>{++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});currentUser=null;clearInterval(refreshTimer);await boot();}; + root.innerHTML=`自动处理未启用${esc(currentUser.username)}${roles[currentUser.role]}退出订单通知自动化刷新数据`; + document.querySelector('#logout').onclick=async()=>{if(window.OrderWorkflowViews?.canLeave()===false)return;window.OrderWorkflowViews?.dispose();++viewGeneration;await window.BpmLogin?.dispose();await api('/logout',{});currentUser=null;clearInterval(refreshTimer);await boot();}; document.querySelector('#refresh').onclick=()=>renderView().catch(error=>notify(error.message,'danger')); - document.querySelectorAll('[data-view]').forEach(link=>link.onclick=()=>{document.querySelector('#sidebar-menu').classList.remove('show');}); + document.querySelectorAll('[data-view]').forEach(link=>link.onclick=event=>{if(link.dataset.view===currentView)event.preventDefault();document.querySelector('#sidebar-menu').classList.remove('show');}); } function empty(title,text){return `▤${title}${text}`;} function readOnlyNote(){return currentUser.role==='admin'?'':`当前账号可查看配置。修改配置请联系管理员。`;} @@ -67,17 +69,19 @@ async function viewUsers(container,isActive=()=>true) { document.querySelector('#user-form').onsubmit=async event=>{event.preventDefault();try{await api('/users',{username:document.querySelector('#new-username').value,password:document.querySelector('#new-password').value,role:document.querySelector('#new-role').value});notify('账号已创建。');await viewUsers(container,isActive);}catch(error){notify(error.message,'danger');}}; } async function viewAudit(container,isActive=()=>true){const [legacy,workspace]=await Promise.all([api('/audit'),api('/workspace')]);if(!isActive())return;const audit=[...legacy.audit,...workspace.audit].sort((a,b)=>new Date(b.at)-new Date(a.at));container.innerHTML=`最近操作记录按时间展示最近 200 条${audit.length?`时间(北京时间)操作人操作详情${audit.slice(0,200).map(item=>`${formatDate(item.at)}${esc(item.actor)}${esc(window.WorkspaceViews.activityText(item.action))}${esc(item.detail)}`).join('')}`:empty('暂无操作记录','保存设置或导出订单后,可在这里查看。')}`;} -function viewRules(container){container.innerHTML=`订单识别与匹配等待业务表格提供业务表格确认字段对应预览匹配订单启用自动处理${empty('依据你的表格识别订单','暂无匹配规则')}`;} +function viewRules(container,isActive=()=>true){return window.OrderWorkflowViews.rules(container,isActive);} async function renderView() { if(!currentUser)return; + if(window.OrderWorkflowViews?.canLeave()===false){history.replaceState(null,'','#'+currentView);return;} + window.OrderWorkflowViews?.dispose(); const generation=++viewGeneration;const isActive=()=>generation===viewGeneration && !!currentUser; await window.BpmLogin?.dispose();if(!isActive())return; - const requested=location.hash.slice(1) || 'overview';currentView=views[requested]?requested:'overview'; + const requested=location.hash.slice(1).split('?')[0] || 'overview',resolved=requested==='order-rules'?'rules':requested;currentView=views[resolved]?resolved:'overview'; if(currentView==='users' && currentUser.role!=='admin')currentView='overview'; document.querySelectorAll('[data-view]').forEach(link=>link.classList.toggle('active',link.dataset.view===currentView)); document.querySelector('#view-title').textContent=views[currentView][0];document.querySelector('#view-description').textContent=views[currentView][1]; const container=document.querySelector('#content');container.innerHTML='正在加载…'; - const fn={health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,notifications:window.NotificationViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,supervisor:window.WorkspaceViews?.supervisor,records:viewRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,connections:viewConnections,users:viewUsers,audit:viewAudit,rules:viewRules}[currentView]; + const fn={'order-center':window.OrderWorkflowViews?.orders,'mail-batches':window.OrderWorkflowViews?.batches,health:window.HealthViews?.render,assistant:window.AssistantViews?.render,storage:window.StorageViews?.render,notifications:window.NotificationViews?.render,overview:viewOverview,calendar:window.WorkspaceViews?.calendar,exceptions:window.WorkspaceViews?.exceptions,bpm:window.WorkspaceViews?.bpm,supervisor:window.WorkspaceViews?.supervisor,records:viewRecords,schedule:viewSchedule,templates:viewTemplates,mail:window.MailViews?.accounts,connections:viewConnections,users:viewUsers,audit:viewAudit,rules:viewRules}[currentView]; try{await fn(container,isActive);}catch(error){if(isActive())container.innerHTML=`${esc(error.message)}`;} } async function authScreen() { @@ -85,8 +89,9 @@ async function authScreen() { root.innerHTML=`单订单通知中心团队协同工作台${initialize?'创建管理员账号':'登录工作台'}${setup.required && !setup.canSetup?'请先由部署机在本机地址创建管理员,再为团队开通账号。':''}账号密码${initialize?'设置至少 12 位密码,后续可在看板中创建同事账号。':''}${initialize?'首次设置仅允许从部署机访问。':'使用管理员分配的账号访问。'}界面基于 Tabler 开源模板`; document.querySelector('#login-form').onsubmit=async event=>{event.preventDefault();const button=event.target.querySelector('button[type="submit"]');button.disabled=true;try{const result=await api(initialize?'/bootstrap':'/login',{username:document.querySelector('#username').value,password:document.querySelector('#password').value});currentUser=result.user;enter();}catch(error){document.querySelector('#auth-error').textContent=error.message;}finally{button.disabled=false;}}; } -function enter(){window.HealthViews?.configure({api,esc,formatDate});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();renderView();clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser && currentView==='overview' && !document.hidden){const generation=++viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);} +function enter(){window.OrderWorkflowViews?.configure({api,esc,formatDate,notify,user:currentUser});window.HealthViews?.configure({api,esc,formatDate});window.AssistantViews?.configure({api,esc,formatDate,notify,user:currentUser});window.StorageViews?.configure({api,esc,formatDate,notify,user:currentUser});window.NotificationViews?.configure({api,esc,formatDate,notify,user:currentUser});window.OrderViews?.configure({api,esc,formatDate,notify,user:currentUser});window.MailViews?.configure({api,esc,formatDate,notify,user:currentUser});window.WorkspaceViews?.configure({api,esc,formatDate,notify,user:currentUser});shell();renderView();clearInterval(refreshTimer);refreshTimer=setInterval(()=>{if(currentUser && currentView==='overview' && !document.hidden){const generation=++viewGeneration;viewOverview(document.querySelector('#content'),()=>generation===viewGeneration && !!currentUser && currentView==='overview').catch(()=>{});}},15000);} async function boot(){try{const setup=await api('/bootstrap/status');currentUser=(await api('/me')).user;enter();}catch{await authScreen();}} -window.addEventListener('pagehide',()=>{window.BpmLogin?.dispose({unload:true});}); +window.addEventListener('beforeunload',event=>{if(window.OrderWorkflowViews?.hasChanges()){event.preventDefault();event.returnValue='';}}); +window.addEventListener('pagehide',()=>{window.OrderWorkflowViews?.dispose();window.BpmLogin?.dispose({unload:true});}); window.addEventListener('hashchange',()=>{if(currentUser)renderView();}); boot().catch(error=>{root.innerHTML=`${esc(error.message)}`;}); diff --git a/web/index.html b/web/index.html index 59366eb..8015140 100644 --- a/web/index.html +++ b/web/index.html @@ -1,3 +1,3 @@ 订单通知中心 -正在连接订单通知中心… +正在连接订单通知中心…
{{订单列表}}
PDF
${text}
${initialize?'首次设置仅允许从部署机访问。':'使用管理员分配的账号访问。'}界面基于 Tabler 开源模板