feat: integrate verified todo archive providers and settings contracts

This commit is contained in:
abaishu0730 committed 2026-10-19 13:42:23 +08:00
1 parent 20589dd950
commit eb92a4f033
20 files changed
+290 -320

No files matched your search

+3 -1
View File
@@ -27,8 +27,10 @@ class BpmOrderProvider{
async capture(connection,principal,row){
return this.saved(connection,principal,async storageState=>{
let entry=this.entries.get(connection.id)?.get(row.taskId);
const sameTask=candidate=>['taskId','instanceId','processName','nodeName','processVersion','revision'].every(key=>String(candidate[key]??'')===String(row[key]??''));
if(entry&&!sameTask(entry.row))throw fail('任务元数据已变化,请重新扫描核验原节点与版本。');
if((!entry||Date.now()-entry.at>5*60*1000)&&row.detailUrl?.includes('/YZSoft/Forms/Process.aspx')){
const rows=await this.client.scan(storageState),fresh=rows.find(r=>r.taskId===row.taskId&&r.instanceId===row.instanceId&&r.nodeName===row.nodeName&&r.processVersion===row.processVersion);
const rows=await this.client.scan(storageState),fresh=rows.find(sameTask);
if(!fresh)throw fail('此任务已不在原节点或版本,请重新扫描核验。');entry={url:fresh.detailUrl,row:fresh,at:Date.now()};
}
const request=await loadPlaywright().request.newContext({storageState,timeout:20000});let loaded,tables;
+5 -2
View File
@@ -1,14 +1,17 @@
const fs=require('node:fs');const path=require('node:path');
const {nextSlots}=require('../../shared/schedule.cjs');
const publicJob=({path:ignored,...job})=>({...job,downloadable:job.status==='success'});
async function dashboardApi({store,outputDir,workspace,mail,scanner,storage,user,route,request,response,body,reply,fail}){
async function dashboardApi({store,outputDir,workspace,mail,scanner,storage,orderRules,user,route,request,response,body,reply,fail}){
const handled=(...args)=>{reply(...args);return true;};
if(route==='/api/overview' && request.method==='GET') {
const jobs=store.jobs();const settings=store.settings();const mailChannels=mail?.store.channels()||[];const mailTemplates=mail?.store.templates()||[];
const today=new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date());
const todayJobs=jobs.filter(job=>new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date(job.updatedAt))===today);
const scan=scanner?.store.status();
return handled(200,{stats:{total:jobs.length,today:todayJobs.length,completed:jobs.filter(job=>job.status==='success').length,failed:jobs.filter(job=>['error','interrupted'].includes(job.status)).length,running:jobs.filter(job=>job.status==='running').length},scan,automation:{enabled:false,reason:'待核实并接入 BPM 业务规则,完整订单自动处理尚未启用。'},connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'订单规则表',ready:false,detail:'等待提供表格,随后配置列映射与筛选'},{name:'BPM 自动扫描',ready:!!scan?.runs.some(r=>r.status==='success'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 已收录 ${scan.total} 条流程`:'扫描服务未启动'},{name:'存储服务器',ready:!!storage?.store.servers().some(s=>s.enabled&&s.state.readable&&s.state.writable),detail:storage?`已配置 ${storage.store.servers().length} 个 SMB 存储服务器`:'存储服务未启动'},{name:'邮件渠道',ready:mailChannels.some(c=>c.state.smtp&&c.state.imap),detail:`已配置 ${mailChannels.length} 个邮箱`},{name:'邮件模板',ready:mailTemplates.some(t=>t.status==='active'),detail:`${mailTemplates.filter(t=>t.status==='active').length} 个已生效,${mailTemplates.filter(t=>t.status==='pending').length} 个待确认`},{name:'产品线群组',ready:settings.groups.length>0,detail:`已配置 ${settings.groups.length} 个产品线`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:jobs.slice(0,6).map(publicJob),audit:store.audit().slice(0,5)});
const rules=orderRules?.snapshot(),published=rules?.rules?.filter(r=>r.status==='enabled')||[];
const capabilities=rules?.capabilities||{},ready=['liveTodo','pdfExport','automaticArchive'].every(key=>capabilities[key]===true);
const automation={enabled:rules?.settings?.enabled===true,ready,reason:rules?.settings?.enabled!==true?'分类自动发信已暂停;请先完成类别字段、目录、邮箱与预览核验。':ready?'分类执行链路已完成实际接入检查。':'分类执行链路仍有未通过的实际检查,请查看订单执行中的阻塞原因。'};
return handled(200,{stats:{total:jobs.length,today:todayJobs.length,completed:jobs.filter(job=>job.status==='success').length,failed:jobs.filter(job=>['error','interrupted'].includes(job.status)).length,running:jobs.filter(job=>job.status==='running').length},scan,automation,connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'Excel 分类规则',ready:published.length>0,detail:`15类规则,已发布 ${published.length} 类;实际字段按流程版本核验`},{name:'BPM 待办执行',ready:capabilities.liveTodo===true,detail:capabilities.liveTodo===true?'真实待办接口检查通过;各类别仍需字段核验':'请在分类规则的订单执行中检查真实待办及字段'},{name:'到达历史扫描',ready:!!scan?.runs.some(r=>r.status==='success'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 已收录 ${scan.total} 条流程`:'历史扫描服务未启动'},{name:'存储服务器',ready:!!storage?.store.servers().some(s=>s.enabled&&s.state.readable&&s.state.writable),detail:storage?`已配置 ${storage.store.servers().length} 个 SMB 存储服务器`:'存储服务未启动'},{name:'邮件渠道',ready:mailChannels.some(c=>!c.readOnly&&c.state.smtp),detail:`已配置 ${mailChannels.length} 个邮箱`},{name:'邮件模板',ready:mailTemplates.some(t=>t.status==='active'),detail:`${mailTemplates.filter(t=>t.status==='active').length} 个已生效,${mailTemplates.filter(t=>t.status==='pending').length} 个待确认;按类别显式关联`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:jobs.slice(0,6).map(publicJob),audit:store.audit().slice(0,5)});
}
if(route==='/api/settings') {
if(request.method==='GET')return handled(200,store.settings());
+8 -1
View File
@@ -40,10 +40,17 @@ class RuntimeHealth {
const checkedAt=timestamp(c.state?.checkedAt),status=!checkedAt?'pending':c.state.smtp&&c.state.imap?'healthy':'error';
return {id:c.id,name:redact(c.name||'托管邮箱'),status,checkedAt,detail:redact(c.state?.message||'尚未检查 SMTP / IMAP。'),...this.remember('mail',c.id,{successAt:status==='healthy'?checkedAt:null,failureAt:status==='error'?checkedAt:null})};
}));
if(this.sources.execution)safe('execution','分类订单执行','#order-rules',()=>{
const data=this.sources.execution.snapshot(),names={liveTodo:'真实待办',pdfExport:'PDF 导出',automaticArchive:'归档校验'};
const items=Object.entries(names).map(([id,name])=>({id,name,global:true,status:data.capabilities?.[id]===true?'healthy':'pending',detail:data.capabilities?.[id]===true?'实际检查已通过;各类别仍需现场核验。':'尚未通过实际接入检查,请在分类规则查看阻塞原因。'}));
for(const task of data.tasks||[]){const status=['blocked','failed'].includes(task.status)?'error':task.status==='unknown'?'unknown':['capturing','preparing','archiving','running','sending'].includes(task.status)?'running':['archived','sent','pending'].includes(task.status)?'healthy':'pending';
items.push({id:task.id,owner:connections.find(c=>c.id===task.connectionId)?.owner,name:redact(task.processName||'订单执行任务'),status,checkedAt:timestamp(task.updatedAt),detail:redact(task.error||task.reason||task.blockedReason||'任务进度已持久保存,请在分类规则查看。'),...this.remember('execution',task.id,{successAt:status==='healthy'?task.updatedAt:null,failureAt:status==='error'?task.updatedAt:null})});}
return items;
});
return groups;
}
snapshot(user){
const now=Date.now(),groups=this.collect().map(g=>{if(!['bpm','scan'].includes(g.key)||user.role==='admin'||g.status==='unknown')return g;const items=g.items.filter(i=>i.owner===user.username);return {...g,items,status:groupStatus(items)};});
const now=Date.now(),groups=this.collect().map(g=>{if(!['bpm','scan','execution'].includes(g.key)||user.role==='admin'||g.status==='unknown')return g;const items=g.items.filter(i=>i.global||i.owner===user.username);return {...g,items,status:groupStatus(items)};});
let saved;try{saved=readSupervisor(this.stateDir);}catch{saved={state:null,events:[],autostart:null};}
const s=saved.state,managed=Boolean(this.instanceId&&s?.childInstanceId===this.instanceId),fresh=managed&&now-Date.parse(s.updatedAt)<45000;
const guard=managed?{status:fresh?s.status:'stale',heartbeatAt:s.heartbeatAt,updatedAt:s.updatedAt,restartCount:s.restartCount,childStartedAt:s.childStartedAt,reason:s.reason,nextRestartAt:s.nextRestartAt,events:saved.events.map(e=>({at:e.at,kind:e.kind,code:e.detail.code,delayMs:e.detail.delayMs,reason:e.detail.reason}))}:{status:'unmanaged',restartCount:0,events:[]};
+15 -7
View File
@@ -16,8 +16,8 @@ function targetFor(storage,directory){
return {server:selected.server,relative:selected.rest.slice(selected.root.length).join('/')};
}
class OrderArchiveProvider{
constructor({storage,outputDir,renderer=renderSnapshot,clock=()=>new Date()}={}){this.storage=storage;this.outputDir=path.resolve(outputDir,'order-execution');this.renderer=renderer;this.clock=clock;this.last=null;}
capabilities(){return {automaticArchive:!!this.last?.success,checkedAt:this.last?.at,message:this.last?.message||'尚无经过实际生成和共享目录读回校验的订单归档。'};}
constructor({storage,outputDir,renderer=renderSnapshot,clock=()=>new Date(),journal}={}){this.storage=storage;this.outputDir=path.resolve(outputDir,'order-execution');this.renderer=renderer;this.clock=clock;this.last=null;this.journal=journal;this.supportsRecovery=!!journal;}
capabilities(){return {automaticArchive:!!this.last?.success,pdfExport:!!this.last?.success,checkedAt:this.last?.at,message:this.last?.message||'尚无经过实际生成和共享目录读回校验的订单归档。'};}
async probe(rule){
try{
const target=targetFor(this.storage,rule.archiveDirectory);await this.storage.check(target.server.id);
@@ -27,25 +27,33 @@ class OrderArchiveProvider{
this.last={success:true,at:this.clock().toISOString(),message:'PDF 运行环境及目标共享目录读写检查成功。'};return {...this.capabilities(),pdfExport:true};
}catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}
}
async archive({order,rule,snapshot,taskId}){
const event=order.event||order,chosen=rule.filenameDate==='appDate'?event.appDate:rule.filenameDate==='receivedAt'?event.receivedAt:this.clock();
async archive(input){try{return await this.performArchive(input);}catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}}
async performArchive({order,rule,snapshot,taskId}){
const id=taskId||order.id,previous=id&&this.journal?.get('archive-intents',id);
if(previous&&previous.sourceHash!==order.sourceHash)throw fail('归档来源版本与持久意图不一致,请人工核验。');
const event=order.event||order,chosen=previous?.chosen||(rule.filenameDate==='appDate'?event.appDate:rule.filenameDate==='receivedAt'?event.receivedAt:this.clock());
if(!['appDate','receivedAt','archiveDate'].includes(rule.filenameDate)||!Number.isFinite(+new Date(chosen)))throw fail('规则的文件名日期来源缺失或无效。');
const target=targetFor(this.storage,rule.archiveDirectory),safe=v=>String(v||'').replace(/[<>:"/\\|?*\x00-\x1f]/g,'_').replace(/[. ]+$/g,'').slice(0,65);
const target=targetFor(this.storage,previous?.directory||rule.archiveDirectory),safe=v=>String(v||'').replace(/[<>:"/\\|?*\x00-\x1f]/g,'_').replace(/[. ]+$/g,'').slice(0,65);
const filename=[event.orderNo,day(chosen),event.serialNum||event.documentNum].map(safe).join('_')+'.pdf';segments(filename);
if(!event.orderNo||!(event.serialNum||event.documentNum))throw fail('归档文件缺少订单号或流程流水号。');
// Renderer public extension contract remains its original four-field filename.
const renderInput={...snapshot,metadata:{order:String(event.orderNo),project:'流程归档',model:'订单',serial:String(event.serialNum||event.documentNum)}};
let generated;
try{
generated=await this.renderer(renderInput,{outputDir:this.outputDir});
generated=previous?{path:previous.localPath}:await this.renderer(renderInput,{outputDir:this.outputDir});
const [root,file]=await Promise.all([fs.realpath(this.outputDir),fs.realpath(generated.path)]);if(!inside(root,file)||file===root)throw fail('生成文件超出订单输出目录。');
const local=await fs.readFile(file),digest=crypto.createHash('sha256').update(local).digest('hex');if(local.subarray(0,5).toString()!=='%PDF-')throw fail('订单 PDF 内容无效。');
if(previous&&(previous.sha256!==digest||previous.size!==local.length))throw fail('待恢复的本地 PDF 已变化,禁止覆盖归档。');
const intent=previous||{id,sourceHash:order.sourceHash,chosen:new Date(chosen).toISOString(),directory:rule.archiveDirectory,filename,localPath:file,sha256:digest,size:local.length};
if(id&&this.journal&&!previous)this.journal.put('archive-intents',intent);
if(previous?.evidence){const bytes=await this.read(previous.evidence.files[0]);if(bytes.length!==local.length||crypto.createHash('sha256').update(bytes).digest('hex')!==digest)throw fail('已归档文件读回校验失败。');this.last={success:true,at:this.clock().toISOString(),message:'已归档文件再次读回核验通过。'};return previous.evidence;}
const receipt=await this.storage.run(target.server.id,async(server,signal)=>{
const saved=await this.storage.operation(server,'archive',[file,filename,target.relative],signal);
const saved=await this.storage.operation(server,'archive',[file,intent.filename,target.relative],signal);
const check=await this.storage.operation(server,'readFile',[saved.relativePath],signal),bytes=Buffer.from(check.bytes);
if(bytes.length!==local.length||crypto.createHash('sha256').update(bytes).digest('hex')!==digest||saved.sha256!==digest||saved.bytes!==bytes.length)throw fail('共享目录归档读回校验失败。');return saved;
});
const evidence={archivedAt:this.clock().toISOString(),files:[{name:receipt.filename,path:path.win32.join('\\\\'+target.server.host,target.server.share,...segments(target.server.directory),...segments(receipt.relativePath)),sha256:digest,size:local.length,kind:'pdf'}]};
if(id&&this.journal)this.journal.put('archive-intents',{...intent,evidence});
this.last={success:true,at:evidence.archivedAt,message:'PDF 已生成、归档并读回校验。'};return evidence;
}catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}
}