fix: preserve late discoveries across notification windows
This commit is contained in:
1 parent
33e9e9c108
commit
3ff69c6832
7 files changed
+338
-67
No files matched your search
@@ -6,5 +6,19 @@ function canReadConnection(workspace,user,id){
|
||||
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;}
|
||||
function canReadIssue(store,workspace,user,issue){
|
||||
if(user?.role==='admin')return true;
|
||||
const orders=issue.orderIds||[],tasks=issue.taskIds||[];
|
||||
if(!orders.length&&!tasks.length)return false;
|
||||
return orders.every(id=>canReadOrder(workspace,user,store.get('orders',id)))
|
||||
&&tasks.every(id=>canReadConnection(workspace,user,store.get('execution-tasks',id)?.connectionId));
|
||||
}
|
||||
function publicSnapshot(store,workspace,user){
|
||||
const value=store.snapshot();
|
||||
value.orders=value.orders.filter(order=>canReadOrder(workspace,user,order)).map(publicOrder);
|
||||
value.batches=value.batches.filter(batch=>canReadBatch(workspace,user,batch,store));
|
||||
value.issues=(store.all?.('business-issues')||[]).filter(issue=>canReadIssue(store,workspace,user,issue));
|
||||
if(user?.role!=='admin')value.audit=[];
|
||||
return value;
|
||||
}
|
||||
module.exports={canReadConnection,canReadOrder,canReadBatch,publicOrder,publicSnapshot};
|
||||
@@ -33,7 +33,7 @@ class OrderRuleDispatcher{
|
||||
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){const current=require('./window.cjs').upcomingWindow(now,schedule,calendar);this.schedule={signature,next:current?.available?current.end:nextSlots(schedule,now,1,calendar)[0]};}
|
||||
if(!this.schedule||this.schedule.signature!==signature||now-Date.parse(this.schedule.next)>60000){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;
|
||||
|
||||
@@ -4,10 +4,100 @@ 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};
|
||||
|
||||
function frozen(store,order){
|
||||
if(!order)return false;
|
||||
return !!order.batchId||!!order.blockedByBatchId||!!order.missedWindow
|
||||
||['batched','sending','sent','unknown'].includes(order.status)
|
||||
||store.all('batches').some(batch=>batch.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字依据。');
|
||||
}
|
||||
}
|
||||
function 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);
|
||||
const before=[outputEvent(order.event),order.ruleSnapshot?.archiveDirectory,order.ruleSnapshot?.filenameDate];
|
||||
const after=[outputEvent(result.event),rule.archiveDirectory,rule.filenameDate];
|
||||
return {result,archiveChanged:digest(before)!==digest(after)};
|
||||
}
|
||||
function invalidateArchive(order){
|
||||
const history=order.archiveHistory||[];
|
||||
if(order.archive)history.push({generation:order.archiveGeneration||1,evidence:order.archive});
|
||||
order.archiveHistory=history;
|
||||
order.archiveGeneration=(order.archiveGeneration||1)+1;
|
||||
order.archive=null;
|
||||
}
|
||||
function synchronizeTasks(store,order){
|
||||
for(const task of store.all('execution-tasks').filter(task=>task.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);
|
||||
}
|
||||
}
|
||||
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=[];
|
||||
const candidates=store.all('orders').filter(order=>order.ruleSnapshot?.id===id||order.categoryId===rule.categoryId);
|
||||
for(const order of candidates){
|
||||
if(frozen(store,order)||!['blocked','identified','preparing','archived','pending'].includes(order.status)){
|
||||
excluded.push({id:order.id,status:order.status,reason:'冻结、逾期或已终结订单不可迁移'});
|
||||
continue;
|
||||
}
|
||||
const proposed=projection(store,order,rule);
|
||||
items.push({id:order.id,archiveChanged:proposed.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]);
|
||||
const inputHash=digest(input);
|
||||
const prior=store.get('migration-requests',requestId);
|
||||
if(prior){
|
||||
if(prior.inputHash!==inputHash)fail('幂等标识已用于不同迁移。',409);
|
||||
return prior.result;
|
||||
}
|
||||
// Validate every candidate before the first mutation; the transaction also
|
||||
// protects replay, archive history, task synchronization and audit as one unit.
|
||||
const result=preview(store,id,input);
|
||||
const rule=store.get('rules',id).published;
|
||||
for(const item of result.items){
|
||||
const order=store.get('orders',item.id);
|
||||
const proposed=projection(store,order,rule);
|
||||
if(proposed.archiveChanged){
|
||||
invalidateArchive(order);
|
||||
order.status='identified';
|
||||
}
|
||||
order.event=proposed.result.event;
|
||||
order.trace=proposed.result;
|
||||
order.ruleSnapshot=structuredClone(rule);
|
||||
order.categoryId=rule.categoryId;
|
||||
order.updatedAt=store.now();
|
||||
order.error=null;
|
||||
store.put('orders',order);
|
||||
synchronizeTasks(store,order);
|
||||
}
|
||||
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,invalidateArchive};
|
||||
@@ -167,14 +167,15 @@ class RuleStore{
|
||||
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.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';
|
||||
require('./migrations.cjs').invalidateArchive(order);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+' 完整对账线索尚未处理。');
|
||||
const pendingSources=new Set([...this.all('execution-discoveries'),...this.all('execution-discovery-runs')].filter(hint=>hint.status==='pending'&&allowed(hint.connectionId)).map(hint=>hint.connectionId));
|
||||
for(const id of pendingSources)blockers.push('连接 '+id+' 完整对账线索尚未处理。');
|
||||
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));
|
||||
@@ -193,7 +194,28 @@ class RuleStore{
|
||||
batchIncomplete(batch){
|
||||
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()});}
|
||||
issueOwners(input){
|
||||
const orderIds=input.orderIds||[];
|
||||
const taskIds=input.taskIds||[];
|
||||
const taskOwners=this.all('execution-tasks')
|
||||
.filter(task=>orderIds.includes(task.orderId)||taskIds.includes(task.id))
|
||||
.map(task=>task.owner);
|
||||
const sourceOwners=orderIds.map(id=>this.get('orders',id)).filter(Boolean)
|
||||
.map(order=>this.ownerForConnection?.(order.sample?.connectionId));
|
||||
return [...new Set([...taskOwners,...sourceOwners].filter(Boolean))];
|
||||
}
|
||||
recordIssue(id,input){
|
||||
const old=this.get('business-issues',id);
|
||||
const owners=this.issueOwners(input);
|
||||
const status=old?.status==='resolved'?'awaiting_verification':old?.status||'open';
|
||||
return this.put('business-issues',{
|
||||
...old,...input,id,status,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());
|
||||
|
||||
Reference in new issue
Block a user