fix: make order processing authorized and recoverable
This commit is contained in:
1 parent
0ab7d62aa6
commit
7e42a6dcc6
15 files changed
+219
-129
No files matched your search
@@ -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};
|
||||
@@ -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);
|
||||
|
||||
@@ -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)<Date.parse(batch.cutoff)))continue;if(await this.dispatch(freeze(structuredClone(batch)),config)===false)continue;}
|
||||
});}catch(error){this.store.recordIssue?.('dispatch:'+String(cutoff),{component:'mail',error:error.message,cutoff});if(error.status!==409)throw error;}
|
||||
// Keep the current slot during its collection allowance so repaired categories retry.
|
||||
if(cutoff&&this.clock()-Date.parse(cutoff)>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;
|
||||
|
||||
@@ -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 };
|
||||
@@ -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};
|
||||
@@ -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)<Date.parse(window.start)){order.status='ignored';order.error='早于当前处理时段的历史订单,不归档、不补发。';}
|
||||
const frozen=this.all('batches').find(b=>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)<Date.parse(cutoff)){
|
||||
batch.status=transition('batch',batch.status,'cancel');batch.error='已错过原发送时段,历史订单不补发。';this.put('batches',batch);this.updateBatchOrders(batch,'ignored',batch.error);
|
||||
}
|
||||
if(this.discoveryBlockers(cutoff).length)return [];
|
||||
// A never-sent partial reservation may be replaced only by one complete batch.
|
||||
for(const batch of this.all('batches'))if(batch.status==='prepared'&&!batch.manual&&Date.parse(batch.cutoff)===Date.parse(cutoff)&&this.batchIncomplete(batch)){
|
||||
batch.status='cancelled';batch.version=(batch.version||1)+1;batch.resolution={resolution:'retry',note:'发现同类别新增订单,完整重建未发送批次。'};this.put('batches',batch);
|
||||
for(const id of batch.orderIds){const order=this.get('orders',id);if(order?.batchId===batch.id){order.status='pending';order.batchId=null;this.put('orders',order);}}
|
||||
}
|
||||
const blockers=this.discoveryBlockers(cutoff);
|
||||
for(const record of this.all('rules').filter(r=>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)<Date.parse(window.start)){order.status='ignored';order.error='早于本时段的历史订单,不补发。';this.put('orders',order);continue;}
|
||||
if(validDate(at)&&Date.parse(at)<Date.parse(window.start)){this.recordIssue('missed:'+order.id,{component:'rules',error:'错过整理时点,等待人工处理。',orderIds:[order.id]});order.status='ignored';order.error='早于本时段的历史订单,不补发。';this.put('orders',order);continue;}
|
||||
if(!inWindow(at,window))continue;
|
||||
if(!grouped.has(order.categoryId))grouped.set(order.categoryId,[]);grouped.get(order.categoryId).push(order);
|
||||
}
|
||||
for(const orders of grouped.values()){
|
||||
if(this.categoryIncomplete(orders[0].categoryId,window))continue;
|
||||
if(this.categoryIncomplete(orders[0].categoryId,window)){const categoryId=orders[0].categoryId,error='本类别存在未完成的采集、归档或核验任务。';this.put('window-results',{id:categoryId+':'+cutoff,categoryId,cutoff,status:'blocked',error,updatedAt:this.now()});this.recordIssue('build:'+categoryId+':'+cutoff,{component:'rules',error,cutoff,categoryId,orderIds:orders.map(o=>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(()=>{
|
||||
|
||||
@@ -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));
|
||||
|
||||
Reference in new issue
Block a user