feat: persist captured order execution and controlled batch resend

This commit is contained in:
abaishu0730 committed 2026-10-19 13:37:32 +08:00
1 parent b8cb1e11c6
commit 20589dd950
12 files changed
+419 -42

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
'use strict';
const {fail}=require('../order-rules/validation.cjs');
async function orderExecutionApi({execution,orderRules,dispatcher,workspace,user,sessionId,route,method,body,reply}){
const task=/^\/api\/order-execution\/tasks\/([\w-]+)\/retry$/.exec(route),resend=/^\/api\/order-rules\/batches\/([\w-]+)\/resend$/.exec(route);
if(!route.startsWith('/api/order-execution')&&!['/api/order-rules/fields','/api/order-rules/adapters'].includes(route)&&!resend)return false;
if(!execution||!orderRules)fail('订单执行服务未启动。',503);
if(method==='GET'&&route==='/api/order-execution'){reply(200,execution.snapshot({user,sessionId}));return true;}
if(method==='GET'&&route==='/api/order-rules/fields'){reply(200,execution.snapshot({user,sessionId}).fields);return true;}
if(method!=='POST')fail('未找到执行操作。',404);
if(user?.role==='viewer')fail('只读成员不能执行此操作。',403);
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(user?.role!=='admin')fail('仅管理员可维护字段适配或人工补发。',403);
if(route==='/api/order-rules/adapters')result=orderRules.saveAdapter(body,user);
else if(resend){if(!dispatcher)fail('分类发信服务未启动。',503);if(!body||Object.keys(body).some(k=>!['version','idempotencyKey','note'].includes(k)))fail('补发参数无效。');result=await dispatcher.resend(resend[1],body,user);}
else fail('未找到执行操作。',404);
}
workspace?.record?.(user,'维护订单执行',route);reply(200,result);return true;
}
module.exports={orderExecutionApi};
+115
View File
@@ -0,0 +1,115 @@
'use strict';
const crypto=require('node:crypto');
const {fail}=require('../order-rules/validation.cjs');
const {dayPolicy}=require('../../shared/schedule.cjs');
const hash=value=>crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
const clone=value=>structuredClone(value);
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});
this.tail=Promise.resolve();this.stopped=false;this.timer=null;this.query=store.get('execution-query','main')||{id:'main',status:'idle'};this.blockers=[];
if(this.query.status==='scanning'){this.query={...this.query,status:'failed',error:'服务重启中断了上次只读扫描,请重新扫描。',finishedAt:this.now()};store.put('execution-query',this.query);}
for(const task of store.all('execution-tasks')){
if(task.status==='archiving'){task.status=archive.supportsRecovery===true?'failed':'unknown';task.step='archive';task.error='归档中断,结果待核验,需人工受控恢复。';this.persist(task);}
else if(task.status==='capturing'){task.status='failed';task.error='只读采集已中断,可重新采集。';this.persist(task);}
}
// Readiness is established exclusively by provider/runtime probes.
store.capabilities={liveTodo:false,pdfExport:false,automaticArchive:false};
}
now(){return this.clock().toISOString();}
persist(task){task.version=(task.version||0)+1;task.updatedAt=this.now();task.history=[...(task.history||[]),{at:task.updatedAt,status:task.status,step:task.step,error:task.error||null}].slice(-100);this.store.put('execution-tasks',task);return task;}
serialize(work){if(this.stopped)return Promise.reject(Object.assign(Error('订单执行服务正在关闭。'),{status:503}));const operation=this.tail.catch(()=>{}).then(work);this.tail=operation;return operation;}
connection(id,principal){const c=this.workspace.getConnection(id);if(!principal?.sessionId||!['admin','operator'].includes(principal?.user?.role)||(principal.user.role!=='admin'&&c.owner!==principal.user.username))fail('仅连接负责人或管理员可以扫描或重试。',403);if(c.status==='disabled')fail('连接已停用。',409);return c;}
async refreshCapabilities(rule){
let p={},a={};this.blockers=[];
try{p=await this.provider.capabilities();}catch(error){this.blockers.push('待办提供器探测失败:'+error.message);}
try{a=rule&&this.archive.probe?await this.archive.probe(rule):await this.archive.capabilities();}catch(error){this.blockers.push('归档运行条件探测失败:'+error.message);}
const capabilities={liveTodo:p.liveTodo===true,pdfExport:p.pdfExport===true&&a.pdfExport===true,automaticArchive:a.automaticArchive===true};
for(const key of Object.keys(capabilities))if(!capabilities[key])this.blockers.push(key+' 尚未通过实际探测。');this.store.capabilities=capabilities;return capabilities;
}
snapshot(principal){
const allowed=id=>{if(!principal||principal.user?.role==='admin')return true;try{return this.workspace.getConnection(id).owner===principal.user?.username;}catch{return false;}};
const fields=this.store.fields();fields.samples=fields.samples.filter(sample=>allowed(sample.sample.connectionId));
const query=(!this.query.connectionId||allowed(this.query.connectionId))?clone(this.query):{id:'main',status:'idle'};
return {tasks:this.store.all('execution-tasks').filter(task=>allowed(task.connectionId)).map(task=>{const order=task.orderId&&this.store.get('orders',task.orderId);return {...task,processName:task.row.processName,title:task.row.title,serialNum:task.row.serialNum,status:['failed','unknown','blocked','capturing','archiving'].includes(task.status)?task.status:order?.status||task.status,error:task.error||order?.error||null};}).reverse(),capabilities:clone(this.store.capabilities),fields,query,blockers:[...this.blockers]};
}
request(input){if(typeof input?.idempotencyKey!=='string'||!/^[\w:.-]{1,160}$/.test(input.idempotencyKey))fail('请提供有效的操作幂等标识。');}
scan(input,principal){
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);
try{
const rows=await this.provider.scan(connection,principal);if(!Array.isArray(rows))throw Error('待办提供器返回格式无效。');
await this.refreshCapabilities();let considered=0;
for(const row of rows){
if(row.source!=='todo')continue;
const rules=this.store.all('rules').map(r=>r.published?.status==='enabled'?r.published:r.draft).filter(rule=>rule.processNames.includes(row.processName)&&rule.nodeNames.includes(row.nodeName));
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)<Date.parse(window.start))continue;
considered++;const id=hash([connection.id,row.source,String(row.instanceId),String(row.taskId),String(row.revision)]);
let task=this.store.get('execution-tasks',id);
if(!task){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()};this.persist(task);}
if(hash(task.row)!==hash(row)){task.status='blocked';task.error='同一事件修订内容冲突,需核对源版本。';task.conflict=true;this.persist(task);await this.exception(task,connection,false);continue;}
if(task.conflict||task.status==='unknown'||task.step==='archive'&&task.status==='failed')continue;
const order=task.orderId&&this.store.get('orders',task.orderId);
if(order&&['pending','batched','sent','unknown','ignored'].includes(order.status)){task.status=order.status;this.persist(task);continue;}
await this.execute(task,connection,principal);
}
this.query={...this.query,status:'complete',finishedAt:this.now(),rowCount:rows.length,targetCount:considered};this.store.put('execution-requests',{id:key,at:this.now()});
}catch(error){this.query={...this.query,status:'failed',error:error.message,finishedAt:this.now()};throw error;}
finally{this.store.put('execution-query',this.query);}
return this.snapshot(principal);
});
}
async execute(task,connection,principal){
try{
if(!task.sampleId){
task.status='capturing';task.step='capture';this.persist(task);
const {sample,snapshot}=await this.provider.capture(connection,principal,clone(task.row));
for(const key of ['source','instanceId','taskId','revision','processName','nodeName','receivedAt'])if(String(sample[key])!==String(task.row[key]))throw Error('采集样本与待办事件身份不一致。');
if(sample.connectionId!==connection.id)throw Error('采集样本连接身份不一致。');
const captured=this.store.recordCapture({sample,snapshot,taskId:task.id});task.sampleId=captured.id;task.step='identify';this.persist(task);
}
const captured=this.store.get('capture-samples',task.sampleId);let order;
await this.refreshCapabilities(this.store.all('rules').find(r=>task.categoryIds.includes(r.id))?.published);
if(task.orderId){order=this.store.get('orders',task.orderId);if(order?.status==='blocked'&&!order.archive)try{order=this.store.recheck(order.id,{note:'重新扫描使用当前已核验规则'},principal.user.username);}catch(error){task.status='blocked';task.error=error.message;this.persist(task);await this.exception(task,connection,false);return;}}
if(!order){order=this.store.ingest(captured.sample,principal.user.username);task.orderId=order.id;}
task.status=order.status;task.error=order.error;task.step='identify';this.persist(task);
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;
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);}
}
retry(id,input,principal){return this.serialize(async()=>{
this.request(input);const task=this.store.get('execution-tasks',id);if(!task)fail('执行任务不存在。',404);const connection=this.connection(task.connectionId,principal);
const requestId=hash(['retry',id,principal.user.username,input.idempotencyKey]),inputHash=hash([input.version,input.note]),previous=this.store.get('execution-requests',requestId);if(previous){if(previous.inputHash!==inputHash)fail('幂等标识已用于不同的重试请求。',409);return this.snapshot(principal);}
if(input.version!==task.version)fail('任务版本已变化,请刷新。',409);if(typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请填写至少5字重试依据。');
if(!['failed','blocked'].includes(task.status)||task.conflict)fail('此任务结果未明确或不允许重试。',409);
this.store.audit(principal.user.username,'人工重试订单任务',id+':'+input.note.trim());await this.execute(task,connection,principal);this.store.put('execution-requests',{id:requestId,taskId:id,inputHash,at:this.now()});return this.snapshot(principal);
});}
async exception(task,connection,recovered){
try{await this.updateException(task,connection,recovered);}catch(error){task.exceptionError=error.message;this.persist(task);this.store.audit('订单执行器','异常关联更新失败',task.id);}
}
async updateException(task,connection,recovered){
if(this.onException){await this.onException({task:clone(task),connection:clone(connection),recovered});return;}
if(!this.workspace.createException)return;
const actor=this.systemPrincipal?.user||{username:'订单执行器',role:'admin'},members=[...(connection.owner?[{username:connection.owner,role:'operator'}]:[]),actor];
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?.();}
async background(){
if(!this.systemPrincipal||!this.store.settings().enabled)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);
}
async drain(){await this.tail.catch(()=>{});}
async stop(){this.stopped=true;clearInterval(this.timer);this.timer=null;await this.drain();}
}
module.exports={OrderExecutionCoordinator};
+6 -5
View File
@@ -8,9 +8,10 @@ async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,re
if(user.role==='viewer')fail('只读成员不能编辑规则或提交样本。',403);
const actor=user.username;
if(route==='/api/order-rules/preview'||route==='/api/order-rules/events'){
if(!body||Object.keys(body).some(k=>k!=='sample')||!body.sample||typeof body.sample!=='object'||Array.isArray(body.sample))fail('请提供 BPM 样本对象。');
const preview=route.endsWith('/preview');reply(preview?200:201,preview?orderRules.preview(body.sample):orderRules.ingest(body.sample,actor));
if(!preview)workspace?.record(user,'识别分类通知订单','来源任务 '+String(body.sample.taskId));return true;
if(route.endsWith('/events'))fail('客户端事件写入已退役,请通过授权待办扫描创建任务。',410);
if(!body||Object.keys(body).some(k=>!['sample','sampleId'].includes(k)))fail('请提供 BPM 样本或服务端采集标识。');
if(body.sampleId){if(typeof body.sampleId!=='string'||body.sample)fail('真实试运行只接受服务端采集标识。');const captured=orderRules.get('capture-samples',body.sampleId);if(!captured)fail('真实采集样本不存在。',404);if(user.role!=='admin'&&workspace?.getConnection(captured.sample.connectionId)?.owner!==user.username)fail('仅连接负责人或管理员可试运行此采集样本。',403);reply(200,orderRules.capturedPreview(body.sampleId));}
else {if(!body.sample||typeof body.sample!=='object'||Array.isArray(body.sample))fail('请提供 BPM 样本对象。');reply(200,orderRules.previewUntrusted(body.sample));}return true;
}
if(user.role!=='admin')fail('仅管理员可维护规则、批次与发送设置。',403);
let result;
@@ -27,8 +28,8 @@ async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,re
const rule=/^\/api\/order-rules\/rules\/([\w-]+)\/(publish|pause)$/.exec(route);
const batch=/^\/api\/order-rules\/batches\/([\w-]+)\/resolve$/.exec(route);
const recheck=/^\/api\/order-rules\/orders\/([\w-]+)\/recheck$/.exec(route);
if(rule){if(!body||Object.keys(body).some(k=>k!=='version'))fail('请提供当前草稿版本。');result=orderRules[rule[2]](rule[1],body,actor);}
else if(batch){if(!body||Object.keys(body).some(k=>!['resolution','note'].includes(k)))fail('核验内容无效。');result=orderRules.resolve(batch[1],body,actor);}
if(rule){if(!body||Object.keys(body).some(k=>k!=='version'))fail('请提供当前草稿版本。');if(rule[2]==='publish'){const record=orderRules.get('rules',rule[1]);if(!record?.trialSampleId||!orderRules.get('capture-samples',record.trialSampleId))fail('发布前必须选择服务端真实采集样本完成试运行。',409);}result=orderRules[rule[2]](rule[1],body,actor);}
else if(batch){if(!body||Object.keys(body).some(k=>!['version','idempotencyKey','resolution','note'].includes(k)))fail('核验内容无效。');result=orderRules.resolve(batch[1],body,actor,{controlled:true});}
else if(recheck){if(!body||Object.keys(body).some(k=>k!=='note'))fail('重新识别内容无效。');result=orderRules.recheck(recheck[1],body,actor);}
else fail('没有找到此规则操作。',404);
}
+39 -10
View File
@@ -4,6 +4,7 @@ const path=require('node:path');
const crypto=require('node:crypto');
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;
@@ -15,9 +16,10 @@ function freeze(value){
}
class OrderRuleDispatcher{
constructor({store,mail,settings,calendar=()=>[],clock=()=>new Date(),providersReady=()=>false}){
constructor({store,mail,settings,calendar=()=>[],clock=()=>new Date(),providersReady=()=>false,attachmentReader,templateResolver}){
this.store=store;this.mail=mail;this.settings=settings;this.calendar=calendar;this.clock=clock;this.providersReady=providersReady;
this.running=null;this.stopped=false;this.schedule=null;this.timer=null;
this.attachmentReader=attachmentReader;if(templateResolver)store.templateResolver=templateResolver;
}
ready(){
const config=this.store.settings(),cap=this.store.snapshot().capabilities;
@@ -65,41 +67,67 @@ class OrderRuleDispatcher{
if(!file||typeof file.path!=='string'||!(path.isAbsolute(file.path)||path.win32.isAbsolute(file.path))||/^[a-z]+:\/\//i.test(file.path)||!/^[a-f\d]{64}$/i.test(file.sha256)||!Number.isSafeInteger(file.size)||file.size<0)throw Error('归档文件证据无效。');
total+=file.size;
if(total>(config.maxMessageBytes||20971520))throw Error('归档文件超过邮件大小限制。');
const stat=await fs.stat(file.path);
if(!stat.isFile()||stat.size!==file.size)throw Error('归档文件大小发生变化。');
const content=await fs.readFile(file.path);
if(!this.attachmentReader){const stat=await fs.stat(file.path);if(!stat.isFile()||stat.size!==file.size)throw Error('归档文件大小发生变化。');}
const content=this.attachmentReader?await this.attachmentReader(file):await fs.readFile(file.path);
if(!Buffer.isBuffer(content))throw Error('归档读取器未返回文件字节。');
if(content.length!==file.size||crypto.createHash('sha256').update(content).digest('hex')!==file.sha256.toLowerCase())throw Error('归档文件校验失败。');
result.push({filename:file.name,content,contentType:file.kind==='pdf'?'application/pdf':'application/octet-stream',contentDisposition:'attachment'});
}
return result;
}
async dispatch(batch,config){
async dispatch(batch,config,{manual=false}={}){
let transport,sending=false;
try{
if(batch.channelId&&batch.channelId!==config.channelId){
this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。');return;
}
const attachments=await this.attachments(batch,config);
if(this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。');
if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。');
const channel=freeze(structuredClone(this.mail.store.channelSecret(config.channelId)));
if(channel.readOnly)throw Error('只读邮箱不能用于分类通知发送。');
transport=this.mail.smtpFactory(channel.smtp);
this.mail.clients?.add(transport);
await transport.verify();
if(!this.ready()||this.store.settings().channelId!==config.channelId)throw Error('发送已暂停或配置已变更。');
if(this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。');
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('本时段发送宽限已结束。');
this.mail.store.guard(channel.id,channel.version);
this.store.beginSending(batch.id);sending=true;
this.store.beginSending(batch.id,{manual});sending=true;
const result=await transport.sendMail({from:{address:channel.email,name:channel.name},to:[...batch.to],cc:[...batch.cc],subject:batch.subject,text:batch.text,html:batch.html,attachments,messageId:`<${batch.id}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
const accepted=new Set((result?.accepted||[]).map(address=>String(address.address||address).toLowerCase()));
const partial=result?.rejected?.length||[...batch.to,...batch.cc].some(address=>!accepted.has(address.toLowerCase()));
this.store.finishSending(batch.id,partial?'unknown':'sent',partial?'部分收件人未被服务器接受,请核对邮件记录后处理。':'邮件服务器已接受全部收件人;最终送达请以邮件记录为准。');
}catch(error){
this.store.finishSending(batch.id,sending?'unknown':'failed',sending?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${error.code==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`);
const rejected=error.code==='EENVELOPE'&&error.command==='RCPT TO'&&Array.isArray(error.rejected)&&error.rejected.length>0&&(!error.accepted||error.accepted.length===0)&&[...batch.to,...batch.cc].every(address=>error.rejected.some(r=>String(r.address||r).toLowerCase()===address.toLowerCase()));
this.store.finishSending(batch.id,sending&&!rejected?'unknown':'failed',sending&&!rejected?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${error.code==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`);
}finally{
try{transport?.close?.();}finally{if(transport)this.mail.clients?.delete(transport);}
}
}
async resend(id,input,actor){
if(actor?.role!=='admin')fail('仅管理员可以人工补发。',403);
if(this.stopped)fail('发送器正在关闭。',503);
if(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 requestId=crypto.createHash('sha256').update(JSON.stringify([id,actor.username,input.idempotencyKey])).digest('hex');
const inputHash=crypto.createHash('sha256').update(JSON.stringify([input.version,input.note])).digest('hex');
const replay=record=>{if(record.inputHash!==inputHash)fail('此幂等标识已用于不同的补发请求。',409);return this.store.get('batches',record.batchId);};
const prior=this.store.get('resend-requests',requestId);if(prior)return replay(prior);
const original=this.store.get('batches',id);if(!original)fail('批次不存在。',404);
if(!original.channelId)fail('原批次未冻结发件邮箱,不能补发。',409);
const operation=this.mail.exclusive(original.channelId,async()=>{
const previous=this.store.get('resend-requests',requestId);if(previous)return replay(previous);
const batch=this.store.transaction(()=>{
const source=this.store.get('batches',id);if(input.version!==(source.version||1)||source.status!=='failed')fail('批次版本已变化,或发送结果尚未核验。',409);
const root=source.rootBatchId||source.id;
if(this.store.all('batches').some(b=>b.id!==source.id&&(b.rootBatchId||b.id)===root&&['sent','sending','unknown','prepared'].includes(b.status)))fail('此批次已发送、结果待核实或已有补发尝试。',409);
if(source.orderIds.some(oid=>{const o=this.store.get('orders',oid);return !o||['sent','unknown','batched'].includes(o.status);}))fail('原订单关联已发送或结果待核实。',409);
const next={...structuredClone(source),id:crypto.randomUUID(),version:1,parentBatchId:source.id,rootBatchId:root,status:'prepared',manual:true,createdAt:this.clock().toISOString(),error:null,resolution:null,finishedAt:null,resend:{actor:actor.username,note:input.note.trim(),at:this.clock().toISOString()}};
this.store.put('batches',next);for(const oid of next.orderIds){const o=this.store.get('orders',oid);o.batchId=next.id;o.status='batched';o.error=null;this.store.put('orders',o);}
this.store.put('resend-requests',{id:requestId,batchId:next.id,inputHash});this.store.audit(actor.username,'人工补发冻结分类邮件',source.id+':'+input.note.trim());return next;
});
await this.dispatch(freeze(structuredClone(batch)),{...this.store.settings(),channelId:batch.channelId},{manual:true});return this.store.get('batches',batch.id);
});
this.manualOperations??=new Set();this.manualOperations.add(operation);try{return await operation;}finally{this.manualOperations.delete(operation);}
}
start(){
if(this.timer||this.stopped)return;
this.timer=setInterval(()=>this.tick().catch(()=>{}),30000);this.timer.unref?.();
@@ -107,6 +135,7 @@ class OrderRuleDispatcher{
async stop(){
this.stopped=true;clearInterval(this.timer);this.timer=null;
if(this.running)await this.running.catch(()=>{});
await Promise.allSettled([...(this.manualOperations||[])]);
}
}
module.exports={OrderRuleDispatcher};
+2 -2
View File
@@ -61,8 +61,8 @@ function previewMatch(rules, adapters, input) {
check('标题提取',extracted.issues.length===0,extracted.issues.join(';')||`从标题提取 ${extracted.orders.length} 个订单段落;惠州线索仅供核实,不触发额外发送`);
}
for (const key of new Set(['orderNo', 'appDate', 'customer', 'productLine', 'quantity', ...Object.keys(mappings), 'brief'])) {
const path = key === 'brief' ? extracted?`${titleSource} → 订单段落`:'brief' : mappings[key] || '';
const value = key === 'brief' ? extracted?extracted.brief:sample.brief : path && Object.hasOwn(raw, path) ? raw[path] : null;
const path = key === 'brief' ? extracted?`${titleSource} → 订单段落`:mappings.brief||'brief' : mappings[key] || '';
const value = key === 'brief' ? extracted?extracted.brief:mappings.brief?raw[mappings.brief]:sample.brief : path && Object.hasOwn(raw, path) ? raw[path] : null;
event[key] = value ?? null;
fieldTrace.push({ key, label: labels[key] || key, path, value: value ?? null });
}
+26
View File
@@ -0,0 +1,26 @@
'use strict';
const crypto=require('node:crypto');
const {adapters}=require('./catalog.cjs');
const {fail}=require('./validation.cjs');
const hash=value=>crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
const keys=new Set(['orderNo','brief','appDate','customer','productLine','quantity','changeReason','changeContent','totalAmount']);
function registry(store){return [...structuredClone(adapters),...store.all('field-adapters')];}
function fields(store){return {samples:store.all('capture-samples').map(({snapshot,...sample})=>({...sample,fields:snapshot.fields})),adapters:registry(store)};}
function recordCapture(store,{sample,snapshot,taskId}){
if(sample?.demo||!snapshot||!Array.isArray(snapshot.fields)||snapshot.processVersion!==sample.processVersion)fail('捕获样本缺少一致的流程版本或实际字段证据。',409);
const paths=new Set();for(const f of snapshot.fields){if(!f||typeof f.path!=='string'||!f.path||paths.has(f.path)||!Object.hasOwn(sample.fields||{},f.path)||JSON.stringify(sample.fields[f.path])!==JSON.stringify(f.value))fail('捕获字段冲突或与样本不一致。',409);paths.add(f.path);}
const id=hash([taskId,sample,snapshot]);const captured={id,taskId,processName:sample.processName,processVersion:sample.processVersion,sample:structuredClone(sample),snapshot:structuredClone(snapshot),capturedAt:store.now(),provenance:'server-provider',evidenceHash:hash({sample,snapshot})};store.put('capture-samples',captured);return captured;
}
function saveAdapter(store,input,actor){return store.transaction(()=>{
if(actor?.role!=='admin')fail('仅管理员可以配置字段适配。',403);
if(!input||Object.keys(input).some(k=>!['sampleId','processName','processVersion','fields','version'].includes(k)))fail('字段适配配置无效。');
const captured=store.get('capture-samples',input.sampleId);
if(!captured||captured.provenance!=='server-provider'||captured.processName!==input.processName||captured.processVersion!==input.processVersion)fail('必须选择服务端已采集且流程版本一致的真实样本。',409);
const paths=new Set(captured.snapshot.fields.map(f=>f.path));
if(!input.fields||Array.isArray(input.fields)||!input.fields.orderNo||!input.fields.brief||Object.entries(input.fields).some(([key,value])=>!keys.has(key)||typeof value!=='string'||!paths.has(value)))fail('字段绑定必须来自已捕获样本的实际字段目录,包含订单号与摘要。');
const id='captured-'+hash([input.processName,input.processVersion]).slice(0,24),old=store.get('field-adapters',id);
if((old&&input.version!==old.version)||(!old&&input.version!==undefined))fail('字段适配版本已变化,请刷新。',409);
const result={id,version:(old?.version||0)+1,label:input.processName+' '+input.processVersion+'(真实采集)',processName:input.processName,processVersion:input.processVersion,fields:structuredClone(input.fields),verified:true,sampleId:captured.id,evidenceHash:captured.evidenceHash,verifiedAt:store.now(),verifiedBy:actor.username};
store.put('field-adapters',result);for(const record of store.all('rules'))if(record.draft.adapterIds.includes(id)||record.published?.adapterIds.includes(id)){record.trialVersion=null;record.trialSampleId=null;if(record.published?.adapterIds.includes(id))record.published.status='paused';store.put('rules',record);}store.audit(actor.username,'绑定真实流程字段',id);return result;
});}
module.exports={registry,fields,recordCapture,saveAdapter};
+1 -1
View File
@@ -15,7 +15,7 @@ const transitions={
},
batch:{
prepared:{send:'sending',fail:'failed',cancel:'cancelled'},
sending:{sent:'sent',unknown:'unknown'},
sending:{sent:'sent',unknown:'unknown',fail:'failed'},
unknown:{resolve_sent:'sent',retry:'cancelled'},
failed:{},sent:{},cancelled:{}
}
+42 -22
View File
@@ -1,8 +1,9 @@
'use strict';
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');
const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('../../platform/security/vault.cjs');
const {seedRules,adapters}=require('./catalog.cjs');const {previewMatch,describeRule}=require('./matching.cjs');
const {seedRules}=require('./catalog.cjs');const registry=require('./registry.cjs');const {previewMatch,describeRule}=require('./matching.cjs');
const {buildBatch}=require('./batch.cjs');const {transition}=require('./state.cjs');
const {applyBodyTemplate}=require('./template.cjs');
const {fail,validateRule,publicationIssues}=require('./validation.cjs');
const {windowForCutoff,upcomingWindow,inWindow}=require('./window.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;
@@ -26,8 +27,11 @@ class RuleStore{
this.put('rules',{id:rule.id,draft:{...draft,status:'draft'},published:null,trialVersion:null,trialDemo:null});
}
for(const batch of this.all('batches')){
if(batch.manual&&batch.status==='prepared'){
batch.status='failed';batch.version=(batch.version||1)+1;batch.error='人工补发在发送前中断,可再次受控补发。';this.put('batches',batch);this.updateBatchOrders(batch,'pending',batch.error);
}
if(batch.status==='sending'){
batch.status='unknown';batch.error='服务重启,发信结果待人工核实。';this.put('batches',batch);
batch.status='unknown';batch.version=(batch.version||1)+1;batch.error='服务重启,发信结果待人工核实。';this.put('batches',batch);
this.updateBatchOrders(batch,'unknown',batch.error);
}
}
@@ -35,6 +39,14 @@ class RuleStore{
}catch(error){try{this.db?.close();}catch{}this.vault?.destroy();throw error;}
}
now(){return this.clock().toISOString();}
providersReady(){return ['liveTodo','pdfExport','automaticArchive'].every(key=>this.capabilities[key]===true);}
adapters(){return registry.registry(this);}
fields(){return registry.fields(this);}
recordCapture(input){return registry.recordCapture(this,input);}
saveAdapter(input,actor){return registry.saveAdapter(this,input,actor);}
capturedPreview(sampleId){const captured=this.get('capture-samples',sampleId);if(!captured||captured.provenance!=='server-provider')fail('真实捕获样本不存在。',404);const result=this.preview(captured.sample);if(result.valid){const record=this.get('rules',result.ruleId);record.trialSampleId=sampleId;this.put('rules',record);}return result;}
previewUntrusted(sample){return previewMatch(this.all('rules').map(r=>r.draft),this.adapters(),sample);}
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(error){this.db.exec('ROLLBACK');throw error;}}
get(kind,id){const row=this.db.prepare('SELECT payload FROM records WHERE kind=? AND id=?').get(kind,id);return row?this.vault.decode(kind+':'+id,row.payload):null;}
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));}
@@ -45,28 +57,28 @@ class RuleStore{
const old=this.settings();
if(!input||Object.keys(input).some(k=>!['version','enabled','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&&(!Object.values(this.capabilities).every(Boolean)||!input.channelId))fail('待办接入、PDF 导出与自动归档尚未全部联调,暂不能启用自动发送。',409);
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();
});}
snapshot(){
const rules=this.all('rules').map(record=>({...record.draft,status:record.published?.status||'draft',hasDraft:!record.published||record.draft.version!==record.published.version,publishedVersion:record.published?.version||null,trialVersion:record.trialVersion,explanation:describeRule(record.draft),validationIssues:publicationIssues(record.draft,adapters)}));
return {rules,adapters:copy(adapters),orders:this.all('orders').reverse(),batches:this.all('batches').reverse(),settings:this.settings(),audit:this.all('audit').slice(-100).reverse(),capabilities:copy(this.capabilities),window:upcomingWindow(this.clock(),this.schedule(),this.calendar())};
const rules=this.all('rules').map(record=>({...record.draft,status:record.published?.status||'draft',hasDraft:!record.published||record.draft.version!==record.published.version,publishedVersion:record.published?.version||null,trialVersion:record.trialVersion,explanation:describeRule(record.draft),validationIssues:publicationIssues(record.draft,this.adapters())}));
return {rules,adapters:this.adapters(),orders:this.all('orders').reverse(),batches:this.all('batches').reverse(),settings:this.settings(),audit:this.all('audit').slice(-100).reverse(),capabilities:copy(this.capabilities),window:upcomingWindow(this.clock(),this.schedule(),this.calendar())};
}
saveRule(input,actor){return this.transaction(()=>{
const record=this.get('rules',input?.id);if(!record)fail('规则不存在。',404);
this.put('rule-history',{id:record.id+':'+record.draft.version,rule:copy(record.draft),at:this.now(),actor});
record.draft=validateRule(input,record.draft);record.trialVersion=null;record.trialDemo=null;this.put('rules',record);
record.draft=validateRule(input,record.draft);record.trialVersion=null;record.trialDemo=null;record.trialSampleId=null;this.put('rules',record);
this.audit(actor,'保存规则草稿',record.id+' v'+record.draft.version);return {...record.draft,explanation:describeRule(record.draft)};
});}
preview(sample){
const records=this.all('rules');const result=previewMatch(records.map(r=>r.draft),adapters,sample);
const records=this.all('rules');const result=previewMatch(records.map(r=>r.draft),this.adapters(),sample);
if(result.valid&&result.ruleId){const record=records.find(r=>r.id===result.ruleId);if(record){record.trialVersion=record.draft.version;record.trialDemo=sample.demo===true;this.put('rules',record);}}
return result;
}
publish(id,input,actor){return this.transaction(()=>{
const record=this.get('rules',id);if(!record)fail('规则不存在。',404);
if(input?.version!==record.draft.version)fail('规则已变化,请刷新。',409);
const issues=publicationIssues(record.draft,adapters);
const issues=publicationIssues(record.draft,this.adapters());
if(record.trialVersion!==record.draft.version)issues.push('请先用真实结构样本试运行当前草稿');
if(record.trialDemo!==false)issues.push('演示样本仅用于理解字段,发布前请校验真实业务样本');
const overlaps=this.all('rules').filter(r=>r.id!==id&&r.published?.status==='enabled'&&r.published.processNames.some(p=>record.draft.processNames.includes(p))&&r.published.nodeNames.some(n=>record.draft.nodeNames.includes(n)));
@@ -95,8 +107,8 @@ class RuleStore{
const sourceHash=digest(sample),old=this.get('orders',id);
if(old){if(old.sourceHash!==sourceHash)fail('相同任务和业务修订的内容已变化,请核实来源版本。',409);return old;}
const active=this.matchingPublications(sample);
const result=previewMatch(active,adapters,sample),rule=active.find(r=>r.id===result.ruleId);
const ready=Object.values(this.capabilities).every(Boolean),enabled=rule?.status==='enabled';
const result=previewMatch(active,this.adapters(),sample),rule=active.find(r=>r.id===result.ruleId);
const ready=this.providersReady(),enabled=rule?.status==='enabled';
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)<Date.parse(window.start)){order.status='ignored';order.error='早于当前处理时段的历史订单,不归档、不补发。';}
@@ -126,10 +138,10 @@ class RuleStore{
const order=this.get('orders',id);
if(!order||order.batchId||!['blocked','identified','preparing','archived','pending'].includes(order.status))fail('仅未进入批次的待处理订单可以重新识别。',409);
const published=this.matchingPublications(order.sample);
const result=previewMatch(published,adapters,order.sample),rule=published.find(r=>r.id===result.ruleId);
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=Object.values(this.capabilities).every(Boolean)?'identified':'blocked';
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;
});}
@@ -149,15 +161,16 @@ class RuleStore{
if(!grouped.has(order.categoryId))grouped.set(order.categoryId,[]);grouped.get(order.categoryId).push(order);
}
for(const orders of grouped.values()){
if(this.all('execution-tasks').some(task=>task.categoryIds?.includes(orders[0].categoryId)&&['blocked','failed','unknown','capturing','archiving'].includes(task.status)&&inWindow(task.row?.receivedAt,window)))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)&&!['failed','cancelled'].includes(b.status)))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;
let error=!published||published.status!=='enabled'?'该类别规则已暂停。':null;
if(!error&&orders.some(o=>o.status!=='pending'))error='本类别存在字段、文件或归档尚未准备完成的订单。';
let snapshot;
if(!error)try{snapshot=buildBatch(rule,orders,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window});}catch(cause){error=cause.message;}
if(!error)try{snapshot=buildBatch(rule,orders,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window});snapshot=applyBodyTemplate(snapshot,this.templateResolver?.(rule.categoryId),orders,this.settings().maxMessageBytes);}catch(cause){error=cause.message;}
if(error){for(const order of orders){order.error=error;this.put('orders',order);}continue;}
const batch={...snapshot,id:crypto.randomUUID(),status:'prepared',createdAt:this.now(),ruleSnapshot:copy(rule),channelId:this.settings().channelId,error:null};
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);
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);
@@ -165,28 +178,35 @@ class RuleStore{
return batches;
});}
updateBatchOrders(batch,status,error=null){for(const id of batch.orderIds){const order=this.get('orders',id);if(order?.batchId===batch.id){order.status=status;order.error=error;order.updatedAt=this.now();this.put('orders',order);}}}
beginSending(id){return this.transaction(()=>{
beginSending(id,{manual=false}={}){return this.transaction(()=>{
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
if(this.get('rules',batch.ruleSnapshot.id)?.published?.status!=='enabled')fail('该类别规则已暂停,批次不能进入发送。',409);
if(!(manual&&batch.manual)&&this.get('rules',batch.ruleSnapshot.id)?.published?.status!=='enabled')fail('该类别规则已暂停,批次不能进入发送。',409);
const orders=batch.orderIds.map(oid=>this.get('orders',oid));
if(orders.some(o=>!o||o.batchId!==id||o.status!=='batched'))fail('批次订单预留已变化。',409);
batch.status=transition('batch',batch.status,'send');this.put('batches',batch);return batch;
batch.version=(batch.version||1)+1;batch.status=transition('batch',batch.status,'send');this.put('batches',batch);return batch;
});}
finishSending(id,status,message=null){return this.transaction(()=>{
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
if(!['sent','unknown','failed'].includes(status))fail('发送结果无效。');
batch.status=transition('batch',batch.status,{sent:'sent',unknown:'unknown',failed:'fail'}[status]);batch.error=message;batch.finishedAt=this.now();this.put('batches',batch);
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);}}
this.audit('系统发送','更新批次结果',id+' '+status);return batch;
});}
resolve(id,input,actor){return this.transaction(()=>{
resolve(id,input,actor,{controlled=false}={}){return this.transaction(()=>{
let requestId,inputHash;
if(controlled){
if(typeof input?.idempotencyKey!=='string'||!/^[\w:.-]{1,160}$/.test(input.idempotencyKey))fail('请提供有效核验幂等标识。');
requestId=digest(['resolve',id,actor,input.idempotencyKey]);inputHash=digest([input.version,input.resolution,input.note]);const previous=this.get('resolve-requests',requestId);
if(previous){if(previous.inputHash!==inputHash)fail('此幂等标识已用于不同的核验请求。',409);return this.get('batches',id);}
}
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
if(controlled&&input.version!==(batch.version||1))fail('批次版本已变化,请刷新。',409);
if(!input||!['sent','retry'].includes(input.resolution)||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请选择核验结果并填写至少5字依据。');
batch.status=transition('batch',batch.status,input.resolution==='sent'?'resolve_sent':'retry');batch.resolution={...input,actor,at:this.now()};this.put('batches',batch);
batch.version=(batch.version||1)+1;batch.status=transition('batch',batch.status,input.resolution==='sent'?'resolve_sent':'retry');batch.resolution={...input,actor,at:this.now()};if(input.resolution==='retry'){batch.status='failed';batch.error='人工已核验未发送,等待受控人工补发。';}this.put('batches',batch);
this.updateBatchOrders(batch,input.resolution==='sent'?'sent':'pending',null);
if(input.resolution==='retry')for(const oid of batch.orderIds){const order=this.get('orders',oid);if(order?.batchId===id){order.batchId=null;this.put('orders',order);}}
this.audit(actor,'核验分类邮件结果',id+':'+input.note.trim());return batch;
if(controlled)this.put('resolve-requests',{id:requestId,batchId:id,inputHash,at:this.now()});this.audit(actor,'核验分类邮件结果',id+':'+input.note.trim());return batch;
});}
close(){this.db.close();this.vault.destroy();}
}
+20
View File
@@ -0,0 +1,20 @@
'use strict';
const {renderTemplate}=require('../mail/parser.cjs');
const {fail}=require('./validation.cjs');
function applyBodyTemplate(snapshot,template,orders,maxMessageBytes){
if(!template)return snapshot;
const listing=orders.map(order=>`${order.event.orderNo}\n${String(order.event.brief||'')}\n${order.archive.files.map(file=>file.path).join('\n')}`).join('\n\n');
const values={'产品线':[...new Set(orders.map(order=>order.event.productLine).filter(Boolean))].join('、'),'订单号':snapshot.orderNos.join('、'),'日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date(snapshot.cutoff)),'订单列表':listing};
const rendered=renderTemplate({...template,attachments:[]},values);
// The frozen mandatory order summary and archive links remain complete even
// when a mail author omitted the list variable from a custom template.
const text=rendered.text+(/{{\s*订单列表\s*}}/.test(template.text||'')?'':'\n\n'+listing);
const token='ORDER_LIST_'+require('node:crypto').randomUUID();
const htmlList=snapshot.html.match(/<ul>[\s\S]*<\/ul>/)?.[0]||snapshot.html;
const formatted=template.html?renderTemplate({...template,attachments:[]},{...values,'订单列表':token}).html?.replaceAll(token,htmlList):null;
const html=formatted?formatted+(/{{\s*订单列表\s*}}/.test(template.html||'')?'':htmlList):snapshot.html;
const bytes=16384+Buffer.byteLength(text+html+snapshot.subject)*2+(snapshot.attachments||[]).reduce((sum,file)=>sum+Math.ceil(file.size/3)*4+4096,0);
if(bytes>maxMessageBytes)fail('关联模板展开后超过邮件容量限制。');
return {...snapshot,text,html,template:{id:template.id,version:template.version,bindingVersion:template.bindingVersion}};
}
module.exports={applyBodyTemplate};
+138
View File
@@ -0,0 +1,138 @@
'use strict';
const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto');
const {RuleStore}=require('../../src/modules/order-rules/store.cjs');
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs');
const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs');
const admin={username:'admin',role:'admin'},principal={user:admin,sessionId:'test-session'};
function fixture(t){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'execution-'));const now=()=>new Date('2026-10-19T02:00:00Z');
const store=new RuleStore(dir,{clock:now});t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
const connection={id:'c1',owner:'admin',status:'connected'},workspace={getConnection:()=>connection,snapshot:()=>({connections:[connection]})};
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:'<p>real fixture</p>',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 execution=new OrderExecutionCoordinator({store,workspace,provider,archive,clock:now});
return {store,execution,row,provider,archive,principal,setFail:v=>{failCapture=v;},counts:()=>({captures,exports})};
}
async function configure(f){
await f.execution.scan({connectionId:'c1',idempotencyKey:'first'},principal);
const captured=f.store.fields().samples[0];
const adapter=f.store.saveAdapter({sampleId:captured.id,processName:f.row.processName,processVersion:'1.4',fields:{orderNo:'order',brief:'brief'}},admin);
const current=f.store.snapshot().rules.find(r=>r.id==='bs-change');
const saved=f.store.saveRule({...current,adapterIds:[adapter.id],to:['orders@example.test'],archiveDirectory:'\\\\server\\orders',filenameDate:'receivedAt'},'admin');
assert.equal(f.store.capturedPreview(captured.id).valid,true);f.store.publish(saved.id,{version:saved.version},'admin');
}
test('capture-backed dynamic binding recovers blocked task with stable identity and exports only once',async t=>{
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal);
assert.equal(f.store.all('orders')[0].status,'pending');assert.equal(f.execution.snapshot().tasks.length,1);assert.equal(f.counts().exports,1);
await f.execution.scan({connectionId:'c1',idempotencyKey:'third'},principal);assert.equal(f.counts().exports,1);assert.equal(f.execution.snapshot().capabilities.automaticArchive,true);
assert.throws(()=>f.store.saveAdapter({sampleId:f.store.fields().samples[0].id,processName:f.row.processName,processVersion:'1.4',fields:{orderNo:'invented',brief:'brief'}},admin),/字段/);
});
test('capture failures block the entire category rather than silently omitting an order',async t=>{
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal);
f.row.taskId='t2';f.row.instanceId='i2';f.setFail(true);await f.execution.scan({connectionId:'c1',idempotencyKey:'third'},principal);
assert.equal(f.execution.snapshot().tasks.filter(t=>t.status==='failed').length,1);
assert.equal(f.store.prepare('2026-10-19T03:00:00Z','admin').length,0);
});
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);
f.store.saveSettings({...f.store.settings(),channelId:'channel1'},'admin');const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0];f.store.finishSending(batch.id,'failed','SMTP verify failed');
let sends=0;const mail={exclusive:async(id,fn)=>fn(),store:{channelSecret:id=>({id,version:1,email:'sender@example.test',name:'s',smtp:{}}),guard:()=>{}},smtpFactory:()=>({verify:async()=>{},sendMail:async message=>{sends++;assert.deepEqual(message.to,['orders@example.test']);return {accepted:message.to,rejected:[]};},close:()=>{}})};
const dispatcher=new OrderRuleDispatcher({store:f.store,mail,clock:()=>new Date('2026-10-21T00:00:00Z'),providersReady:()=>true});
const input={version:f.store.get('batches',batch.id).version,idempotencyKey:'resend1',note:'已检查SMTP已修复'};
await assert.rejects(dispatcher.resend(batch.id,input,{username:'op',role:'operator'}),{status:403});
const sent=await dispatcher.resend(batch.id,input,admin);assert.equal(sent.status,'sent');assert.equal(sent.parentBatchId,batch.id);
assert.equal((await dispatcher.resend(batch.id,input,admin)).id,sent.id);assert.equal(sends,1);
await assert.rejects(dispatcher.resend(batch.id,{...input,note:'与原请求不同的依据'},admin),{status:409});
await assert.rejects(dispatcher.resend(batch.id,{...input,idempotencyKey:'again'},admin),{status:409});
});
test('scope, calendar and pause gates survive actual persisted capture provenance',async t=>{
const f=fixture(t);await configure(f);
assert.equal(f.execution.snapshot({user:{username:'other',role:'operator'},sessionId:'other'}).fields.samples.length,0);
assert.equal(f.execution.snapshot({user:{username:'other',role:'operator'},sessionId:'other'}).tasks.length,0);
await assert.rejects(f.execution.scan({connectionId:'c1',idempotencyKey:'foreign'}, {user:{username:'other',role:'operator'},sessionId:'other'}),{status:403});
let scans=0;const scan=f.provider.scan;f.provider.scan=async(...args)=>{scans++;return scan(...args);};
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);
const captured=f.store.fields().samples[0],adapter=f.store.fields().adapters.find(a=>a.sampleId===captured.id);
f.store.saveAdapter({sampleId:captured.id,processName:captured.processName,processVersion:captured.processVersion,fields:adapter.fields,version:adapter.version},admin);
assert.equal(f.store.get('rules','bs-change').published.status,'paused');
assert.throws(()=>f.store.publish('bs-change',{version:f.store.get('rules','bs-change').draft.version},'admin'),{status:409});
});
test('restart converts a never-sent manual attempt into a reachable failed attempt',async t=>{
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'resend-restart-'));let store=new RuleStore(dir);t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});});
store.put('orders',{id:'o1',status:'batched',batchId:'manual1'});store.put('batches',{id:'manual1',version:1,manual:true,status:'prepared',orderIds:['o1']});
store.close();store=new RuleStore(dir);assert.equal(store.get('batches','manual1').status,'failed');assert.equal(store.get('orders','o1').status,'pending');
store.put('batches',{id:'manual2',version:1,manual:true,status:'sending',orderIds:['o1']});store.put('orders',{id:'o1',status:'batched',batchId:'manual2'});
store.close();store=new RuleStore(dir);assert.equal(store.get('batches','manual2').status,'unknown');assert.equal(store.get('orders','o1').status,'unknown');
});
test('workspace exceptions deduplicate per task and recovery requests verification without claiming manual closure',async t=>{
const {WorkspaceStore}=require('../../src/modules/workspace/store.cjs');const f=fixture(t),dir=fs.mkdtempSync(path.join(os.tmpdir(),'execution-exception-')),workspace=new WorkspaceStore(dir);t.after(()=>{workspace.close();fs.rmSync(dir,{recursive:true,force:true});});
const connection=f.execution.workspace.getConnection('c1');f.execution.workspace={getConnection:()=>connection,snapshot:()=>({...workspace.snapshot(),connections:[connection]}),createException:workspace.createException.bind(workspace),actOnException:workspace.actOnException.bind(workspace),record:workspace.record.bind(workspace)};
await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'recover'},principal);assert.equal(workspace.snapshot().exceptions.length,1);assert.equal(workspace.snapshot().exceptions[0].status,'verifying');assert.equal(f.execution.snapshot().tasks[0].recovery.status,'awaiting_verification');
connection.owner='';f.row.taskId='unassigned';f.row.instanceId='unassigned';f.setFail(true);await f.execution.scan({connectionId:'c1',idempotencyKey:'failed-unassigned'},principal);
f.setFail(false);await f.execution.scan({connectionId:'c1',idempotencyKey:'recover-unassigned'},principal);const item=workspace.snapshot().exceptions.find(e=>!e.owner);assert.equal(item.status,'open');assert.equal(f.execution.snapshot().tasks.find(t=>t.row.taskId==='unassigned').recovery.status,'awaiting_verification');assert.equal(workspace.snapshot().exceptions.filter(e=>e.status==='resolved').length,0);
});
test('interrupted archive recovery is explicitly retried and never silently replayed by scan',async t=>{
const f=fixture(t);await configure(f);f.archive.supportsRecovery=true;
const archive=f.archive.archive;f.archive.archive=async()=>{throw Error('worker interrupted');};
await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal);
const task=f.execution.snapshot().tasks[0];assert.equal(task.status,'failed');assert.equal(task.step,'archive');
f.archive.archive=archive;await f.execution.scan({connectionId:'c1',idempotencyKey:'third'},principal);assert.equal(f.counts().exports,0);
await f.execution.retry(task.id,{version:task.version,idempotencyKey:'retry',note:'已核对归档幂等凭据'},principal);
assert.equal(f.execution.snapshot().tasks[0].status,'pending');assert.equal(f.counts().exports,1);
const running=f.store.get('execution-tasks',task.id);running.status='archiving';f.store.put('execution-tasks',running);
const restarted=new OrderExecutionCoordinator({...f.execution,store:f.store,workspace:f.execution.workspace,provider:f.provider,archive:f.archive});
assert.equal(restarted.snapshot().tasks[0].status,'failed');await restarted.stop();
});
test('unknown send first requires recorded verification; only then frozen manual resend is reachable',async t=>{
const f=fixture(t);await configure(f);await f.execution.scan({connectionId:'c1',idempotencyKey:'second'},principal);
f.store.saveSettings({...f.store.settings(),channelId:'channel1'},'admin');const batch=f.store.prepare('2026-10-19T03:00:00Z','admin')[0];
f.store.beginSending(batch.id);f.store.finishSending(batch.id,'unknown','connection lost');
const dispatcher=new OrderRuleDispatcher({store:f.store,mail:{exclusive:async(id,fn)=>fn()},providersReady:()=>true});
await assert.rejects(dispatcher.resend(batch.id,{version:f.store.get('batches',batch.id).version,idempotencyKey:'bad',note:'尚未完成服务端核对'},admin),{status:409});
const resolveInput={version:f.store.get('batches',batch.id).version,idempotencyKey:'verified',resolution:'retry',note:'服务器确认未接受本次邮件'};
assert.throws(()=>f.store.resolve(batch.id,{...resolveInput,version:0},'admin',{controlled:true}),{status:409});
const resolved=f.store.resolve(batch.id,resolveInput,'admin',{controlled:true});assert.equal(resolved.status,'failed');
assert.equal(f.store.resolve(batch.id,resolveInput,'admin',{controlled:true}).status,'failed');
assert.throws(()=>f.store.resolve(batch.id,{...resolveInput,note:'与原来不同的核验结论'},'admin',{controlled:true}),{status:409});
assert.equal(f.store.prepare('2026-10-19T03:00:00Z','system').length,0);
});
test('all fifteen categories capture actual fixture fields, archive to temporary files and send through real loopback SMTP',async t=>{
const {SMTPServer}=require('smtp-server'),nodemailer=require('nodemailer'),{simpleParser}=require('mailparser');
const f=fixture(t),rows=f.store.snapshot().rules.map((rule,i)=>({...f.row,instanceId:'i'+i,taskId:'t'+i,processName:rule.processNames[0],nodeName:rule.nodeNames[0],processVersion:'fixture-1',title:'订单号:SO-'+i,serialNum:'S'+i}));
f.provider.scan=async()=>rows;
f.provider.capture=async(connection,principal,row)=>({sample:{...row,connectionId:connection.id,fields:{'actual.order':'SO-'+row.taskId,'actual.summary':'采集摘要'}},snapshot:{processVersion:row.processVersion,html:'<p>captured fixture</p>',fields:[{path:'actual.order',label:'订单号',value:'SO-'+row.taskId},{path:'actual.summary',label:'摘要',value:'采集摘要'}]}});
await f.execution.scan({connectionId:'c1',idempotencyKey:'capture15'},principal);
for(const [index,current] of f.store.snapshot().rules.entries()){
const captured=f.store.fields().samples.find(s=>s.processName===rows[index].processName);
const adapter=f.store.saveAdapter({sampleId:captured.id,processName:captured.processName,processVersion:captured.processVersion,fields:{orderNo:'actual.order',brief:'actual.summary'}},admin);
const saved=f.store.saveRule({...current,processNames:[captured.processName],nodeNames:[rows[index].nodeName],adapterIds:[adapter.id],to:['orders@example.test'],archiveDirectory:'\\\\server\\orders',filenameDate:'receivedAt'},'admin');
assert.equal(f.store.capturedPreview(captured.id).valid,true);f.store.publish(saved.id,{version:saved.version},'admin');
}
await f.execution.scan({connectionId:'c1',idempotencyKey:'archive15'},principal);assert.equal(f.store.all('orders').filter(o=>o.status==='pending').length,15);
let messages=[];const smtp=new SMTPServer({secure:false,hideSTARTTLS:true,authOptional:true,disabledCommands:['AUTH'],onData(stream,session,cb){const chunks=[];stream.on('data',chunk=>chunks.push(chunk));stream.on('end',()=>{messages.push(Buffer.concat(chunks));cb();});}});
await new Promise(resolve=>smtp.listen(0,'127.0.0.1',resolve));t.after(()=>new Promise(resolve=>smtp.close(resolve)));
const mail={exclusive:async(id,work)=>work(),store:{channelSecret:id=>({id,version:1,email:'sender@example.test',name:'通知',smtp:{}}),guard:()=>{}},smtpFactory:()=>nodemailer.createTransport({host:'127.0.0.1',port:smtp.server.address().port,secure:false,ignoreTLS:true})};
f.store.saveSettings({...f.store.settings(),enabled:true,channelId:'channel1'},'admin');
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:'<div>{{订单列表}}</div>',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);}
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=>{
const {SMTPServer}=require('smtp-server'),nodemailer=require('nodemailer');const f=fixture(t);await configure(f);
const current=f.store.snapshot().rules.find(r=>r.id==='bs-change'),saved=f.store.saveRule({...current,to:['accepted@example.test'],cc:['rejected@example.test']},'admin');
f.store.capturedPreview(f.store.fields().samples[0].id);f.store.publish(saved.id,{version:saved.version},'admin');
await f.execution.scan({connectionId:'c1',idempotencyKey:'archive'},principal);f.store.saveSettings({...f.store.settings(),enabled:true,channelId:'channel1'},'admin');
let messages=0;const smtp=new SMTPServer({secure:false,hideSTARTTLS:true,authOptional:true,disabledCommands:['AUTH'],onRcptTo(address,session,cb){if(!partial||address.address==='rejected@example.test'){const error=Error('Recipient refused');error.responseCode=550;return cb(error);}cb();},onData(stream,session,cb){stream.resume();stream.on('end',()=>{messages++;cb();});}});
await new Promise(resolve=>smtp.listen(0,'127.0.0.1',resolve));t.after(()=>new Promise(resolve=>smtp.close(resolve)));
const mail={exclusive:async(id,work)=>work(),store:{channelSecret:id=>({id,version:1,email:'sender@example.test',name:'通知',smtp:{}}),guard:()=>{}},smtpFactory:()=>nodemailer.createTransport({host:'127.0.0.1',port:smtp.server.address().port,secure:false,ignoreTLS:true})};
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});
await dispatcher.tick();now=new Date('2026-10-19T03:00:00Z');await dispatcher.tick();await dispatcher.stop();assert.equal(f.store.all('batches')[0].status,partial?'unknown':'failed');assert.equal(messages,partial?1:0);
assert.equal(f.store.prepare('2026-10-19T03:00:00Z','system').length,0);
});
+3 -1
View File
@@ -24,6 +24,8 @@ test('rule HTTP authorizes drafts and trials, prevents origin forgery and archiv
const preview=await(await call('/order-rules/preview',{sample},operator)).json();assert.equal(preview.valid,true);assert.equal(orderRules.snapshot().orders.length,0);
assert.equal((await call('/order-rules/orders/not-real/archive',{status:'archived',files:[]},admin)).status,404);
assert.equal((await call('/order-rules/settings',{...snapshot.settings,enabled:true,channelId:'fake'},admin)).status,409);
assert.equal((await call('/order-rules/events',{sample:{...sample,demo:true}},admin)).status,400);
assert.equal((await call('/order-rules/events',{sample:{...sample,demo:true}},admin)).status,410);
assert.equal((await call('/order-rules/preview',{sample:{...sample,demo:false}},operator)).status,200);
assert.equal(orderRules.get('rules','bs-change').trialVersion,null);
assert.equal((await call('/order-rules/preview',{sample,ruleId:'untrusted'},operator)).status,400);
});
+4 -1
View File
@@ -51,7 +51,10 @@ test('real catalog workflow publishes a saved and sampled draft while roles and
async function open(role){const page=await browser.newPage({viewport:{width:1440,height:1000}});page.setDefaultTimeout(7000);await page.goto(base+'/#order-rules');await page.getByLabel('账号',{exact:true}).fill(role);await page.getByLabel('密码',{exact:true}).fill('Test-password-123');await page.getByRole('button',{name:'登录',exact:true}).click();await page.getByRole('button',{name:'通知规则',exact:true}).click();return page;}
const page=await open('admin');await page.locator('[data-rule-id="bs-change"]').click();await page.getByLabel('规则名称',{exact:true}).fill('备损更改通知测试');await page.getByLabel('归档目录',{exact:true}).fill('\\\\fixture-server\\orders\\changes');await page.getByLabel('文件名日期依据',{exact:true}).selectOption('appDate');await page.getByLabel('收件人',{exact:true}).fill('recipient@example.test');await page.getByRole('button',{name:'保存草稿',exact:true}).click();await page.getByText('规则草稿已保存。',{exact:true}).waitFor();
await page.reload();await page.getByRole('button',{name:'通知规则',exact:true}).click();await page.locator('[data-rule-id="bs-change"]').click();assert.equal(await page.getByLabel('规则名称',{exact:true}).inputValue(),'备损更改通知测试');
await page.locator('#order-rule-advanced summary').click();const realSample=JSON.parse(await page.getByLabel('待校验 JSON 样本',{exact:true}).inputValue());realSample.demo=false;await page.getByLabel('待校验 JSON 样本',{exact:true}).fill(JSON.stringify(realSample));await page.getByRole('button',{name:'校验已保存规则',exact:true}).click();await page.locator('#order-rule-preview-result .alert').getByText(/样本校验通过/).waitFor();assert.match(await page.locator('#order-rule-preview-result').innerText(),/OFR_BS_Applicant.OrderNum/);await page.getByRole('button',{name:'发布此版本',exact:true}).click();await page.getByText('规则版本已发布。自动执行仍由全局设置与接入状态控制。',{exact:true}).waitFor();
await page.locator('#order-rule-advanced summary').click();const realSample=JSON.parse(await page.getByLabel('待校验 JSON 样本',{exact:true}).inputValue());realSample.demo=false;await page.getByLabel('待校验 JSON 样本',{exact:true}).fill(JSON.stringify(realSample));await page.getByRole('button',{name:'校验已保存规则',exact:true}).click();await page.locator('#order-rule-preview-result .alert').getByText(/样本校验通过/).waitFor();assert.match(await page.locator('#order-rule-preview-result').innerText(),/OFR_BS_Applicant.OrderNum/);await page.getByRole('button',{name:'发布此版本',exact:true}).click();await page.getByText('发布前必须选择服务端真实采集样本完成试运行。',{exact:true}).waitFor();
const captured=orderRules.recordCapture({sample:realSample,snapshot:{processVersion:realSample.processVersion,html:'<p>isolated provider fixture</p>',fields:Object.entries(realSample.fields).map(([path,value])=>({path,label:path,value}))},taskId:'isolated-provider-fixture'});
const trial=await page.request.post(base+'/api/order-rules/preview',{headers:{Origin:base},data:{sampleId:captured.id}});assert.equal(trial.status(),200);assert.equal((await trial.json()).valid,true);
await page.getByRole('button',{name:'发布此版本',exact:true}).click();await page.getByText('规则版本已发布。自动执行仍由全局设置与接入状态控制。',{exact:true}).waitFor();
assert.equal(orderRules.snapshot().rules.find(r=>r.id==='bs-change').status,'enabled');assert.equal(orderRules.snapshot().settings.enabled,false);assert.equal(orderRules.snapshot().orders.length,0);
await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
await fs.mkdir(path.resolve('output/verification'),{recursive:true});await page.screenshot({path:path.resolve('output/verification/order-rules-mobile.png'),fullPage:true});await page.setViewportSize({width:1440,height:1000});await page.screenshot({path:path.resolve('output/verification/order-rules-desktop.png'),fullPage:true});