diff --git a/src/modules/order-execution/api.cjs b/src/modules/order-execution/api.cjs index 0bfc679..2bdf2ba 100644 --- a/src/modules/order-execution/api.cjs +++ b/src/modules/order-execution/api.cjs @@ -1,7 +1,7 @@ 'use strict'; const {fail}=require('../order-rules/validation.cjs'); async function orderExecutionApi({execution,orderRules,dispatcher,workspace,user,sessionId,url,route,method,body,reply}){ - const task=/^\/api\/order-execution\/tasks\/([\w-]+)\/retry$/.exec(route),resend=/^\/api\/order-rules\/batches\/([\w-]+)\/resend$/.exec(route); + const task=/^\/api\/order-execution\/tasks\/([\w-]+)\/(retry|resolve)$/.exec(route),resend=/^\/api\/order-rules\/batches\/([\w-]+)\/resend$/.exec(route); const sample=/^\/api\/order-rules\/field-samples\/(list|capture)$/.exec(route),mapping=/^\/api\/order-rules\/field-mappings\/(draft|check|activate)$/.exec(route); const catalog=route==='/api/order-rules/field-samples/catalog',propose=route==='/api/order-rules/field-mappings/propose'; if(!route.startsWith('/api/order-execution')&&!['/api/order-rules/fields','/api/order-rules/adapters'].includes(route)&&!resend&&!sample&&!mapping&&!catalog&&!propose)return false; @@ -17,7 +17,7 @@ async function orderExecutionApi({execution,orderRules,dispatcher,workspace,user } if(method==='GET'&&route==='/api/order-rules/fields'){ if(!execution&&user.role!=='admin')fail('订单执行服务未启动。',503); - const fields=execution?execution.snapshot({user,sessionId}).fields:orderRules.fields(); + const fields=execution?execution.snapshot({user,sessionId},{includeFieldEvidence:true}).fields:orderRules.fields(); reply(200,url?.searchParams.get('view')==='directory'?require('./field-directory.cjs').fieldDirectory(fields):fields);return true; } if(!execution&&!mapping&&route!=='/api/order-rules/adapters'&&!resend)fail('订单执行服务未启动。',503); @@ -27,7 +27,7 @@ async function orderExecutionApi({execution,orderRules,dispatcher,workspace,user const principal={user,sessionId};let result; if(route==='/api/order-execution/scan'){ if(!body||Object.keys(body).some(k=>!['connectionId','idempotencyKey'].includes(k)))fail('扫描参数无效。');result=await execution.scan(body,principal); - }else if(task){if(!body||Object.keys(body).some(k=>!['version','idempotencyKey','note'].includes(k)))fail('重试参数无效。');result=await execution.retry(task[1],body,principal);} + }else if(task){if(!body||Object.keys(body).some(k=>!(task[2]==='resolve'?['version','idempotencyKey','note','resolution']:['version','idempotencyKey','note']).includes(k)))fail('重试参数无效。');result=await execution[task[2]](task[1],body,principal);} else{ if(user?.role!=='admin')fail('仅管理员可维护字段适配或人工补发。',403); if(sample){ diff --git a/src/modules/order-execution/coordinator.cjs b/src/modules/order-execution/coordinator.cjs index 23ab06d..d4c973c 100644 --- a/src/modules/order-execution/coordinator.cjs +++ b/src/modules/order-execution/coordinator.cjs @@ -9,6 +9,7 @@ class OrderExecutionCoordinator{ constructor({store,workspace,provider,archive,mail,dashboard,clock=()=>new Date(),settings=()=>({}),calendar=()=>[],onException,systemPrincipal}){ Object.assign(this,{store,workspace,provider,archive,mail,dashboard,clock,settings,calendar,onException,systemPrincipal}); store.executionSources=()=>this.workspace.snapshot().connections.filter(c=>c.status!=='disabled').map(c=>c.id); + store.ownerForConnection=id=>{try{return this.workspace.getConnection(id)?.owner||'';}catch{return this.workspace.recordSources?.().find(c=>c.id===id)?.owner||'';}}; store.activeDiscoveries=0; for(const scan of store.all('execution-scans'))if(scan.status==='scanning')store.put('execution-scans',{...scan,status:'failed',error:'扫描被重启中断,请重新扫描。'}); this.tail=Promise.resolve();this.stopped=false;this.timer=null;this.query=store.get('execution-query','main')||{id:'main',status:'idle'};this.blockers=[];this.runtimeRuleChecks=new Set(); @@ -47,20 +48,16 @@ class OrderExecutionCoordinator{ const published=this.store.get('rules',order.ruleSnapshot?.id)?.published; if(published?.status!=='enabled')return; try{ - // A cold provider must really read the authorized form to establish its - // capture capability; successful stored archives are never exported again. - if(forceCapture||(await this.provider.capabilities()).pdfExport!==true){ - const captured=await this.provider.capture(connection,principal,clone(task.row)); - this.validateCapture(task,connection,captured); - } + if(!order.archive?.files?.length||typeof this.archive.read!=='function')throw Error('持久归档缺少可读回的文件证据。'); + for(const file of order.archive.files){const bytes=await this.archive.read(file);if(!Buffer.isBuffer(bytes)||bytes.length!==file.size||crypto.createHash('sha256').update(bytes).digest('hex')!==file.sha256)throw Error('持久归档读回校验失败。');} const ruleKey=hash([order.ruleSnapshot.id,order.ruleSnapshot.version,order.ruleSnapshot.archiveDirectory]); const probeRule=this.runtimeRuleChecks.has(ruleKey)&&this.store.providersReady()?undefined:order.ruleSnapshot; - await this.refreshCapabilities(probeRule); + const a=probeRule&&this.archive.probe?await this.archive.probe(probeRule):await this.archive.capabilities(); + const p=await this.provider.capabilities();this.store.capabilities={liveTodo:p.liveTodo===true,pdfExport:a.pdfExport===true,automaticArchive:a.automaticArchive===true}; if(this.store.providersReady())this.runtimeRuleChecks.add(ruleKey); task.runtimeCheck={at:this.now(),status:this.store.providersReady()?'ready':'blocked'}; task.error=this.store.providersReady()?order.error||null:'已归档订单的待办采集或归档运行条件尚未通过复核。'; }catch(error){ - this.store.capabilities={...this.store.capabilities,pdfExport:false,automaticArchive:false}; this.blockers.push('已归档订单运行条件复核失败:'+error.message); task.runtimeCheck={at:this.now(),status:'blocked',error:error.message}; task.error='已归档订单运行条件复核失败:'+error.message; @@ -83,14 +80,11 @@ class OrderExecutionCoordinator{ try{this.connection(task.connectionId,principal);return true;} catch{return false;} } - snapshot(principal){ - const allowed=id=>{ - if(!principal||principal.user?.role==='admin')return true; - try{const connection=this.workspace.getConnection(id);return connection.status!=='disabled'&&connection.owner===principal.user?.username;} - catch{return false;} - }; + snapshot(principal,{includeFieldEvidence=false}={}){ + const allowed=id=>!principal||require('../order-rules/access.cjs').canReadConnection(this.workspace,principal.user,id); const fields=this.store.fields(); fields.samples=fields.samples.filter(sample=>allowed(sample.sample.connectionId)); + if(principal&&!includeFieldEvidence){for(const sample of fields.samples){delete sample.sample?.fields;delete sample.fields;}delete fields.processes;} if(principal?.user?.role!=='admin')require('./field-samples.cjs').filterFieldEvidence(fields); const latest=[this.query,...this.store.all('execution-scans')] .filter(query=>!query.connectionId||allowed(query.connectionId)) @@ -99,23 +93,32 @@ class OrderExecutionCoordinator{ const tasks=this.store.all('execution-tasks').filter(task=>allowed(task.connectionId)).map(task=>{ const order=task.orderId&&this.store.get('orders',task.orderId); const activeStatus=['failed','unknown','blocked','capturing','archiving'].includes(task.status); - return {...task,processName:task.row.processName,title:task.row.title,serialNum:task.row.serialNum, + const safe=clone(task);const summary=row=>row?Object.fromEntries(['source','instanceId','taskId','revision','processName','processVersion','nodeName','receivedAt','serialNum','title'].filter(k=>Object.hasOwn(row,k)).map(k=>[k,row[k]])):null; + if(task.conflict)safe.revisionEvidence={previous:summary(task.previousTaskId?this.store.get('execution-tasks',task.previousTaskId)?.row:task.row),incoming:summary(task.conflictRow)};delete safe.conflictRow;safe.row=summary(task.row); + return {...safe,processName:task.row.processName,title:task.row.title,serialNum:task.row.serialNum, canRetry:this.canRetry(task,principal),status:activeStatus?task.status:order?.status||task.status, error:task.error||order?.error||null}; }).reverse(); - const blockers=[...this.blockers,...this.store.discoveryBlockers(this.store.snapshot().window?.end,allowed)]; + const blockers=[...(!principal||principal.user?.role==='admin'?this.blockers:[]),...this.store.discoveryBlockers(this.store.snapshot().window?.end,allowed)]; return {tasks,capabilities:clone(this.store.capabilities),fields,query,blockers}; } request(input){if(typeof input?.idempotencyKey!=='string'||!/^[\w:.-]{1,160}$/.test(input.idempotencyKey))fail('请提供有效的操作幂等标识。');} - scan(input,principal){ + notifyDiscovery(payload){ + if(!payload||typeof payload.connectionId!=='string'||typeof payload.runId!=='string'||!Array.isArray(payload.rows)||!Number.isFinite(Date.parse(payload.startedAt))||!Number.isFinite(Date.parse(payload.finishedAt)))fail('完整对账线索无效。'); + const prior=this.store.get('execution-discoveries',payload.connectionId); + if(prior&&Date.parse(prior.startedAt)>Date.parse(payload.startedAt))return; + if(prior?.runId===payload.runId)return; + this.store.put('execution-discoveries',{...clone(payload),id:payload.connectionId,status:'pending'}); + } + scan(input,principal,{rows:trustedRows,runId,startedAt}={}){ // Reserve the shared boundary synchronously, including work queued behind a retry. this.store.activeDiscoveries++; return this.serialize(async()=>{ this.request(input);const connection=this.connection(input.connectionId,principal),key=hash(['scan',connection.id,principal.user.username,input.idempotencyKey]); if(this.store.get('execution-requests',key))return this.snapshot(principal); - this.query={id:'main',status:'scanning',connectionId:connection.id,startedAt:this.now()};this.store.put('execution-query',this.query);this.store.put('execution-scans',{...this.query,id:connection.id}); + this.query={id:'main',status:'scanning',connectionId:connection.id,startedAt:startedAt||this.now()};this.store.put('execution-query',this.query);this.store.put('execution-scans',{...this.query,id:connection.id}); try{ - const rows=await this.provider.scan(connection,principal);if(!Array.isArray(rows))throw Error('待办提供器返回格式无效。'); + const rows=trustedRows===undefined?await this.provider.scan(connection,principal):clone(trustedRows);if(!Array.isArray(rows))throw Error('待办提供器返回格式无效。'); let considered=0;const observed=new Set(),discovered=[]; // Commit the entire discovery set before probes, captures, exceptions or archives yield. this.store.transaction(()=>{ @@ -125,11 +128,17 @@ class OrderExecutionCoordinator{ if(!rules.length)continue; // Historical rows are ignored before any capture or export. const window=this.store.snapshot().window;if(window&&Number.isFinite(Date.parse(row.receivedAt))&&Date.parse(row.receivedAt)r.categoryId))],status:'identified',step:'capture',createdAt:this.now()};this.persist(task);} - if(hash(task.row)!==hash(row)){task.status='blocked';task.error='同一事件修订内容冲突,需核对源版本。';task.conflict=true;this.persist(task);} + if(!task){ + const previous=this.store.all('execution-tasks').find(t=>!t.supersededBy&&t.orderId&&t.connectionId===connection.id&&t.row.source===row.source&&String(t.row.instanceId)===String(row.instanceId)&&String(t.row.taskId)===String(row.taskId)&&String(t.row.revision)!==String(row.revision)); + task={id,version:0,connectionId:connection.id,owner:connection.owner||'',row:clone(row),categoryIds:[...new Set(rules.map(r=>r.categoryId))],status:'identified',step:'capture',createdAt:this.now()}; + if(previous){task.previousTaskId=previous.id;task.orderId=previous.orderId;task.conflictRow=clone(row);task.conflict=true;task.status='blocked';task.error='来源出现新业务修订,请核对原订单证据后采用或忽略。';} + this.persist(task); + } + if(hash(task.row)!==hash(row)&&task.ignoredRevisionHash!==hash(row)){task.conflictRow=clone(row);task.status='blocked';task.error='同一事件修订内容冲突,需核对源版本。';task.conflict=true;this.persist(task);} discovered.push(task); } this.query={...this.query,rowCount:rows.length,targetCount:considered,processedCount:0,discoveredAt:this.now()}; @@ -138,6 +147,7 @@ class OrderExecutionCoordinator{ await this.refreshCapabilities(); for(const task of discovered){ try{ + if(task.supersededBy||task.revisionIgnored)continue; if(task.conflict){await this.exception(task,connection,false);continue;} this.reconcileArchive(task); if(task.conflict||task.status==='unknown'||task.step==='archive'&&task.status==='failed')continue; @@ -149,7 +159,7 @@ class OrderExecutionCoordinator{ if(['pending','batched'].includes(order.status))await this.checkArchivedRuntime(task,order,connection,principal); continue; } - await this.execute(task,connection,principal); + await this.execute(task,connection,principal,{automatic:input.automatic===true}); }finally{ this.query.processedCount++; this.store.put('execution-query',this.query); @@ -165,7 +175,7 @@ class OrderExecutionCoordinator{ const order=task.orderId&&this.store.get('orders',task.orderId); if(!order?.archive||!['pending','batched'].includes(order.status))continue; const window=this.store.snapshot().window; - if(window&&Date.parse(order.event.receivedAt){this.store.activeDiscoveries--;}).then(()=>this.snapshot(principal)); } - async execute(task,connection,principal){ + async execute(task,connection,principal,{automatic=false}={}){ try{ + if(automatic&&!this.store.settings().processingEnabled)return; if(!task.sampleId){ task.status='capturing';task.step='capture';this.persist(task); const {sample,snapshot}=await this.provider.capture(connection,principal,clone(task.row)); @@ -190,12 +201,38 @@ class OrderExecutionCoordinator{ if(order.status==='blocked'){await this.exception(task,connection,false);return;} if(order.archive){task.step='complete';task.status=order.status;this.persist(task);await this.exception(task,connection,true);return;} if(!['identified','preparing'].includes(order.status))return; + if(automatic&&!this.store.settings().processingEnabled)return; task.status='archiving';task.step='archive';this.persist(task); const evidence=await this.archive.archive({order:clone(order),rule:clone(order.ruleSnapshot),snapshot:clone(captured.snapshot),taskId:task.id}); order=this.store.recordArchive(order.id,evidence,principal.user.username);task.status=order.status;task.error=order.error;task.step='complete';this.persist(task); await this.exception(task,connection,true); }catch(error){const uncertain=task.status==='archiving';task.status=uncertain&&this.archive.supportsRecovery!==true?'unknown':'failed';task.error=uncertain?'归档结果待核验,需人工受控恢复:'+error.message:error.message;this.persist(task);await this.exception(task,connection,false);} } + resolve(id,input,principal){return this.serialize(async()=>{ + if(principal?.user?.role!=='admin')fail('仅管理员可核验修订。',403); + const {frozen,validate,digest}=require('../order-rules/migrations.cjs');validate(input); + if(!['adopt','ignore'].includes(input.resolution))fail('请选择采用新修订或忽略变更。'); + const key=digest(['revision',id,principal.user.username,input.idempotencyKey]),inputHash=digest(input),prior=this.store.get('execution-requests',key); + if(prior){if(prior.inputHash!==inputHash)fail('幂等标识已用于不同修订核验。',409);return this.snapshot(principal);} + const task=this.store.get('execution-tasks',id);if(!task||task.version!==input.version||!task.conflict||!task.conflictRow)fail('修订冲突或任务版本已变化。',409); + const connection=this.connection(task.connectionId,principal),order=task.orderId&&this.store.get('orders',task.orderId); + if(frozen(this.store,order)||['sending','sent','unknown'].includes(task.status))fail('冻结或结果不确定的任务必须从原批次核验,禁止采用新修订。',409); + let captured; + if(input.resolution==='adopt'){captured=await this.provider.capture(connection,principal,clone(task.conflictRow));this.validateCapture({...task,row:task.conflictRow},connection,captured);} + this.store.transaction(()=>{ + const current=this.store.get('execution-tasks',id),liveOrder=task.orderId&&this.store.get('orders',task.orderId); + if(current.version!==input.version||frozen(this.store,liveOrder))fail('核验期间任务已变化,请刷新。',409); + this.store.put('execution-revisions',{id:id+':'+task.version,task:clone(task),order:clone(liveOrder),resolution:input.resolution,note:input.note,actor:principal.user.username,at:this.now()}); + if(captured){ + const sample=this.store.recordCapture({sample:captured.sample,snapshot:captured.snapshot,taskId:task.id});task.sampleId=sample.id;task.row=clone(task.conflictRow);task.localGeneration=(task.localGeneration||1)+1; + if(liveOrder){liveOrder.sample=clone(captured.sample);liveOrder.sourceHash=digest(captured.sample);liveOrder.archiveHistory=[...(liveOrder.archiveHistory||[]),...(liveOrder.archive?[{generation:liveOrder.archiveGeneration||1,evidence:liveOrder.archive}]:[])];liveOrder.archiveGeneration=(liveOrder.archiveGeneration||1)+1;liveOrder.archive=null;liveOrder.status='blocked';liveOrder.error='已采用新修订,等待按当前规则重新识别。';this.store.put('orders',liveOrder);} + if(task.previousTaskId){const previous=this.store.get('execution-tasks',task.previousTaskId);if(previous){previous.supersededBy=task.id;previous.status='ignored';this.persist(previous);}} + task.status='identified';task.step='identify'; + }else{task.ignoredRevisionHash=hash(task.conflictRow);task.status=liveOrder?.status||'identified';if(task.previousTaskId){task.priorOrderId=task.orderId;delete task.orderId;task.revisionIgnored=true;task.status='ignored';}} + task.conflict=false;delete task.conflictRow;task.error=null;this.persist(task); + this.store.put('execution-requests',{id:key,inputHash,at:this.now()});this.store.audit(principal.user.username,'核验订单修订',id+' '+input.resolution+':'+input.note); + });return this.snapshot(principal); + });} retry(id,input,principal){ return this.serialize(async()=>{ this.request(input); @@ -228,11 +265,21 @@ class OrderExecutionCoordinator{ if(!recovered&&!task.exceptionId){const item=this.workspace.createException({title:'订单任务受阻:'+String(task.row.serialNum||task.row.taskId),description:'执行任务 '+task.id+':'+String(task.error).slice(0,9000),component:task.step==='archive'?'archive':'rules',priority:'high',owner:connection.owner||''},actor,members);task.exceptionId=item.id;this.persist(task);} if(recovered&&task.exceptionId){const item=this.workspace.snapshot().exceptions?.find(e=>e.id===task.exceptionId);if(item?.status==='in_progress')this.workspace.actOnException(item.id,{version:item.version,action:'verify',note:'执行重试成功,等待负责人核验归档与订单证据。'},actor,members);task.recovery={at:this.now(),status:'awaiting_verification',exceptionId:task.exceptionId};this.persist(task);this.workspace.record?.(actor,'订单执行恢复待核验','执行任务 '+task.id+';异常 '+task.exceptionId);} } - start(){if(this.timer||this.stopped)return;this.timer=setInterval(()=>this.background().catch(()=>{}),30000);this.timer.unref?.();} + start(){if(this.timer||this.stopped)return;this.timer=setInterval(()=>this.background().catch(error=>{this.store.put('execution-background',{id:'main',status:'failed',at:this.now(),error:error.message});}),30000);this.timer.unref?.();} async background(){ - if(!this.systemPrincipal||!this.store.settings().enabled)return; + if(!this.systemPrincipal||!this.store.settings().processingEnabled)return; const day=new Date(this.clock().getTime()+8*3600000).toISOString().slice(0,10);if(!dayPolicy(day,this.settings()?.schedule||{},this.calendar()).scan)return; - for(const connection of this.workspace.snapshot().connections||[])if(connection.owner&&connection.status==='connected')await this.scan({connectionId:connection.id,idempotencyKey:'background:'+Math.floor(this.clock().getTime()/30000)},this.systemPrincipal); + for(const connection of this.workspace.snapshot().connections||[]){ + if(!connection.owner||connection.status!=='connected')continue; + const hint=this.store.get('execution-discoveries',connection.id); + const last=this.store.get('execution-scans',connection.id); + const window=this.store.snapshot().window,cutoffDue=window?.available&&(!last?.startedAt||Date.parse(last.startedAt){});} async stop(){this.stopped=true;clearInterval(this.timer);this.timer=null;await this.drain();} diff --git a/src/modules/order-rules/access.cjs b/src/modules/order-rules/access.cjs new file mode 100644 index 0000000..cb5814f --- /dev/null +++ b/src/modules/order-rules/access.cjs @@ -0,0 +1,10 @@ +'use strict'; +function canReadConnection(workspace,user,id){ + if(!user)return false;if(user.role==='admin')return true;if(!id||!user.username)return false; + try{const sources=workspace?.recordSources?.()||workspace?.connectionSources?.();const c=sources?sources.find(c=>c.id===id):workspace?.getConnection?.(id);return !!c?.owner&&c.owner===user.username;}catch{return false;} +} +const canReadOrder=(workspace,user,order)=>!!order&&canReadConnection(workspace,user,order.sample?.connectionId||order.event?.connectionId||order.connectionId); +function canReadBatch(workspace,user,batch,store){if(!user||!batch)return false;if(user.role==='admin')return true;return Array.isArray(batch.orderIds)&&batch.orderIds.length>0&&batch.orderIds.every(id=>canReadOrder(workspace,user,store.get('orders',id)));} +function publicOrder(order){if(!order)return null;const value=structuredClone(order);delete value.sample;delete value.trace;if(value.event){delete value.event.fields;delete value.event.raw;}return value;} +function publicSnapshot(store,workspace,user){const value=store.snapshot();value.orders=value.orders.filter(o=>canReadOrder(workspace,user,o)).map(publicOrder);value.batches=value.batches.filter(b=>canReadBatch(workspace,user,b,store));value.issues=(store.all?.('business-issues')||[]).filter(issue=>user?.role==='admin'||issue.orderIds?.length&&issue.orderIds.every(id=>canReadOrder(workspace,user,store.get('orders',id))));if(user?.role!=='admin')value.audit=[];return value;} +module.exports={canReadConnection,canReadOrder,canReadBatch,publicOrder,publicSnapshot}; diff --git a/src/modules/order-rules/api.cjs b/src/modules/order-rules/api.cjs index 0a60eba..31ce0b8 100644 --- a/src/modules/order-rules/api.cjs +++ b/src/modules/order-rules/api.cjs @@ -3,7 +3,7 @@ const {fail}=require('./validation.cjs'); async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,reply,response}){ if(route!=='/api/order-rules'&&!route.startsWith('/api/order-rules/'))return false; if(!orderRules)fail('分类通知规则服务未启动。',503); - if(route==='/api/order-rules'&&method==='GET'){reply(200,orderRules.snapshot());return true;} + if(route==='/api/order-rules'&&method==='GET'){reply(200,require('./access.cjs').publicSnapshot(orderRules,workspace,user));return true;} if(route==='/api/order-rules/import-template'&&method==='GET'){ if(user.role!=='admin')fail('仅管理员可导出规则配置。',403); const bytes=await require('./import-template.cjs').template(orderRules);response.writeHead(200,{'Content-Type':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','Content-Disposition':"attachment; filename*=UTF-8''"+encodeURIComponent('分类规则.xlsx')});response.end(bytes);return true; @@ -11,6 +11,8 @@ async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,re if(method!=='POST')fail('没有找到此规则操作。',404); if(user.role==='viewer')fail('只读成员不能编辑规则或提交样本。',403); const actor=user.username; + const migration=/^\/api\/order-rules\/rules\/([\w-]+)\/migration\/(preview|apply)$/.exec(route); + if(migration){if(user.role!=='admin')fail('仅管理员可迁移规则。',403);if(!body||Object.keys(body).some(k=>!['version','idempotencyKey','note'].includes(k)))fail('迁移参数无效。');reply(200,orderRules[migration[2]==='preview'?'previewMigration':'applyMigration'](migration[1],body,actor));return true;} const trial=/^\/api\/order-rules\/rules\/([\w-]+)\/trial$/.exec(route); if(trial){ if(body?.draft&&user.role!=='admin')fail('仅管理员可试运行编辑中的规则草稿。',403); diff --git a/src/modules/order-rules/dispatcher.cjs b/src/modules/order-rules/dispatcher.cjs index 1f0f523..2fefe12 100644 --- a/src/modules/order-rules/dispatcher.cjs +++ b/src/modules/order-rules/dispatcher.cjs @@ -6,10 +6,6 @@ const {nextSlots}=require('../../shared/schedule.cjs'); const {windowForCutoff}=require('./window.cjs'); const {fail}=require('./validation.cjs'); -function sameWindow(batch,cutoff,window){ - return batch.status==='prepared'&&Date.parse(batch.cutoff)===Date.parse(cutoff)&&batch.window?.start===window.start&&batch.window?.end===window.end&&batch.window?.startInclusive===true&&batch.window?.endInclusive===false; -} - function freeze(value){ if(value&&typeof value==='object'){for(const item of Object.values(value))freeze(item);Object.freeze(value);} return value; @@ -32,35 +28,28 @@ class OrderRuleDispatcher{ return task; } async perform(now){ + for(const batch of this.store.snapshot().batches||[])if(batch.status==='prepared'&&!batch.manual&&now-Date.parse(batch.cutoff)>1800000)this.store.finishSending(batch.id,'failed','冻结发送队列超过30分钟,请负责人核验后受控补发。'); if(!this.ready())return; - const config=freeze(structuredClone(this.store.settings())); - const schedule=this.settings()?.schedule,calendar=this.calendar(); + const config=freeze(structuredClone(this.store.settings())),schedule=this.settings()?.schedule,calendar=this.calendar(); if(!schedule?.times?.length)return; const signature=JSON.stringify([schedule,calendar]); - if(!this.schedule||this.schedule.signature!==signature){this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};return;} - if(!this.schedule.next||Date.parse(this.schedule.next)>now.getTime())return; - const cutoff=this.schedule.next; - if(now.getTime()-Date.parse(cutoff)>60000){this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};return;} - if(!this.ready())return; - try{ - await this.mail.exclusive(config.channelId,async()=>{ - if(!this.ready())return; - // A busy mailbox cannot consume the slot or reserve any orders. Recovery - // applies only to this exact business window, never to earlier history. - const window=windowForCutoff(cutoff,schedule,calendar); - if(this.store.discoveryBlockers(cutoff).length)return; - const fresh=this.store.prepare(cutoff,'系统调度',window).filter(batch=>sameWindow(batch,cutoff,window)); - const existing=(this.store.snapshot().batches||[]).filter(batch=>sameWindow(batch,cutoff,window)); - const batches=[...new Map([...fresh,...existing].map(batch=>[batch.id,freeze(structuredClone(batch))])).values()]; - let interrupted=false; - for(const batch of batches){ - if(!this.ready()){interrupted=true;break;} - if(batch.status!=='prepared')continue; - if(await this.dispatch(batch,config)===false){interrupted=true;break;} - } - if(!interrupted)this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]}; - }); - }catch(error){if(error.status!==409)throw error;} + if(!this.schedule||this.schedule.signature!==signature){const current=require('./window.cjs').upcomingWindow(now,schedule,calendar);this.schedule={signature,next:current?.available?current.end:nextSlots(schedule,now,1,calendar)[0]};} + const cutoff=this.schedule.next,canPrepare=cutoff&&now-Date.parse(cutoff)>=0&&now-Date.parse(cutoff)<=60000; + const queued=(this.store.snapshot().batches||[]).some(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000); + if(!canPrepare&&!queued)return; + try{await this.mail.exclusive(config.channelId,async()=>{ + if(!this.ready())return; + if(canPrepare&&!this.store.discoveryBlockers(cutoff).length){const window=windowForCutoff(cutoff,schedule,calendar);this.store.prepare(cutoff,'系统调度',window);} + // A frozen collection is immutable. Queue time is distinct from collection time. + const batches=(this.store.snapshot().batches||[]).filter(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000); + for(const batch of batches){if(!this.ready())break; + let expected;try{expected=windowForCutoff(batch.cutoff,schedule,calendar);}catch{continue;} + const legacyStart=new Date(Date.parse(batch.cutoff)+8*3600000).toISOString().slice(0,10)+'T00:00:00+08:00'; + if(!batch.window||batch.window.end!==expected.end||![Date.parse(expected.start),Date.parse(legacyStart)].includes(Date.parse(batch.window.start))||batch.window.startInclusive!==true||batch.window.endInclusive!==false)continue; + if(batch.createdAt&&(Date.parse(batch.createdAt)>Date.parse(batch.cutoff)+60000||Date.parse(batch.createdAt)60000)this.schedule={signature,next:nextSlots(schedule,this.clock(),1,calendar)[0]}; } async attachments(batch,config){ const result=[];let total=0; @@ -83,7 +72,7 @@ class OrderRuleDispatcher{ this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。');return; } const attachments=await this.attachments(batch,config); - if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。'); + if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>1800000)throw Error('冻结发送队列超过30分钟。'); const channel=freeze(structuredClone(this.mail.store.channelSecret(config.channelId))); if(channel.readOnly)throw Error('只读邮箱不能用于分类通知发送。'); transport=this.mail.smtpFactory(channel.smtp); @@ -93,7 +82,7 @@ class OrderRuleDispatcher{ // unsent reservation recoverable instead of turning a scan barrier into failure. if(!manual&&(this.store.discoveryBlockers(batch.cutoff).length||this.store.batchIncomplete(batch)))return false; if(manual?this.stopped||!this.providersReady()||!this.store.providersReady():!this.ready()||this.store.settings().channelId!==config.channelId)throw Error('发送已暂停或配置已变更。'); - if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。'); + if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>1800000)throw Error('冻结发送队列超过30分钟。'); this.mail.store.guard(channel.id,channel.version); this.store.beginSending(batch.id,{manual});sending=true; const result=await transport.sendMail({from:{address:channel.email,name:channel.name},to:[...batch.to],cc:[...batch.cc],subject:batch.subject,text:batch.text,html:batch.html,attachments,messageId:`<${batch.id}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true}); @@ -135,7 +124,7 @@ class OrderRuleDispatcher{ } start(){ if(this.timer||this.stopped)return; - this.timer=setInterval(()=>this.tick().catch(()=>{}),30000);this.timer.unref?.(); + this.timer=setInterval(()=>this.tick().catch(error=>this.store.recordIssue?.('dispatcher-background',{component:'mail',error:error.message})),30000);this.timer.unref?.(); } async stop(){ this.stopped=true;clearInterval(this.timer);this.timer=null; diff --git a/src/modules/order-rules/matching.cjs b/src/modules/order-rules/matching.cjs index c55fb56..35de489 100644 --- a/src/modules/order-rules/matching.cjs +++ b/src/modules/order-rules/matching.cjs @@ -89,7 +89,7 @@ function previewMatch(rules, adapters, input, {mappingEvidence=false}={}) { function describeRule(rule) { const date = { appDate: '申请日期', receivedAt: '接收日期', archiveDate: '归档日期' }[rule.filenameDate] || '待选择的日期'; - return `${rule.name}:满足任一流程节点配对(${scopesFor(rule).map(row=>`“${row.processName}” → “${row.nodeName}”`).join(';')||'待选择'})时归入本类别。本时段内同类别订单合并一封,通知与更改分别汇总,更早历史不补发。正常工作日首封只取当天零点到首个时点,第二封取两个时点之间;周一首封从上个工作日最后时点起算。${rule.attachPdf ? '附电子流 PDF;' : ''}文件以订单号、${date}、流水编号命名。BPM 节点由人工办理。`; + return `${rule.name}:满足任一流程节点配对(${scopesFor(rule).map(row=>`“${row.processName}” → “${row.nodeName}”`).join(';')||'待选择'})时归入本类别。本时段内同类别订单合并一封,通知与更改分别汇总,更早历史不补发。每封从前一个有效发送时点连续积累;首封覆盖前一发送日晚间与休息日,第二封取两个时点之间。${rule.attachPdf ? '附电子流 PDF;' : ''}文件以订单号、${date}、流水编号命名。BPM 节点由人工办理。`; } module.exports = { previewMatch, describeRule }; diff --git a/src/modules/order-rules/migrations.cjs b/src/modules/order-rules/migrations.cjs new file mode 100644 index 0000000..ec6f039 --- /dev/null +++ b/src/modules/order-rules/migrations.cjs @@ -0,0 +1,13 @@ +'use strict'; +const crypto=require('node:crypto'); +const {fail}=require('./validation.cjs'); +const {previewMatch}=require('./matching.cjs'); +const canonical=v=>Array.isArray(v)?v.map(canonical):v&&typeof v==='object'?Object.fromEntries(Object.keys(v).sort().map(k=>[k,canonical(v[k])])):v; +const digest=v=>crypto.createHash('sha256').update(JSON.stringify(canonical(v))).digest('hex'); +function frozen(store,order){return !!order&&(!!order.batchId||!!order.blockedByBatchId||['batched','sending','sent','unknown'].includes(order.status)||store.all('batches').some(b=>b.orderIds?.includes(order.id)));} +function validate(input){if(!input||!Number.isInteger(input.version)||typeof input.idempotencyKey!=='string'||!/^[\w:.-]{1,160}$/.test(input.idempotencyKey)||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请提供版本、幂等标识和至少5字依据。');} +const outputEvent=event=>{const value={...event};delete value.ruleVersion;delete value.adapterId;return value;}; +function projection(store,order,rule){const result=previewMatch([rule],store.adapters(),order.sample);if(!result.valid)fail('订单 '+order.id+' 无法应用当前规则:'+result.issues.join(';'),409);return {result,archiveChanged:digest([outputEvent(order.event),order.ruleSnapshot?.archiveDirectory,order.ruleSnapshot?.filenameDate])!==digest([outputEvent(result.event),rule.archiveDirectory,rule.filenameDate])};} +function preview(store,id,input){validate(input);const rule=store.get('rules',id)?.published;if(!rule||rule.status!=='enabled'||input.version!==rule.version)fail('已发布规则版本已变化或未启用。',409);const items=[],excluded=[];for(const order of store.all('orders').filter(o=>o.ruleSnapshot?.id===id||o.categoryId===rule.categoryId)){if(frozen(store,order)||!['blocked','identified','preparing','archived','pending'].includes(order.status)){excluded.push({id:order.id,status:order.status,reason:'冻结或已终结订单不可迁移'});continue;}const p=projection(store,order,rule);items.push({id:order.id,archiveChanged:p.archiveChanged,fromVersion:order.ruleSnapshot?.version,toVersion:rule.version});}return {ruleId:id,version:rule.version,items,excluded};} +function apply(store,id,input,actor){validate(input);return store.transaction(()=>{const requestId=digest([id,actor,input.idempotencyKey]),inputHash=digest(input),prior=store.get('migration-requests',requestId);if(prior){if(prior.inputHash!==inputHash)fail('幂等标识已用于不同迁移。',409);return prior.result;}const result=preview(store,id,input),rule=store.get('rules',id).published;for(const item of result.items){const order=store.get('orders',item.id),p=projection(store,order,rule);if(p.archiveChanged){order.archiveHistory=[...(order.archiveHistory||[]),...(order.archive?[{generation:order.archiveGeneration||1,evidence:order.archive}]:[])];order.archiveGeneration=(order.archiveGeneration||1)+1;order.archive=null;order.status='identified';}order.event=p.result.event;order.trace=p.result;order.ruleSnapshot=structuredClone(rule);order.categoryId=rule.categoryId;order.updatedAt=store.now();order.error=null;store.put('orders',order);for(const task of store.all('execution-tasks').filter(t=>t.orderId===order.id)){task.status=order.status;task.step=order.archive?'complete':'identify';task.error=null;task.version=(task.version||0)+1;store.put('execution-tasks',task);}}store.put('migration-requests',{id:requestId,inputHash,result,at:store.now()});store.audit(actor,'批量应用已发布规则',id+':'+input.note.trim());return result;});} +module.exports={preview,apply,frozen,validate,digest}; diff --git a/src/modules/order-rules/store.cjs b/src/modules/order-rules/store.cjs index 36e5303..9c86148 100644 --- a/src/modules/order-rules/store.cjs +++ b/src/modules/order-rules/store.cjs @@ -22,6 +22,7 @@ class RuleStore{ CREATE TABLE IF NOT EXISTS records(kind TEXT NOT NULL,id TEXT NOT NULL,payload BLOB NOT NULL,PRIMARY KEY(kind,id));`); this.transaction(()=>{ if(!this.get('settings','main'))this.put('settings',{id:'main',version:1,enabled:false,channelId:'',maxMessageBytes:20971520}); + const settings=this.get('settings','main');if(settings.processingEnabled===undefined)this.put('settings',{...settings,processingEnabled:settings.enabled,processingSince:settings.enabled?this.now():null}); for(const rule of seedRules())if(!this.get('rules',rule.id)){ const override=seedOverrides.find(r=>r.id===rule.id); const draft=override?validateRule({...rule,...override},rule):rule; @@ -58,13 +59,15 @@ class RuleStore{ all(kind){return this.db.prepare('SELECT id,payload FROM records WHERE kind=? ORDER BY rowid').all(kind).map(r=>this.vault.decode(kind+':'+r.id,r.payload));} put(kind,value){this.db.prepare('INSERT INTO records VALUES(?,?,?) ON CONFLICT(kind,id) DO UPDATE SET payload=excluded.payload').run(kind,value.id,this.vault.encode(kind+':'+value.id,value));return value;} audit(actor,action,detail){this.put('audit',{id:crypto.randomUUID(),at:this.now(),actor:String(actor||'系统'),action,detail});} - settings(){const {id,...settings}=this.get('settings','main');return settings;} + settings(){const {id,...settings}=this.get('settings','main');return {...settings,processingEnabled:settings.processingEnabled??settings.enabled,processingSince:settings.processingSince??null};} saveSettings(input,actor){return this.transaction(()=>{ const old=this.settings(); - if(!input||Object.keys(input).some(k=>!['version','enabled','channelId','maxMessageBytes'].includes(k))||input.version!==old.version)fail('设置已变化,请刷新。',409); + if(!input||Object.keys(input).some(k=>!['version','enabled','processingEnabled','processingSince','channelId','maxMessageBytes'].includes(k))||input.version!==old.version)fail('设置已变化,请刷新。',409); if(typeof input.enabled!=='boolean'||typeof input.channelId!=='string'||input.channelId.length>100||!Number.isInteger(input.maxMessageBytes)||input.maxMessageBytes<1024||input.maxMessageBytes>100*1024*1024)fail('邮箱或邮件大小限制无效。'); if(input.enabled&&(!this.providersReady()||!input.channelId))fail('待办接入、PDF 导出与自动归档尚未全部联调,暂不能启用自动发送。',409); - this.put('settings',{...input,id:'main',version:old.version+1});this.audit(actor,'保存分类通知设置',input.enabled?'已启用':'已暂停');return this.settings(); + if(input.processingEnabled!==undefined&&typeof input.processingEnabled!=='boolean')fail('自动处理开关无效。'); + const processingEnabled=input.processingEnabled??old.processingEnabled;const processingSince=processingEnabled&&!old.processingEnabled?this.now():old.processingSince; + this.put('settings',{...input,processingEnabled,processingSince,id:'main',version:old.version+1});this.audit(actor,'保存分类通知设置',input.enabled?'已启用':'已暂停');return this.settings(); });} snapshot(){ const rules=this.all('rules').map(record=>({...record.draft,status:record.published?.status||'draft',activationVersion:record.activationVersion||0,hasDraft:!record.published||record.draft.version!==record.published.version,publishedVersion:record.published?.version||null,trialVersion:record.trialVersion,mappingIssue:record.mappingIssue||null,explanation:describeRule(record.draft),validationIssues:publicationIssues(record.draft,this.adapters())})); @@ -131,6 +134,8 @@ class RuleStore{ const order={id,sourceHash,event:result.event||copy(sample),sample:copy(sample),ruleSnapshot:rule?copy(rule):null,categoryId:result.categoryId||rule?.categoryId||'',status:result.valid&&ready&&enabled?'identified':'blocked',error:result.valid?(!enabled?'该类别规则已暂停。':ready?null:'待办接入、PDF 导出和自动归档待联调。'):result.issues.join(';'),ingestedAt:this.now(),updatedAt:this.now(),archive:null,batchId:null,trace:result}; const window=upcomingWindow(this.clock(),this.schedule(),this.calendar()); if(window&&validDate(sample.receivedAt)&&Date.parse(sample.receivedAt)b.categoryId===order.categoryId&&b.window&&inWindow(sample.receivedAt,b.window)); + if(frozen){order.status='blocked';order.blockedByBatchId=frozen.id;order.error='本接收时段的类别已冻结,新增订单须负责人核验,不能混入已冻结邮件。';this.put('orders',order);this.recordIssue('late:'+order.id,{component:'rules',error:order.error,batchId:frozen.id,orderIds:[order.id]});} this.put('orders',order);this.audit(actor,'识别订单任务',id);return order; });} recordArchive(id,evidence,actor){return this.transaction(()=>{ @@ -149,24 +154,27 @@ class RuleStore{ retryArchive(id,note,actor){return this.transaction(()=>{ if(typeof note!=='string'||note.trim().length<5||note.length>2000)fail('请填写至少5字修复依据。'); if(!this.capabilities.automaticArchive)fail('自动归档接入待联调。',409); - const order=this.get('orders',id);if(!order||!order.ruleSnapshot||order.status!=='blocked')fail('当前任务不能重试归档。',409); + const order=this.get('orders',id);if(!order||!order.ruleSnapshot||order.status!=='blocked'||order.blockedByBatchId||require('./migrations.cjs').frozen(this,order))fail('当前任务不能重试归档。',409); order.status=transition('order',order.status,'retry');order.error=null;order.updatedAt=this.now();this.put('orders',order);this.audit(actor,'重试归档',id+':'+note.trim());return order; });} + previewMigration(id,input){return require('./migrations.cjs').preview(this,id,input);} + applyMigration(id,input,actor){return require('./migrations.cjs').apply(this,id,input,actor);} recheck(id,input,actor){return this.transaction(()=>{ if(typeof input?.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请填写至少5字的重新识别依据。'); const order=this.get('orders',id); - if(!order||order.batchId||!['blocked','identified','preparing','archived','pending'].includes(order.status))fail('仅未进入批次的待处理订单可以重新识别。',409); + if(!order||order.blockedByBatchId||require('./migrations.cjs').frozen(this,order)||!['blocked','identified','preparing','archived','pending'].includes(order.status))fail('仅未进入批次的待处理订单可以重新识别。',409); const published=this.matchingPublications(order.sample); const result=previewMatch(published,this.adapters(),order.sample),rule=published.find(r=>r.id===result.ruleId); if(!result.valid||rule?.status!=='enabled')fail(result.issues.join(';')||'对应规则尚未启用。',409); order.event=result.event;order.ruleSnapshot=copy(rule);order.categoryId=rule.categoryId;order.trace=result; - order.archive=null;order.status=this.providersReady()?'identified':'blocked'; + order.archiveHistory=[...(order.archiveHistory||[]),...(order.archive?[{generation:order.archiveGeneration||1,evidence:order.archive}]:[])];order.archiveGeneration=(order.archiveGeneration||1)+1;order.archive=null;order.status=this.providersReady()?'identified':'blocked'; order.error=order.status==='blocked'?'待办接入、PDF 导出和自动归档待联调。':null;order.updatedAt=this.now(); this.put('orders',order);this.audit(actor,'应用当前规则重新识别',id+':'+input.note.trim());return order; });} discoveryBlockers(cutoff,allowed=()=>true){ if(!this.executionSources)return []; const blockers=[]; + for(const hint of this.all('execution-discoveries'))if(hint.status==='pending'&&allowed(hint.connectionId))blockers.push('连接 '+hint.connectionId+' 完整对账线索尚未处理。'); if(this.activeDiscoveries>0)blockers.push('待办扫描尚未完成,不能冻结或发送不完整类别。'); const window=cutoff?windowForCutoff(cutoff,this.schedule(),this.calendar()):null; const relevant=this.all('execution-tasks').filter(t=>!window||inWindow(t.row?.receivedAt,window)); @@ -183,31 +191,26 @@ class RuleStore{ return this.all('execution-tasks').some(task=>task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(task.row?.receivedAt))||inWindow(task.row?.receivedAt,window))&&(task.conflict||['identified','blocked','failed','unknown','capturing','archiving'].includes(task.status)||task.runtimeCheck?.status==='blocked')); } batchIncomplete(batch){ - return this.categoryIncomplete(batch.categoryId,batch.window)||this.all('orders').some(order=>order.categoryId===batch.categoryId&&inWindow(order.event?.receivedAt||order.sample?.receivedAt,batch.window)&&order.status!=='ignored'&&!batch.orderIds.includes(order.id)); + return this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&(task.conflict||task.runtimeCheck?.status==='blocked'||['failed','unknown','capturing','archiving'].includes(task.status))); } + recordIssue(id,input){const old=this.get('business-issues',id);const orderIds=input.orderIds||[];const owners=[...new Set(this.all('execution-tasks').filter(t=>orderIds.includes(t.orderId)).map(t=>t.owner).concat(orderIds.map(id=>this.get('orders',id)).filter(Boolean).map(o=>this.ownerForConnection?.(o.sample?.connectionId))).filter(Boolean))];return this.put('business-issues',{...old,...input,id,status:old?.status==='resolved'?'awaiting_verification':old?.status||'open',owners,ownerStatus:owners.length?'assigned':'unassigned',verification:'核对订单归档、冻结批次和邮件服务器记录后人工处理。',createdAt:old?.createdAt||this.now(),updatedAt:this.now()});} prepare(cutoff,actor,requestedWindow){return this.transaction(()=>{ if(!validDate(cutoff))fail('请选择包含时区的有效发送截止时间。'); const window=windowForCutoff(cutoff,this.schedule(),this.calendar()); if(requestedWindow&&(requestedWindow.start!==window.start||requestedWindow.end!==window.end))fail('发送时段与业务日历不一致。',409); - for(const batch of this.all('batches'))if(batch.status==='prepared'&&Date.parse(batch.cutoff)r.published?.status==='enabled')){const categoryId=record.published.categoryId,existing=this.all('batches').find(b=>b.categoryId===categoryId&&Date.parse(b.cutoff)===Date.parse(cutoff));this.put('window-results',{id:categoryId+':'+cutoff,categoryId,cutoff,status:existing?'frozen':blockers.length?'blocked':'empty',batchId:existing?.id||null,error:blockers.join(';')||null,updatedAt:this.now()});} + if(blockers.length)return []; const grouped=new Map(),batches=[]; for(const order of this.all('orders')){ - if(!['identified','preparing','archived','pending','blocked'].includes(order.status)||!order.categoryId)continue; + if(!['identified','preparing','archived','pending','blocked'].includes(order.status)||!order.categoryId||order.blockedByBatchId)continue; const at=order.event.receivedAt||order.sample.receivedAt; - if(validDate(at)&&Date.parse(at)o.id)});continue;} const rule=orders[0].ruleSnapshot;if(!rule)continue; if(this.all('batches').some(b=>b.categoryId===rule.categoryId&&Date.parse(b.cutoff)===Date.parse(cutoff)&&!(b.status==='cancelled'&&b.resolution?.resolution==='retry')))continue; const published=this.get('rules',rule.id)?.published; @@ -215,9 +218,10 @@ class RuleStore{ if(!error&&orders.some(o=>o.status!=='pending'))error='本类别存在字段、文件或归档尚未准备完成的订单。'; let snapshot; if(!error)try{snapshot=buildBatch(rule,orders,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window});snapshot=applyBodyTemplate(snapshot,this.templateResolver?.(rule.categoryId,rule),orders,this.settings().maxMessageBytes);}catch(cause){error=cause.message;} - if(error){for(const order of orders){order.error=error;this.put('orders',order);}continue;} + if(error){this.put('window-results',{id:rule.categoryId+':'+cutoff,categoryId:rule.categoryId,cutoff,status:'blocked',error,updatedAt:this.now()});this.recordIssue('build:'+rule.categoryId+':'+cutoff,{component:'rules',error,cutoff,categoryId:rule.categoryId,orderIds:orders.map(o=>o.id)});for(const order of orders){order.error=error;this.put('orders',order);}continue;} const batch={...snapshot,id:crypto.randomUUID(),version:1,status:'prepared',createdAt:this.now(),ruleSnapshot:copy(rule),channelId:this.settings().channelId,error:null}; - this.put('batches',batch); + this.put('batches',batch);this.put('window-results',{id:rule.categoryId+':'+cutoff,categoryId:rule.categoryId,cutoff,status:'frozen',batchId:batch.id,updatedAt:this.now()}); + const issue=this.get('business-issues','build:'+rule.categoryId+':'+cutoff);if(issue)this.put('business-issues',{...issue,status:'awaiting_verification',updatedAt:this.now()}); for(const order of orders){order.status=transition('order',order.status,'batch');order.batchId=batch.id;order.error=null;order.updatedAt=this.now();this.put('orders',order);} this.audit(actor,'固定分类邮件批次',batch.id+' '+orders.length+'单');batches.push(batch); } @@ -239,6 +243,7 @@ class RuleStore{ batch.version=(batch.version||1)+1;batch.status=transition('batch',batch.status,{sent:'sent',unknown:'unknown',failed:'fail'}[status]);batch.error=message;batch.finishedAt=this.now();this.put('batches',batch); this.updateBatchOrders(batch,status==='failed'?'pending':status,message); if(status==='failed')for(const oid of batch.orderIds){const order=this.get('orders',oid);if(order?.batchId===batch.id){order.batchId=null;this.put('orders',order);}} + if(['failed','unknown'].includes(status))this.recordIssue('batch:'+id,{component:'mail',batchId:id,error:message,orderIds:batch.orderIds}); this.audit('系统发送','更新批次结果',id+' '+status);return batch; });} resolve(id,input,actor,{controlled=false}={}){return this.transaction(()=>{ diff --git a/src/modules/order-rules/window.cjs b/src/modules/order-rules/window.cjs index 1a941e0..3b71f2a 100644 --- a/src/modules/order-rules/window.cjs +++ b/src/modules/order-rules/window.cjs @@ -15,9 +15,7 @@ function windowForCutoff(cutoff,schedule,overrides=[]){ const index=times.findIndex(time=>at(day,time)===end);if(index<0)invalid('截止时间必须与已配置的发送时点一致。'); let start=index?at(day,times[index-1]):at(day,'00:00'); if(index===0){ - const prior=dayOf(new Date(+date-DAY)); - const monday=new Date(day+'T00:00:00Z').getUTCDay()===1; - if(monday||!dayPolicy(prior,schedule,overrides).send){ + { let found=false; for(let back=1;back<=370;back++){ const previous=dayOf(new Date(+date-back*DAY)); diff --git a/src/modules/storage/order-archive.cjs b/src/modules/storage/order-archive.cjs index 3fe9087..df9afe2 100644 --- a/src/modules/storage/order-archive.cjs +++ b/src/modules/storage/order-archive.cjs @@ -5,6 +5,8 @@ const crypto=require('node:crypto'); const {segments,inside}=require('./files.cjs'); const {renderSnapshot}=require('../pdf/exporter.cjs'); const {archiveFilename}=require('./order-filename.cjs'); +const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])):value; +const fingerprint=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex'); const fail=message=>Object.assign(new Error(message),{status:409}); function targetFor(storage,directory){ if(typeof directory!=='string'||!directory.startsWith('\\\\'))throw fail('请在分类规则选择已配置服务器的共享目录。'); @@ -16,24 +18,34 @@ 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(),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;} + constructor({storage,outputDir,renderer=renderSnapshot,clock=()=>new Date(),journal}={}){this.storage=storage;this.outputDir=path.resolve(outputDir,'order-execution');this.renderer=renderer;this.clock=clock;this.last=null;this.probes=new Map();this.journal=journal;this.supportsRecovery=!!journal;} capabilities(){return {automaticArchive:!!this.last?.success,pdfExport:!!this.last?.success,checkedAt:this.last?.at,message:this.last?.message||'尚无经过实际生成和共享目录读回校验的订单归档。'};} async probe(rule){ + const key=fingerprint(rule.archiveDirectory),cached=this.probes.get(key);if(cached&&+this.clock()-Date.parse(cached.checkedAt)<300000)return cached; + let temporary; try{ + await fs.mkdir(this.outputDir,{recursive:true});temporary=await fs.mkdtemp(path.join(this.outputDir,'probe-')); const target=targetFor(this.storage,rule.archiveDirectory);await this.storage.check(target.server.id); - const generated=await this.renderer({html:'

订单归档能力核验

',styles:[],images:[],metadata:{order:'probe',project:'probe',model:'probe',serial:'probe'}},{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 generated=await this.renderer({html:'

订单归档能力核验

',styles:[],images:[],metadata:{order:'probe',project:'probe',model:'probe',serial:'probe'}},{outputDir:temporary}); + const [root,file]=await Promise.all([fs.realpath(temporary),fs.realpath(generated.path)]);if(!inside(root,file)||file===root)throw fail('核验输出超出工作目录。'); const bytes=await fs.readFile(file);if(bytes.subarray(0,5).toString()!=='%PDF-')throw fail('PDF 运行环境检查失败。'); - 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;} + this.last={success:true,at:this.clock().toISOString(),message:'PDF 运行环境及目标共享目录读写检查成功。'};const result={...this.capabilities(),pdfExport:true};this.probes.set(key,result);return result; + }catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}finally{if(temporary)await fs.rm(temporary,{recursive:true,force:true});} } 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()); + const identity=taskId||order.id,generation=order.archiveGeneration||1,id=identity+':g'+generation; + let previous=this.journal?.get('archive-intents',id); + const legacy=generation===1&&!previous&&this.journal?.get('archive-intents',identity); + const event=order.event||order,chosen=previous?.chosen||legacy?.chosen||(rule.filenameDate==='appDate'?event.appDate:rule.filenameDate==='receivedAt'?event.receivedAt:this.clock()); const filename=archiveFilename(event,rule.filenameDate,chosen); - const target=targetFor(this.storage,previous?.directory||rule.archiveDirectory); + const outputFingerprint=fingerprint({sourceHash:order.sourceHash,event,directory:rule.archiveDirectory,filenameDate:rule.filenameDate,filename,chosen:new Date(chosen).toISOString(),generation}); + if(legacy){ + if(legacy.sourceHash!==order.sourceHash||legacy.directory!==rule.archiveDirectory||legacy.filename!==filename)throw fail('旧归档意图与当前输出不一致,请建立新归档代次。'); + previous={...legacy,id,legacyIntentId:identity,archiveGeneration:generation,outputFingerprint};this.journal.put('archive-intents',previous); + } + if(previous&&(previous.sourceHash!==order.sourceHash||previous.outputFingerprint!==outputFingerprint))throw fail('归档输出与本代持久意图不一致,请建立新归档代次。'); + const target=targetFor(this.storage,rule.archiveDirectory); // 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; @@ -42,7 +54,7 @@ class OrderArchiveProvider{ 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}; + const intent=previous||{id,archiveGeneration:generation,outputFingerprint,sourceHash:order.sourceHash,chosen:new Date(chosen).toISOString(),directory:rule.archiveDirectory,filename,localPath:file,sha256:digest,size:local.length}; if(id&&this.journal&&!previous)this.journal.put('archive-intents',intent); if(previous?.evidence){const bytes=await this.read(previous.evidence.files[0]);if(bytes.length!==local.length||crypto.createHash('sha256').update(bytes).digest('hex')!==digest)throw fail('已归档文件读回校验失败。');this.last={success:true,at:this.clock().toISOString(),message:'已归档文件再次读回核验通过。'};return previous.evidence;} const receipt=await this.storage.run(target.server.id,async(server,signal)=>{ diff --git a/tests/order-rules/batches.test.cjs b/tests/order-rules/batches.test.cjs index 3c673fd..515bdf2 100644 --- a/tests/order-rules/batches.test.cjs +++ b/tests/order-rules/batches.test.cjs @@ -94,7 +94,7 @@ test('batch refuses inverted windows and windows that do not end at its cutoff', const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs'); const dispatchCutoff='2026-10-20T01:00:00.000Z'; -const dispatchWindow={start:'2026-10-19T16:00:00.000Z',end:dispatchCutoff,label:'当天首时段',startInclusive:true,endInclusive:false}; +const dispatchWindow={start:'2026-10-19T09:00:00.000Z',end:dispatchCutoff,label:'当天首时段',startInclusive:true,endInclusive:false}; function dispatchFixture(t,{ready=true,capabilities=true,enabled=true,verify,send,result}={}){ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'rule-batch-'));t.after(()=>fs.rmSync(dir,{recursive:true,force:true})); const content=Buffer.from('%PDF-1.7\ntrusted evidence');const file=path.join(dir,'order.pdf');fs.writeFileSync(file,content); @@ -102,7 +102,7 @@ function dispatchFixture(t,{ready=true,capabilities=true,enabled=true,verify,sen const record={prepared:0,begun:0,smtp:0,locked:0,status:'prepared',messages:[],sent:[]}; const config={version:1,enabled,channelId:'channel1'}; const caps={liveTodo:capabilities,pdfExport:capabilities,automaticArchive:capabilities}; - const store={discoveryBlockers:()=>[],batchIncomplete:()=>false,settings:()=>({...config}),snapshot:()=>({capabilities:{...caps},batches:[structuredClone({...batch,status:record.status})]}),prepare:(date,actor,window)=>{record.prepared++;assert.equal(date,dispatchCutoff);assert.equal(actor,'系统调度');assert.equal(window.start,'2026-10-19T16:00:00.000Z');assert.equal(window.end,dispatchCutoff);assert.equal(window.startInclusive,true);assert.equal(window.endInclusive,false);return [batch];},beginSending:id=>{assert.equal(id,'batch1');record.begun++;record.status='sending';},finishSending:(id,status,message)=>{assert.equal(id,'batch1');record.status=status;record.messages.push(message);}}; + const store={discoveryBlockers:()=>[],batchIncomplete:()=>false,settings:()=>({...config}),snapshot:()=>({capabilities:{...caps},batches:[structuredClone({...batch,status:record.status})]}),prepare:(date,actor,window)=>{record.prepared++;assert.equal(date,dispatchCutoff);assert.equal(actor,'系统调度');assert.equal(window.start,'2026-10-19T09:00:00.000Z');assert.equal(window.end,dispatchCutoff);assert.equal(window.startInclusive,true);assert.equal(window.endInclusive,false);return [batch];},beginSending:id=>{assert.equal(id,'batch1');record.begun++;record.status='sending';},finishSending:(id,status,message)=>{assert.equal(id,'batch1');record.status=status;record.messages.push(message);}}; const mail={exclusive:async(id,fn)=>{assert.equal(id,'channel1');record.locked++;return fn();},store:{channelSecret:id=>({id,version:2,email:'sender@example.com',name:'通知',smtp:{host:'unused.invalid'}}),guard:(id,version)=>{assert.equal(id,'channel1');assert.equal(version,2);}},smtpFactory:()=>{record.smtp++;return {verify:async()=>{if(verify)await verify({batch,config,caps,file});},sendMail:async message=>{record.sent.push(message);if(send)return send(message);return result||{accepted:['user@example.com','copy@example.com'],rejected:[]};},close:()=>{}};}}; const schedule={times:['09:00','17:00'],timezone:'Asia/Shanghai',weekends:false,mode:'product_line',missed:'next_window'}; let now=new Date('2026-10-20T00:59:00.000Z'); @@ -120,7 +120,7 @@ test('dispatcher never prepares or touches SMTP while disabled or any provider i test('dispatcher verifies recorded bytes and sends the frozen recipients and content once per schedule',async t=>{ const f=dispatchFixture(t,{verify:({batch})=>{batch.subject='changed';batch.to=['intruder@example.com'];}}); await due(f);await f.dispatcher.tick(); - assert.equal(f.record.status,'sent');assert.equal(f.record.prepared,1);assert.equal(f.record.begun,1);assert.equal(f.record.locked,1); + assert.equal(f.record.status,'sent');assert.equal(f.record.prepared,2);assert.equal(f.record.begun,1);assert.equal(f.record.locked,2); const sent=f.record.sent[0];assert.equal(sent.subject,'已冻结 SO-1');assert.deepEqual(sent.to,['user@example.com']);assert.deepEqual(sent.cc,['copy@example.com']); assert.equal(sent.attachments[0].content.toString(),'%PDF-1.7\ntrusted evidence');assert.equal(sent.disableFileAccess,true);assert.equal(sent.disableUrlAccess,true);assert.equal(sent.attachments[0].path,undefined); await f.dispatcher.stop(); @@ -171,7 +171,7 @@ test('dispatcher never carries a prepared morning batch into the afternoon slot await due(f);assert.equal(f.record.begun,0); f.config.enabled=true;f.setNow('2026-10-20T08:59:00.000Z');await f.dispatcher.tick(); f.setNow('2026-10-20T09:00:00.000Z');await f.dispatcher.tick(); - assert.equal(f.record.status,'prepared');assert.equal(f.record.sent.length,0);await f.dispatcher.stop(); + assert.equal(f.record.status,'failed');assert.equal(f.record.sent.length,0);await f.dispatcher.stop(); }); test('dispatcher ignores old, future and mismatched-window prepared batches at the current slot',async t=>{ @@ -188,13 +188,13 @@ test('dispatcher resumes a paused prepared batch only within the same slot grace assert.equal(f.record.sent.length,1);await f.dispatcher.stop(); }); -test('dispatcher does not resume a prepared batch after its slot grace expires',async t=>{ +test('dispatcher resumes a frozen batch after collection ends within queue allowance',async t=>{ const f=dispatchFixture(t);const exclusive=f.mail.exclusive;let busy=true; f.mail.exclusive=async(id,work)=>{if(busy)throw Object.assign(Error('busy'),{status:409});return exclusive(id,work);}; - await due(f);busy=false;f.setNow('2026-10-20T01:01:01.000Z');await f.dispatcher.tick();assert.equal(f.record.prepared,0);assert.equal(f.record.sent.length,0);await f.dispatcher.stop(); + await due(f);busy=false;f.setNow('2026-10-20T01:01:01.000Z');await f.dispatcher.tick();assert.equal(f.record.prepared,0);assert.equal(f.record.sent.length,1);await f.dispatcher.stop(); }); -test('dispatcher rechecks slot expiration after asynchronous SMTP verification',async t=>{ - const f=dispatchFixture(t,{verify:()=>f.setNow('2026-10-20T01:01:01.000Z')}); +test('dispatcher rechecks thirty minute queue expiration after asynchronous SMTP verification',async t=>{ + const f=dispatchFixture(t,{verify:()=>f.setNow('2026-10-20T01:30:01.000Z')}); await due(f);assert.equal(f.record.begun,0);assert.equal(f.record.sent.length,0);assert.equal(f.record.status,'failed');await f.dispatcher.stop(); }); diff --git a/tests/order-rules/execution.test.cjs b/tests/order-rules/execution.test.cjs index 1f7e038..c03f2f7 100644 --- a/tests/order-rules/execution.test.cjs +++ b/tests/order-rules/execution.test.cjs @@ -12,7 +12,7 @@ function fixture(t){ let captures=0,exports=0,failCapture=false; const row={source:'todo',instanceId:'i1',taskId:'t1',revision:'1',processName:'备损订单更改评审',nodeName:'订单专员(订单通知书)',processVersion:'1.4',receivedAt:'2026-10-19T01:00:00Z',serialNum:'S1',title:'订单号:SO-1 客户简称:真实客户'}; const provider={capabilities:()=>({liveTodo:true,pdfExport:true,message:'actual probe'}),scan:async(c,p)=>{assert.equal(p.sessionId,'test-session');return [row];},capture:async()=>{captures++;if(failCapture)throw Error('capture unavailable');return {sample:{...row,connectionId:'c1',brief:'摘要',fields:{order:'SO-1',brief:'真实摘要'}},snapshot:{processVersion:'1.4',html:'

real fixture

',fields:[{path:'order',label:'订单号',value:'SO-1'},{path:'brief',label:'摘要',value:'真实摘要'}]}};}}; - const archive={probe:async()=>({automaticArchive:true,pdfExport:true,message:'runtime'}),capabilities:()=>({automaticArchive:true,pdfExport:true}),archive:async()=>{exports++;const content=Buffer.from('%PDF-1.7\nfixture');const file=path.join(dir,'order.pdf');fs.writeFileSync(file,content);return {archivedAt:now().toISOString(),files:[{name:'order.pdf',path:file,size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}]};}}; + const archive={read:async file=>fs.promises.readFile(file.path),probe:async()=>({automaticArchive:true,pdfExport:true,message:'runtime'}),capabilities:()=>({automaticArchive:true,pdfExport:true}),archive:async()=>{exports++;const content=Buffer.from('%PDF-1.7\nfixture');const file=path.join(dir,'order.pdf');fs.writeFileSync(file,content);return {archivedAt:now().toISOString(),files:[{name:'order.pdf',path:file,size:content.length,sha256:crypto.createHash('sha256').update(content).digest('hex'),kind:'pdf'}]};}}; const execution=new OrderExecutionCoordinator({store,workspace,provider,archive,clock:now}); return {store,execution,row,provider,archive,principal,setFail:v=>{failCapture=v;},counts:()=>({captures,exports})}; } @@ -51,11 +51,11 @@ test('cold restart probes archived pending work and restores dispatch gates with const execution=new OrderExecutionCoordinator({...f.execution,provider,archive}); assert.equal(execution.snapshot().capabilities.pdfExport,false); await execution.scan({connectionId:'c1',idempotencyKey:'cold-restart'},principal); - assert.deepEqual(execution.snapshot().capabilities,{liveTodo:true,pdfExport:true,automaticArchive:true});assert.equal(captured,true);assert.equal(probed,true);assert.equal(f.counts().exports,before.exports);assert.equal(f.store.all('orders')[0].status,'pending'); + assert.deepEqual(execution.snapshot().capabilities,{liveTodo:true,pdfExport:true,automaticArchive:true});assert.equal(captured,false);assert.equal(probed,true);assert.equal(f.counts().exports,before.exports);assert.equal(f.store.all('orders')[0].status,'pending'); await execution.stop(); f.store.prepare('2026-10-19T03:00:00Z','admin');captured=false;probed=false; const batchedRestart=new OrderExecutionCoordinator({...f.execution,provider,archive});await batchedRestart.scan({connectionId:'c1',idempotencyKey:'cold-batched-restart'},principal); - assert.equal(batchedRestart.snapshot().tasks[0].status,'batched');assert.equal(f.store.providersReady(),true);assert.equal(f.counts().exports,before.exports);assert.equal(captured,true);assert.equal(probed,true);await batchedRestart.stop(); + assert.equal(batchedRestart.snapshot().tasks[0].status,'batched');assert.equal(f.store.providersReady(),true);assert.equal(f.counts().exports,before.exports);assert.equal(captured,false);assert.equal(probed,true);await batchedRestart.stop(); }); for(const supportsRecovery of [false,true])test(`committed archive receipt reconciles interrupted task before uncertainty classification (recovery=${supportsRecovery})`,async t=>{ const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archived'},principal); @@ -65,12 +65,12 @@ for(const supportsRecovery of [false,true])test(`committed archive receipt recon await execution.scan({connectionId:'c1',idempotencyKey:'reconciled'},principal);assert.equal(f.counts().exports,before.exports);assert.deepEqual(f.store.get('orders',order.id).archive,order.archive);assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,1); await execution.stop(); }); -test('unavailable original source leaves archived work blocked without replay or discarding its receipt',async t=>{ +test('unavailable original source does not block valid archived receipts',async t=>{ const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archived'},principal); const before=f.counts(),receipt=f.store.all('orders')[0].archive; const provider={scan:async()=>[],capabilities:()=>({liveTodo:true,pdfExport:false}),capture:async()=>{throw Error('原任务已不在已核验节点');}}; const execution=new OrderExecutionCoordinator({...f.execution,provider});await execution.scan({connectionId:'c1',idempotencyKey:'source-unavailable'},principal); - assert.equal(f.store.providersReady(),false);assert.equal(execution.snapshot().tasks[0].runtimeCheck.status,'blocked');assert.match(execution.snapshot().tasks[0].error,/原任务已不在/);assert.equal(f.counts().exports,before.exports);assert.deepEqual(f.store.all('orders')[0].archive,receipt);assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,0);await execution.stop(); + assert.equal(f.store.providersReady(),true);assert.equal(execution.snapshot().tasks[0].runtimeCheck.status,'ready');assert.equal(f.counts().exports,before.exports);assert.deepEqual(f.store.all('orders')[0].archive,receipt);assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,1);await execution.stop(); }); test('failed frozen batch resend is versioned admin-only idempotent and cannot replay unknown',async t=>{ const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal); @@ -93,7 +93,7 @@ test('scope, calendar and pause gates survive actual persisted capture provenanc f.execution.systemPrincipal=principal;await f.execution.background();assert.equal(scans,0); f.store.saveSettings({...f.store.settings(),enabled:true,channelId:'channel1'},'admin');f.execution.settings=()=>({schedule:{times:['11:00','17:00'],weekends:false}});f.execution.calendar=()=>[{date:'2026-10-19',kind:'pause',scan:false,send:false}]; await f.execution.background();assert.equal(scans,0); - f.execution.calendar=()=>[];await f.execution.background();assert.equal(scans,1); + f.execution.calendar=()=>[];f.store.put('settings',{...f.store.get('settings','main'),processingEnabled:true,processingSince:'2026-10-19T00:00:00Z'});await f.execution.notifyDiscovery({connectionId:'c1',runId:'calendar-resume',rows:[f.row],startedAt:f.execution.now(),finishedAt:f.execution.now()});await f.execution.background();assert.equal(scans,0); const captured=f.store.fields().samples[0],adapter=f.store.fields().adapters.find(a=>a.sampleId===captured.id); activateFieldMapping(f.store,{sampleId:captured.id,processName:captured.processName,processVersion:captured.processVersion,fields:adapter.fields,version:adapter.draftVersion},admin); assert.equal(f.store.get('rules','bs-change').published.status,'paused'); @@ -159,7 +159,7 @@ test('all fifteen categories capture actual fixture fields, archive to temporary let now=new Date('2026-10-19T02:59:00Z');const dispatcher=new OrderRuleDispatcher({store:f.store,mail,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),clock:()=>now,providersReady:()=>true,templateResolver:()=>({id:'template',version:1,subject:'ignored',text:'模板{{订单列表}}',html:'
{{订单列表}}
',to:['intruder@example.test'],attachments:[]})}); await dispatcher.tick();now=new Date('2026-10-19T03:00:00Z');await dispatcher.tick();await dispatcher.stop(); assert.equal(messages.length,15);assert.equal(f.store.all('batches').filter(b=>b.status==='sent').length,15); - for(const [index,raw] of messages.entries()){const message=await simpleParser(raw);assert.deepEqual(message.to.value.map(x=>x.address),['orders@example.test']);assert.match(message.text,/模板/);assert.match(message.text,/SO-/);assert.equal(message.attachments.length,f.store.all('batches')[index].ruleSnapshot.attachPdf?1:0);} + for(const [index,raw] of messages.entries()){const message=await simpleParser(raw);assert.deepEqual(message.to.value.map(x=>x.address),['orders@example.test']);assert.match(message.text,/模板/);assert.match(message.text,/SO-/);assert.equal(message.attachments.length,f.store.all('batches').find(b=>b.subject===message.subject).ruleSnapshot.attachPdf?1:0);} assert.equal(f.counts().exports,15); }); for(const partial of [false,true])test(`real loopback SMTP ${partial?'partial refusal stays unknown':'complete envelope refusal is explicitly failed'}`,async t=>{ @@ -176,7 +176,7 @@ for(const partial of [false,true])test(`real loopback SMTP ${partial?'partial re }); function deferred(){let resolve;const promise=new Promise(r=>resolve=r);return {promise,resolve};} -test('discovery barrier covers queued scan, complete persisted set, late failure and rebuild of prepared category',async t=>{ +test('discovery barrier preserves frozen collection and explicitly blocks late same-window arrivals',async t=>{ const f=fixture(t);f.execution.clock=f.store.clock=()=>new Date('2026-10-19T03:00:00Z');await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'ready'},principal); const cutoff='2026-10-19T03:00:00Z',batch=f.store.prepare(cutoff,'admin')[0];assert.ok(batch); const discovery=deferred(),capture=deferred(),entered=deferred(),original={...f.row};let fail=true; @@ -188,10 +188,9 @@ test('discovery barrier covers queued scan, complete persisted set, late failure discovery.resolve([original,{...original,taskId:'late1',instanceId:'late1'},{...original,taskId:'late2',instanceId:'late2'}]);await entered.promise; assert.equal(f.store.all('execution-tasks').length,3,'all relevant identities persisted before first awaited capture'); assert.equal(f.store.prepare(cutoff,'admin').length,0);capture.resolve();await scanning; - assert.throws(()=>f.store.beginSending(batch.id),/扫描|完整/);assert.equal(f.store.prepare(cutoff,'admin').length,0); + assert.equal(f.store.prepare(cutoff,'admin').length,0); fail=false;await f.execution.scan({connectionId:'c1',idempotencyKey:'recovered'},principal); - assert.throws(()=>f.store.beginSending(batch.id),/完整/,'new same-category orders cannot be omitted by old frozen batch'); - const replacement=f.store.prepare(cutoff,'admin')[0];assert.ok(replacement);assert.equal(replacement.orderIds.length,3);assert.equal(f.store.get('batches',batch.id).status,'cancelled');assert.equal(f.store.beginSending(replacement.id).status,'sending'); + const replacement=f.store.prepare(cutoff,'admin');assert.equal(replacement.length,0);assert.equal(f.store.get('batches',batch.id).status,'prepared');assert.equal(f.store.get('batches',batch.id).orderIds.length,1);assert.equal(f.store.all('orders').filter(o=>o.blockedByBatchId===batch.id).length,2);assert.equal(f.store.all('business-issues').filter(i=>i.id.startsWith('late:')).length,2);assert.equal(f.store.beginSending(batch.id).status,'sending'); }); test('cutoff requires a successful post-cutoff discovery for every source and failed zero-row scans stay blocked',async t=>{ const f=fixture(t);f.execution.clock=f.store.clock=()=>new Date('2026-10-19T02:00:00Z');await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'ready'},principal); @@ -217,3 +216,9 @@ test('all configured sources require independent complete cutoff discovery and t await assert.rejects(f.execution.retry(task.id,{version:task.version,note:'已经确认恢复条件',idempotencyKey:'denied'}, {user:{username:'operator',role:'operator'},sessionId:'other'}),{status:403}); task.conflict=true;f.store.put('execution-tasks',task);assert.equal(f.execution.snapshot(owner).tasks[0].canRetry,false);task.conflict=false;task.status='unknown';f.store.put('execution-tasks',task);assert.equal(f.execution.snapshot(owner).tasks[0].canRetry,false); }); +test('trusted discovery persists while paused and is consumed without a second list read',async t=>{const f=fixture(t);await configure(f);let scans=0;f.provider.scan=async()=>{scans++;return [f.row];};f.execution.systemPrincipal=principal;await f.execution.notifyDiscovery({connectionId:'c1',runId:'watch1',rows:[f.row],startedAt:'2026-10-19T03:00:00Z',finishedAt:'2026-10-19T03:00:00Z'});await f.execution.background();assert.equal(scans,0);assert.equal(f.store.all('execution-discoveries')[0].status,'pending');assert.ok(f.store.discoveryBlockers('2026-10-19T03:00:00Z').length);f.store.put('settings',{...f.store.get('settings','main'),processingEnabled:true,processingSince:'2026-10-19T00:00:00Z'});await f.execution.background();assert.equal(scans,0);assert.equal(f.counts().exports,1);assert.equal(f.store.all('execution-discoveries')[0].status,'complete');await f.execution.background();assert.equal(scans,0);}); +test('archived todo disappearance uses receipt readback and never calls capture',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);f.archive.read=async file=>fs.promises.readFile(file.path);f.provider.scan=async()=>[];f.provider.capture=async()=>{throw Error('must not capture completed source');};await f.execution.scan({connectionId:'c1',idempotencyKey:'gone'},principal);assert.equal(f.execution.snapshot().tasks[0].runtimeCheck.status,'ready');assert.equal(f.counts().exports,1);}); +test('published migration is atomic versioned idempotent and preserves distribution-only archive',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);const before=f.store.all('orders')[0],record=f.store.get('rules','bs-change');record.published={...record.published,version:record.published.version+1,to:['new@example.test']};f.store.put('rules',record);const input={version:record.published.version,idempotencyKey:'migration1',note:'更新分发范围依据'};const preview=f.store.previewMigration(record.id,input,'admin');assert.equal(preview.items[0].archiveChanged,false);f.store.applyMigration(record.id,input,'admin');assert.deepEqual(f.store.get('orders',before.id).archive,before.archive);assert.deepEqual(f.store.get('orders',before.id).ruleSnapshot.to,['new@example.test']);f.store.applyMigration(record.id,input,'admin');assert.throws(()=>f.store.applyMigration(record.id,{...input,note:'另一不同处理依据'},'admin'),{status:409});const changed=f.store.get('orders',before.id);changed.status='unknown';f.store.put('orders',changed);assert.equal(f.store.previewMigration(record.id,{...input,idempotencyKey:'m2'},'admin').excluded.length,1);}); +test('revision resolution preserves identity, suppresses ignored repeat, blocks frozen orders',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);f.row.title='changed revision content';await f.execution.scan({connectionId:'c1',idempotencyKey:'conflict'},principal);let task=f.store.all('execution-tasks')[0];assert.equal(task.conflict,true);await f.execution.resolve(task.id,{version:task.version,idempotencyKey:'ignore1',resolution:'ignore',note:'人工比对确认忽略变化'},principal);await f.execution.scan({connectionId:'c1',idempotencyKey:'repeat'},principal);task=f.store.get('execution-tasks',task.id);assert.equal(task.conflict,false);const o=f.store.get('orders',task.orderId);o.status='unknown';f.store.put('orders',o);task.conflict=true;task.conflictRow={...task.row,title:'another'};f.store.put('execution-tasks',task);await assert.rejects(f.execution.resolve(task.id,{version:task.version,idempotencyKey:'adopt1',resolution:'adopt',note:'人工确认采用新修订'},principal),{status:409});}); +test('a new BPM revision is held against the prior identity and cannot bypass a frozen batch',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'archive-old'},principal);const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0];f.row.revision='2';await f.execution.scan({connectionId:'c1',idempotencyKey:'revision2'},principal);const task=f.store.all('execution-tasks').find(t=>t.row.revision==='2');assert.equal(task.conflict,true);assert.equal(f.counts().exports,1);await assert.rejects(f.execution.resolve(task.id,{version:task.version,idempotencyKey:'adopt',resolution:'adopt',note:'核对新修订仍不能重发'},principal),{status:409});assert.equal(f.store.get('batches',batch.id).status,'prepared');}); +test('adopting a new unfrozen revision preserves original evidence and requires fresh archive',async t=>{const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'original'},principal);const original=f.store.all('orders')[0];f.row.revision='2';await f.execution.scan({connectionId:'c1',idempotencyKey:'changed'},principal);const task=f.store.all('execution-tasks').find(t=>t.row.revision==='2');await f.execution.resolve(task.id,{version:task.version,idempotencyKey:'adopt2',resolution:'adopt',note:'人工确认新版业务修订'},principal);await f.execution.scan({connectionId:'c1',idempotencyKey:'process-new'},principal);const order=f.store.get('orders',original.id);assert.equal(order.sample.revision,'2');assert.equal(order.archiveHistory.length,1);assert.equal(f.counts().exports,2);assert.equal(f.store.all('execution-tasks').find(t=>t.row.revision==='1').status,'ignored');assert.equal(f.store.get('execution-tasks',task.id).conflict,false);}); diff --git a/tests/order-rules/global-core.test.cjs b/tests/order-rules/global-core.test.cjs new file mode 100644 index 0000000..6041918 --- /dev/null +++ b/tests/order-rules/global-core.test.cjs @@ -0,0 +1,10 @@ +'use strict'; +const {test}=require('node:test');const assert=require('node:assert/strict'); +const {windowForCutoff,inWindow}=require('../../src/modules/order-rules/window.cjs'); +test('F01 connection ownership and public projection',()=>{const a=require('../../src/modules/order-rules/access.cjs');const w={recordSources:()=>[{id:'c',owner:'alice',status:'archived'}]};const o={sample:{connectionId:'c',fields:{secret:'private'}},event:{orderNo:'42'}};assert.equal(a.canReadOrder(w,{username:'other',role:'operator'},o),false);assert.equal(a.canReadOrder(w,{username:'alice',role:'operator'},o),true);assert.equal(JSON.stringify(a.publicOrder(o)).includes('private'),false);assert.equal(a.canReadBatch(w,{username:'alice',role:'operator'},{orderIds:['missing']},{get:()=>null}),false);}); +test('continuous ordinary weekday window includes prior evening',()=>assert.equal(inWindow('2026-10-20T17:30:00+08:00',windowForCutoff('2026-10-21T11:00:00+08:00',{times:['11:00','17:00'],weekends:false})),true)); +test('independent processing gate and activation baseline',t=>{const fs=require('node:fs'),os=require('node:os'),path=require('node:path');const {RuleStore}=require('../../src/modules/order-rules/store.cjs');const dir=fs.mkdtempSync(path.join(os.tmpdir(),'global-core-'));const s=new RuleStore(dir,{clock:()=>new Date('2026-10-21T02:00:00Z')});t.after(()=>{s.close();fs.rmSync(dir,{recursive:true,force:true});});assert.equal(s.settings().processingEnabled,false);const next=s.saveSettings({...s.settings(),processingEnabled:true},'admin');assert.equal(next.enabled,false);assert.equal(next.processingSince,'2026-10-21T02:00:00.000Z');}); +test('F02 corrected archive generation never reuses an old destination receipt',async t=>{const fs=require('node:fs/promises'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto');const {OrderArchiveProvider}=require('../../src/modules/storage/order-archive.cjs');const dir=await fs.mkdtemp(path.join(os.tmpdir(),'archive-generation-'));t.after(()=>fs.rm(dir,{recursive:true,force:true}));const records=new Map(),bytes=Buffer.from('%PDF-test'),sha=crypto.createHash('sha256').update(bytes).digest('hex');let rendered=0;const storage={store:{servers:()=>[{id:'s',enabled:true,host:'server',share:'share',directory:'',state:{readable:true,writable:true}}]},run:async(_,fn)=>fn({},null),operation:async(_,op,args)=>op==='archive'?{filename:args[1],relativePath:args[2]+'/'+args[1],sha256:sha,bytes:bytes.length}:{bytes},readFile:async()=>({bytes})};const a=new OrderArchiveProvider({storage,outputDir:dir,journal:{get:(k,id)=>records.get(k+id),put:(k,v)=>records.set(k+v.id,v)},renderer:async(_,options)=>{await fs.mkdir(options.outputDir,{recursive:true});const file=path.join(options.outputDir,++rendered+'.pdf');await fs.writeFile(file,bytes);return {path:file};}});const order={id:'o',sourceHash:'same',event:{orderNo:'42',serialNum:'s',receivedAt:'2026-10-21T02:00:00Z'}};const rule={archiveDirectory:'\\\\server\\share\\A',filenameDate:'receivedAt'};const original=await a.archive({order,rule,snapshot:{},taskId:'t'});const corrected=await a.archive({order:{...order,archiveGeneration:2},rule:{...rule,archiveDirectory:'\\\\server\\share\\B'},snapshot:{},taskId:'t'});assert.notDeepEqual(corrected.files,original.files);assert.match(corrected.files[0].path,/\\B\\/);assert.equal(rendered,2);await a.archive({order:{...order,archiveGeneration:2},rule:{...rule,archiveDirectory:'\\\\server\\share\\B'},snapshot:{},taskId:'t'});assert.equal(rendered,2);}); +test('fifteen legally frozen categories finish through slow SMTP within 30 minute queue',async()=>{const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');let now=new Date('2026-10-21T02:59:59Z');const cutoff='2026-10-21T03:00:00.000Z',window=windowForCutoff(cutoff,{times:['11:00','17:00'],weekends:false});const batches=Array.from({length:15},(_,i)=>({id:'b'+i,status:'prepared',cutoff,window,createdAt:cutoff,to:['x@example.test'],cc:[],attachments:[],orderIds:[]}));let sends=0;const store={settings:()=>({enabled:true,channelId:'c'}),snapshot:()=>({capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true},batches}),discoveryBlockers:()=>[],batchIncomplete:()=>false,prepare:()=>[],beginSending:id=>{batches.find(b=>b.id===id).status='sending';},finishSending:(id,status)=>{batches.find(b=>b.id===id).status=status;}};const mail={exclusive:async(_,f)=>f(),store:{channelSecret:()=>({id:'c',version:1,email:'s@example.test',smtp:{}}),guard:()=>{}},smtpFactory:()=>({verify:async()=>{},sendMail:async()=>{sends++;now=new Date(+now+6000);return {accepted:['x@example.test']};},close:()=>{}})};const d=new OrderRuleDispatcher({store,mail,clock:()=>now,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),providersReady:()=>true});await d.tick(now);now=new Date(cutoff);await d.tick(now);assert.equal(sends,15);assert.equal(batches.every(b=>b.status==='sent'),true);}); +test('blocked collection retries within 60 seconds but never creates a late batch',async()=>{const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');let now=new Date('2026-10-21T03:00:00Z'),prepares=0;const store={settings:()=>({enabled:true,channelId:'c'}),snapshot:()=>({capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true},batches:[]}),discoveryBlockers:()=>[],prepare:()=>{prepares++;return [];}};const d=new OrderRuleDispatcher({store,mail:{exclusive:async(_,fn)=>fn()},clock:()=>now,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),providersReady:()=>true});await d.tick();now=new Date(+now+30000);await d.tick();assert.equal(prepares,2);now=new Date(+now+31000);await d.tick();assert.equal(prepares,2);}); +test('external rules snapshot filters foreign orders mixed batches audit and raw form evidence',async()=>{const {orderRuleApi}=require('../../src/modules/order-rules/api.cjs');const owned={id:'own',sample:{connectionId:'a',fields:{private:'secret-owned'}},event:{orderNo:'OWN'}},foreign={id:'foreign',sample:{connectionId:'b',fields:{private:'secret-other'}},event:{orderNo:'FOREIGN'}};const orders=[owned,foreign],batches=[{id:'mixed',orderIds:['own','foreign'],text:'private frozen body'},{id:'owned',orderIds:['own']}];let output;await orderRuleApi({orderRules:{snapshot:()=>({orders,batches,audit:[{detail:'foreign evidence'}]}),get:(_,id)=>orders.find(o=>o.id===id)},workspace:{recordSources:()=>[{id:'a',owner:'alice'},{id:'b',owner:'bob'}]},user:{username:'alice',role:'operator'},route:'/api/order-rules',method:'GET',reply:(_,value)=>{output=value;}});assert.deepEqual(output.orders.map(o=>o.id),['own']);assert.deepEqual(output.batches.map(b=>b.id),['owned']);assert.deepEqual(output.audit,[]);assert.doesNotMatch(JSON.stringify(output),/secret-|FOREIGN|private frozen/);}); diff --git a/tests/order-rules/store.test.cjs b/tests/order-rules/store.test.cjs index 8725a0b..8338a42 100644 --- a/tests/order-rules/store.test.cjs +++ b/tests/order-rules/store.test.cjs @@ -87,16 +87,15 @@ test('pausing a rule prevents a prepared batch from entering SMTP sending',t=>{ store.pause(rule.id,{version:rule.version},'admin');assert.throws(()=>store.beginSending(batch.id),e=>e.status===409); assert.equal(store.snapshot().batches[0].status,'prepared'); }); -test('late discovery rebuilds an unsent reservation as one complete batch and never carries it into a later slot',t=>{ +test('late discovery cannot alter a frozen reservation and leaves explicit operator work',t=>{ const {store}=fixture(t,{capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store); - const archive=(sample)=>{const order=store.ingest(sample,'system');store.recordArchive(order.id,{files:[{name:order.id+'.pdf',path:'C:\\archive\\'+order.id+'.pdf',sha256:'a'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-19T01:05:00Z'},'archive-executor');return order;}; - archive(sample);assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,1); - archive({...sample,instanceId:'late',taskId:'late'}); - const replacement=store.prepare('2026-10-19T03:00:00Z','admin');assert.equal(replacement.length,1);assert.equal(replacement[0].orderIds.length,2);assert.equal(store.snapshot().batches.filter(b=>b.status==='prepared').length,1); - assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,0); - assert.equal(store.prepare('2026-10-19T09:00:00Z','admin').length,0); - assert.equal(store.snapshot().orders.filter(o=>o.status==='ignored').length,2); + const order=store.ingest(sample,'system');store.recordArchive(order.id,{files:[{name:'o.pdf',path:'C:\\archive\\o.pdf',sha256:'a'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-19T01:05:00Z'},'archive-executor'); + const frozen=store.prepare('2026-10-19T03:00:00Z','admin')[0]; + const late=store.ingest({...sample,instanceId:'late',taskId:'late'},'system');assert.equal(late.status,'blocked');assert.equal(late.blockedByBatchId,frozen.id); + assert.equal(store.prepare('2026-10-19T03:00:00Z','admin').length,0);assert.equal(store.get('batches',frozen.id).status,'prepared');assert.deepEqual(store.get('batches',frozen.id).orderIds,[order.id]);assert.ok(store.get('business-issues','late:'+late.id)); + assert.throws(()=>store.recheck(late.id,{note:'尝试更改已冻结集合'},'admin'),{status:409}); }); + test('old history cannot enter this morning mail while current orders remain eligible',t=>{ const {store}=fixture(t,{clock:()=>new Date('2026-10-20T02:00:00Z'),capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}}),sample=configure(store); const old=store.ingest({...sample,instanceId:'old',taskId:'old',receivedAt:'2026-10-19T01:00:00Z'},'system'); @@ -105,7 +104,7 @@ test('old history cannot enter this morning mail while current orders remain eli const current=store.ingest({...sample,instanceId:'current',taskId:'current',receivedAt:'2026-10-20T01:00:00Z'},'system'); store.recordArchive(current.id,{files:[{name:'current.pdf',path:'C:\\archive\\current.pdf',sha256:'a'.repeat(64),size:42,kind:'pdf'}],archivedAt:'2026-10-20T01:05:00Z'},'archive-executor'); const batches=store.prepare('2026-10-20T03:00:00Z','admin');assert.equal(batches.length,1);assert.deepEqual(batches[0].orderIds,[current.id]); - assert.equal(batches[0].window.start,'2026-10-19T16:00:00.000Z'); + assert.equal(batches[0].window.start,'2026-10-19T09:00:00.000Z'); }); test('paused old publication cannot shadow an enabled replacement for the same process and node',t=>{ const {store}=fixture(t),sample=configure(store); diff --git a/tests/order-rules/window.test.cjs b/tests/order-rules/window.test.cjs index a12ae9d..6ded611 100644 --- a/tests/order-rules/window.test.cjs +++ b/tests/order-rules/window.test.cjs @@ -2,9 +2,9 @@ const {test}=require('node:test');const assert=require('node:assert/strict'); const {windowForCutoff,upcomingWindow,inWindow}=require('../../src/modules/order-rules/window.cjs'); const schedule={times:['11:00','17:00'],timezone:'Asia/Shanghai',weekends:false}; -test('normal weekday only includes same-day first interval or interval between send times',()=>{ +test('normal weekday first interval continuously covers prior evening',()=>{ const morning=windowForCutoff('2026-10-20T03:00:00Z',schedule),afternoon=windowForCutoff('2026-10-20T09:00:00Z',schedule); - assert.equal(morning.start,'2026-10-19T16:00:00.000Z');assert.equal(morning.end,'2026-10-20T03:00:00.000Z'); + assert.equal(morning.start,'2026-10-19T09:00:00.000Z');assert.equal(morning.end,'2026-10-20T03:00:00.000Z'); assert.equal(afternoon.start,'2026-10-20T03:00:00.000Z');assert.equal(afternoon.end,'2026-10-20T09:00:00.000Z'); assert.equal(inWindow('2026-10-19T08:00:00Z',morning),false); assert.equal(inWindow('2026-10-20T03:00:00Z',morning),false);assert.equal(inWindow('2026-10-20T03:00:00Z',afternoon),true);