feat: complete workflow recovery and safe administration
This commit is contained in:
1 parent
1148aa6f14
commit
69583e8c33
46 files changed
+756
-120
No files matched your search
@@ -9,6 +9,9 @@ async function assistantApi({assistant,user,sessionId,route,method,body,request,
|
||||
if(route.endsWith('/settings')){const saved=assistant.store.saveSettings(body);workspace?.record(user,'配置 ZCode 助手',saved.enabled?'已启用':'已暂停');reply(200,saved);}else{bodyKeys(body,[]);reply(200,await assistant.check());}return true;
|
||||
}
|
||||
if(route==='/api/assistant/conversations'&&method==='POST'){bodyKeys(body,[]);reply(201,assistant.store.create(user.id));return true;}
|
||||
if(route==='/api/assistant/conversations'&&method==='GET'){const params=new URL(request.url,'http://localhost').searchParams,filters={};for(const [key,value]of params){if(!['scope','page','pageSize'].includes(key))throw fail('会话查询参数无效。');filters[key]=key==='scope'?value:Number(value);}reply(200,assistant.store.listConversations(user.id,filters));return true;}
|
||||
const history=/^\/api\/assistant\/conversations\/([\w-]+)\/(archive|restore|continue)$/.exec(route);
|
||||
if(history&&method==='POST'){bodyKeys(body,['version']);const result=assistant.store[{archive:'archive',restore:'restore',continue:'continueConversation'}[history[2]]](history[1],user.id,body);workspace?.record(user,'管理个人助手会话',history[2]);reply(200,result);return true;}
|
||||
const match=/^\/api\/assistant\/conversations\/([\w-]+)(?:\/(messages|cancel)|\/actions\/([\w-]+)\/execute)?$/.exec(route);
|
||||
if(match){const [,id,action,actionId]=match;
|
||||
if(!action&&!actionId&&method==='GET'){reply(200,assistant.store.conversation(id,user.id));return true;}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');
|
||||
const fail=(message,status=400)=>Object.assign(Error(message),{status});
|
||||
class ConversationHistory{
|
||||
constructor(store){this.store=store;if(!store.db.prepare('PRAGMA table_info(conversations)').all().some(column=>column.name==='archived'))store.db.exec('ALTER TABLE conversations ADD COLUMN archived INTEGER NOT NULL DEFAULT 0');store.db.exec('CREATE INDEX IF NOT EXISTS conversation_scope ON conversations(owner,archived,updated_at DESC)');}
|
||||
metadata(row){return this.store.decode(row.id,row.payload);}
|
||||
count(owner){return this.store.db.prepare('SELECT COUNT(*) AS n FROM conversations WHERE owner=? AND archived=0').get(owner).n;}
|
||||
list(owner,{scope='active',page=1,pageSize=50}={}){
|
||||
if(!['active','archived'].includes(scope)||!Number.isSafeInteger(page)||page<1||!Number.isInteger(pageSize)||pageSize<1||pageSize>50)throw fail('会话查询条件无效。');
|
||||
const archived=Number(scope==='archived'),total=this.store.db.prepare('SELECT COUNT(*) AS n FROM conversations WHERE owner=? AND archived=?').get(owner,archived).n,actual=Math.min(page,Math.max(1,Math.ceil(total/pageSize)));
|
||||
const items=this.store.db.prepare('SELECT * FROM conversations WHERE owner=? AND archived=? ORDER BY updated_at DESC,rowid DESC LIMIT ? OFFSET ?').all(owner,archived,pageSize,(actual-1)*pageSize).map(row=>({id:row.id,...this.metadata(row),version:this.metadata(row).version||1,archived:!!row.archived,createdAt:row.created_at,updatedAt:row.updated_at}));
|
||||
return {items,total,page:actual,pageSize};
|
||||
}
|
||||
create(owner,{continuationOf}={}){
|
||||
if(this.count(owner)>=50)throw fail('活跃会话已达50个,请先归档旧会话。',409);if(continuationOf)this.store.row(continuationOf,owner);
|
||||
const id=crypto.randomUUID(),at=new Date().toISOString(),metadata={title:'新对话',version:1,...(continuationOf?{continuationOf}: {})};
|
||||
this.store.db.prepare('INSERT INTO conversations(id,owner,payload,created_at,updated_at,archived) VALUES(?,?,?,?,?,0)').run(id,owner,this.store.encode(id,metadata),at,at);return this.conversation(id,owner);
|
||||
}
|
||||
conversation(id,owner){const row=this.store.row(id,owner),metadata=this.metadata(row);return {id,title:metadata.title,version:metadata.version||1,archived:!!row.archived,continuationOf:metadata.continuationOf||null,continuedTo:metadata.continuedTo||null,turns:this.store.db.prepare('SELECT * FROM turns WHERE conversation_id=? ORDER BY rowid').all(id).map(turn=>({id:turn.id,status:turn.status,createdAt:turn.created_at,...this.store.decode(turn.id,turn.payload)}))};}
|
||||
checkIdle(id){for(const turn of this.store.db.prepare('SELECT id,status,payload FROM turns WHERE conversation_id=?').all(id))if(turn.status==='running'||this.store.decode(turn.id,turn.payload).actions?.some(action=>action.status==='running'))throw fail('此会话仍在回复或执行操作,请先停止并等待完成。',409);}
|
||||
validate(row,input){if(!input||Object.keys(input).some(key=>key!=='version')||!Number.isSafeInteger(input.version)||input.version!==(this.metadata(row).version||1))throw fail('会话已变化,请刷新后重试。',409);}
|
||||
setArchived(id,owner,archived,input){return this.store.transaction(()=>{
|
||||
const row=this.store.row(id,owner);this.validate(row,input);if(!!row.archived===archived)return this.conversation(id,owner);this.checkIdle(id);
|
||||
if(!archived&&this.count(owner)>=50)throw fail('活跃会话已达50个,请先归档其他会话。',409);
|
||||
const metadata=this.metadata(row);metadata.version=(metadata.version||1)+1;this.store.db.prepare('UPDATE conversations SET archived=?,payload=?,updated_at=? WHERE id=?').run(Number(archived),this.store.encode(id,metadata),new Date().toISOString(),id);return this.conversation(id,owner);
|
||||
});}
|
||||
continue(id,owner,input){return this.store.transaction(()=>{
|
||||
const row=this.store.row(id,owner),metadata=this.metadata(row);if(!Number.isSafeInteger(input?.version)||input.version<1)throw fail('会话版本无效。');
|
||||
if(metadata.continuedTo)return this.conversation(metadata.continuedTo,owner);
|
||||
this.validate(row,input);this.checkIdle(id);const at=new Date().toISOString();
|
||||
this.store.db.prepare('UPDATE conversations SET archived=1 WHERE id=?').run(id);const child=this.create(owner,{continuationOf:id});metadata.version=(metadata.version||1)+1;metadata.continuedTo=child.id;
|
||||
this.store.db.prepare('UPDATE conversations SET payload=?,updated_at=? WHERE id=?').run(this.store.encode(id,metadata),at,id);return child;
|
||||
});}
|
||||
history(id,owner){const current=this.conversation(id,owner),prior=current.continuationOf?this.conversation(current.continuationOf,owner).turns.filter(turn=>turn.status==='success').slice(-3):[];return [...prior,...current.turns.filter(turn=>turn.status==='success')].slice(-12);}
|
||||
}
|
||||
module.exports={ConversationHistory};
|
||||
@@ -8,7 +8,7 @@ function snapshot({workspace,scanner,storage,dashboard,orderRules,orderExecution
|
||||
const runs=(scanner?.store.status().runs||[]).filter(r=>ids.has(r.connectionId)).slice(0,10).map(r=>({connectionId:r.connectionId,status:r.status,startedAt:r.startedAt,finishedAt:r.finishedAt,seen:r.seen,added:r.added,message:redact(r.message)}));
|
||||
const servers=(storage?.store.servers()||[]).map(s=>({id:s.id,name:redact(s.name),enabled:s.enabled,state:{readable:s.state.readable,writable:s.state.writable,message:redact(s.state.message)}}));
|
||||
const archives=(storage?.store.archives()||[]).slice(0,15).map(a=>({id:a.id,serverId:a.serverId,jobId:a.jobId,status:a.status,orderNumber:a.orderNumber,error:redact(a.error)}));
|
||||
const jobs=(dashboard?.jobs()||[]).slice(0,15).map(j=>({jobId:j.jobId,status:j.status,orderNumber:j.metadata?.order,error:redact(j.error)}));
|
||||
const jobs=(dashboard?.recentJobs?dashboard.recentJobs(15):dashboard?.jobs()||[]).slice(0,15).map(j=>({jobId:j.jobId,status:j.status,orderNumber:j.metadata?.order,error:redact(j.error)}));
|
||||
const exceptions=w.exceptions.filter(e=>user.role==='admin'||e.owner===user.username).slice(0,15).map(e=>({id:e.id,title:redact(e.title),status:e.status,component:e.component,owner:e.owner}));
|
||||
return {at:new Date().toISOString(),role:user.role,connections,runs,servers,archives,jobs,exceptions,fieldMapping:require('./field-skill.cjs').coverage({workspace,orderRules,orderExecution},user)};
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ class AssistantService{
|
||||
if(this.running.size>=2)throw fail('助手正在处理其他对话,请稍后重试。',429);
|
||||
const config=this.store.secretSettings();if(!config.enabled||!config.runtimePath||!config.apiBase||!config.model||!config.apiKey)throw fail('请管理员先配置并启用 ZCode 助手。',409);
|
||||
const context=JSON.parse(JSON.stringify(this.context(principal.user),(_key,value)=>typeof value==='string'?cleanMessage(value,config.apiKey):value));
|
||||
const history=this.store.conversation(id,principal.user.id).turns.filter(t=>t.status==='success').slice(-12).map(t=>({user:cleanMessage(redact(t.text),config.apiKey),assistant:cleanMessage(redact(t.reply),config.apiKey)}));
|
||||
const history=this.store.history(id,principal.user.id).map(t=>({user:cleanMessage(redact(t.text),config.apiKey),assistant:cleanMessage(redact(t.reply),config.apiKey)}));
|
||||
const turn=this.store.beginTurn(id,principal.user.id,cleanMessage(redact(text.trim(),4000),config.apiKey)),controller=new AbortController();
|
||||
const timer=setTimeout(()=>controller.abort(fail('ZCode 回复超时,可稍后重试。',504)),config.timeoutSeconds*1000);
|
||||
const task=Promise.resolve().then(async()=>{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
'use strict';
|
||||
const path=require('node:path'),crypto=require('node:crypto'),fs=require('node:fs'),{DatabaseSync}=require('node:sqlite'),{BpmVault}=require('../../platform/security/vault.cjs');
|
||||
const fail=(message,status=400)=>Object.assign(new Error(message),{status}),now=()=>new Date().toISOString();
|
||||
const {ConversationHistory}=require('./conversation-history.cjs');
|
||||
const day=()=>new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date());
|
||||
function installedRuntime(dir){try{
|
||||
const root=path.join(path.dirname(dir),'zcode-runtime'),manifest=JSON.parse(fs.readFileSync(path.join(root,'manifest.json'),'utf8')),entry=path.join(root,'3.14.3','package','resources','glm','zcode.cjs');
|
||||
@@ -16,6 +17,7 @@ class AssistantStore{
|
||||
CREATE TABLE IF NOT EXISTS conversations(id TEXT PRIMARY KEY,owner TEXT NOT NULL,payload BLOB NOT NULL,created_at TEXT NOT NULL,updated_at TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS turns(id TEXT PRIMARY KEY,conversation_id TEXT NOT NULL,status TEXT NOT NULL,payload BLOB NOT NULL,day TEXT NOT NULL,created_at TEXT NOT NULL);
|
||||
CREATE INDEX IF NOT EXISTS conversation_turns ON turns(conversation_id,created_at);`);
|
||||
this.conversationHistory=new ConversationHistory(this);
|
||||
} catch(error) {
|
||||
try { this.db?.close(); } catch {}
|
||||
try { this.vault?.destroy(); } catch {}
|
||||
@@ -43,20 +45,26 @@ class AssistantStore{
|
||||
if(saved.enabled&&(!runtimePath||!apiBase||!model||!saved.apiKey))throw fail('启用前请填写运行包路径、模型 API 地址、模型名称和密钥。');
|
||||
this.db.prepare('INSERT INTO config VALUES(1,?,?) ON CONFLICT(id) DO UPDATE SET version=excluded.version,payload=excluded.payload').run(old.version+1,this.encode('config',saved));return this.settings();
|
||||
});}
|
||||
conversations(owner){return this.db.prepare('SELECT * FROM conversations WHERE owner=? ORDER BY updated_at DESC,rowid DESC LIMIT 50').all(owner).map(row=>({id:row.id,...this.decode(row.id,row.payload),createdAt:row.created_at,updatedAt:row.updated_at}));}
|
||||
conversations(owner,filters){return this.conversationHistory.list(owner,filters).items;}
|
||||
listConversations(owner,filters){return this.conversationHistory.list(owner,filters);}
|
||||
row(id,owner){const row=this.db.prepare('SELECT * FROM conversations WHERE id=? AND owner=?').get(id,owner);if(!row)throw fail('没有找到此对话。',404);return row;}
|
||||
create(owner){if(this.conversations(owner).length>=50)throw fail('个人会话已达 50 个,请继续使用已有会话。',409);const id=crypto.randomUUID(),at=now();this.db.prepare('INSERT INTO conversations VALUES(?,?,?,?,?)').run(id,owner,this.encode(id,{title:'新对话'}),at,at);return this.conversation(id,owner);}
|
||||
conversation(id,owner){const row=this.row(id,owner);return {id,title:this.decode(id,row.payload).title,turns:this.db.prepare('SELECT * FROM turns WHERE conversation_id=? ORDER BY rowid').all(id).map(t=>({id:t.id,status:t.status,createdAt:t.created_at,...this.decode(t.id,t.payload)}))};}
|
||||
create(owner,options){return this.conversationHistory.create(owner,options);}
|
||||
conversation(id,owner){return this.conversationHistory.conversation(id,owner);}
|
||||
archive(id,owner,input){return this.conversationHistory.setArchived(id,owner,true,input);}
|
||||
restore(id,owner,input){return this.conversationHistory.setArchived(id,owner,false,input);}
|
||||
continueConversation(id,owner,input){return this.conversationHistory.continue(id,owner,input);}
|
||||
history(id,owner){return this.conversationHistory.history(id,owner);}
|
||||
beginTurn(id,owner,text){return this.transaction(()=>{
|
||||
const row=this.row(id,owner),count=this.db.prepare('SELECT COUNT(*) AS n FROM turns WHERE conversation_id=?').get(id).n;
|
||||
if(row.archived)throw fail('请先恢复归档会话或继续新对话。',409);
|
||||
if(count>=100)throw fail('此对话已达 100 轮,请新建对话。',409);
|
||||
if(this.db.prepare("SELECT 1 FROM turns WHERE conversation_id=? AND status='running'").get(id))throw fail('当前对话正在回复,请等待或停止。',409);
|
||||
if(this.db.prepare('SELECT COUNT(*) AS n FROM turns WHERE day=?').get(day()).n>=this.settings().dailyLimit)throw fail('已达到今天的模型调用上限。',429);
|
||||
const turnId=crypto.randomUUID(),at=now(),payload={text,reply:'',actions:[],evidence:[]};this.db.prepare('INSERT INTO turns VALUES(?,?,?,?,?,?)').run(turnId,id,'running',this.encode(turnId,payload),day(),at);
|
||||
this.db.prepare('UPDATE conversations SET payload=?,updated_at=? WHERE id=?').run(this.encode(id,{title:count?this.decode(id,row.payload).title:text.slice(0,40)}),at,id);return {id:turnId,status:'running',createdAt:at,...payload};
|
||||
const metadata=this.decode(id,row.payload);this.db.prepare('UPDATE conversations SET payload=?,updated_at=? WHERE id=?').run(this.encode(id,{...metadata,title:count?metadata.title:text.slice(0,40),version:(metadata.version||1)+1}),at,id);return {id:turnId,status:'running',createdAt:at,...payload};
|
||||
});}
|
||||
updateTurn(id,status,patch){const row=this.db.prepare('SELECT * FROM turns WHERE id=?').get(id);if(!row)throw fail('回复不存在。',404);const value={...this.decode(id,row.payload),...patch};this.db.prepare('UPDATE turns SET status=?,payload=? WHERE id=?').run(status,this.encode(id,value),id);return {id,status,createdAt:row.created_at,...value};}
|
||||
action(conversationId,owner,actionId,work){return this.transaction(()=>{this.row(conversationId,owner);for(const row of this.db.prepare('SELECT * FROM turns WHERE conversation_id=? ORDER BY rowid DESC').all(conversationId)){const turn=this.decode(row.id,row.payload),action=turn.actions.find(a=>a.id===actionId);if(action){const result=work(action);this.updateTurn(row.id,row.status,{actions:turn.actions});return result;}}throw fail('操作卡片不存在。',404);});}
|
||||
action(conversationId,owner,actionId,work){return this.transaction(()=>{if(this.row(conversationId,owner).archived)throw fail('请先恢复归档会话。',409);for(const row of this.db.prepare('SELECT * FROM turns WHERE conversation_id=? ORDER BY rowid DESC').all(conversationId)){const turn=this.decode(row.id,row.payload),action=turn.actions.find(a=>a.id===actionId);if(action){const result=work(action);this.updateTurn(row.id,row.status,{actions:turn.actions});return result;}}throw fail('操作卡片不存在。',404);});}
|
||||
recover(){for(const row of this.db.prepare('SELECT * FROM turns').all()){const turn=this.decode(row.id,row.payload);let changed=row.status==='running';for(const a of turn.actions)if(a.status==='running'){a.status='interrupted';a.error='服务重启,操作结果需要核实。';changed=true;}if(changed)this.updateTurn(row.id,row.status==='running'?'interrupted':row.status,{...turn,error:'服务重启,上一轮已中断。'});}}
|
||||
usage(){return {today:day(),calls:this.db.prepare('SELECT COUNT(*) AS n FROM turns WHERE day=?').get(day()).n,limit:this.settings().dailyLimit};}
|
||||
close(){this.db.close();this.vault.destroy();}
|
||||
|
||||
@@ -6,6 +6,7 @@ class BpmConnectionLifecycle{
|
||||
async invoke(method,id){try{await this.manager?.[method]?.(id);}catch(error){fail('BPM 连接操作未完成,请刷新状态后重试。',[409,503].includes(error.status)?error.status:502);}}
|
||||
change(id,enabled,input,user){return this.run(id,async()=>{
|
||||
if(user.role!=='admin')fail('仅管理员可以启用或停用连接。',403);
|
||||
if(enabled&&this.pendingCleanup?.hasConnection(id))fail('连接交接清理尚未完成,请刷新管理页面重试后再启用。',503);
|
||||
if(typeof enabled!=='boolean'||!input||Object.keys(input).some(k=>k!=='version')||!Number.isInteger(input.version)||input.version<0)fail('请提供当前连接版本。',400);
|
||||
const current=this.workspace.getConnection(id);
|
||||
if((current.status!=='disabled')!==enabled&&(current.version||0)!==input.version)fail('连接状态已变化,请刷新后重试。',409);
|
||||
|
||||
@@ -4,14 +4,15 @@ const {queryJobs,publicJobs,jobFile}=require('./job-records.cjs');
|
||||
async function dashboardApi({store,outputDir,workspace,mail,scanner,storage,orderRules,user,route,request,response,body,reply,fail}){
|
||||
const handled=(...args)=>{reply(...args);return true;};
|
||||
if(route==='/api/overview' && request.method==='GET') {
|
||||
const jobs=store.jobs();const settings=store.settings();const mailChannels=mail?.store.channels()||[];const mailTemplates=mail?.store.templates()||[];
|
||||
const jobs=store.recentJobs?store.recentJobs(6):store.jobs();const settings=store.settings();const mailChannels=mail?.store.channels()||[];const mailTemplates=mail?.store.templates()||[];
|
||||
const today=new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date());
|
||||
const todayJobs=jobs.filter(job=>new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date(job.updatedAt))===today);
|
||||
const stats=store.jobStats?store.jobStats():{total:jobs.length,today:todayJobs.length,completed:jobs.filter(job=>job.status==='success').length,failed:jobs.filter(job=>['error','interrupted'].includes(job.status)).length,running:jobs.filter(job=>job.status==='running').length};
|
||||
const scan=scanner?.store.status();
|
||||
const rules=orderRules?.snapshot(),published=rules?.rules?.filter(r=>r.status==='enabled')||[];
|
||||
const rules=orderRules?.snapshot({includeRecords:false}),published=rules?.rules?.filter(r=>r.status==='enabled')||[];
|
||||
const capabilities=rules?.capabilities||{},ready=['liveTodo','pdfExport','automaticArchive'].every(key=>capabilities[key]===true);
|
||||
const automation={enabled:rules?.settings?.enabled===true,ready,reason:rules?.settings?.enabled!==true?'分类自动发信已暂停;请先完成类别字段、目录、邮箱与预览核验。':ready?'分类执行链路已完成实际接入检查。':'分类执行链路仍有未通过的实际检查,请查看订单执行中的阻塞原因。'};
|
||||
return handled(200,{stats:{total:jobs.length,today:todayJobs.length,completed:jobs.filter(job=>job.status==='success').length,failed:jobs.filter(job=>['error','interrupted'].includes(job.status)).length,running:jobs.filter(job=>job.status==='running').length},scan,automation,connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'Excel 分类规则',ready:published.length>0,detail:`15类规则,已发布 ${published.length} 类;实际字段按流程版本核验`},{name:'BPM 待办执行',ready:capabilities.liveTodo===true,detail:capabilities.liveTodo===true?'真实待办接口检查通过;各类别仍需字段核验':'请在订单通知管理的订单执行中检查实时待办,字段映射在业务设置维护'},{name:'到达历史扫描',ready:!!scan?.runs.some(r=>r.status==='success'&&(r.kind||'inform')==='inform'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 已收录 ${scan.total} 条流程`:'历史扫描服务未启动'},{name:'存储服务器',ready:!!storage?.store.servers().some(s=>s.enabled&&s.state.readable&&s.state.writable),detail:storage?`已配置 ${storage.store.servers().length} 个 SMB 存储服务器`:'存储服务未启动'},{name:'邮件渠道',ready:mailChannels.some(c=>!c.readOnly&&c.state.smtp),detail:`已配置 ${mailChannels.length} 个邮箱`},{name:'邮件模板',ready:mailTemplates.some(t=>t.status==='active'),detail:`${mailTemplates.filter(t=>t.status==='active').length} 个已生效,${mailTemplates.filter(t=>t.status==='pending').length} 个待确认;按类别显式关联`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:await publicJobs(jobs.slice(0,6),outputDir,storage?.store),audit:store.audit().slice(0,5)});
|
||||
return handled(200,{stats,scan,automation,connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'Excel 分类规则',ready:published.length>0,detail:`15类规则,已发布 ${published.length} 类;实际字段按流程版本核验`},{name:'BPM 待办执行',ready:capabilities.liveTodo===true,detail:capabilities.liveTodo===true?'真实待办接口检查通过;各类别仍需字段核验':'请在订单通知管理的订单执行中检查实时待办,字段映射在业务设置维护'},{name:'到达历史扫描',ready:!!scan?.runs.some(r=>r.status==='success'&&(r.kind||'inform')==='inform'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 累计待办 ${scan.todoTotal||0} 条、待阅 ${scan.total} 条;不代表当前待办`:'历史扫描服务未启动'},{name:'存储服务器',ready:!!storage?.store.servers().some(s=>s.enabled&&s.state.readable&&s.state.writable),detail:storage?`已配置 ${storage.store.servers().length} 个 SMB 存储服务器`:'存储服务未启动'},{name:'邮件渠道',ready:mailChannels.some(c=>!c.readOnly&&c.state.smtp),detail:`已配置 ${mailChannels.length} 个邮箱`},{name:'邮件模板',ready:mailTemplates.some(t=>t.status==='active'),detail:`${mailTemplates.filter(t=>t.status==='active').length} 个已生效,${mailTemplates.filter(t=>t.status==='pending').length} 个待确认;分类规则选择正文`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:await publicJobs(jobs.slice(0,6),outputDir,storage?.store),audit:store.audit().slice(0,5)});
|
||||
}
|
||||
if(route==='/api/settings') {
|
||||
if(request.method==='GET')return handled(200,store.settings());
|
||||
@@ -19,18 +20,18 @@ const handled=(...args)=>{reply(...args);return true;};
|
||||
}
|
||||
if(route==='/api/jobs' && request.method==='GET'){
|
||||
const params=new URL(request.url,'http://localhost').searchParams;
|
||||
if(params.get('view')==='ledger'){const filters={};for(const key of ['q','status','page','pageSize'])if(params.has(key))filters[key]=['page','pageSize'].includes(key)?Number(params.get(key)):params.get(key);return handled(200,await queryJobs({jobs:store.jobs(),outputDir,archiveStore:storage?.store},filters));}
|
||||
if(params.get('view')==='ledger'){const filters={};for(const key of ['q','status','page','pageSize'])if(params.has(key))filters[key]=['page','pageSize'].includes(key)?Number(params.get(key)):params.get(key);if(store.jobPage){const page=store.jobPage(filters);return handled(200,{...page,jobs:await publicJobs(page.jobs,outputDir,storage?.store)});}return handled(200,await queryJobs({jobs:store.jobs(),outputDir,archiveStore:storage?.store},filters));}
|
||||
return handled(200,{jobs:await publicJobs(store.jobs(),outputDir,storage?.store)});
|
||||
}
|
||||
if(route==='/api/audit' && request.method==='GET')return handled(200,{audit:store.audit()});
|
||||
if(route==='/api/users') {
|
||||
if(user.role!=='admin')fail(403,'仅管理员可以管理账号。');
|
||||
if(request.method==='GET')return handled(200,{users:store.users()});
|
||||
if(request.method==='GET'){const users=store.users();return handled(200,{users,assignments:Object.fromEntries(users.map(member=>[member.username,workspace?.ownedWork(member.username)||{connections:[],exceptions:[]}]))});}
|
||||
if(request.method==='POST')return handled(201,{user:store.addUser(body,user.username)});
|
||||
}
|
||||
const download=/^\/api\/jobs\/([\w-]+)\/file$/.exec(route);
|
||||
if(download && request.method==='GET') {
|
||||
const job=store.jobs().find(job=>job.jobId===download[1]);
|
||||
const job=store.job?store.job(download[1]):store.jobs().find(job=>job.jobId===download[1]);
|
||||
const {file:realFile}=await jobFile(job,outputDir);
|
||||
const bytes=await fs.promises.readFile(realFile);
|
||||
response.writeHead(200,{'Content-Type':'application/pdf','Content-Disposition':`attachment; filename*=UTF-8''${encodeURIComponent(path.basename(realFile))}`});response.end(bytes);return true;
|
||||
|
||||
@@ -2,8 +2,9 @@ const path=require('node:path');
|
||||
const {SessionStore,SESSION_MS}=require('./sessions.cjs');
|
||||
const {isLoopback}=require('../../app/request.cjs');
|
||||
const {validateChange}=require('./passwords.cjs');
|
||||
function createAuth({store,bpmSessions}){
|
||||
function createAuth({store,workspace,bpmSessions,bpmMonitor,bpmLifecycle}){
|
||||
const sessions=new SessionStore(path.dirname(store.file));const failures=new Map(),passwordFailures=new Map();
|
||||
const cleanup=require('./pending-cleanup.cjs').accessCleanup({store,workspace,bpmSessions,bpmMonitor,bpmLifecycle,sessions});
|
||||
const sessionCookieName='order_session';
|
||||
const sessionCookiePattern=new RegExp('(?:^|;\\s*)'+sessionCookieName+'=([a-f0-9]{64})(?:;|$)');
|
||||
async function authenticate({request,response,route,body,reply,fail,encryptedTransport}){
|
||||
@@ -30,11 +31,44 @@ const handled=(...args)=>{reply(...args);return {handled:true};};
|
||||
}
|
||||
const token=sessionCookiePattern.exec(request.headers.cookie || '')?.[1];
|
||||
const session=sessions.lookup(token);const user=session?store.user(session.userId):null;
|
||||
if(!user||session.passwordVersion!==store.passwordVersion(user.id))fail(401,'请先登录。');
|
||||
if(!user||user.enabled===false||session.passwordVersion!==store.passwordVersion(user.id)||cleanup.revoked(token))fail(401,'请先登录。');
|
||||
const reset=/^\/api\/users\/([\w-]+)\/password$/.exec(route);
|
||||
const passwordRequest=(route==='/api/account/password'||reset)&&request.method==='POST';
|
||||
if(session.renewed&&!passwordRequest)response.setHeader('Set-Cookie',`${sessionCookieName}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_MS/1000}${encryptedTransport?'; Secure':''}`);
|
||||
if(route==='/api/me' && request.method==='GET')return handled(200,{user});
|
||||
if(user.role==='admin'&&request.method==='GET'&&['/api/users','/api/workspace'].includes(route))await cleanup.retry();
|
||||
if(route==='/api/users'&&request.method==='GET'){
|
||||
if(user.role!=='admin')fail(403,'仅管理员可以管理账号。');
|
||||
const users=store.users(),evidence=cleanup.evidence(cleanup.rows());return handled(200,{users,assignments:Object.fromEntries(users.map(member=>[member.username,workspace?.ownedWork(member.username)||{connections:[],exceptions:[]}])),cleanupPending:evidence.pending,cleanup:evidence});
|
||||
}
|
||||
const lifecycle=/^\/api\/users\/([\w-]+)\/(lifecycle|revoke-sessions)$/.exec(route);
|
||||
if(lifecycle&&request.method==='POST'){
|
||||
if(user.role!=='admin')fail(403,'仅管理员可以调整账号或撤销登录。');
|
||||
const target=store.user(lifecycle[1]);if(!target)fail(404,'账号不存在。');
|
||||
const revokeOnly=lifecycle[2]==='revoke-sessions',allowed=revokeOnly?['version']:['version','enabled','role','transferTo'];
|
||||
if(!body||Array.isArray(body)||Object.keys(body).some(key=>!allowed.includes(key)))fail(400,'账号管理参数无效。');
|
||||
const change={version:body.version,enabled:revokeOnly?target.enabled:body.enabled,role:revokeOnly?target.role:body.role};
|
||||
store.validateUserChange(target.id,change,user);
|
||||
const transferTo=body.transferTo??'';if(typeof transferTo!=='string'||transferTo.length>40)fail(400,'请选择有效的新负责人。');
|
||||
const prior=await cleanup.retry(target.id),unfinished=cleanup.rows().find(row=>row.userId===target.id&&!row.stages.account);
|
||||
const work=workspace?.ownedWork(target.username)||{connections:[],exceptions:[]};
|
||||
const lockedIds=[...work.connections,...(unfinished?.connections.map(item=>item.id)||[])];
|
||||
return cleanup.locked(lockedIds,async()=>{
|
||||
store.validateUserChange(target.id,change,user);
|
||||
const current=workspace?.ownedWork(target.username)||{connections:[],exceptions:[]};
|
||||
if(current.connections.some(id=>!lockedIds.includes(id)))fail(409,'账号负责的连接已变化,请刷新后重试交接。');
|
||||
if((!change.enabled||change.role==='viewer')&&(current.connections.length||current.exceptions.length)&&!transferTo)fail(409,'此账号仍有连接或未结异常,请先选择交接负责人。');
|
||||
const targets={hashes:sessions.userSessionHashes(target.id),connections:transferTo?current.connections:[],exceptions:transferTo?current.exceptions:[]};
|
||||
// No await between the final ownership/session snapshot and account save.
|
||||
const row=unfinished?cleanup.refreshAccount(unfinished,targets):cleanup.create({userId:target.id,...targets,account:false});
|
||||
if(transferTo&&(current.connections.length||current.exceptions.length))try{workspace?.handoffOwner(target.username,transferTo,user,store.users());}catch(error){if(!unfinished)cleanup.remove(row.id);throw error;}
|
||||
const transfer={connections:row.connections.map(item=>item.id),exceptions:row.exceptions};
|
||||
let saved,saveFailed=false;try{saved=store.updateUser(target.id,change,user);row.stages.account=true;cleanup.save(row);}catch{saveFailed=true;}
|
||||
await cleanup.drainLocked(row);
|
||||
const evidence=cleanup.evidence([...prior.filter(item=>item.id!==row.id),row]);
|
||||
return handled(saveFailed?503:200,{...(saveFailed?{error:'负责人交接与会话清理已记录,账号设置保存失败;请刷新核对后重试。'}:{}),user:saved||store.user(target.id),transfer,cleanupPending:evidence.pending,cleanup:evidence,requiresLogin:target.id===user.id});
|
||||
});
|
||||
}
|
||||
if(passwordRequest){
|
||||
if(reset&&user.role!=='admin')fail(403,'仅管理员可以重置成员密码。');
|
||||
const targetId=reset?reset[1]:user.id;
|
||||
|
||||
@@ -13,11 +13,15 @@ async function publicJobs(jobs,outputDir,archiveStore){
|
||||
result[index]={...job,downloadable:fileStatus==='available',fileStatus,fileBytes,fileCheckedAt:new Date().toISOString(),archiveKnown:!!archiveStore?.archivesForJobs,archiveReceipts:receipts.filter(r=>r.jobId===job.jobId).map(({id,status,serverName,relativePath,finishedAt})=>({id,status,serverName:serverName||'',relativePath:relativePath||'',finishedAt:finishedAt||null}))};
|
||||
}}await Promise.all(Array.from({length:Math.min(8,jobs.length)},worker));return result;
|
||||
}
|
||||
async function queryJobs({jobs,outputDir,archiveStore},input={}){
|
||||
function normalizeJobQuery(input={}){
|
||||
const {q='',status='',page=1,pageSize=25}=input;
|
||||
if(typeof q!=='string'||q.length>200||!['','success','running','error','interrupted'].includes(status)||!Number.isSafeInteger(page)||page<1||page>1000000||!Number.isInteger(pageSize)||pageSize<1||pageSize>100)throw fail('导出记录查询条件无效。');
|
||||
return {q,status,page,pageSize};
|
||||
}
|
||||
async function queryJobs({jobs,outputDir,archiveStore},input={}){
|
||||
const {q,status,page,pageSize}=normalizeJobQuery(input);
|
||||
const needle=q.trim().toLowerCase(),filtered=jobs.filter(j=>(!status||j.status===status)&&(!needle||[j.metadata?.order,j.metadata?.project,j.metadata?.model,j.metadata?.serial,j.filename].join(' ').toLowerCase().includes(needle))).sort((a,b)=>String(b.updatedAt||'').localeCompare(String(a.updatedAt||''))||String(a.jobId).localeCompare(String(b.jobId)));
|
||||
const actualPage=Math.min(page,Math.max(1,Math.ceil(filtered.length/pageSize)));
|
||||
return {jobs:await publicJobs(filtered.slice((actualPage-1)*pageSize,actualPage*pageSize),outputDir,archiveStore),total:filtered.length,page:actualPage,pageSize};
|
||||
}
|
||||
module.exports={queryJobs,publicJobs,jobFile};
|
||||
module.exports={queryJobs,publicJobs,jobFile,normalizeJobQuery};
|
||||
@@ -0,0 +1,25 @@
|
||||
'use strict';
|
||||
const {normalizeJobQuery}=require('./job-records.cjs');
|
||||
class JobStore{
|
||||
constructor(store){
|
||||
this.store=store;const draft=structuredClone(store.data);
|
||||
store.database(db=>{
|
||||
db.exec("CREATE TABLE IF NOT EXISTS pdf_jobs(job_id TEXT PRIMARY KEY,value TEXT NOT NULL); CREATE INDEX IF NOT EXISTS pdf_jobs_updated ON pdf_jobs(json_extract(value,'$.updatedAt') DESC,job_id);");
|
||||
if(!Object.hasOwn(draft,'jobs'))return;
|
||||
db.exec('BEGIN IMMEDIATE');
|
||||
try{const insert=db.prepare('INSERT OR IGNORE INTO pdf_jobs(job_id,value) VALUES(?,?)');for(const job of [...(draft.jobs||[])].reverse()){if(typeof job.jobId!=='string'||!job.jobId)throw Error('历史PDF任务标识无效,未修改原记录。');insert.run(job.jobId,JSON.stringify(job));}delete draft.jobs;db.prepare('UPDATE dashboard_state SET value=? WHERE id=1').run(JSON.stringify(draft));db.exec('COMMIT');}
|
||||
catch(error){db.exec('ROLLBACK');throw error;}
|
||||
});store.data=draft;
|
||||
}
|
||||
get(id){return this.store.database(db=>{const row=db.prepare('SELECT value FROM pdf_jobs WHERE job_id=?').get(id);return row?JSON.parse(row.value):null;});}
|
||||
list(limit){return this.store.database(db=>db.prepare('SELECT value FROM pdf_jobs ORDER BY rowid DESC'+(limit?' LIMIT ?':'')).all(...(limit?[limit]:[])).map(row=>JSON.parse(row.value)));}
|
||||
set(db,value){db.prepare('DELETE FROM pdf_jobs WHERE job_id=?').run(value.jobId);db.prepare('INSERT INTO pdf_jobs(job_id,value) VALUES(?,?)').run(value.jobId,JSON.stringify(value));}
|
||||
page(input={}){
|
||||
const {q,status,page,pageSize}=normalizeJobQuery(input),conditions=[],args=[];
|
||||
if(status){conditions.push("json_extract(value,'$.status')=?");args.push(status);}
|
||||
if(q.trim()){conditions.push("LOWER(COALESCE(json_extract(value,'$.metadata.order'),'')||' '||COALESCE(json_extract(value,'$.metadata.project'),'')||' '||COALESCE(json_extract(value,'$.metadata.model'),'')||' '||COALESCE(json_extract(value,'$.metadata.serial'),'')||' '||COALESCE(json_extract(value,'$.filename'),'')) LIKE ? ESCAPE '\\'");args.push('%'+q.trim().toLowerCase().replace(/[\\%_]/g,'\\$&')+'%');}
|
||||
return this.store.database(db=>{const where=conditions.length?' WHERE '+conditions.join(' AND '):'',total=db.prepare('SELECT COUNT(*) AS n FROM pdf_jobs'+where).get(...args).n,actual=Math.min(page,Math.max(1,Math.ceil(total/pageSize)));const jobs=db.prepare("SELECT value FROM pdf_jobs"+where+" ORDER BY COALESCE(json_extract(value,'$.updatedAt'),'') DESC,job_id LIMIT ? OFFSET ?").all(...args,pageSize,(actual-1)*pageSize).map(row=>JSON.parse(row.value));return {jobs,total,page:actual,pageSize};});
|
||||
}
|
||||
stats(today){return this.store.database(db=>{const result=db.prepare("SELECT COUNT(*) AS total,SUM(CASE WHEN strftime('%Y-%m-%d',json_extract(value,'$.updatedAt'),'+8 hours')=? THEN 1 ELSE 0 END) AS today,SUM(CASE WHEN json_extract(value,'$.status')='success' THEN 1 ELSE 0 END) AS completed,SUM(CASE WHEN json_extract(value,'$.status') IN ('error','interrupted') THEN 1 ELSE 0 END) AS failed,SUM(CASE WHEN json_extract(value,'$.status')='running' THEN 1 ELSE 0 END) AS running FROM pdf_jobs").get(today);return Object.fromEntries(Object.entries(result).map(([key,value])=>[key,value||0]));});}
|
||||
}
|
||||
module.exports={JobStore};
|
||||
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs/promises'),path=require('node:path'),{DatabaseSync}=require('node:sqlite'),{once}=require('node:events');
|
||||
async function capacity(root){let files=0,bytes=0;async function visit(dir){let entries;try{entries=await fs.readdir(dir,{withFileTypes:true});}catch(e){if(e.code==='ENOENT')return;throw e;}for(const entry of entries){const file=path.join(dir,entry.name),stat=await fs.lstat(file);if(stat.isSymbolicLink())continue;if(stat.isDirectory())await visit(file);else if(stat.isFile()){files++;bytes+=stat.size;}}}await visit(root);return {files,bytes};}
|
||||
function publicHistory(job){return {jobId:job.jobId,status:job.status,filename:job.filename||'',createdAt:job.createdAt||null,updatedAt:job.updatedAt||null,metadata:Object.fromEntries(['order','project','model','serial'].filter(key=>typeof job.metadata?.[key]==='string').map(key=>[key,job.metadata[key]]))};}
|
||||
async function maintenanceApi({store,outputDir,user,route,method,reply,response}){
|
||||
if(!['/api/maintenance','/api/jobs/export'].includes(route)||method!=='GET')return false;if(user.role!=='admin')throw Object.assign(Error('仅管理员可以查看容量和导出历史。'),{status:403});
|
||||
if(route==='/api/maintenance'){const [state,pdf]=await Promise.all([capacity(path.dirname(path.dirname(store.file))),capacity(outputDir)]);reply(200,{retention:'permanent',policy:'默认永久保留;归档不会删除业务证据。',state,pdf,jobs:store.jobStats(),exportUrl:'/api/jobs/export'});return true;}
|
||||
const db=new DatabaseSync(store.file,{readOnly:true});try{response.writeHead(200,{'Content-Type':'application/x-ndjson; charset=utf-8','Content-Disposition':'attachment; filename="pdf-history.ndjson"','Cache-Control':'no-store'});for(const row of db.prepare('SELECT value FROM pdf_jobs ORDER BY rowid').iterate()){if(response.destroyed)break;if(!response.write(JSON.stringify(publicHistory(JSON.parse(row.value)))+'\n'))await once(response,'drain',{signal:AbortSignal.timeout(30000)});}response.end();}finally{db.close();}return true;
|
||||
}
|
||||
module.exports={maintenanceApi,capacity,publicHistory};
|
||||
@@ -0,0 +1,58 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');
|
||||
const {BpmConnectionLifecycle}=require('../bpm/connection-lifecycle.cjs');
|
||||
const instances=new WeakMap();
|
||||
// Only opaque identifiers, session digests and completion flags are persisted.
|
||||
class PendingCleanup{
|
||||
constructor(store){this.store=store;store.database(db=>db.exec('CREATE TABLE IF NOT EXISTS pending_access_cleanup(id TEXT PRIMARY KEY,value TEXT NOT NULL)'));}
|
||||
configure({workspace,bpmSessions,bpmMonitor,bpmLifecycle,sessions}){
|
||||
if(sessions)this.sessions=sessions;
|
||||
this.manager=bpmSessions;this.monitor=bpmMonitor;
|
||||
this.lifecycle=bpmLifecycle||this.lifecycle||(workspace?new BpmConnectionLifecycle({workspace,manager:bpmSessions,monitor:bpmMonitor}):null);
|
||||
if(this.lifecycle)this.lifecycle.pendingCleanup=this;
|
||||
return this;
|
||||
}
|
||||
rows(){return this.store.database(db=>db.prepare('SELECT value FROM pending_access_cleanup').all().map(row=>JSON.parse(row.value)));}
|
||||
save(row){this.store.database(db=>db.prepare('INSERT OR REPLACE INTO pending_access_cleanup(id,value) VALUES(?,?)').run(row.id,JSON.stringify(row)));return row;}
|
||||
remove(id){this.store.database(db=>db.prepare('DELETE FROM pending_access_cleanup WHERE id=?').run(id));}
|
||||
create({userId=null,hashes=[],connections=[],exceptions=[],account=true}){return this.save({id:crypto.randomUUID(),userId,hashes,connections:connections.map(id=>({id,suspended:false,monitor:false})),exceptions,stages:{account,sessionRows:!userId,sessionHashes:!hashes.length}});}
|
||||
refreshAccount(row,{hashes,connections,exceptions}){
|
||||
// An uncommitted account can issue new sessions and receive work. Retain old
|
||||
// targets, but re-arm cleanup for every target present at this commit boundary.
|
||||
row.hashes=[...new Set([...row.hashes,...hashes])];
|
||||
row.stages.sessionRows=false;row.stages.sessionHashes=!row.hashes.length;
|
||||
for(const id of connections){const item=row.connections.find(item=>item.id===id);if(item){item.suspended=false;item.monitor=false;}else row.connections.push({id,suspended:false,monitor:false});}
|
||||
row.exceptions=[...new Set([...row.exceptions,...exceptions])];
|
||||
return this.save(row);
|
||||
}
|
||||
revoked(token){if(!token)return false;const hash=crypto.createHash('sha256').update(token).digest('hex');return this.rows().some(row=>row.hashes.includes(hash));}
|
||||
hasConnection(id){return this.rows().some(row=>row.connections.some(item=>item.id===id&&(!item.suspended||!item.monitor)));}
|
||||
locked(ids,work){const sorted=[...new Set(ids)].sort();const next=index=>index===sorted.length?work():this.lifecycle.run(sorted[index],()=>next(index+1));return next(0);}
|
||||
evidence(rows){const stages={account:true,sessionRows:true,sessionHashes:true,connections:true};for(const row of rows){for(const key of ['account','sessionRows','sessionHashes'])stages[key]&&=row.stages[key];stages.connections&&=row.connections.every(item=>item.suspended&&item.monitor);}return {stages,pending:!Object.values(stages).every(Boolean)};}
|
||||
async drainLocked(row){
|
||||
const complete=async(work,mark)=>{try{await work();mark();this.save(row);}catch{/* The durable target remains available for another management request. */}};
|
||||
// suspend publishes the runtime barrier synchronously, before monitor shutdown awaits.
|
||||
const work=row.connections.flatMap(item=>[
|
||||
...(!item.suspended?[complete(()=>this.manager?this.manager.suspend(item.id):undefined,()=>{item.suspended=true;})]:[]),
|
||||
...(!item.monitor?[complete(()=>this.monitor?.stopConnection(item.id),()=>{item.monitor=true;})]:[])
|
||||
]);
|
||||
if(!row.stages.sessionRows)work.push(complete(()=>{if(!this.sessions)throw Error('Session store unavailable');this.sessions.revokeUser(row.userId);},()=>{row.stages.sessionRows=true;}));
|
||||
if(!row.stages.sessionHashes)work.push(complete(()=>this.manager?this.manager.releaseSessionHashes(row.hashes):undefined,()=>{row.stages.sessionHashes=true;}));
|
||||
await Promise.all(work);
|
||||
if(!this.evidence([row]).pending)this.remove(row.id);
|
||||
return row;
|
||||
}
|
||||
async retry(userId){
|
||||
const result=[];
|
||||
for(const row of this.rows().filter(row=>userId===undefined||row.userId===userId))await this.locked(row.connections.map(item=>item.id),async()=>{
|
||||
const current=this.rows().find(item=>item.id===row.id);if(!current)return;
|
||||
// Capture before a retried revokeUser can erase the only source of a newly
|
||||
// issued token's digest while the account save is still unfinished.
|
||||
if(!current.stages.account&&this.sessions)this.refreshAccount(current,{hashes:this.sessions.userSessionHashes(current.userId),connections:[],exceptions:[]});
|
||||
result.push(await this.drainLocked(current));
|
||||
});
|
||||
return result;
|
||||
}
|
||||
}
|
||||
function accessCleanup(options){let instance=instances.get(options.store);if(!instance){instance=new PendingCleanup(options.store);instances.set(options.store,instance);}return instance.configure(options);}
|
||||
module.exports={accessCleanup};
|
||||
@@ -3,8 +3,9 @@ const path=require('node:path');
|
||||
const crypto=require('node:crypto');
|
||||
const {DatabaseSync}=require('node:sqlite');
|
||||
const {validatePassword,hashPassword,matchesPassword}=require('./passwords.cjs');
|
||||
const {JobStore}=require('./job-store.cjs');
|
||||
const copy=value=>structuredClone(value);
|
||||
const safeUser=({id,username,role,createdAt})=>({id,username,role,createdAt});
|
||||
const safeUser=({id,username,role,createdAt,enabled=true,version=1})=>({id,username,role,createdAt,enabled,version});
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
|
||||
function validateSettings(settings) {
|
||||
@@ -41,14 +42,15 @@ class Store {
|
||||
db.prepare('INSERT OR IGNORE INTO dashboard_state(id,value) VALUES(1,?)').run(JSON.stringify(data));
|
||||
return JSON.parse(db.prepare('SELECT value FROM dashboard_state WHERE id=1').get().value);
|
||||
});
|
||||
this.jobStore=new JobStore(this);
|
||||
}
|
||||
database(work){
|
||||
const db=new DatabaseSync(this.file);
|
||||
try{db.exec('PRAGMA busy_timeout=5000; PRAGMA synchronous=FULL;');return work(db);}finally{db.close();}
|
||||
}
|
||||
commit(mutator) {
|
||||
commit(mutator,mutateDatabase) {
|
||||
const draft=copy(this.data);const result=mutator(draft);
|
||||
this.database(db=>db.prepare('UPDATE dashboard_state SET value=? WHERE id=1').run(JSON.stringify(draft)));
|
||||
this.database(db=>{db.exec('BEGIN IMMEDIATE');try{mutateDatabase?.(db);db.prepare('UPDATE dashboard_state SET value=? WHERE id=1').run(JSON.stringify(draft));db.exec('COMMIT');}catch(error){db.exec('ROLLBACK');throw error;}});
|
||||
this.data=draft;return copy(result);
|
||||
}
|
||||
addAudit(draft,actor,action,detail='') {draft.audit.unshift({id:crypto.randomUUID(),at:new Date().toISOString(),actor,action,detail});draft.audit=draft.audit.slice(0,2000);}
|
||||
@@ -73,7 +75,7 @@ class Store {
|
||||
validatePassword(password);
|
||||
if(!['admin','operator','viewer'].includes(role))fail('账号角色不正确。');
|
||||
if(this.data.users.some(user=>user.username.toLowerCase()===username.toLowerCase()))fail('账号已存在。',409);
|
||||
return {id:crypto.randomUUID(),username,role,createdAt:new Date().toISOString(),passwordHash:hashPassword(password)};
|
||||
return {id:crypto.randomUUID(),username,role,enabled:true,version:1,createdAt:new Date().toISOString(),passwordHash:hashPassword(password)};
|
||||
}
|
||||
bootstrap(username,password) {
|
||||
if(this.data.users.length)fail('管理员已经创建,请登录。',409);
|
||||
@@ -87,10 +89,22 @@ class Store {
|
||||
authenticate(username,password) {
|
||||
if(typeof username!=='string' || typeof password!=='string' || password.length>128)return null;
|
||||
const user=this.data.users.find(user=>user.username.toLowerCase()===username.toLowerCase());
|
||||
if(!matchesPassword(password,user?.passwordHash) || !user)return null;
|
||||
if(!matchesPassword(password,user?.passwordHash) || !user || user.enabled===false)return null;
|
||||
return safeUser(user);
|
||||
}
|
||||
passwordVersion(id){return this.data.users.find(user=>user.id===id)?.passwordVersion||0;}
|
||||
validateUserChange(id,input,actor){
|
||||
if(actor?.role!=='admin')fail('仅管理员可以调整账号。',403);
|
||||
const target=this.user(id);if(!target)fail('账号不存在。',404);
|
||||
if(!input||Object.keys(input).some(key=>!['version','enabled','role'].includes(key))||input.version!==target.version)fail('账号已变化,请刷新后重试。',409);
|
||||
if(typeof input.enabled!=='boolean'||!['admin','operator','viewer'].includes(input.role))fail('账号启用状态或角色无效。');
|
||||
if(target.role==='admin'&&target.enabled&&(!input.enabled||input.role!=='admin')&&!this.users().some(user=>user.id!==id&&user.role==='admin'&&user.enabled))fail('必须保留至少一个启用的管理员。',409);
|
||||
return target;
|
||||
}
|
||||
updateUser(id,input,actor){
|
||||
this.validateUserChange(id,input,actor);
|
||||
return this.commit(draft=>{const target=draft.users.find(user=>user.id===id);target.role=input.role;target.enabled=input.enabled;target.version=(target.version||1)+1;target.passwordVersion=(target.passwordVersion||0)+1;this.addAudit(draft,actor.username,'调整账号权限',target.username+' / '+input.role+' / '+(input.enabled?'启用':'停用'));return safeUser(target);});
|
||||
}
|
||||
updatePassword(id,password,actor){
|
||||
const user=this.data.users.find(user=>user.id===id);if(!user)fail('账号不存在。',404);
|
||||
validatePassword(password);if(matchesPassword(password,user.passwordHash))fail('新密码不能与原密码相同。');
|
||||
@@ -103,20 +117,19 @@ class Store {
|
||||
});
|
||||
}
|
||||
recordJob(record) {
|
||||
return this.commit(draft=>{
|
||||
const index=draft.jobs.findIndex(job=>job.jobId===record.jobId);
|
||||
const prior=index>=0?draft.jobs[index]:{createdAt:new Date().toISOString()};
|
||||
const saved={...prior,...copy(record),updatedAt:new Date().toISOString()};
|
||||
if(index>=0)draft.jobs.splice(index,1);draft.jobs.unshift(saved);draft.jobs=draft.jobs.slice(0,5000);
|
||||
if(record.status!=='running')this.addAudit(draft,'浏览器导出',record.status==='success'?'PDF 导出完成':'PDF 导出失败',record.filename || record.error || '');
|
||||
return saved;
|
||||
});
|
||||
if(typeof record?.jobId!=='string'||!record.jobId||record.jobId.length>200)fail('导出任务标识无效。');
|
||||
const prior=this.job(record.jobId)||{createdAt:new Date().toISOString()},saved={...prior,...copy(record),updatedAt:new Date().toISOString()};
|
||||
return this.commit(draft=>{if(saved.status!=='running')this.addAudit(draft,'浏览器导出',saved.status==='success'?'PDF 导出完成':'PDF 导出失败',saved.filename||saved.error||'');return saved;},db=>this.jobStore.set(db,saved));
|
||||
}
|
||||
jobs(){return copy(this.data.jobs);}
|
||||
job(id){return this.jobStore.get(id);}
|
||||
jobs(){return this.jobStore.list();}
|
||||
recentJobs(limit=15){if(!Number.isInteger(limit)||limit<1||limit>5000)fail('记录条数无效。');return this.jobStore.list(limit);}
|
||||
jobPage(filters){return this.jobStore.page(filters);}
|
||||
jobStats(){return this.jobStore.stats(new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date()));}
|
||||
audit(){return copy(this.data.audit);}
|
||||
recoverJobs() {
|
||||
if(!this.data.jobs.some(job=>job.status==='running'))return;
|
||||
this.commit(draft=>{for(const job of draft.jobs)if(job.status==='running'){job.status='interrupted';job.error='服务重启,请核对输出文件后重新导出。';}return null;});
|
||||
const running=this.database(db=>db.prepare("SELECT value FROM pdf_jobs WHERE json_extract(value,'$.status')='running'").all().map(row=>JSON.parse(row.value)));
|
||||
for(const job of running)this.recordJob({...job,status:'interrupted',error:'服务重启,请核对输出文件后重新导出。'});
|
||||
}
|
||||
}
|
||||
module.exports={Store};
|
||||
@@ -243,6 +243,7 @@ class OrderExecutionCoordinator{
|
||||
}).finally(()=>{this.store.activeDiscoveries--;}).then(()=>this.snapshot(principal));
|
||||
}
|
||||
async execute(task,connection,principal,{automatic=false}={}){
|
||||
let expectedArchive;
|
||||
try{
|
||||
if(task.missedWindow||automatic&&!this.store.settings().processingEnabled)return;
|
||||
if(!task.sampleId){
|
||||
@@ -255,16 +256,23 @@ class OrderExecutionCoordinator{
|
||||
await this.refreshCapabilities(this.store.all('rules').find(r=>task.categoryIds.includes(r.id))?.published);
|
||||
if(task.orderId){order=this.store.get('orders',task.orderId);if(order?.status==='blocked'&&!order.archive)try{order=this.store.recheck(order.id,{note:'重新扫描使用当前已核验规则'},principal.user.username);}catch(error){task.status='blocked';task.error=error.message;this.persist(task);await this.exception(task,connection,false);return;}}
|
||||
if(!order){order=this.store.ingest(captured.sample,principal.user.username);task.orderId=order.id;}
|
||||
task.status=order.status;task.error=order.error;task.step='identify';this.persist(task);
|
||||
Object.assign(task,this.store.get('execution-tasks',task.id));
|
||||
task.orderId=order.id;task.status=order.status;task.error=order.error;task.step='identify';this.persist(task);
|
||||
if(order.status==='blocked'){await this.exception(task,connection,false);return;}
|
||||
if(order.archive){task.step='complete';task.status=order.status;this.persist(task);await this.exception(task,connection,true);return;}
|
||||
if(!['identified','preparing'].includes(order.status))return;
|
||||
if(task.missedWindow||automatic&&!this.store.settings().processingEnabled)return;
|
||||
task.status='archiving';task.step='archive';this.persist(task);
|
||||
expectedArchive=require('../order-rules/migrations.cjs').archiveContext(order,task);
|
||||
const evidence=await this.archive.archive({order:clone(order),rule:clone(order.ruleSnapshot),snapshot:clone(captured.snapshot),taskId:task.id});
|
||||
order=this.store.recordArchive(order.id,evidence,principal.user.username);task.status=order.status;task.error=order.error;task.step='complete';this.persist(task);
|
||||
order=this.store.recordArchive(order.id,evidence,principal.user.username,expectedArchive);
|
||||
if(!order)return;
|
||||
task.status=order.status;task.error=order.error;task.step='complete';this.persist(task);
|
||||
await this.exception(task,connection,true);
|
||||
}catch(error){const uncertain=task.status==='archiving';task.status=uncertain&&this.archive.supportsRecovery!==true?'unknown':'failed';task.error=uncertain?'归档结果待核验,需人工受控恢复:'+error.message:error.message;this.persist(task);await this.exception(task,connection,false);}
|
||||
}catch(error){
|
||||
if(expectedArchive&&!require('../order-rules/migrations.cjs').archiveContextMatches(this.store,this.store.get('orders',task.orderId),expectedArchive))return;
|
||||
const uncertain=task.status==='archiving';task.status=uncertain&&this.archive.supportsRecovery!==true?'unknown':'failed';task.error=uncertain?'归档结果待核验,需人工受控恢复:'+error.message:error.message;this.persist(task);await this.exception(task,connection,false);
|
||||
}
|
||||
}
|
||||
adoptRevision(task,order,captured){
|
||||
const {digest,invalidateArchive}=require('../order-rules/migrations.cjs');
|
||||
|
||||
@@ -38,8 +38,16 @@ function invalidateArchive(order){
|
||||
order.archiveGeneration=(order.archiveGeneration||1)+1;
|
||||
order.archive=null;
|
||||
}
|
||||
function archiveContext(order,task){
|
||||
return {generation:order.archiveGeneration||1,sourceHash:order.sourceHash,
|
||||
outputFingerprint:digest([order.event,order.ruleSnapshot]),taskId:task.id,taskVersion:task.version};
|
||||
}
|
||||
function archiveContextMatches(store,order,expected){
|
||||
const task=store.get('execution-tasks',expected.taskId);
|
||||
return !!order&&!!task&&task.orderId===order.id&&digest(archiveContext(order,task))===digest(expected);
|
||||
}
|
||||
function synchronizeTasks(store,order){
|
||||
for(const task of store.all('execution-tasks').filter(task=>task.orderId===order.id)){
|
||||
for(const task of store.all('execution-tasks').filter(task=>task.orderId===order.id&&!task.supersededBy&&!task.revisionIgnored)){
|
||||
task.status=order.status;
|
||||
task.step=order.archive?'complete':'identify';
|
||||
task.error=null;
|
||||
@@ -82,7 +90,9 @@ function apply(store,id,input,actor){
|
||||
for(const item of result.items){
|
||||
const order=store.get('orders',item.id);
|
||||
const proposed=projection(store,order,rule);
|
||||
if(proposed.archiveChanged){
|
||||
// A pending intent freezes its original rule metadata. Until a receipt has
|
||||
// committed, a publication migration starts a new generation for safe retry.
|
||||
if(proposed.archiveChanged||!order.archive&&order.ruleSnapshot?.version!==rule.version){
|
||||
invalidateArchive(order);
|
||||
order.status='identified';
|
||||
}
|
||||
@@ -100,4 +110,4 @@ function apply(store,id,input,actor){
|
||||
return result;
|
||||
});
|
||||
}
|
||||
module.exports={preview,apply,frozen,validate,digest,invalidateArchive};
|
||||
module.exports={preview,apply,frozen,validate,digest,invalidateArchive,synchronizeTasks,archiveContext,archiveContextMatches};
|
||||
@@ -139,13 +139,22 @@ class RuleStore{
|
||||
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(()=>{
|
||||
recordArchive(id,evidence,actor,expected){return this.transaction(()=>{
|
||||
if(!this.capabilities.automaticArchive)fail('自动归档接入待联调。',409);
|
||||
const order=this.get('orders',id);if(!order)fail('订单任务不存在。',404);
|
||||
if(!['identified','preparing'].includes(order.status))fail('当前状态不允许记录归档结果。',409);
|
||||
const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
|
||||
if(window&&Date.parse(order.event.receivedAt)<Date.parse(window.start))fail('该订单已超出当前时段,不再自动归档或补发。',409);
|
||||
const stale=expected&&!require('./migrations.cjs').archiveContextMatches(this,order,expected);
|
||||
if(!stale){
|
||||
if(!['identified','preparing'].includes(order.status))fail('当前状态不允许记录归档结果。',409);
|
||||
const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
|
||||
if(window&&Date.parse(order.event.receivedAt)<Date.parse(window.start))fail('该订单已超出当前时段,不再自动归档或补发。',409);
|
||||
}
|
||||
if(!evidence||!validDate(evidence.archivedAt)||!Array.isArray(evidence.files)||!evidence.files.length||evidence.files.some(f=>!f||typeof f.name!=='string'||!f.name||/[\\/\x00-\x1f]/.test(f.name)||typeof f.path!=='string'||!path.win32.isAbsolute(f.path)||! /^[a-f0-9]{64}$/i.test(f.sha256)||!Number.isSafeInteger(f.size)||f.size<1||!['pdf','notice'].includes(f.kind)))fail('归档证据不完整。');
|
||||
if(stale){
|
||||
// Keep the old operation's receipt under its original context. It cannot
|
||||
// satisfy a newer generation or change that generation's processing state.
|
||||
order.archiveHistory=[...(order.archiveHistory||[]),{...copy(expected),evidence:copy(evidence),stale:true}];
|
||||
this.put('orders',order);this.audit(actor,'保留过期归档回执',id+' generation '+expected.generation);return null;
|
||||
}
|
||||
if(order.status==='identified')order.status=transition('order',order.status,'prepare');
|
||||
order.status=transition('order',order.status,'archive');order.archive=copy(evidence);
|
||||
if(order.ruleSnapshot.attachPdf&&!evidence.files.some(f=>f.kind==='pdf')){order.status='blocked';order.error='缺少本类别要求的电子流 PDF。';}
|
||||
@@ -170,7 +179,7 @@ class RuleStore{
|
||||
order.event=result.event;order.ruleSnapshot=copy(rule);order.categoryId=rule.categoryId;order.trace=result;
|
||||
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;
|
||||
this.put('orders',order);require('./migrations.cjs').synchronizeTasks(this,order);this.audit(actor,'应用当前规则重新识别',id+':'+input.note.trim());return order;
|
||||
});}
|
||||
discoveryBlockers(cutoff,allowed=()=>true){
|
||||
const blockers=(this.deliveryBlockers?.(allowed)||[]).map(id=>'连接 '+id+' 本地执行线索尚未交付。');
|
||||
|
||||
@@ -76,7 +76,7 @@ class StorageService{
|
||||
archive(id,jobId,directory='',actor='自动归档'){
|
||||
return this.run(id,async (server,signal)=>{
|
||||
segments(directory);if(typeof jobId!=='string'||!jobId||jobId.length>200)throw fail('请选择已完成的 PDF 导出任务。');
|
||||
const job=this.jobs.jobs().find(j=>j.jobId===jobId);if(!job||job.status!=='success'||typeof job.path!=='string')throw fail('请选择已完成且存在的 PDF。');
|
||||
const job=this.jobs.job?this.jobs.job(jobId):this.jobs.jobs().find(j=>j.jobId===jobId);if(!job||job.status!=='success'||typeof job.path!=='string')throw fail('请选择已完成且存在的 PDF。');
|
||||
const record=this.store.beginArchive(id,jobId,actor,directory);
|
||||
try{
|
||||
const [root,file]=await Promise.all([fs.realpath(this.outputDir),fs.realpath(job.path)]);
|
||||
|
||||
@@ -1,13 +1,24 @@
|
||||
// This router is called only after dashboard authentication and same-origin validation.
|
||||
function workspaceApi({workspace,store,user,route,method,body,reply,bpmSessions,bpmMonitor}){
|
||||
async function workspaceApi({workspace,store,user,route,method,body,reply,bpmSessions,bpmMonitor,bpmLifecycle,orderRules}){
|
||||
if(!workspace)return false;
|
||||
const members=()=>store.users();
|
||||
if(route==='/api/workspace'||route.startsWith('/api/exceptions'))workspace.syncBusinessIssues?.(orderRules?.all('business-issues')||[],members());
|
||||
if(route==='/api/workspace' && method==='GET'){const snapshot=workspace.snapshot(members());snapshot.capabilities.remoteLogin=Boolean(bpmSessions);snapshot.connections=snapshot.connections.map(c=>({...c,health:bpmSessions?.health?.snapshot(c.id)||{},monitoring:bpmMonitor?.snapshot(c.id)||{status:c.status==='disabled'?'paused':'waiting'}}));reply(200,snapshot);return true;}
|
||||
if(method!=='POST')return false;
|
||||
if(route==='/api/calendar'){reply(200,workspace.saveCalendar(body,user));return true;}
|
||||
if(route==='/api/exceptions'){reply(201,workspace.createException(body,user,members()));return true;}
|
||||
const action=/^\/api\/exceptions\/([\w-]+)\/action$/.exec(route);if(action){reply(200,workspace.actOnException(action[1],body,user,members()));return true;}
|
||||
const action=/^\/api\/exceptions\/([\w-]+)\/action$/.exec(route);if(action){const issue=workspace.snapshot().exceptions.find(i=>i.id===action[1]);if(body?.action==='resolve'&&issue?.batchId&&orderRules?.get('batches',issue.batchId)?.status==='unknown')throw Object.assign(Error('请先在邮件批次中核验不确定结果,再关闭异常。'),{status:409});reply(200,workspace.actOnException(action[1],body,user,members()));return true;}
|
||||
if(route==='/api/connections'){reply(201,workspace.createConnection(body,user,members()));return true;}
|
||||
const owner=/^\/api\/connections\/([\w-]+)\/owner$/.exec(route);if(owner){
|
||||
if(user.role!=='admin')throw Object.assign(Error('仅管理员可以转交连接。'),{status:403});
|
||||
const cleanup=require('../dashboard/pending-cleanup.cjs').accessCleanup({store,workspace,bpmSessions,bpmMonitor,bpmLifecycle});
|
||||
await cleanup.retry();
|
||||
await cleanup.locked([owner[1]],async()=>{
|
||||
const row=cleanup.create({connections:[owner[1]]});let connection;
|
||||
try{connection=workspace.transferConnection(owner[1],body,user,members());}catch(error){cleanup.remove(row.id);throw error;}
|
||||
await cleanup.drainLocked(row);const evidence=cleanup.evidence([row]);reply(200,{connection,cleanupPending:evidence.pending,cleanup:evidence});
|
||||
});return true;
|
||||
}
|
||||
const disable=/^\/api\/connections\/([\w-]+)\/disable$/.exec(route);if(disable){if(Object.keys(body).length)throw Object.assign(new Error('停用连接不接受额外数据。'),{status:400});reply(200,workspace.disableConnection(disable[1],user));return true;}
|
||||
if(route==='/api/supervisor')throw Object.assign(new Error('监管草稿已停用,请在系统健康和异常待办中查看实际运行结果。'),{status:410});
|
||||
return false;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');
|
||||
function issueId(id){return 'business-'+crypto.createHash('sha256').update(id).digest('hex').slice(0,32);}
|
||||
// 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 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(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;
|
||||
});}
|
||||
module.exports={reconcile,issueId};
|
||||
@@ -4,7 +4,7 @@ const object=(input,keys)=>{if(!input || Array.isArray(input) || typeof input!==
|
||||
const text=(value,label,max,required=false)=>{if(typeof value!=='string' || value.length>max || (required && !value.trim()))fail(`${label}格式不正确。`);return value.trim();};
|
||||
const version=value=>{if(!Number.isSafeInteger(value) || value<1)fail('版本号不正确。');};
|
||||
const authorize=(actor,roles)=>{if(!actor || typeof actor.username!=='string' || !roles.includes(actor.role))fail('当前账号没有执行此操作的权限。',403);};
|
||||
const owner=(value,members,required=false)=>{const name=text(value,'负责人',40,required);if(name && !members?.some(user=>user.username===name && ['admin','operator'].includes(user.role)))fail('请选择有效的管理员或操作员作为负责人。');return name;};
|
||||
const owner=(value,members,required=false)=>{const name=text(value,'负责人',40,required);if(name && !members?.some(user=>user.username===name && user.enabled!==false && ['admin','operator'].includes(user.role)))fail('请选择有效且启用的管理员或操作员作为负责人。');return name;};
|
||||
const validDate=date=>typeof date==='string' && /^\d{4}-\d{2}-\d{2}$/.test(date) && date>='0001-01-01' && date<='9999-12-31' && !Number.isNaN(Date.parse(date+'T00:00:00Z')) && new Date(date+'T00:00:00Z').toISOString().slice(0,10)===date;
|
||||
|
||||
class WorkspaceStore {
|
||||
@@ -39,7 +39,7 @@ class WorkspaceStore {
|
||||
const exceptions=this.db.prepare('SELECT value FROM exceptions ORDER BY rowid DESC').all().map(row=>JSON.parse(row.value));
|
||||
const connections=this.db.prepare('SELECT value FROM connections ORDER BY rowid DESC').all().map(row=>JSON.parse(row.value));
|
||||
const audit=this.db.prepare('SELECT value FROM audit ORDER BY seq DESC LIMIT 2000').all().map(row=>JSON.parse(row.value));
|
||||
return {calendar,exceptions,connections,supervisor,audit,members:members.map(({username,role})=>({username,role})),capabilities:{remoteLogin:false,zcode:false,automaticProcessing:false},stats:{open:exceptions.filter(e=>e.status==='open').length,inProgress:exceptions.filter(e=>e.status==='in_progress').length,verifying:exceptions.filter(e=>e.status==='verifying').length,resolved:exceptions.filter(e=>e.status==='resolved').length,connections:connections.filter(c=>c.status!=='disabled').length,overrides:calendar.overrides.length}};
|
||||
return {calendar,exceptions,connections,supervisor,audit,members:members.filter(member=>member.enabled!==false).map(({username,role})=>({username,role})),capabilities:{remoteLogin:false,zcode:false,automaticProcessing:false},stats:{open:exceptions.filter(e=>e.status==='open').length,inProgress:exceptions.filter(e=>e.status==='in_progress').length,verifying:exceptions.filter(e=>e.status==='verifying').length,resolved:exceptions.filter(e=>e.status==='resolved').length,retired:exceptions.filter(e=>e.status==='retired').length,connections:connections.filter(c=>c.status!=='disabled').length,overrides:calendar.overrides.length}};
|
||||
});
|
||||
}
|
||||
saveCalendar(input,actor){
|
||||
@@ -54,11 +54,13 @@ class WorkspaceStore {
|
||||
if(!['bpm','pdf','archive','mail','system','rules'].includes(input.component) || !['normal','high','critical'].includes(input.priority))fail('异常组件或优先级不正确。');
|
||||
return this.transaction(()=>{const at=new Date().toISOString();const item={id:crypto.randomUUID(),title,description,component:input.component,priority:input.priority,owner:assigned,status:assigned?'in_progress':'open',version:1,createdAt:at,updatedAt:at,history:[{at,actor:actor.username,action:'create',note:description,toOwner:assigned}]};this.db.prepare('INSERT INTO exceptions(id,value) VALUES(?,?)').run(item.id,JSON.stringify(item));this.record(actor,'建立异常',title);return item;});
|
||||
}
|
||||
syncBusinessIssues(issues,members){return require('./business-issues.cjs').reconcile(this,issues,members);}
|
||||
businessIssue(id){const row=this.db.prepare('SELECT value FROM exceptions WHERE id=?').get(require('./business-issues.cjs').issueId(id));return row?JSON.parse(row.value):null;}
|
||||
actOnException(id,input,actor,members){
|
||||
authorize(actor,['admin','operator']);object(input,['version','action','owner','note']);version(input.version);
|
||||
if(!['claim','transfer','verify','resolve','reopen'].includes(input.action))fail('异常操作不正确。');
|
||||
if(!['claim','transfer','verify','resolve','reopen','archive'].includes(input.action))fail('异常操作不正确。');
|
||||
const note=input.note===undefined?'':text(input.note,'处理记录',5000);
|
||||
if(['transfer','resolve','reopen'].includes(input.action) && !note)fail('请填写交接原因或人工核验依据。');
|
||||
if(['transfer','resolve','reopen','archive'].includes(input.action) && !note)fail('请填写交接原因或人工核验依据。');
|
||||
const assigned=input.action==='transfer'?owner(input.owner,members,true):undefined;
|
||||
if(input.action!=='transfer' && input.owner!==undefined)fail('此操作不接受指定负责人。');
|
||||
return this.transaction(()=>{
|
||||
@@ -69,7 +71,9 @@ class WorkspaceStore {
|
||||
owner(actor.username,members,true);item.owner=actor.username;item.status='in_progress';
|
||||
}else {
|
||||
if(actor.role!=='admin' && item.owner!==actor.username)fail('只有负责人或管理员可以处理此异常。',403);
|
||||
if(input.action==='transfer'){
|
||||
if(input.action==='archive'){
|
||||
if(actor.role!=='admin'||item.sourceIssueId||(item.kind==='bpm_login'&&this.db.prepare('SELECT 1 FROM connections WHERE id=?').get(item.connectionId))||item.status==='retired')fail('仅管理员可归档旧手工、演示或已失去来源的异常;业务问题须先完成实际处理。',409);item.status='retired';item.retiredAt=new Date().toISOString();
|
||||
}else if(input.action==='transfer'){
|
||||
if(!['open','in_progress','verifying'].includes(item.status))fail('已关闭异常需先重新打开。',409);
|
||||
if(assigned===item.owner)fail('新负责人必须与当前负责人不同。');
|
||||
}else if(input.action==='verify'){
|
||||
@@ -83,7 +87,7 @@ class WorkspaceStore {
|
||||
const at=new Date().toISOString();const history={at,actor:actor.username,action:input.action,note};
|
||||
if(input.action==='transfer'){history.fromOwner=item.owner;history.toOwner=assigned;item.owner=assigned;item.status='in_progress';}
|
||||
if(input.action==='reopen'){history.fromOwner=item.owner;history.toOwner='';item.owner='';}
|
||||
item.updatedAt=at;item.version++;item.history.push(history);this.db.prepare('UPDATE exceptions SET value=? WHERE id=?').run(JSON.stringify(item),id);this.record(actor,({claim:'认领异常',transfer:'转交异常',verify:'提交异常验证',resolve:'人工核验关闭异常',reopen:'重新打开异常'})[input.action],item.title+(note?':'+note:''));return item;
|
||||
item.updatedAt=at;item.version++;item.history.push(history);this.db.prepare('UPDATE exceptions SET value=? WHERE id=?').run(JSON.stringify(item),id);this.record(actor,({claim:'认领异常',transfer:'转交异常',verify:'提交异常验证',resolve:'人工核验关闭异常',reopen:'重新打开异常',archive:'归档旧异常'})[input.action],item.title+(note?':'+note:''));return item;
|
||||
});
|
||||
}
|
||||
createConnection(input,actor,members){
|
||||
@@ -91,6 +95,19 @@ class WorkspaceStore {
|
||||
return this.transaction(()=>{const at=new Date().toISOString();const item={id:crypto.randomUUID(),name,owner:assigned,status:'disconnected',mainUrl:'https://bpmn.skyworthdigital.com',createdAt:at,updatedAt:at};this.db.prepare('INSERT INTO connections(id,value) VALUES(?,?)').run(item.id,JSON.stringify(item));this.record(actor,'创建连接',name);return item;});
|
||||
}
|
||||
getConnection(id){const row=this.db.prepare('SELECT value FROM connections WHERE id=?').get(id);if(!row)fail('没有找到此连接。',404);return JSON.parse(row.value);}
|
||||
ownedWork(username){return {connections:this.db.prepare('SELECT value FROM connections').all().map(row=>JSON.parse(row.value)).filter(item=>item.owner===username).map(item=>item.id),exceptions:this.db.prepare('SELECT value FROM exceptions').all().map(row=>JSON.parse(row.value)).filter(item=>item.owner===username&&!['resolved','retired'].includes(item.status)).map(item=>item.id)};}
|
||||
handoffOwner(from,to,actor,members){
|
||||
authorize(actor,['admin']);const assigned=owner(to,members,true);if(from===assigned)fail('新负责人必须与原负责人不同。');
|
||||
return this.transaction(()=>{const result={connections:[],exceptions:[]},at=new Date().toISOString();
|
||||
for(const {id,value} of this.db.prepare('SELECT id,value FROM connections').all()){const item=JSON.parse(value);if(item.owner!==from)continue;Object.assign(item,{owner:assigned,status:'disabled',disabledAt:at,updatedAt:at,version:(item.version||0)+1});this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),id);result.connections.push(id);}
|
||||
for(const {id,value} of this.db.prepare('SELECT id,value FROM exceptions').all()){const item=JSON.parse(value);if(item.owner!==from||['resolved','retired'].includes(item.status))continue;item.owner=assigned;item.status='in_progress';item.updatedAt=at;item.version++;item.history.push({at,actor:actor.username,action:'transfer',fromOwner:from,toOwner:assigned,note:'账号交接,等待新负责人处理和核验。'});this.db.prepare('UPDATE exceptions SET value=? WHERE id=?').run(JSON.stringify(item),id);result.exceptions.push(id);}
|
||||
this.record(actor,'账号负责人交接',from+' → '+assigned+';连接已暂停');return result;
|
||||
});
|
||||
}
|
||||
transferConnection(id,input,actor,members){
|
||||
authorize(actor,['admin']);object(input,['version','owner']);if(!Number.isSafeInteger(input.version)||input.version<0)fail('版本号不正确。');const assigned=owner(input.owner,members,true);
|
||||
return this.transaction(()=>{const item=this.getConnection(id);if(input.version!==(item.version||0))fail('连接已变化,请刷新后重试。',409);if(assigned===item.owner)fail('新负责人必须与当前负责人不同。');const from=item.owner,at=new Date().toISOString();Object.assign(item,{owner:assigned,status:'disabled',disabledAt:at,updatedAt:at,version:(item.version||0)+1});this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),id);this.record(actor,'转交BPM连接',from+' → '+assigned+';连接已暂停');return item;});
|
||||
}
|
||||
resetConnectionSession(id,actor){
|
||||
authorize(actor,['admin','operator']);return this.transaction(()=>{
|
||||
const item=this.getConnection(id);if(actor.role!=='admin' && item.owner!==actor.username)fail('仅连接负责人或管理员可以操作此连接。',403);if(item.status==='disabled')fail('此连接已停用。',409);
|
||||
@@ -114,8 +131,10 @@ class WorkspaceStore {
|
||||
const changed=item.status!==result.status||item.identity!==identity||JSON.stringify(item.checks)!==JSON.stringify(checks);
|
||||
const at=new Date().toISOString();Object.assign(item,{status:result.status,identity,checkedAt:result.checkedAt,checks,updatedAt:at});if(item.status==='connected')item.lastConnectedAt=result.checkedAt;
|
||||
this.db.prepare('UPDATE connections SET value=? WHERE id=?').run(JSON.stringify(item),id);
|
||||
if(item.status==='connected')for(const row of this.db.prepare('SELECT id,value FROM exceptions').all()){const entry=JSON.parse(row.value);if(entry.connectionId!==id||entry.kind!=='bpm_login'||!['open','in_progress'].includes(entry.status))continue;entry.status='verifying';entry.version++;entry.updatedAt=at;entry.history.push({at,actor:actor.username,action:'verify',note:'连接已恢复,等待负责人核验;未自动关闭异常。',evidence:{connectionId:id,checkedAt:item.checkedAt}});this.db.prepare('UPDATE exceptions SET value=? WHERE id=?').run(JSON.stringify(entry),row.id);}
|
||||
if(['error','login_required'].includes(item.status) && item.lastConnectedAt){
|
||||
const existing=this.db.prepare('SELECT value FROM exceptions').all().map(row=>JSON.parse(row.value)).some(entry=>entry.connectionId===id && entry.kind==='bpm_login' && entry.status!=='resolved');
|
||||
const existing=this.db.prepare('SELECT value FROM exceptions').all().map(row=>JSON.parse(row.value)).find(entry=>entry.connectionId===id && entry.kind==='bpm_login' && !['resolved','retired'].includes(entry.status));
|
||||
if(existing?.status==='verifying'){existing.status=existing.owner?'in_progress':'open';existing.version++;existing.updatedAt=at;existing.history.push({at,actor:actor.username,action:'reopen',note:'连接再次检查失败,先前恢复验证已失效。',evidence:{connectionId:id,checkedAt:item.checkedAt,status:item.status}});this.db.prepare('UPDATE exceptions SET value=? WHERE id=?').run(JSON.stringify(existing),existing.id);}
|
||||
if(!existing){const unavailable=item.status==='error',title=unavailable?'BPM 连接需要检查:'+item.name:item.name+' 需要登录验证',description=unavailable?'新版 BPM 暂时无法连接,请检查网络和连接状态。':'BPM 自动续登未完成,请连接负责人检查托管账号或完成登录验证。';const task={id:crypto.randomUUID(),title,description,component:'bpm',priority:'high',owner:item.owner,status:'in_progress',version:1,kind:'bpm_login',connectionId:id,createdAt:at,updatedAt:at,history:[{at,actor:actor.username,action:'create',note:unavailable?'连接检查未通过':'连接检查需要登录验证'}]};this.db.prepare('INSERT INTO exceptions(id,value) VALUES(?,?)').run(task.id,JSON.stringify(task));this.record(actor,unavailable?'创建 BPM 连接检查待办':'创建 BPM 续登待办',item.name);}
|
||||
}
|
||||
if(audit||changed)this.record(actor,'检查 BPM 连接',item.name+':'+item.status);return item;
|
||||
@@ -133,16 +152,11 @@ class WorkspaceStore {
|
||||
});
|
||||
}
|
||||
deleteConnection(id,actor){
|
||||
authorize(actor,['admin']);return this.transaction(()=>{const item=this.getConnection(id);if(item.status!=='disabled')fail('请先停用连接再删除。',409);const archive={id,name:item.name,owner:item.owner,identity:item.identity||'',archivedAt:new Date().toISOString()};this.db.prepare('INSERT INTO connection_archives(id,value) VALUES(?,?)').run(id,JSON.stringify(archive));this.db.prepare('DELETE FROM connections WHERE id=?').run(id);this.record(actor,'删除连接',item.name);return {id,deleted:true};});
|
||||
authorize(actor,['admin']);return this.transaction(()=>{const item=this.getConnection(id);if(item.status!=='disabled')fail('请先停用连接再删除。',409);const at=new Date().toISOString(),archive={id,name:item.name,owner:item.owner,identity:item.identity||'',archivedAt:at};this.db.prepare('INSERT INTO connection_archives(id,value) VALUES(?,?)').run(id,JSON.stringify(archive));this.db.prepare('DELETE FROM connections WHERE id=?').run(id);for(const row of this.db.prepare('SELECT id,value FROM exceptions').all()){const entry=JSON.parse(row.value);if(entry.connectionId!==id||['resolved','retired'].includes(entry.status))continue;Object.assign(entry,{status:'retired',retiredAt:at,updatedAt:at,version:entry.version+1});entry.history.push({at,actor:actor.username,action:'retire',note:'来源连接已删除,保留历史;未视为业务核验通过。'});this.db.prepare('UPDATE exceptions SET value=? WHERE id=?').run(JSON.stringify(entry),row.id);}this.record(actor,'删除连接',item.name);return {id,deleted:true};});
|
||||
}
|
||||
recordSources(){
|
||||
return this.transaction(()=>[...this.db.prepare('SELECT value FROM connections').all().map(({value})=>{const c=JSON.parse(value);return {id:c.id,name:c.name,owner:c.owner,identity:c.identity||'',status:'current',enabled:c.status!=='disabled',archivedAt:null};}),...this.db.prepare('SELECT value FROM connection_archives').all().map(({value})=>({...JSON.parse(value),status:'archived',enabled:false}))]);
|
||||
}
|
||||
saveSupervisor(input,actor,members){
|
||||
authorize(actor,['admin']);object(input,['version','defaultOwner','notifyChannel','maxAttempts']);version(input.version);const defaultOwner=owner(input.defaultOwner,members);
|
||||
if(!['none','manual'].includes(input.notifyChannel) || !Number.isInteger(input.maxAttempts) || input.maxAttempts<0 || input.maxAttempts>3)fail('监管草稿渠道或尝试次数不正确。');
|
||||
return this.transaction(()=>{const previous=this.meta('supervisor');if(previous.version!==input.version)fail('监管草稿已被其他人更新,请刷新后重试。',409);const saved={version:previous.version+1,defaultOwner,notifyChannel:input.notifyChannel,maxAttempts:input.maxAttempts};this.setMeta('supervisor',saved);this.record(actor,'保存监管策略草稿','仅保存草稿,不执行自动处理或通知');return saved;});
|
||||
}
|
||||
close(){if(this.db){this.db.close();this.db=null;}}
|
||||
}
|
||||
module.exports={WorkspaceStore};
|
||||
Reference in new issue
Block a user