77 lines
8.6 KiB
JavaScript
77 lines
8.6 KiB
JavaScript
'use strict';
|
|
const crypto=require('node:crypto');
|
|
const {frozen}=require('./migrations.cjs');
|
|
const RECIPIENT='2639266652@qq.com';
|
|
const usableTemplate=(t,channelId)=>t?.status==='active'&&t.channelId===channelId&&(!t.notificationMode||t.notificationMode==='normal')&&(t.attachments||[]).length===0;
|
|
function hasEvidence(store,adapter){const capture=store.get('capture-samples',adapter.sampleId||'');if(!capture||capture.provenance!=='server-provider'||capture.sample?.demo||capture.evidenceHash!==adapter.evidenceHash||capture.processName!==adapter.processName||capture.processVersion!==adapter.processVersion)return false;return require('./field-mappings.cjs').evaluateMapping(store,{...adapter,version:adapter.version},capture,{relatedRules:[]}).valid;}
|
|
function existingTemplate(mail,rule,channelId){
|
|
for(const get of [()=>rule.bodyTemplateId?mail.template(rule.bodyTemplateId):null,()=>mail.categoryTemplate(rule.categoryId)]){
|
|
let t;try{t=get();}catch{continue;}
|
|
if(usableTemplate(t,channelId))return t;
|
|
}
|
|
return null;
|
|
}
|
|
function buildPreparationPlan({store,mailStore,source,runId=crypto.randomUUID(),channelId,archiveRoot}){
|
|
const oldRun=store.get('restricted-test','main')?.value||null;
|
|
channelId=channelId||oldRun?.channelId||store.settings().channelId;
|
|
archiveRoot=archiveRoot||oldRun?.archiveRoot;
|
|
const blockers=[],uncovered=[],records=store.all('rules'),adapters=store.adapters(),rules=[],catalog=require('./catalog.cjs').seedRules();
|
|
if(source?.rules?.length!==15)blockers.push('Source must contain exactly 15 categories');
|
|
if(!channelId)blockers.push('Missing existing test channel');if(!archiveRoot)blockers.push('Missing existing Desktop test archive root');
|
|
for(const row of source.rules||[]){
|
|
const identity=row.id||catalog.find(r=>r.sourceRow===row.sourceRow&&r.name===row.name)?.id;
|
|
const matches=records.filter(r=>r.draft.name===row.name||(identity&&r.id===identity));
|
|
if(matches.length!==1){blockers.push('Native category not uniquely matched: '+row.name);continue;}
|
|
const record=matches[0],old=record.draft;
|
|
if(row.id&&row.id!==record.id){blockers.push('Source category identity mismatch: '+row.name);continue;}
|
|
const selected=adapters.filter(a=>old.adapterIds.includes(a.id)&&a.verified&&!a.reference&&row.processNames.includes(a.processName)&&hasEvidence(store,a));
|
|
const missing=row.processNames.filter(p=>!selected.some(a=>a.processName===p));uncovered.push(...missing.map(processName=>({categoryId:record.id,processName})));
|
|
if(!selected.length)blockers.push('Missing verified adapter for category: '+record.id);
|
|
if(!old.archiveDirectory)blockers.push('Missing existing Desktop directory: '+record.id);
|
|
if(archiveRoot)try{require('./restricted-test.cjs').assertPath(store,old.archiveDirectory,{archiveRoot});}catch{blockers.push('Existing archive directory is outside the Desktop test root: '+record.id);}
|
|
const template=existingTemplate(mailStore,old,channelId);
|
|
const templateIntent=template?{action:'reuse',id:template.id}:{action:'create',scope:('test-'+runId+'-'+record.id).slice(0,80),subject:old.subjectPrefix,text:[old.intro,'{{订单列表}}','存放地址:\n{{存放地址}}',old.signature].filter(Boolean).join('\n\n')};
|
|
const draft={...structuredClone(old),processNames:[...row.processNames],nodeNames:[...row.nodeNames],scopes:row.processNames.flatMap(processName=>row.nodeNames.map(nodeName=>({processName,nodeName}))),adapterIds:selected.map(a=>a.id),productLine:old.name,to:[RECIPIENT],cc:[],attachPdf:false,huizhouEnabled:false,huizhouTemplateId:'',sourceRow:row.sourceRow};
|
|
rules.push({id:record.id,previousName:old.name,expectedVersion:old.version,draft,template:templateIntent,source:structuredClone(row.provenance||{})});
|
|
}
|
|
if(new Set(rules.map(r=>r.id)).size!==15)blockers.push('All 15 unique native categories are required');
|
|
return {format:1,runId,source:{file:source.source,sha256:source.sourceSha256,worksheet:source.worksheet},productLineSource:'test-label:rule.name',previousRunId:oldRun?.id||null,previousRunVersion:oldRun?.version||0,channelId,archiveRoot,recipient:RECIPIENT,rules,uncovered,blockers,settings:{enabled:false,processingEnabled:false}};
|
|
}
|
|
function prepareNativeTemplate(mailStore,item,plan,actor){
|
|
if(item.template.action==='reuse'){const t=mailStore.template(item.template.id);if(!usableTemplate(t,plan.channelId))throw Error('Template changed');return t;}
|
|
const channel=mailStore.row(plan.channelId),cursor=channel.cursor,receipts=mailStore.db.prepare('SELECT * FROM receipts WHERE channel_id=?').all(plan.channelId);
|
|
// Native ingest normally advances IMAP state. Restore it within this same
|
|
// mail transaction so a local admin import never skips inbound messages.
|
|
return mailStore.transaction(()=>{
|
|
const intent=item.template,raw=Buffer.from(JSON.stringify({run:plan.runId,category:item.id,subject:intent.subject,text:intent.text}));
|
|
const pending=mailStore.ingest(plan.channelId,'admin-test-'+plan.runId,plan.rules.indexOf(item)+1,{subject:intent.subject,scope:intent.scope,text:intent.text,html:'',sender:'local-admin',sourceSubject:intent.subject,messageId:'admin-test-'+plan.runId+'-'+item.id,attachments:[],notes:['Local test template; no inbound mail or send operation.']},raw,channel.version);
|
|
const active=mailStore.confirm(pending.id,{version:pending.version,scope:intent.scope,subject:intent.subject,useText:true,text:intent.text,notificationMode:'normal'},actor.username);
|
|
mailStore.db.prepare('UPDATE channels SET cursor=? WHERE id=?').run(cursor,plan.channelId);
|
|
mailStore.db.prepare('DELETE FROM receipts WHERE channel_id=?').run(plan.channelId);
|
|
const insert=mailStore.db.prepare('INSERT INTO receipts(id,channel_id,epoch,uid,status,detail,at) VALUES(?,?,?,?,?,?,?)');for(const r of receipts)insert.run(r.id,r.channel_id,r.epoch,r.uid,r.status,r.detail,r.at);
|
|
return active;
|
|
});
|
|
}
|
|
function applyPreparationPlan({store,mailStore,plan,actor,prepareTemplate=prepareNativeTemplate,saveRun=(s,input,a)=>s.saveRestrictedTest(input,a)}){
|
|
if(actor?.role!=='admin'||!actor.username)throw Error('Administrator required');
|
|
if(plan.blockers.length)throw Error('Preparation blocked: '+plan.blockers.join('; '));
|
|
return store.transaction(()=>{
|
|
const old=store.get('restricted-test','main')?.value||null;
|
|
if((old?.id||null)!==plan.previousRunId||(old?.version||0)!==plan.previousRunVersion)throw Error('Previous test run changed');
|
|
for(const item of plan.rules)if(store.get('rules',item.id)?.draft.version!==item.expectedVersion)throw Error('Rule draft changed: '+item.id);
|
|
const settings=store.get('settings','main');store.put('settings',{...settings,version:settings.version+1,channelId:plan.channelId,enabled:false,processingEnabled:false});
|
|
for(const item of plan.rules){const template=prepareTemplate(mailStore,item,plan,actor);store.saveRule({...item.draft,bodyTemplateId:template.id},actor.username);}
|
|
if(old){
|
|
const historyId=old.id+':'+old.version;if(store.get('restricted-test-history',historyId))throw Error('Previous test history already exists');
|
|
store.put('restricted-test-history',{id:historyId,value:structuredClone(old),archivedAt:store.now(),reason:'Replaced by original Excel scopes',source:plan.source});
|
|
for(const order of store.all('orders'))if(order.ruleSnapshot?.testRunId===old.id&&!frozen(store,order)&&!['sent','sending','unknown'].includes(order.status))store.put('orders',{...order,status:'blocked',error:'此前测试运行已替换;保留旧归档和规则快照,须人工核验,不自动重排或发送。',updatedAt:store.now(),preparationHold:{previousRunId:old.id,previousStatus:order.status}});
|
|
store.db.prepare('DELETE FROM records WHERE kind=? AND id=?').run('restricted-test','main');
|
|
}
|
|
const run=saveRun(store,{version:0,enabled:true,recipient:RECIPIENT,archiveRoot:plan.archiveRoot,channelId:plan.channelId,ruleIds:plan.rules.map(r=>r.id)},actor);
|
|
store.put('test-preparation',{id:run.id,source:plan.source,provenance:plan.rules.map(r=>({id:r.id,source:r.source})),productLineSource:plan.productLineSource,preparedAt:store.now(),automaticProcessing:false,automaticSending:false});
|
|
return {run,settings:store.settings(),templates:plan.rules.length};
|
|
});
|
|
}
|
|
function publicPlan(plan){return {...plan,rules:plan.rules.map(r=>({id:r.id,name:r.draft.name,expectedVersion:r.expectedVersion,processNames:r.draft.processNames,nodeNames:r.draft.nodeNames,scopes:r.draft.scopes,productLine:r.draft.productLine,productLineSource:plan.productLineSource,to:r.draft.to,cc:[],attachPdf:false,archiveDirectory:r.draft.archiveDirectory,adapterIds:r.draft.adapterIds,template:r.template.action==='reuse'?r.template:{action:'create',scope:r.template.scope,variables:['订单列表','存放地址']},source:r.source}))};}
|
|
module.exports={RECIPIENT,existingTemplate,buildPreparationPlan,prepareNativeTemplate,applyPreparationPlan,publicPlan};
|