fix: carry confirmed unsent orders into the next scheduled batch

This commit is contained in:
abaishu0730 committed 2026-10-27 12:11:28 +08:00
1 parent dfdcf0cc2d
commit 069a69af93
23 files changed
+338 -40

No files matched your search

+2 -2
View File
@@ -1,7 +1,7 @@
'use strict';
const {fail}=require('../order-rules/validation.cjs');
async function orderExecutionApi({execution,orderRules,dispatcher,workspace,user,sessionId,url,route,method,body,reply}){
const task=/^\/api\/order-execution\/tasks\/([\w-]+)\/(retry|resolve)$/.exec(route),resend=/^\/api\/order-rules\/batches\/([\w-]+)\/resend$/.exec(route);
const task=/^\/api\/order-execution\/tasks\/([\w-]+)\/(retry|resolve|dismiss)$/.exec(route),resend=/^\/api\/order-rules\/batches\/([\w-]+)\/resend$/.exec(route);
const sample=/^\/api\/order-rules\/field-samples\/(list|capture)$/.exec(route),mapping=/^\/api\/order-rules\/field-mappings\/(draft|check|activate)$/.exec(route);
const catalog=route==='/api/order-rules/field-samples/catalog',propose=route==='/api/order-rules/field-mappings/propose';
const scopeSettings=route==='/api/order-rules/field-mappings/catalog-settings';
@@ -30,7 +30,7 @@ async function orderExecutionApi({execution,orderRules,dispatcher,workspace,user
const principal={user,sessionId};let result;
if(route==='/api/order-execution/scan'){
if(!body||Object.keys(body).some(k=>!['connectionId','idempotencyKey'].includes(k)))fail('扫描参数无效。');result=await execution.scan(body,principal);
}else if(task){if(!body||Object.keys(body).some(k=>!(task[2]==='resolve'?['version','idempotencyKey','note','resolution']:['version','idempotencyKey','note']).includes(k)))fail('重试参数无效。');result=await execution[task[2]](task[1],body,principal);}
}else if(task){if(!body||Object.keys(body).some(k=>!(task[2]==='resolve'?['version','idempotencyKey','note','resolution']:['version','idempotencyKey','note']).includes(k)))fail('重试参数无效。');if(task[2]==='dismiss'){result=require('./dismiss-task.cjs').dismissTask(orderRules,task[1],body,user);const members=execution.dashboard?.users?.()||[user];workspace?.syncBusinessIssues?.(orderRules.all('business-issues'),members);const id=orderRules.get('execution-tasks',task[1])?.exceptionId,item=id&&workspace?.snapshot?.().exceptions?.find(e=>e.id===id);if(item&&item.status!=='retired'&&!item.sourceIssueId)workspace.actOnException(item.id,{version:item.version,action:'archive',note:body.note},user,members);}else result=await execution[task[2]](task[1],body,principal);}
else{
if(user?.role!=='admin')fail('仅管理员可维护字段适配或人工补发。',403);
if(sample){
+4 -3
View File
@@ -251,7 +251,7 @@ class OrderExecutionCoordinator{
const eligibleAt=eligibility.eventTime(this.store,row);
if(testing&&(row.configurationOnly||Date.parse(eligibleAt)<Date.parse(testing.since)))continue;
if(taskIdentity.records(this.store,'processed-task-receipts',row).length)continue;
let task=taskIdentity.lookup(this.store,'execution-tasks',row);
let task=taskIdentity.lookup(this.store,'execution-tasks',row);if(task?.removedAt||task?.revisionIgnored)continue;
const rules=this.store.all('rules').map(r=>this.store.executionRule(r)||(!testing?r.draft:null)).filter(rule=>rule&&matchesScope(rule,row));
if(!rules.length&&!task)continue;
const id=task?.id||taskIdentity.taskIdentity(row);
@@ -260,7 +260,8 @@ class OrderExecutionCoordinator{
// Pre-activation backlog requires explicit admission. Eligible missed-window work is
// retained below without recapturing, archiving, or widening frozen mail.
if(baseline&&received<Date.parse(baseline)&&!task&&!eligibility.isAdmitted(this.store,row))continue;
const historical=window&&Number.isFinite(received)&&received<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this.store,row)&&!this.store.intakeWindow(row);
const carried=task?.orderId&&require('../order-rules/carry-forward.cjs').hasCarry(this.store,this.store.get('orders',task.orderId));
const historical=!carried&&window&&Number.isFinite(received)&&received<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this.store,row)&&!this.store.intakeWindow(row);
const frozen=historical&&this.store.all('batches').find(batch=>rules.some(rule=>rule.categoryId===batch.categoryId)&&batch.window&&inWindow(eligibleAt,batch.window));
if(historical&&!baseline&&!frozen)continue;
considered++;
@@ -332,7 +333,7 @@ class OrderExecutionCoordinator{
this.reconcileArchive(task);
const order=task.orderId&&this.store.get('orders',task.orderId);
if(!needsRuntimeCheck(order))continue;
if(window&&!reserved(order)&&Date.parse(eligibility.orderTime(this.store,order))<Date.parse(collectionBounds(window).start)&&!this.store.intakeWindow(task.row))continue;
if(window&&!reserved(order)&&!require('../order-rules/carry-forward.cjs').hasCarry(this.store,order)&&!require('../order-rules/carry-forward.cjs').hasCarry(this.store,order,'huizhou')&&Date.parse(eligibility.orderTime(this.store,order))<Date.parse(collectionBounds(window).start)&&!this.store.intakeWindow(task.row))continue;
await this.checkArchivedRuntime(task,order,connection,principal);
}
if(input.automatic&&!this.store.settings().processingEnabled)throw Error('自动处理已暂停,待处理对账保留到恢复后继续。');
@@ -0,0 +1,20 @@
'use strict';
const {fail}=require('../order-rules/validation.cjs');
const identity=require('../order-rules/task-identity.cjs');
function dismissTask(store,id,input,user){
if(user?.role!=='admin')fail('仅管理员可移出待处理记录。',403);
if(!input||Array.isArray(input)||Object.keys(input).some(k=>!['version','note','idempotencyKey'].includes(k))||!Number.isSafeInteger(input.version)||input.version<1||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000||typeof input.idempotencyKey!=='string'||!input.idempotencyKey.trim()||input.idempotencyKey.length>200)fail('须提供当前版本、至少五字的操作依据和幂等标识。');
const inputHash=identity.digest({version:input.version,note:input.note.trim(),actor:user.username});
return store.transaction(()=>{
const task=store.get('execution-tasks',id);if(!task)fail('执行任务不存在。',404);
const safe=()=>({id:task.id,status:task.status,removedAt:task.removedAt});
if(task.removal?.idempotencyKey===input.idempotencyKey){if(task.removal.inputHash!==inputHash)fail('幂等标识已用于不同操作。',409);return safe();}
if(task.version!==input.version||task.removedAt)fail('记录已变化,请刷新后重试。',409);
const referenced=row=>row.taskId===id||row.executionTaskId===id||row.identity===id||row.taskIds?.includes(id)||row.id===id||String(row.id||'').startsWith(id+':');
if(task.orderId||store.get('orders',id)||task.blockedByBatchId||task.conflict||!['blocked','failed'].includes(task.status)||task.step!=='capture'||!(task.errorCode==='BPM_TASK_NOT_CURRENT'||task.recovery?.status==='requires-history-verification')||store.all('archive-intents').some(referenced)||store.all('processed-task-receipts').some(r=>referenced(r)||identity.sameTask(r,task.row))||store.all('batches').some(b=>referenced(b)||b.orderIds?.includes(id)||b.orderIds?.includes('task:'+id)))fail('仅可移出尚未归档、编批或发送的离开节点采集任务。',409);
const at=store.now();task.removedAt=at;task.removal={at,actor:user.username,note:input.note.trim(),idempotencyKey:input.idempotencyKey,inputHash};task.revisionIgnored=true;task.status='ignored';task.version++;task.updatedAt=at;task.history=[...(task.history||[]),{at,actor:user.username,action:'dismiss',status:'ignored',step:task.step,note:input.note.trim()}];store.put('execution-tasks',task);
for(const issue of store.all('business-issues'))if(issue.taskId===id||issue.taskIds?.includes(id))store.put('business-issues',{...issue,status:'retired',retiredAt:at,updatedAt:at,retirement:{actor:user.username,note:input.note.trim(),taskId:id}});
store.audit(user.username,'移出未处理采集任务',id+':'+input.note.trim());return safe();
});
}
module.exports={dismissTask};
+1 -1
View File
@@ -40,7 +40,7 @@ function buildBatch(rule,orders,cutoff,{maxMessageBytes=20971520,window,notifica
if(order.ruleSnapshot[binding]!==rule[binding])fail('同一批次不能混合不同模板绑定。');
if(order.status&&order.status!=='pending')fail('此类别包含未准备完成的订单。');
const received=Date.parse(store?require('./restricted-test.cjs').orderTime(store,order):order.event?.receivedAt);
if(window&&(store?!require('./restricted-test.cjs').orderInWindow(store,order,window):!require('./window.cjs').inWindow(order.event?.receivedAt,window)))fail('订单接收时间不属于本批时段窗口。');
if(window&&(store?!require('./restricted-test.cjs').orderInWindow(store,order,window,notificationMode):!require('./window.cjs').inWindow(order.event?.receivedAt,window)))fail('订单接收时间不属于本批时段窗口。');
if(!Number.isFinite(received)||received>limit)fail('订单接收时间超出本批截止范围。');
const number=order.event?.orderNo;
if(typeof number!=='string'||!number.trim()||/[\r\n\x00-\x1f]/.test(number))fail('订单号无效。');
+100
View File
@@ -0,0 +1,100 @@
'use strict';
const path=require('node:path');
const identity=require('./task-identity.cjs'),eligibility=require('./restricted-test.cjs');
const {delivery,updateDelivery,modeOf}=require('./delivery.cjs');
const {windowForCutoff}=require('./window.cjs'),{nextSlots}=require('../../shared/schedule.cjs');
const validDate=value=>typeof value==='string'&&Number.isFinite(Date.parse(value));
function receipt(archive){return !!archive&&validDate(archive.archivedAt)&&Array.isArray(archive.files)&&archive.files.some(f=>f?.kind==='pdf'&&/\.pdf$/i.test(f.name))&&archive.files.every(f=>f&&typeof f.name==='string'&&f.name&&!/[\\/\x00-\x1f]/.test(f.name)&&typeof f.path==='string'&&path.win32.isAbsolute(f.path)&&/^[a-f\d]{64}$/i.test(f.sha256)&&Number.isSafeInteger(f.size)&&f.size>0&&['pdf','notice'].includes(f.kind));}
function basis(order){return identity.digest([order.sourceHash,order.sample,order.ruleSnapshot,order.archiveGeneration,order.archive]);}
function proof(batch){const p=batch.deliveryEvidence;return !!p&&['not_submitted','all_recipients_rejected','manual_confirmed_unsent'].includes(p.outcome)&&typeof p.phase==='string'&&!!p.phase&&validDate(p.at);}
function associated(store,order,mode){return store.all('batches').filter(b=>modeOf(b)===mode&&b.orderIds?.includes(order.id));}
function safeHistory(batches){return batches.every(b=>proof(b)&&(b.status==='failed'||b.status==='cancelled'&&b.resolution?.resolution==='carry_forward'));}
function qualified(store,order,{active=true}={}){
if(!order||order.removedAt||!order.categoryId||!order.sample||!receipt(order.archive)||!order.ruleSnapshot)return null;
const tasks=store.all('execution-tasks').filter(t=>t.orderId===order.id);if(tasks.length!==1)return null;const task=tasks[0];
if(task.removedAt||task.supersededBy||task.revisionIgnored||task.conflict||task.blockedByBatchId||!['complete','missed_window'].includes(task.step))return null;
if(!identity.sameTask(task.row,order.sample)||['source','portalSource','taskId','instanceId','revision','processName','nodeName','receivedAt'].some(k=>String(task.row?.[k])!==String(order.sample[k])))return null;
const captured=store.get('capture-samples',task.sampleId||'');if(captured?.provenance!=='server-provider'||captured.taskId!==task.id||typeof captured.snapshot?.html!=='string'||!captured.snapshot.html.trim()||!captured.sample||identity.fingerprint(captured.sample)!==identity.fingerprint(order.sample))return null;
let original;try{original=store.intakeWindow(order.sample,{includeExpired:true});}catch{return null;}if(!original)return null;
if(active){
if(task.sourceUnavailableAt||task.runtimeCheck?.status==='blocked'||typeof store.executionSources==='function'&&!store.executionSources().includes(task.connectionId))return null;
let current;try{current=store.executionRule(store.get('rules',order.ruleSnapshot.id));eligibility.assertOrder(store,order);}catch{return null;}
if(current?.status!=='enabled'||current.version!==order.ruleSnapshot.version)return null;
}
return {task,original};
}
function windowForOrder(store,value,mode='normal'){
if(!['normal','huizhou'].includes(mode))return null;
// A Hui projection replaces event/order numbers. Always validate the persisted source.
const order=value?.id&&store.get('orders',value.id),stamp=order?.carryForward?.[mode];if(!stamp||stamp.basisHash!==basis(order)||!qualified(store,order,{active:false}))return null;
try{return windowForCutoff(stamp.targetCutoff,store.schedule(),store.calendar());}catch{return null;}
}
function hasCarry(store,order,mode='normal'){return !!windowForOrder(store,order,mode);}
function knownMissed(store,value,original,stamp){
if(!value)return true;
if(![original.end,stamp?.targetCutoff].includes(value.end))return false;
let expected;try{expected=windowForCutoff(value.end,store.schedule(),store.calendar());}catch{return false;}
return ['start','end','collectionStart','collectionEnd','collectionLeadMinutes','policyVersion','startInclusive','endInclusive'].every(key=>value[key]===expected[key]);
}
function candidate(store,order,mode){
const q=qualified(store,order),state=delivery(order,mode);if(!q||!state||order.blockedByBatchId||state.blockedByBatchId||!['pending','blocked','archived'].includes(state.status))return null;
const batches=associated(store,order,mode);if(!safeHistory(batches))return null;
const failed=batches.filter(b=>b.status==='failed');if(state.batchId&&!failed.some(b=>b.id===state.batchId))return null;
if(mode==='normal'&&['unknown','sending','sent','ignored','archiving','capturing','failed'].includes(q.task.status))return null;
if(mode==='huizhou'&&(order.ruleSnapshot.huizhouEnabled!==true||!state.orderNos?.length||state.issues?.length||!['pending','blocked','archived','batched','sent','unknown'].includes(order.status)||q.task.step!=='complete'&&q.task.step!=='missed_window'))return null;
const stamp=order.carryForward?.[mode];if(stamp&&!windowForOrder(store,order,mode))return null;
if(!knownMissed(store,mode==='normal'?order.missedWindow:state.missedWindow,q.original,stamp)||mode==='normal'&&!knownMissed(store,q.task.missedWindow,q.original,stamp))return null;
return {...q,order,mode,state,stamp,failed,previous:stamp?.targetCutoff||q.original.end};
}
function nextWindow(store,item,now){
let cursor=new Date(Math.max(+now,Date.parse(item.previous)));const batches=store.all('batches');
for(let n=0;n<740;n++){const cutoff=nextSlots(store.schedule(),cursor,1,store.calendar())[0];if(!cutoff)return null;
if(!batches.some(b=>b.categoryId===item.order.categoryId&&modeOf(b)===item.mode&&b.cutoff===cutoff))return windowForCutoff(cutoff,store.schedule(),store.calendar());cursor=new Date(cutoff);
}return null;
}
function retireIssue(store,id,targetCutoff,at){
const issue=store.get('business-issues',id);if(!issue||['retired','resolved'].includes(issue.status))return;
store.put('business-issues',{...issue,previousStatus:issue.status,status:'retired',retiredAt:at,updatedAt:at,retirement:{reason:'carry_forward',targetCutoff,at}});
}
function advance(store,actor='系统调度'){
return store.transaction(()=>{
const moved=[],config=store.settings(),now=store.clock();if(config.enabled!==true||config.processingEnabled!==true||require('./stability-period.cjs').period(store)?.expired)return {moved};
const candidates=new Map(),deferredCollections=new Set();
for(const order of store.all('orders'))for(const mode of ['normal','huizhou']){
if(windowForOrder(store,order,mode))for(const entry of order.carryForward[mode].history||[])deferredCollections.add(JSON.stringify([order.categoryId,mode,entry.fromCutoff]));
const item=candidate(store,order,mode);if(item)candidates.set(order.id+':'+mode,item);
}
// Remove the entire failed collection if any member is unsafe, including linked failures.
let changed=true;while(changed){changed=false;for(const [key,item] of candidates)if(item.failed.some(b=>!b.orderIds?.length||b.orderIds.some(id=>!candidates.has(id+':'+item.mode)))){candidates.delete(key);changed=true;}}
for(const [key,item] of candidates){
const result=store.get('window-results',item.order.categoryId+':'+item.previous+(item.mode==='huizhou'?':huizhou':''));
// Once a collection has deferred, its admitted slow members must join that
// decision even if a later prepare pass overwrote the old result as empty.
const deferred=deferredCollections.has(JSON.stringify([item.order.categoryId,item.mode,item.previous]));
const elapsed=+now-Date.parse(item.previous);if(!item.failed.length&&elapsed<=(result?.status==='blocked'||deferred?60000:1800000))continue;
item.target=nextWindow(store,item,now);if(!item.target)candidates.delete(key);
}
// Each failed collection gets one target; no members may be cancelled in isolation.
changed=true;while(changed){changed=false;for(const [key,item] of candidates)if(item.failed.some(b=>b.orderIds.some(id=>!candidates.get(id+':'+item.mode)?.target||candidates.get(id+':'+item.mode).target.end!==item.target?.end))){candidates.delete(key);changed=true;}}
for(const item of candidates.values()){
if(!item.target)continue;
const order=store.get('orders',item.order.id),state=delivery(order,item.mode),at=now.toISOString(),reason=item.failed.length?'confirmed_unsent':item.stamp?'carry_window_missed':'original_window_missed';
const entry={fromCutoff:item.previous,targetCutoff:item.target.end,at,reason,lastError:state.error||null,batchIds:item.failed.map(b=>b.id)};
order.carryForward={...(order.carryForward||{}),[item.mode]:{originCutoff:item.stamp?.originCutoff||item.original.end,targetCutoff:item.target.end,basisHash:basis(order),reason,lastError:state.error||null,updatedAt:at,history:[...(item.stamp?.history||[]),entry]}};
updateDelivery(order,item.mode,{status:'pending',batchId:null,error:null});if(item.mode==='normal')delete order.missedWindow;else delete order.notifications.huizhou.missedWindow;
order.updatedAt=at;store.put('orders',order);
for(const id of item.mode==='normal'?['missed:'+order.id,'missed:'+order.id+':normal']:['missed:'+order.id+':huizhou'])retireIssue(store,id,item.target.end,at);
if(item.mode==='normal'){const task=store.get('execution-tasks',item.task.id);task.status='pending';task.step='complete';task.error=null;delete task.missedWindow;task.version=(task.version||0)+1;task.updatedAt=at;store.put('execution-tasks',task);}
for(const old of item.failed){const batch=store.get('batches',old.id);if(batch.status!=='failed')continue;batch.status='cancelled';batch.version=(batch.version||0)+1;batch.resolution={...(batch.resolution||{}),resolution:'carry_forward',targetCutoff:item.target.end,at,actor:actor?.username||actor};store.put('batches',batch);retireIssue(store,'batch:'+batch.id,item.target.end,at);}
store.audit(actor?.username||actor,'未发送订单顺延',order.id+' '+item.mode+' '+item.previous+' → '+item.target.end);moved.push({orderId:order.id,mode:item.mode,targetCutoff:item.target.end});
}
// Evaluate shared build issues only after all member updates are persisted.
for(const item of candidates.values()){
if(!item.target)continue;
const id='build:'+item.order.categoryId+':'+item.previous+(item.mode==='huizhou'?':huizhou':''),issue=store.get('business-issues',id);
if(issue?.orderIds?.length&&issue.orderIds.every(orderId=>store.get('orders',orderId)?.carryForward?.[item.mode]?.history?.some(entry=>entry.fromCutoff===item.previous&&entry.targetCutoff===item.target.end)))retireIssue(store,id,item.target.end,now.toISOString());
}
return {moved};
});
}
module.exports={advance,windowForOrder,hasCarry};
@@ -20,8 +20,9 @@ function list(store,{cutoff}={}){
const groups=new Map(),frozen=store.all('batches');
for(const order of store.all('orders')){
const rule=order.ruleSnapshot;if(order.removedAt||!rule?.id||!rule.categoryId||!require('./scopes.cjs').matchesScope(rule,order.event||{}))continue;
if(order.blockedByBatchId||order.missedWindow||order.status==='ignored'||!require('./restricted-test.cjs').orderInWindow(store,order,window))continue;
if(order.blockedByBatchId||order.status==='ignored')continue;
for(const mode of ['normal','huizhou']){
const carried=require('./carry-forward.cjs').windowForOrder(store,order,mode);if(order.missedWindow&&!carried||!require('./restricted-test.cjs').orderInWindow(store,order,window,mode))continue;
const notice=delivery(order,mode);if(!notice||notice.batchId||!['identified','preparing','archived','pending','blocked','failed'].includes(notice.status))continue;
if(mode==='huizhou'&&rule.huizhouEnabled!==true)continue;
if(frozen.some(b=>b.categoryId===rule.categoryId&&(b.notificationMode||'normal')===mode&&b.cutoff===window.end))continue;
@@ -30,7 +31,7 @@ function list(store,{cutoff}={}){
}
return [...groups.values()].map(group=>{
const {rule,orders,...value}=group,saved=store.get('batch-content-drafts',group.id);let template,sourceError;try{template=store.templateResolver?.(rule.categoryId,rule,group.notificationMode);}catch(error){sourceError=error.message;}let base;try{base=definition(store,rule,window.end,group.notificationMode,template);}catch(error){sourceError=error.message;base={context:digest([rule,window.end,group.notificationMode]),subject:rule.subjectPrefix||rule.name,format:'text',body:'{{订单明细}}\n{{存放地址}}'};}
const row={...value,version:saved?.version||0,context:base.context,editor:saved?{subject:saved.subject,format:saved.format,body:saved.body}:base,edited:!!saved,editable:!sourceError&&+store.clock()<Date.parse(window.end),subject:saved?.subject||base.subject,to:rule.to,cc:rule.cc||[],orderNos:orders.map(o=>o.event?.orderNo).filter(Boolean),ruleSnapshot:rule};
const row={...value,carriedOrderIds:orders.filter(o=>require('./carry-forward.cjs').windowForOrder(store,o,group.notificationMode)?.end===window.end).map(o=>o.id),version:saved?.version||0,context:base.context,editor:saved?{subject:saved.subject,format:saved.format,body:saved.body}:base,edited:!!saved,editable:!sourceError&&+store.clock()<Date.parse(window.end),subject:saved?.subject||base.subject,to:rule.to,cc:rule.cc||[],orderNos:orders.map(o=>o.event?.orderNo).filter(Boolean),ruleSnapshot:rule};
try{if(sourceError)fail(sourceError,409);const snapshot=require('./template.cjs').composeBatch(rule,require('./huizhou.cjs').ordersForMode(orders,group.notificationMode),window.end,store,{window,notificationMode:group.notificationMode});Object.assign(row,{subject:snapshot.subject,text:snapshot.text,html:snapshot.html,template:snapshot.template,signature:snapshot.signature});}
catch(error){row.error=error.message;row.text='';row.html='';}
return row;
@@ -4,7 +4,7 @@ const eligibility=require('./restricted-test.cjs');
function discoveryBlockers(store,cutoff,allowed=()=>true){
if(!store.executionSources)return (store.deliveryBlockers?.(allowed)||[]).map(id=>'连接 '+id+' 本地执行线索尚未交付。');
const window=cutoff?windowForCutoff(cutoff,store.schedule(),store.calendar()):null;
const relevant=store.all('execution-tasks').filter(task=>!task.removedAt&&!['sent','ignored'].includes(task.status)&&(!window||eligibility.eventInWindow(store,task.row,window)));
const relevant=store.all('execution-tasks').filter(task=>!task.removedAt&&!['sent','ignored'].includes(task.status)&&(!window||eligibility.eventInWindow(store,task.row,window)||['normal','huizhou'].some(mode=>require('./carry-forward.cjs').windowForOrder(store,task.orderId&&store.get('orders',task.orderId),mode)?.end===window.end)));
const sources=new Set([...store.executionSources(),...relevant.map(task=>task.connectionId)].filter(allowed));
// Inactive sources cannot consume hints. Retain their evidence without
// blocking unrelated work, unless a retained task still needs that source.
+6 -5
View File
@@ -35,7 +35,7 @@ class OrderRuleDispatcher{
}
async perform(now){
this.store.expireIntakes?.();
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分钟,请负责人核验后受控补发。');
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分钟,请负责人核验后受控补发。',{outcome:'not_submitted',phase:'queue_expired',at:this.clock().toISOString()});
if(!this.ready())return;
const config=freeze(structuredClone(this.store.settings())),schedule=this.settings()?.schedule,calendar=this.calendar();
if(!schedule?.times?.length)return;
@@ -54,7 +54,7 @@ class OrderRuleDispatcher{
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;
const grace=batch.intakeGrace?.cutoff===batch.cutoff&&Date.parse(batch.intakeGrace.expiresAt)===Date.parse(batch.cutoff)+1800000&&Date.parse(batch.createdAt)<=Date.parse(batch.intakeGrace.expiresAt)&&batch.orderIds?.every(id=>{const order=this.store.get('orders',id);return order&&this.store.intakeWindow(order.sample||order.event)?.end===batch.cutoff;});
const grace=batch.intakeGrace?.cutoff===batch.cutoff&&Date.parse(batch.intakeGrace.expiresAt)===Date.parse(batch.cutoff)+1800000&&Date.parse(batch.createdAt)<=Date.parse(batch.intakeGrace.expiresAt)&&batch.orderIds?.every(id=>{const order=this.store.get('orders',id);return order&&(this.store.intakeWindow(order.sample||order.event)?.end===batch.cutoff||require('./carry-forward.cjs').windowForOrder(this.store,order,modeOf(batch))?.end===batch.cutoff);});
if(batch.createdAt&&(Date.parse(batch.createdAt)>Date.parse(batch.cutoff)+60000&&!grace||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.
@@ -81,7 +81,7 @@ class OrderRuleDispatcher{
assertMailPolicy(batch);
require('./restricted-test.cjs').assertBatch(this.store,batch,config);
if(batch.channelId&&batch.channelId!==config.channelId){
this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。');return;
this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。',{outcome:'not_submitted',phase:'preflight',at:this.clock().toISOString()});return;
}
const attachments=await this.attachments(batch,config);
if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>1800000)throw Error('冻结发送队列超过30分钟。');
@@ -106,7 +106,8 @@ class OrderRuleDispatcher{
}catch(error){
if(!sending&&!manual&&error.code==='DISCOVERY_INCOMPLETE')return false;
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==='MAIL_POLICY_BLOCKED'?error.message:error.code==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`);
const evidence=!sending?{outcome:'not_submitted',phase:'preflight',at:this.clock().toISOString()}:rejected?{outcome:'all_recipients_rejected',phase:'smtp_envelope',at:this.clock().toISOString()}:undefined;
this.store.finishSending(batch.id,sending&&!rejected?'unknown':'failed',sending&&!rejected?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${error.code==='MAIL_POLICY_BLOCKED'?error.message:error.code==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`,evidence);
}finally{
try{transport?.close?.();}finally{if(transport)this.mail.clients?.delete(transport);}
}
@@ -129,7 +130,7 @@ class OrderRuleDispatcher{
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 state=delivery(this.store.get('orders',oid),modeOf(source));return !state||['sent','unknown','batched','sending'].includes(state.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()}};
const next={...structuredClone(source),id:crypto.randomUUID(),version:1,parentBatchId:source.id,rootBatchId:root,status:'prepared',deliveryEvidence:null,submissionAttemptedAt:null,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);updateDelivery(o,modeOf(next),{batchId:next.id,status:'batched',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;
});
+2 -2
View File
@@ -49,7 +49,7 @@ function captureEvidence(context,task,user){
}
function orderRow(order,task){
const event=identity(order?.event||task?.row);
return {...event,...pick(order,['id','status','categoryId','error','reason','batchId','createdAt','updatedAt','orderNo','receivedAt']),...(order?{notifications:notifications(order),...(order.ruleSnapshot?.testRunId?{testRunId:order.ruleSnapshot.testRunId}:{})}:{}),
return {...event,...pick(order,['id','status','categoryId','error','reason','batchId','createdAt','updatedAt','orderNo','receivedAt']),...(order?{notifications:notifications(order),carryForward:Object.fromEntries(['normal','huizhou'].filter(mode=>order.carryForward?.[mode]).map(mode=>[mode,pick(order.carryForward[mode],['originCutoff','targetCutoff','reason','lastError','updatedAt'])])),...(order.ruleSnapshot?.testRunId?{testRunId:order.ruleSnapshot.testRunId}:{})}:{}),
id:order?.id||'task:'+task.id,connectionId:order?.sample?.connectionId||event.connectionId||task?.connectionId,
error:task?.error||order?.error,executionTaskId:task?.id,executionStatus:task?.status,executionStep:task?.step,deferredUntil:task?.deferredUntil,deferredSendAt:task?.deferredSendAt,exceptionId:task?.exceptionId,orderNo:order?.orderNo||event.orderNo||event.serialNum||event.taskId,
categoryName:order?.ruleSnapshot?.name||'',categoryId:order?.categoryId||order?.ruleSnapshot?.categoryId||order?.ruleSnapshot?.id||task?.categoryIds?.[0]||'',status:task&&['failed','blocked','unknown','capturing','archiving'].includes(task.status)?task.status:order?.status||task?.status};
@@ -91,7 +91,7 @@ function publicRevision(context,user){
}
function queryOrders(context,input,user){const rows=visibleOrders(context,user),revision=crypto.createHash('sha256').update(publicRevision(context,user)+JSON.stringify(rows.map(r=>[r.id,r.collectingBatches]))).digest('hex').slice(0,24);return page(rows,filters(input,'orders'),revision);}
function batchRow(context,batch){
return {...pick(batch,['id','version','categoryId','subject','status','error','createdAt','sentAt','resolvedAt','windowStart','windowEnd','cutoff','orderNos','testRunId']),categoryName:batch.ruleSnapshot?.name||context.orderRules.get('rules',batch.categoryId)?.draft?.name||batch.categoryId,notificationMode:modeOf(batch),collectionStart:batch.window?.collectionStart,collectionEnd:batch.window?.collectionEnd,windowStart:batch.windowStart||batch.window?.start,windowEnd:batch.windowEnd||batch.window?.end||batch.cutoff,orderCount:batch.orderIds?.length||0,connectionIds:[...new Set((batch.orderIds||[]).map(id=>{const o=context.orderRules.get('orders',id);return o?.sample?.connectionId||o?.event?.connectionId||o?.connectionId;}).filter(Boolean))]};
return {carryCount:batch.carriedOrderIds?.length||0,...pick(batch,['id','version','categoryId','subject','status','error','createdAt','sentAt','resolvedAt','windowStart','windowEnd','cutoff','orderNos','testRunId']),categoryName:batch.ruleSnapshot?.name||context.orderRules.get('rules',batch.categoryId)?.draft?.name||batch.categoryId,notificationMode:modeOf(batch),collectionStart:batch.window?.collectionStart,collectionEnd:batch.window?.collectionEnd,windowStart:batch.windowStart||batch.window?.start,windowEnd:batch.windowEnd||batch.window?.end||batch.cutoff,orderCount:batch.orderIds?.length||0,connectionIds:[...new Set((batch.orderIds||[]).map(id=>{const o=context.orderRules.get('orders',id);return o?.sample?.connectionId||o?.event?.connectionId||o?.connectionId;}).filter(Boolean))]};
}
function queryBatches(context,input,user){
const f=filters(input,'batches'),data=records(context.orderRules);
+1 -1
View File
@@ -157,7 +157,7 @@ function eventInWindow(store,row,window){
}
return require('./window.cjs').inWindow(at,window);
}
function orderInWindow(store,order,window){const row=order?.sample||order?.event;return store.intakeWindow?.(row)?.end===window.end||eventInWindow(store,row,window);}
function orderInWindow(store,order,window,mode='normal'){const carried=require('./carry-forward.cjs').windowForOrder(store,order,mode);if(carried)return carried.end===window.end;const row=order?.sample||order?.event;return store.intakeWindow?.(row)?.end===window.end||eventInWindow(store,row,window);}
function assertCurrentPresence(store,row){
const run=state(store),entry=(run?.currentBacklog||[]).find(item=>taskIdentity.sameTask(item.snapshot,row));if(!entry)return;
const scan=store.get('current-task-scans',entry.scanConnectionId),matches=scan?.rows.filter(observed=>taskIdentity.sameTask(observed,row))||[];
+22 -16
View File
@@ -152,22 +152,25 @@ class RuleStore{
return window;
}
pendingIntakeCutoffs(){
const now=+this.clock();
return [...new Set(this.all('execution-tasks').filter(task=>!['sent','ignored','unknown','sending'].includes(task.status)||task.step==='complete'&&this.pendingCompanion(task.orderId&&this.get('orders',task.orderId))).map(task=>this.intakeWindow(task.row)?.end).filter(cutoff=>cutoff&&now>=Date.parse(cutoff)&&now<=Date.parse(cutoff)+1800000))].sort();
const now=+this.clock(),carry=require('./carry-forward.cjs'),cutoffs=[];
for(const task of this.all('execution-tasks')){const order=task.orderId&&this.get('orders',task.orderId);if(!['sent','ignored','unknown','sending'].includes(task.status)&&!carry.hasCarry(this,order)||task.step==='complete'&&this.pendingCompanion(order)&&!carry.hasCarry(this,order,'huizhou'))cutoffs.push(this.intakeWindow(task.row)?.end);}
for(const order of this.all('orders'))for(const mode of ['normal','huizhou']){const state=delivery(order,mode);if(state&&!state.batchId&&['pending','blocked','archived'].includes(state.status))cutoffs.push(carry.windowForOrder(this,order,mode)?.end);}
return [...new Set(cutoffs.filter(cutoff=>cutoff&&now>=Date.parse(cutoff)&&now<=Date.parse(cutoff)+1800000))].sort();
}
pendingCompanion(order){
const hui=delivery(order,'huizhou'),normal=order?.batchId&&this.get('batches',order.batchId);
return !!order?.archive&&order.ruleSnapshot?.huizhouEnabled===true&&['batched','sending','sent','unknown'].includes(order.status)&&!!hui&&['pending','blocked'].includes(hui.status)&&!hui.batchId&&!hui.missedWindow&&normal?.huizhouPlanned===true&&modeOf(normal)==='normal'&&normal.orderIds?.includes(order.id)&&normal.cutoff===this.intakeWindow(order.sample||order.event,{includeExpired:true})?.end;
}
expireIntakes(){return this.transaction(()=>{
const carry=require('./carry-forward.cjs');carry.advance(this);
for(const order of this.all('orders')){
const window=this.intakeWindow(order.sample||order.event,{includeExpired:true});
if(!window||+this.clock()<=Date.parse(window.end)+1800000)continue;
if(this.pendingCompanion(order)){
if(this.pendingCompanion(order)&&!carry.hasCarry(this,order,'huizhou')){
updateDelivery(order,'huizhou',{status:'blocked',error:'原处理时段超过30分钟,等待负责人核验。',missedWindow:window});order.updatedAt=this.now();this.put('orders',order);
this.recordIssue('missed:'+order.id+':huizhou',{component:'rules',notificationMode:'huizhou',error:delivery(order,'huizhou').error,window,orderIds:[order.id]});
}
if(!['identified','preparing','archived','pending','blocked'].includes(order.status)||order.batchId||order.missedWindow)continue;
if(carry.hasCarry(this,order)||!['identified','preparing','archived','pending','blocked'].includes(order.status)||order.batchId||order.missedWindow)continue;
order.status='blocked';order.error='原处理时段超过30分钟,等待负责人核验。';order.missedWindow=window;order.updatedAt=this.now();this.put('orders',order);
for(const task of this.all('execution-tasks').filter(task=>task.orderId===order.id&&!['unknown','sending','sent','ignored'].includes(task.status)))this.put('execution-tasks',{...task,status:'blocked',step:'missed_window',missedWindow:window,error:order.error,version:(task.version||0)+1,updatedAt:this.now()});
this.recordIssue('missed:'+order.id,{component:'rules',error:order.error,window,orderIds:[order.id]});
@@ -243,8 +246,8 @@ class RuleStore{
discoveryBlockers(cutoff,allowed=()=>true){
return require('./discovery-barrier.cjs').discoveryBlockers(this,cutoff,allowed);
}
categoryIncomplete(categoryId,window){
return this.all('execution-tasks').some(task=>!task.removedAt&&task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(eligibility.eventTime(this,task.row)))||eligibility.eventInWindow(this,task.row,window)||this.intakeWindow(task.row)?.end===window.end)&&(task.conflict||['identified','blocked','failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'||task.runtimeCheck?.status==='blocked'));
categoryIncomplete(categoryId,window,mode='normal'){
return this.all('execution-tasks').some(task=>!task.removedAt&&task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(eligibility.eventTime(this,task.row)))||eligibility.eventInWindow(this,task.row,window)||this.intakeWindow(task.row)?.end===window.end||require('./carry-forward.cjs').windowForOrder(this,task.orderId&&this.get('orders',task.orderId),mode)?.end===window.end)&&(task.conflict||['identified','blocked','failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'||task.runtimeCheck?.status==='blocked'));
}
batchIncomplete(batch){
return this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&(task.conflict||task.runtimeCheck?.status==='blocked'||['failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'));
@@ -285,17 +288,18 @@ class RuleStore{
if(blockers.length)return [];
const grouped=new Map(),batches=[];
for(const order of this.all('orders'))for(const mode of ['normal','huizhou']){
const state=delivery(order,mode);
if(!state||!['identified','preparing','archived','pending','blocked'].includes(state.status)||state.missedWindow||!order.categoryId||order.blockedByBatchId||order.missedWindow||order.status==='ignored')continue;
if(resuming&&this.intakeWindow(order.sample||order.event)?.end!==window.end)continue;
const state=delivery(order,mode),carryWindow=require('./carry-forward.cjs').windowForOrder(this,order,mode);
if(carryWindow&&carryWindow.end!==window.end)continue;
if(!state||!['identified','preparing','archived','pending','blocked'].includes(state.status)||state.missedWindow&&!carryWindow||!order.categoryId||order.blockedByBatchId||order.missedWindow&&!carryWindow||order.status==='ignored')continue;
if(resuming&&carryWindow?.end!==window.end&&this.intakeWindow(order.sample||order.event)?.end!==window.end)continue;
if(mode==='huizhou'&&(order.ruleSnapshot?.huizhouEnabled!==true||(!state.orderNos?.length&&!state.issues?.length)))continue;
const at=eligibility.orderTime(this,order);
if(validDate(at)&&Date.parse(at)<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this,order.sample||order.event)){
if(!carryWindow&&validDate(at)&&Date.parse(at)<Date.parse(collectionBounds(window).start)&&!eligibility.isAdmitted(this,order.sample||order.event)){
const expired=this.intakeWindow(order.sample||order.event,{includeExpired:true});
this.recordIssue('missed:'+order.id+':'+mode,{component:'rules',notificationMode:mode,error:'错过整理时点,等待人工处理。',orderIds:[order.id]});
updateDelivery(order,mode,{status:expired?'blocked':'ignored',error:expired?'原处理时段超过30分钟,等待负责人核验。':'早于本时段的历史订单,不补发。',...(expired?{missedWindow:expired}:{})});this.put('orders',order);continue;
}
if(!eligibility.orderInWindow(this,order,window)&&this.intakeWindow(order.sample||order.event)?.end!==window.end)continue;
if(!eligibility.orderInWindow(this,order,window,mode))continue;
const key=order.categoryId+':'+mode;if(!grouped.has(key))grouped.set(key,{mode,orders:[]});grouped.get(key).orders.push(order);
}
for(const {mode,orders} of grouped.values()){
@@ -308,14 +312,14 @@ class RuleStore{
const published=this.executionRule(this.get('rules',rule.id));
let error=!published||published.status!=='enabled'?'该类别规则已暂停。':null;
if(!error&&published.version!==rule.version)error='本类别订单规则版本已过期,请应用当前已发布规则后处理。';
if(!error&&this.categoryIncomplete(rule.categoryId,window))error='本类别存在未完成的采集、归档或核验任务。';
if(!error&&this.categoryIncomplete(rule.categoryId,window,mode))error='本类别存在未完成的采集、归档或核验任务。';
if(!error&&mode==='huizhou'&&orders.some(o=>delivery(o,mode).issues?.length))error=orders.flatMap(o=>delivery(o,mode).issues||[]).join(';');
if(!error&&orders.some(o=>mode==='normal'?o.status!=='pending':!o.archive||!['pending','batched','sent','unknown'].includes(o.status)))error='本类别存在字段、文件或归档尚未准备完成的订单。';
let snapshot;
if(!error)try{for(const order of orders)require('./restricted-test.cjs').assertOrder(this,order);snapshot=composeBatch(rule,ordersForMode(orders,mode),cutoff,this,{window,notificationMode:mode});}catch(cause){error=cause.message;}
const key=resultId(rule.categoryId,mode);
if(error){this.put('window-results',{id:key,categoryId:rule.categoryId,notificationMode:mode,cutoff,status:'blocked',error,updatedAt:this.now()});this.recordIssue('build:'+key,{component:'rules',notificationMode:mode,error,cutoff,categoryId:rule.categoryId,orderIds:orders.map(o=>o.id)});for(const original of orders){const order=this.get('orders',original.id);updateDelivery(order,mode,{error,...(mode==='huizhou'?{status:'blocked'}:{})});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};
const batch={...snapshot,carriedOrderIds:orders.filter(order=>require('./carry-forward.cjs').windowForOrder(this,order,mode)?.end===window.end).map(o=>o.id),id:crypto.randomUUID(),version:1,status:'prepared',createdAt:this.now(),ruleSnapshot:copy(rule),channelId:this.settings().channelId,error:null};
if(resuming)batch.intakeGrace={cutoff:window.end,expiresAt:new Date(Date.parse(window.end)+1800000).toISOString()};
if(rule.testRunId)batch.testRunId=rule.testRunId;
require('./restricted-test.cjs').assertBatch(this,batch,this.settings());
@@ -337,11 +341,13 @@ class RuleStore{
const orders=batch.orderIds.map(oid=>this.get('orders',oid));
if(this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&task.runtimeCheck?.status==='blocked'))fail('已归档订单的运行条件复核未通过,批次不能进入发送。',409);
if(orders.some(o=>!o||delivery(o,modeOf(batch))?.batchId!==id||delivery(o,modeOf(batch))?.status!=='batched'))fail('批次订单预留已变化。',409);
batch.version=(batch.version||1)+1;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');batch.submissionAttemptedAt=this.now();delete batch.deliveryEvidence;this.put('batches',batch);return batch;
});}
finishSending(id,status,message=null){return this.transaction(()=>{
finishSending(id,status,message=null,evidence){return this.transaction(()=>{
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
if(!['sent','unknown','failed'].includes(status))fail('发送结果无效。');
if(evidence&&!(status==='failed'&&validDate(evidence.at)&&((evidence.outcome==='not_submitted'&&['preflight','queue_expired'].includes(evidence.phase)&&batch.status==='prepared')||(evidence.outcome==='all_recipients_rejected'&&evidence.phase==='smtp_envelope'&&batch.status==='sending'))))fail('未发送证明与批次阶段不一致。',409);
if(evidence)batch.deliveryEvidence=copy(evidence);else delete batch.deliveryEvidence;
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')this.releaseBatchOrders(batch);
@@ -358,7 +364,7 @@ class RuleStore{
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.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);
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'){if(controlled)batch.deliveryEvidence={outcome:'manual_confirmed_unsent',phase:'manual_review',at:this.now(),actor};batch.status='failed';batch.error='人工已核验未发送,等待受控人工补发。';}this.put('batches',batch);
this.updateBatchOrders(batch,input.resolution==='sent'?'sent':'pending',null);
if(input.resolution==='retry')this.releaseBatchOrders(batch);
if(controlled)this.put('resolve-requests',{id:requestId,batchId:id,inputHash,at:this.now()});this.audit(actor,'核验分类邮件结果',id+':'+input.note.trim());return batch;
+2 -1
View File
@@ -4,11 +4,12 @@ function issueId(id){return 'business-'+crypto.createHash('sha256').update(id).d
// The source ledger is durable first. Reconciliation is idempotent and requires no cross-DB commit.
function reconcile(store,issues,members){return store.transaction(()=>{
for(const issue of issues){const id=issueId(issue.id),row=store.db.prepare('SELECT value FROM exceptions WHERE id=?').get(id),old=row?JSON.parse(row.value):null;if(old?.sourceUpdatedAt===issue.updatedAt&&old?.sourceStatus===issue.status)continue;
const at=new Date().toISOString(),owner=(issue.owners||[]).find(name=>members.some(m=>m.username===name&&m.enabled!==false&&m.role!=='viewer'))||'',recovered=issue.status==='awaiting_verification',freshFailure=old&&old.sourceUpdatedAt!==issue.updatedAt&&!recovered;
const at=new Date().toISOString(),owner=(issue.owners||[]).find(name=>members.some(m=>m.username===name&&m.enabled!==false&&m.role!=='viewer'))||'',recovered=issue.status==='awaiting_verification',retired=issue.status==='retired',freshFailure=old&&old.sourceUpdatedAt!==issue.updatedAt&&!recovered&&!retired;
const item=old||{id,sourceIssueId:issue.id,version:0,owner,status:owner?'in_progress':'open',createdAt:issue.createdAt||at,history:[],priority:issue.component==='mail'?'critical':'high'};
Object.assign(item,{title:'业务异常:'+(issue.component==='mail'?'邮件结果需要处理':'订单处理受阻'),description:issue.error||issue.message||'请核对关联订单和批次。',component:issue.component||'rules',sourceUpdatedAt:issue.updatedAt,sourceStatus:issue.status,batchId:issue.batchId||null,orderIds:issue.orderIds||[],taskIds:issue.taskIds||[],updatedAt:at});
if(!old)item.history.push({at,actor:'system',action:'create',note:'由持久业务问题建立;关闭异常不会更改批次或重新发信。'});
else if(freshFailure&&['resolved','verifying','retired'].includes(item.status)){item.status=item.owner?'in_progress':'open';item.history.push({at,actor:'system',action:'source_reopened',note:'来源再次报告失败,恢复为待处理。'});}
if(retired){item.status='retired';item.retiredAt=issue.retiredAt||at;item.history.push({at,actor:'system',action:'source_retired',note:'来源记录已移出或顺延,原错误与证据保留。'});}
if(recovered&&!['resolved','retired'].includes(item.status)){item.status='verifying';item.history.push({at,actor:'system',action:'verify',note:'来源报告恢复,仍须人工核验。'});}
item.version++;store.db.prepare('INSERT INTO exceptions VALUES(?,?) ON CONFLICT(id) DO UPDATE SET value=excluded.value').run(id,JSON.stringify(item));
}return true;