feat(records): add source history and Tabler record ledgers
This commit is contained in:
1 parent
1421edd6d4
commit
20bb68615f
27 files changed
+291
-91
No files matched your search
@@ -64,7 +64,7 @@ class BpmArrivalMonitor{
|
||||
const runId=this.scanner.store.begin(id,principal.user.username,'todo');
|
||||
const promise=Promise.resolve().then(async()=>{
|
||||
try{let rows;try{rows=await this.provider.scan(connection,principal);}catch(error){if(error.status!==401)throw error;const result=await this.manager.ensure(connection,principal);if(result.status!=='connected')throw error;rows=await this.provider.scan(connection,principal);}
|
||||
if(this.stopped||this.workspace.getConnection(id).status==='disabled')fail('连接已暂停,本次对账未提交。',409);return {...this.scanner.store.complete(runId,id,rows.map(todoArrival)),runId};
|
||||
const current=this.workspace.getConnection(id);if(this.stopped||current.status==='disabled')fail('连接已暂停,本次对账未提交。',409);return {...this.scanner.store.complete(runId,id,rows.map(todoArrival),current),runId};
|
||||
}catch(error){this.scanner.store.fail(runId,error.status===401?'需要恢复BPM登录。':error.status===409?'连接忙碌或已暂停。':'待办对账失败,请稍后重试。');throw error;}
|
||||
}).finally(()=>this.todoPending.delete(id));this.todoPending.set(id,promise);return {runId,promise};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
'use strict';
|
||||
const fail=message=>{throw Object.assign(new Error(message),{status:400});};
|
||||
function queryLedger({store,workspace,processNames},input={}){
|
||||
const filters={scope:'current',business:'orders',kind:'all',q:'',connectionId:'',from:'',to:'',page:1,pageSize:25,...input};
|
||||
if(!['current','archived','all'].includes(filters.scope)||!['orders','all'].includes(filters.business)||!['all','todo','inform'].includes(filters.kind))fail('记录筛选范围无效。');
|
||||
for(const key of ['q','connectionId'])if(typeof filters[key]!=='string'||filters[key].length>200)fail('记录查询条件过长。');
|
||||
const date=value=>!value||typeof value==='string'&&/^\d{4}-\d{2}-\d{2}$/.test(value)&&Number.isFinite(Date.parse(value+'T00:00:00Z'))&&new Date(value+'T00:00:00Z').toISOString().slice(0,10)===value;
|
||||
if(!date(filters.from)||!date(filters.to)||filters.from&&filters.to&&filters.from>filters.to)fail('请选择有效的起止日期。');
|
||||
if(!Number.isSafeInteger(filters.page)||filters.page<1||filters.page>1000000||!Number.isInteger(filters.pageSize)||filters.pageSize<1||filters.pageSize>100)fail('记录分页无效。');
|
||||
const catalog=workspace.recordSources(),sources=new Map(catalog.map(c=>[c.id,{...c,missing:false}]));
|
||||
for(const id of store.sourceIds())if(!sources.has(id))sources.set(id,{id,name:'历史连接 · '+id.slice(0,8),owner:'',identity:'',status:'archived',enabled:false,archivedAt:null,missing:true});
|
||||
const page=store.ledger(filters,catalog.filter(c=>c.status==='current').map(c=>c.id),[...new Set(processNames)]);
|
||||
return {...page,items:page.items.map(row=>{const current=sources.get(row.connectionId),first=row.origin;const origin={...current};if(first)for(const key of ['name','owner','identity'])if(typeof first[key]==='string')origin[key]=first[key].slice(0,200);return {...row,kind:row.source.startsWith('todo:')?'todo':'inform',origin};}),sources:[...sources.values()]};
|
||||
}
|
||||
module.exports={queryLedger};
|
||||
@@ -1,9 +1,15 @@
|
||||
'use strict';
|
||||
async function bpmScanApi({scanner,workspace,bpmMonitor,user,sessionId,url,route,method,body,reply}){
|
||||
async function bpmScanApi({scanner,workspace,bpmMonitor,orderRules,user,sessionId,url,route,method,body,reply}){
|
||||
if(!route.startsWith('/api/bpm-scan')&&route!=='/api/arrivals')return false;
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
if(!scanner)fail('BPM 扫描暂不可用。',503);
|
||||
if(route==='/api/arrivals'&&method==='GET'){
|
||||
if(url.searchParams.get('view')==='ledger'){
|
||||
const filters={};for(const key of ['scope','business','kind','q','connectionId','from','to','page','pageSize'])if(url.searchParams.has(key))filters[key]=['page','pageSize'].includes(key)?Number(url.searchParams.get(key)):url.searchParams.get(key);
|
||||
const configured=(orderRules?.all('rules')||[]).flatMap(r=>[...(r.draft?.processNames||[]),...(r.published?.processNames||[]),...(r.draft?.scopes||[]).map(s=>s.processName),...(r.published?.scopes||[]).map(s=>s.processName)]);
|
||||
const processNames=[...require('../order-rules/catalog.cjs').seedRules().flatMap(r=>r.processNames),...configured];
|
||||
reply(200,require('./records-query.cjs').queryLedger({store:scanner.store,workspace,processNames},filters));return true;
|
||||
}
|
||||
const filters={connectionId:url.searchParams.get('connectionId')||'',q:url.searchParams.get('q')||'',before:url.searchParams.get('before')||'',days:Number(url.searchParams.get('days')||7),kind:url.searchParams.get('kind')||'inform'};
|
||||
reply(200,scanner.store.list(filters));return true;
|
||||
}
|
||||
|
||||
@@ -21,15 +21,29 @@ class BpmScanStore{
|
||||
config(){return JSON.parse(this.db.prepare('SELECT value FROM config WHERE id=1').get().value);}
|
||||
saveConfig(input){if(!input||Object.keys(input).some(k=>!['enabled','intervalMinutes'].includes(k))||typeof input.enabled!=='boolean'||!Number.isInteger(input.intervalMinutes)||input.intervalMinutes<1||input.intervalMinutes>1440)throw invalid('扫描间隔需为 1–1440 分钟。');this.db.prepare('UPDATE config SET value=? WHERE id=1').run(JSON.stringify(input));return this.config();}
|
||||
begin(connectionId,actor,kind='inform'){if(!['inform','todo'].includes(kind))throw invalid('到达类型无效。');const id=crypto.randomUUID();this.db.prepare('INSERT INTO runs(id,connection_id,actor,started_at,status,kind) VALUES(?,?,?,?,?,?)').run(id,connectionId,actor,new Date().toISOString(),'running',kind);return id;}
|
||||
complete(id,connectionId,rows){return this.transaction(()=>{
|
||||
complete(id,connectionId,rows,connection){return this.transaction(()=>{
|
||||
let added=0;const now=new Date().toISOString();
|
||||
const insert=this.db.prepare('INSERT OR IGNORE INTO arrivals VALUES(?,?,?,?,?,?,?)');const update=this.db.prepare('UPDATE arrivals SET day=?,value=?,last_seen=? WHERE connection_id=? AND source=? AND task_id=?');
|
||||
for(const row of rows){if(!row.arrivalDay||!row.taskId||!row.source)throw invalid('流程记录无效。');const value=JSON.stringify(row),key=row.recordKey||row.taskId;added+=Number(insert.run(connectionId,row.source,key,row.arrivalDay,value,now,now).changes);update.run(row.arrivalDay,value,now,connectionId,row.source,key);}
|
||||
const prior=this.db.prepare('SELECT value FROM arrivals WHERE connection_id=? AND source=? AND task_id=?');
|
||||
for(const row of rows){if(!row.arrivalDay||!row.taskId||!row.source)throw invalid('流程记录无效。');const key=row.recordKey||row.taskId,old=prior.get(connectionId,row.source,key),snapshot=old?JSON.parse(old.value).origin:null,saved={...row};delete saved.origin;if(snapshot||connection)saved.origin=snapshot||{id:connectionId,name:connection.name,owner:connection.owner,identity:connection.identity||''};const value=JSON.stringify(saved);added+=Number(insert.run(connectionId,row.source,key,row.arrivalDay,value,now,now).changes);update.run(row.arrivalDay,value,now,connectionId,row.source,key);}
|
||||
this.db.prepare('UPDATE runs SET status=?,finished_at=?,seen=?,added=?,message=? WHERE id=? AND status=?').run('success',now,rows.length,added,'',id,'running');this.prune();return {seen:rows.length,added};
|
||||
});}
|
||||
fail(id,message){this.db.prepare('UPDATE runs SET status=?,finished_at=?,message=? WHERE id=?').run('error',new Date().toISOString(),message,id);this.prune();}
|
||||
prune(){this.db.exec("DELETE FROM runs WHERE status!='running' AND id NOT IN(SELECT id FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 200)");}
|
||||
status(){return {config:this.config(),total:this.db.prepare("SELECT COUNT(*) n FROM arrivals WHERE source NOT LIKE 'todo:%'").get().n,todoTotal:this.db.prepare("SELECT COUNT(*) n FROM arrivals WHERE source LIKE 'todo:%'").get().n,runs:this.db.prepare('SELECT id,connection_id AS connectionId,actor,started_at AS startedAt,finished_at AS finishedAt,status,seen,added,message,kind FROM runs ORDER BY started_at DESC,rowid DESC LIMIT 30').all()};}
|
||||
sourceIds(){return this.db.prepare('SELECT DISTINCT connection_id AS id FROM arrivals').all().map(row=>row.id);}
|
||||
ledger({scope,business,kind,q,connectionId,from,to,page,pageSize},currentIds,processNames){
|
||||
const conditions=[],args=[];
|
||||
if(scope!=='all'){conditions.push('connection_id '+(scope==='archived'?'NOT IN':'IN')+' (SELECT value FROM json_each(?))');args.push(JSON.stringify(currentIds));}
|
||||
if(business==='orders'){conditions.push("json_extract(value,'$.processName') IN (SELECT value FROM json_each(?))");args.push(JSON.stringify(processNames));}
|
||||
if(kind!=='all')conditions.push(kind==='todo'?"source LIKE 'todo:%'":"source NOT LIKE 'todo:%'");
|
||||
if(connectionId){conditions.push('connection_id=?');args.push(connectionId);}
|
||||
if(q){conditions.push("value LIKE ? ESCAPE '\\'");args.push('%'+q.replace(/[\\%_]/g,'\\$&')+'%');}
|
||||
if(from){conditions.push('day>=?');args.push(from);}if(to){conditions.push('day<=?');args.push(to);}
|
||||
const where=conditions.length?' WHERE '+conditions.join(' AND '):'',total=this.db.prepare('SELECT COUNT(*) n FROM arrivals'+where).get(...args).n;
|
||||
const items=this.db.prepare("SELECT connection_id AS connectionId,source,task_id AS storageKey,value,first_seen AS firstSeenAt,last_seen AS lastSeenAt FROM arrivals"+where+" ORDER BY json_extract(value,'$.arrivedAt') DESC,connection_id,source,task_id LIMIT ? OFFSET ?").all(...args,pageSize,(page-1)*pageSize).map(({value,storageKey,...rest})=>({...JSON.parse(value),...rest,recordId:JSON.stringify([rest.connectionId,rest.source,storageKey])}));
|
||||
return {items,total,page,pageSize};
|
||||
}
|
||||
list({connectionId='',q='',before='',days=7,kind='inform'}={}){
|
||||
if(!['inform','todo'].includes(kind))throw invalid('到达类型无效。');
|
||||
if(typeof q!=='string'||q.length>200||typeof connectionId!=='string'||connectionId.length>200||typeof before!=='string'||(before&&!/^\d{4}-\d{2}-\d{2}$/.test(before))||!Number.isInteger(days)||days<1||days>31)throw invalid('查询条件无效。');
|
||||
|
||||
@@ -12,7 +12,7 @@ class BpmScanner{
|
||||
if(this.pending.has(id))throw fail('此连接正在扫描,请稍后查看结果。',409);
|
||||
const runId=this.store.begin(id,principal.user.username);
|
||||
const operation=Promise.resolve().then(async()=>{
|
||||
try{const rows=await this.manager.scanArrivals(connection,principal);if(this.workspace.getConnection(id).status==='disabled')throw fail('此 BPM 连接已停用。',409);return {...this.store.complete(runId,id,rows),runId};}
|
||||
try{const rows=await this.manager.scanArrivals(connection,principal);const current=this.workspace.getConnection(id);if(current.status==='disabled')throw fail('此 BPM 连接已停用。',409);return {...this.store.complete(runId,id,rows,current),runId};}
|
||||
catch(cause){this.store.fail(runId,cause.status?cause.message:'BPM 扫描失败,请稍后重试。');throw cause;}
|
||||
}).finally(()=>this.pending.delete(id));this.pending.set(id,operation);return {promise:operation,runId};
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user