feat: add configurable SMB archival and notification queues

This commit is contained in:
阿白叔 committed 2026-10-17 10:53:18 +08:00
1 parent 34770ed338
commit c2f16a5c56
29 files changed
+809 -26

No files matched your search

+8 -2
View File
@@ -4,11 +4,13 @@ const {workspaceApi}=require('./workspace-api.cjs');
const {bpmApi}=require('./bpm-api.cjs');
const {mailApi}=require('./mail-api.cjs');
const {bpmScanApi}=require('./bpm-scan-api.cjs');
const {storageApi}=require('./storage-api.cjs');
const {notificationApi}=require('./notification-api.cjs');
const {SessionStore,SESSION_MS}=require('./dashboard-sessions.cjs');
const isLoopback=address=>['127.0.0.1','::1','::ffff:127.0.0.1'].includes(address);
const publicJob=({path:ignored,...job})=>({...job,downloadable:job.status==='success'});
function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,trustedProxy=false}) {
function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,storage,notifications,trustedProxy=false}) {
const sessions=new SessionStore(path.dirname(store.file));const failures=new Map();
const sessionCookieName=previewUserId?'order_preview_session':'order_session';
const sessionCookiePattern=new RegExp('(?:^|;\\s*)'+sessionCookieName+'=([a-f0-9]{64})(?:;|$)');
@@ -20,6 +22,8 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma
'/bpm.js':{path:path.join(webRoot,'bpm.js'),type:'text/javascript'},
'/mail.js':{path:path.join(webRoot,'mail.js'),type:'text/javascript'},
'/orders.js':{path:path.join(webRoot,'orders.js'),type:'text/javascript'},
'/storage.js':{path:path.join(webRoot,'storage.js'),type:'text/javascript'},
'/notifications.js':{path:path.join(webRoot,'notifications.js'),type:'text/javascript'},
'/app.css':{path:path.join(webRoot,'app.css'),type:'text/css'},
'/vendor/tabler.css':{path:require.resolve('@tabler/core/dist/css/tabler.min.css'),type:'text/css'},
'/vendor/tabler.js':{path:require.resolve('@tabler/core/dist/js/tabler.min.js'),type:'text/javascript'}
@@ -82,13 +86,15 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma
if(await bpmApi({workspace,bpmSessions,user,sessionId:token,route,method:request.method,body,request,response,reply,trustedProxy}))return;
if(await mailApi({mail,workspace,user,route,method:request.method,body,request,response,reply,trustedProxy}))return;
if(await bpmScanApi({scanner,workspace,user,sessionId:token,url,route,method:request.method,body,reply}))return;
if(await storageApi({storage,workspace,user,url,route,method:request.method,body,request,response,reply,trustedProxy}))return;
if(await notificationApi({notifications,workspace,user,route,method:request.method,body,reply}))return;
if(workspaceApi({workspace,store,user,route,method:request.method,body,reply,bpmSessions}))return;
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 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 scan=scanner?.store.status();
return reply(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:{enabled:false,reason:'待接入订单规则表和归档目录,业务自动处理尚未启用。'},connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'订单规则表',ready:false,detail:'等待提供表格,随后配置列映射与筛选'},{name:'BPM 自动扫描',ready:!!scan?.runs.some(r=>r.status==='success'),detail:scan?`${scan.config.enabled?'已开启':'已暂停'},每 ${scan.config.intervalMinutes} 分钟扫描 · 已收录 ${scan.total} 条流程`:'扫描服务未启动'},{name:'210 服务器',ready:false,detail:'等待完整地址、协议和归档目录'},{name:'邮件渠道',ready:mailChannels.some(c=>c.state.smtp&&c.state.imap),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} 个待确认`},{name:'产品线群组',ready:settings.groups.length>0,detail:`已配置 ${settings.groups.length} 个产品线`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:jobs.slice(0,6).map(publicJob),audit:store.audit().slice(0,5)});
return reply(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:{enabled:false,reason:'待核实并接入 BPM 业务规则,完整订单自动处理尚未启用。'},connections:[{name:'PDF 导出',ready:true,detail:'浏览器扩展导出与任务记录已接入'},{name:'订单规则表',ready:false,detail:'等待提供表格,随后配置列映射与筛选'},{name:'BPM 自动扫描',ready:!!scan?.runs.some(r=>r.status==='success'),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.state.smtp&&c.state.imap),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} 个待确认`},{name:'产品线群组',ready:settings.groups.length>0,detail:`已配置 ${settings.groups.length} 个产品线`}],nextSlots:nextSlots(settings.schedule,new Date(),2,workspace?workspace.snapshot(store.users()).calendar.overrides:[]),schedule:settings.schedule,jobs:jobs.slice(0,6).map(publicJob),audit:store.audit().slice(0,5)});
}
if(route==='/api/settings') {
if(request.method==='GET')return reply(200,store.settings());
+13
View File
@@ -0,0 +1,13 @@
'use strict';
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
async function notificationApi({notifications,workspace,user,route,method,body,reply}){
if(!route.startsWith('/api/notifications'))return false;if(!notifications)fail('业务通知服务暂不可用。',503);
if(route==='/api/notifications'&&method==='GET'){reply(200,{settings:notifications.store.settings(),items:notifications.store.items(),batches:notifications.store.batches()});return true;}
if(method!=='POST')fail('没有找到此通知操作。',404);
if(user.role==='viewer')fail('只读成员不能提交通知数据或修改配置。',403);
if(route==='/api/notifications/settings'){if(user.role!=='admin')fail('仅管理员可以修改业务通知配置。',403);const saved=notifications.saveSettings(body);workspace?.record(user,'保存业务通知配置',saved.enabled?'已启用':'已暂停');reply(200,saved);return true;}
if(route==='/api/notifications/preview'||route==='/api/notifications/events'){if(!body||Object.keys(body).some(k=>k!=='data'))fail('请提交来源数据对象。');const preview=route.endsWith('/preview');const result=preview?notifications.preview(body.data):notifications.ingest(body.data);if(!preview)workspace?.record(user,'通知数据入队',result.sourceId);reply(preview?200:201,result);return true;}
const match=/^\/api\/notifications\/batches\/([\w-]+)\/resolve$/.exec(route);if(match){if(user.role!=='admin')fail('仅管理员可以核验发送结果。',403);const result=notifications.resolve(match[1],body,user.username);workspace?.record(user,'核验通知发送结果',match[1]);reply(200,result);return true;}
fail('没有找到此通知操作。',404);
}
module.exports={notificationApi};
+76
View File
@@ -0,0 +1,76 @@
'use strict';
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('./bpm-vault.cjs');const {nextSlots}=require('./schedule.cjs');
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
const hash=value=>crypto.createHash('sha256').update(value).digest('hex');
const DEFAULT_MAP={id:'id',version:'version',industry:'industry',brief:'brief',subject:'subject',occurredAt:'occurredAt'};
function validateMap(map){if(!map||typeof map!=='object'||Array.isArray(map)||Object.keys(map).some(k=>!Object.hasOwn(DEFAULT_MAP,k)))fail('通知字段映射无效。');for(const key of Object.keys(DEFAULT_MAP)){const p=map[key];if(typeof p!=='string'||p.length>200||(p&&!/^[\p{L}\p{N}_-]+(?:\.[\p{L}\p{N}_-]+)*$/u.test(p))||p.split('.').some(s=>['__proto__','constructor','prototype'].includes(s)))fail('字段路径只支持普通对象的点分隔路径。');if(['id','industry','brief'].includes(key)&&!p)fail('请配置通知 ID、产业与简要说明字段。');}return {...map};}
function valueAt(data,p){if(!p)return undefined;for(const part of p.split('.')){if(!data||typeof data!=='object'||!Object.hasOwn(data,part))return undefined;data=data[part];}return data;}
class NotificationStore{
constructor(dir){fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});this.db=new DatabaseSync(path.join(dir,'notifications.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS settings(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS items(id TEXT PRIMARY KEY,payload BLOB NOT NULL,status TEXT NOT NULL,attempts INTEGER NOT NULL DEFAULT 0,error TEXT,batch_id TEXT,created_at TEXT NOT NULL,industry TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS batches(id TEXT PRIMARY KEY,status TEXT NOT NULL,payload BLOB NOT NULL,error TEXT,created_at TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY,value TEXT NOT NULL);
UPDATE items SET status='pending',batch_id=NULL WHERE batch_id IN(SELECT id FROM batches WHERE status='prepared');
UPDATE items SET status='unknown',error='服务重启,发送结果需要核实。' WHERE batch_id IN(SELECT id FROM batches WHERE status='sending');
UPDATE batches SET status='cancelled' WHERE status='prepared';
UPDATE batches SET status='unknown',error='服务重启,发送结果需要核实。' WHERE status='sending';`);
this.db.prepare('INSERT OR IGNORE INTO settings VALUES(1,?)').run(JSON.stringify({version:1,enabled:false,sourceKey:crypto.randomUUID(),sourceName:'业务来源',channelId:'',fieldMap:DEFAULT_MAP,maxAttempts:3}));
if(!this.db.prepare('PRAGMA table_info(items)').all().some(c=>c.name==='industry')){this.db.exec("ALTER TABLE items ADD COLUMN industry TEXT NOT NULL DEFAULT ''");for(const row of this.db.prepare('SELECT id,payload FROM items').all())this.db.prepare('UPDATE items SET industry=? WHERE id=?').run(this.decode(row.id,row.payload).industry,row.id);}
this.db.exec('CREATE INDEX IF NOT EXISTS notification_pending ON items(status,industry,attempts)');
}
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(e){this.db.exec('ROLLBACK');throw e;}}
encode(id,data){try{return this.vault.encode(id,data);}catch{fail('通知内容加密不可用,请联系管理员。',503);}}
decode(id,data){try{return this.vault.decode(id,data);}catch{fail('通知内容无法解密,请联系管理员。',503);}}
settings(){return JSON.parse(this.db.prepare('SELECT value FROM settings WHERE id=1').get().value);}
saveSettings(input){const old=this.settings();if(!input||Object.keys(input).some(k=>!['version','enabled','sourceKey','sourceName','channelId','fieldMap','maxAttempts'].includes(k)))fail('通知配置无效。');if(input.version!==old.version)fail('通知配置已被修改,请刷新。',409);if(typeof input.enabled!=='boolean'||typeof input.sourceName!=='string'||!input.sourceName.trim()||input.sourceName.length>80||typeof input.channelId!=='string'||input.channelId.length>100||!Number.isInteger(input.maxAttempts)||input.maxAttempts<1||input.maxAttempts>10)fail('请检查来源、邮箱和尝试次数(1–10)。');if(input.sourceKey&&input.sourceKey!==old.sourceKey)fail('来源标识不能更改。');const saved={...input,sourceKey:old.sourceKey,sourceName:input.sourceName.trim(),fieldMap:validateMap(input.fieldMap),version:old.version+1};this.db.prepare('UPDATE settings SET value=? WHERE id=1').run(JSON.stringify(saved));return saved;}
scheduleState(){const row=this.db.prepare("SELECT value FROM metadata WHERE key='schedule'").get();return row?JSON.parse(row.value):null;}
setSchedule(value){this.db.prepare("INSERT INTO metadata VALUES('schedule',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value").run(JSON.stringify(value));}
ingest(event){const id=hash([event.sourceKey,event.sourceId,event.sourceVersion,event.industry].join('\0')),old=this.db.prepare('SELECT * FROM items WHERE id=?').get(id);if(old){const value=this.decode(id,old.payload);if(value.brief!==event.brief||value.subject!==event.subject)fail('同一通知版本的内容已变化,请核实来源版本。',409);return this.item(old);}this.db.prepare('INSERT INTO items(id,payload,status,created_at,industry) VALUES(?,?,?,?,?)').run(id,this.encode(id,event),'pending',new Date().toISOString(),event.industry);return this.item(this.db.prepare('SELECT * FROM items WHERE id=?').get(id));}
item({payload,...row}){return {...this.decode(row.id,payload),...row};}
items(){return this.db.prepare('SELECT * FROM items ORDER BY rowid DESC LIMIT 100').all().map(r=>this.item(r));}
pending(attempts,industries){if(!industries.length)return [];return this.db.prepare("SELECT * FROM items WHERE status IN('pending','blocked') AND attempts<? AND industry IN("+industries.map(()=>'?').join(',')+") ORDER BY rowid LIMIT 200").all(attempts,...industries).map(r=>this.item(r));}
blockUnmapped(industries){this.db.prepare("UPDATE items SET status='blocked',error='此产业尚未配置接口人收件组。' WHERE status IN('pending','blocked')"+(industries.length?' AND industry NOT IN('+industries.map(()=>'?').join(',')+')':'')).run(...industries);}
block(id,message){this.db.prepare("UPDATE items SET status='blocked',error=? WHERE id=? AND status IN('pending','blocked')").run(message,id);}
prepare(items,snapshot){return this.transaction(()=>{const id=crypto.randomUUID();this.db.prepare('INSERT INTO batches VALUES(?,?,?,?,?)').run(id,'prepared',this.encode(id,snapshot),null,new Date().toISOString());for(const item of items){const result=this.db.prepare("UPDATE items SET status='reserved',attempts=attempts+1,error=NULL,batch_id=? WHERE id=? AND status IN('pending','blocked')").run(id,item.id);if(!result.changes)fail('通知队列已变化,请重试。',409);}return id;});}
mark(id,status,message=null){this.transaction(()=>{this.db.prepare('UPDATE batches SET status=?,error=? WHERE id=?').run(status,message,id);if(status!=='sending')this.db.prepare('UPDATE items SET status=?,error=? WHERE batch_id=?').run(status==='failed'?'pending':status,message,id);});}
batches(){return this.db.prepare("SELECT * FROM batches ORDER BY CASE status WHEN 'unknown' THEN 0 ELSE 1 END,rowid DESC LIMIT 100").all().map(({payload,...r})=>({...this.decode(r.id,payload),...r}));}
resolve(id,input,actor){return this.transaction(()=>{const row=this.db.prepare('SELECT * FROM batches WHERE id=?').get(id);if(!row||row.status!=='unknown')fail('只能核验结果待核实的批次。',409);if(!input||!['sent','retry'].includes(input.resolution)||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请选择核验结果并填写至少 5 字的核验依据。');const data={...this.decode(id,row.payload),resolution:input.resolution,note:input.note.trim(),resolvedBy:actor,resolvedAt:new Date().toISOString()};this.db.prepare('UPDATE batches SET status=?,payload=? WHERE id=?').run('resolved_'+input.resolution,this.encode(id,data),id);this.db.prepare('UPDATE items SET status=?,error=NULL,attempts=CASE WHEN ? THEN 0 ELSE attempts END WHERE batch_id=?').run(input.resolution==='sent'?'sent':'pending',input.resolution==='retry'?1:0,id);return {ok:true};});}
close(){if(this.db){this.db.close();this.db=null;}this.vault.destroy();}
}
class NotificationService{
constructor({store,mail,settings,calendar=()=>[],clock=()=>new Date()}){this.store=store;this.mail=mail;this.settings=settings;this.calendar=calendar;this.clock=clock;this.running=null;this.stopped=false;}
map(data){if(!data||typeof data!=='object'||Array.isArray(data))fail('通知来源必须是 JSON 对象。');const config=this.store.settings(),raw=Object.fromEntries(Object.entries(config.fieldMap).map(([key,p])=>[key,valueAt(data,p)]));if(!['string','number'].includes(typeof raw.id)||!String(raw.id).trim()||String(raw.id).length>200||/[\x00-\x1f]/.test(String(raw.id))||typeof raw.industry!=='string'||!raw.industry.trim()||raw.industry.length>100||/[\x00-\x1f]/.test(raw.industry)||typeof raw.brief!=='string'||!raw.brief.trim()||raw.brief.length>20000)fail('通知 ID、产业和简要说明不能为空,正文最多 20000 字。');if(raw.subject!==undefined&&(typeof raw.subject!=='string'||raw.subject.length>300||/[\r\n\x00]/.test(raw.subject)))fail('通知标题最多 300 字,不能包含换行。');if(raw.version!==undefined&&(!['string','number'].includes(typeof raw.version)||String(raw.version).length>200||/[\x00-\x1f]/.test(String(raw.version))))fail('来源版本无效。');if(raw.occurredAt!==undefined&&(typeof raw.occurredAt!=='string'||!Number.isFinite(Date.parse(raw.occurredAt))))fail('业务时间无效。');return {source:config.sourceName,sourceKey:config.sourceKey,sourceId:String(raw.id).trim(),sourceVersion:raw.version===undefined||raw.version===''?hash(raw.brief):String(raw.version),industry:raw.industry.trim(),brief:raw.brief,subject:raw.subject||raw.industry.trim()+'业务通知',occurredAt:raw.occurredAt||this.clock().toISOString()};}
preview(data){try{const event=this.map(data),group=this.settings().groups.find(g=>g.productLine===event.industry);return {valid:!!group,event,to:group?.to||[],cc:group?.cc||[],issues:group?[]:['此产业尚未配置接口人收件组。']};}catch(e){if(!e.status)throw e;return {valid:false,issues:[e.message]};}}
ingest(data){return this.store.ingest(this.map(data));}
saveSettings(input){if(this.running)fail('通知正在发送,请稍后修改配置。',409);if(input?.enabled){const c=this.mail.store.publicChannel(input.channelId);if(!c.state.smtp)fail('请先验证发件邮箱的 SMTP 连接。',409);if(!this.settings().groups.length)fail('请先配置产业接口人收件组。',409);}const old=this.store.settings(),saved=this.store.saveSettings(input);if(saved.enabled&&!old.enabled)this.resetSchedule(this.clock());return saved;}
resetSchedule(now){const schedule=this.settings().schedule,calendar=this.calendar();const state={signature:JSON.stringify([schedule,calendar]),next:nextSlots(schedule,now,1,calendar)[0]};this.store.setSchedule(state);return state;}
tick(now=this.clock()){
if(this.stopped||this.running)return this.running||Promise.resolve();
const task=this.perform(now);this.running=task;task.finally(()=>{if(this.running===task)this.running=null;}).catch(()=>{});return task;
}
async perform(now){
const config=this.store.settings();if(!config.enabled)return;
const settings=this.settings(),calendar=this.calendar(),signature=JSON.stringify([settings.schedule,calendar]);let schedule=this.store.scheduleState();
if(!schedule||schedule.signature!==signature){this.resetSchedule(now);return;}if(!schedule.next||Date.parse(schedule.next)>now.getTime())return;
const due=Date.parse(schedule.next);if(now.getTime()-due>60000){this.resetSchedule(now);return;}
const industries=settings.groups.filter(g=>g.to?.length).map(g=>g.productLine);this.store.blockUnmapped(industries);const grouped=new Map();for(const item of this.store.pending(config.maxAttempts,industries)){const group=settings.groups.find(g=>g.productLine===item.industry);if(!group||!group.to?.length){this.store.block(item.id,'此产业尚未配置接口人收件组。');continue;}const key=settings.schedule.mode==='order'?item.id:item.industry;if(!grouped.has(key))grouped.set(key,{items:[],group});if(grouped.get(key).items.length<50)grouped.get(key).items.push(item);}
if(!grouped.size){this.resetSchedule(now);return;}
await this.mail.exclusive(config.channelId,async()=>{
this.resetSchedule(now);
for(const {items,group}of grouped.values()){
if(this.stopped)break;
const channel=this.mail.store.channelSecret(config.channelId),snapshot={channelId:channel.id,industry:items[0].industry,sourceIds:items.map(i=>i.sourceId),subject:items.length===1?items[0].subject:items[0].industry+'业务通知',text:items.map(i=>i.brief).join('\n\n'),to:[...group.to],cc:[...group.cc],slot:new Date(due).toISOString()};
const batch=this.store.prepare(items,snapshot);let transport,sending=false;
try{transport=this.mail.smtpFactory(channel.smtp);await transport.verify();this.mail.store.guard(channel.id,channel.version);this.store.mark(batch,'sending');sending=true;
const result=await transport.sendMail({from:{address:channel.email,name:channel.name},to:snapshot.to,cc:snapshot.cc,subject:snapshot.subject,text:snapshot.text,attachments:[],messageId:`<${batch}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
const accepted=new Set((result.accepted||[]).map(a=>String(a.address||a).toLowerCase()));if(result.rejected?.length||[...snapshot.to,...snapshot.cc].some(a=>!accepted.has(a.toLowerCase()))){this.store.mark(batch,'unknown','部分收件人未被邮件服务器接受,请核实后处理。');}else this.store.mark(batch,'sent');
}catch{this.store.mark(batch,sending?'unknown':'failed',sending?'发信结果待核实,请查询邮件服务器记录。':'SMTP 检查失败,等待下个时段按次数上限重试。');}finally{transport?.close?.();}
}
}).catch(e=>{if(e.status!==409)throw e;});
}
resolve(id,input,actor){if(this.running)fail('通知正在发送,请稍后核验。',409);return this.store.resolve(id,input,actor);}
start(){this.timer=setInterval(()=>this.tick().catch(()=>{}),30000);this.timer.unref?.();}
async stop(){this.stopped=true;clearInterval(this.timer);if(this.running)await this.running.catch(()=>{});}
}
module.exports={NotificationStore,NotificationService};
+16 -8
View File
@@ -13,6 +13,9 @@ const { MailStore } = require('./mail-store.cjs');
const { MailService } = require('./mail-service.cjs');
const { BpmScanStore } = require('./bpm-scan-store.cjs');
const { BpmScanner } = require('./bpm-scanner.cjs');
const { StorageStore } = require('./storage-store.cjs');
const { StorageService } = require('./storage-service.cjs');
const { NotificationStore, NotificationService } = require('./notifications.cjs');
function createServer(options) {
let busy = false;
@@ -58,7 +61,8 @@ function createServer(options) {
catch(error) {busy=false;jobs.delete(jobId);throw error;}
reply(202,{status:'running',jobId});
renderSnapshot(snapshot, options).then(result => {
options.store?.recordJob({status:'success',jobId,...result});
const saved=options.store?.recordJob({status:'success',jobId,...result});
if(saved)options.storage?.automatic(saved).catch(()=>{});
jobs.set(jobId,{status:'success',jobId,...result});
console.log(`已保存:${result.filename} (${result.bytes} bytes)`);
}).catch(error=>{const failed={status:'error',jobId,error:error.message || '导出失败。'};jobs.set(jobId,failed);try{options.store?.recordJob(failed);}catch(storeError){console.error('保存任务状态失败:'+storeError.message);}}).finally(()=>{busy=false;});
@@ -105,18 +109,20 @@ async function main(options = {}) {
const custodian=new BpmCustodian({workspace,manager:bpmSessions});
let server;
let dashboard;
let mailStore,mail,scanStore,scanner;
let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications;
try {
mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore});
mailStore.migrateLegacy(store.settings().templates);
scanStore=new BpmScanStore(path.join(stateDir,'bpm-scan'));scanner=new BpmScanner({store:scanStore,workspace,manager:bpmSessions,settings:()=>store.settings()});
storageStore=new StorageStore(path.join(stateDir,'storage'));storage=new StorageService({store:storageStore,jobs:store,outputDir});
notificationStore=new NotificationStore(path.join(stateDir,'notifications'));notifications=new NotificationService({store:notificationStore,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides});
await bpmSessions.migrateAccounts(workspace.snapshot().connections);
workspace.markSessionChecksPending();
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store});
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,trustedProxy:dashboardConfig.trustedProxy===true});
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();scanner.start();
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage});
dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,storage,notifications,trustedProxy:dashboardConfig.trustedProxy===true});
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();scanner.start();notifications.start();
}
catch(error){if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;}
catch(error){if(server?.listening)await new Promise(resolve=>server.close(resolve));if(dashboard?.listening)await new Promise(resolve=>dashboard.close(resolve));await notifications?.stop();notificationStore?.close();await storage?.stop();storageStore?.close();await scanner?.stop();scanStore?.close();await mail?.stop();mailStore?.close();await bpmSessions.shutdown();workspace.close();throw error;}
if(!options.quiet){
console.log('订单通知中心已启动。\nWeb 工作台支持业务日历、异常待办与转交、BPM 连接管理。\n在 Chrome 订单页仍可点击扩展中的“导出当前订单”。');
console.log(`首次使用:Chrome 扩展管理 → 开发者模式 → 加载已解压的扩展程序\n选择目录:${installedExtension}\n输出目录:${outputDir}\n本地服务:http://127.0.0.1:${port}`);
@@ -125,13 +131,15 @@ async function main(options = {}) {
}
let stopping;
const stop=()=>stopping ||= (async()=>{
await scanner.stop();await mail.stop();await custodian.stop();await bpmSessions.shutdown();
await notifications.stop();await storage.stop();await scanner.stop();await mail.stop();await custodian.stop();await bpmSessions.shutdown();
await Promise.all([dashboard,server].map(socket=>new Promise((resolve,reject)=>socket.close(error=>error?reject(error):resolve()))));
workspace.close();
mailStore.close();
scanStore.close();
storageStore.close();
notificationStore.close();
})();
return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,stop};
return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,stop};
}
if (require.main === module) main().then(app=>{
const stop=()=>app.stop().then(()=>process.exit(0),()=>process.exit(1));
+28
View File
@@ -0,0 +1,28 @@
'use strict';
const {execFile}=require('node:child_process');
const fs=require('node:fs/promises');
const path=require('node:path');
const messages={5:'存储服务器拒绝访问,请检查账号权限。',53:'找不到存储服务器,请检查地址与网络。',67:'找不到共享目录,请检查共享名称。',86:'SMB 账号或密码不正确。',1326:'SMB 账号或密码不正确。',1219:'此服务器已使用其他账号连接,请先由管理员处理 Windows SMB 凭据冲突。',183:'目标文件已存在。',80:'目标文件已存在。'};
function native(operation,input){
return new Promise((resolve,reject)=>{
const child=execFile('powershell.exe',['-NoLogo','-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-File',path.resolve(__dirname,'../scripts/smb-native.ps1')],{windowsHide:true,timeout:25000,maxBuffer:16384,encoding:'utf8'},(error,stdout)=>{
let result;try{result=JSON.parse(stdout.replace(/^\uFEFF/,''));}catch{}
if(result?.ok)return resolve();
const code=result?.code;const failure=Object.assign(new Error(messages[code]||'SMB 操作未完成,请检查网络、共享权限或服务器状态。'),{status:502});
if([80,183].includes(code))failure.code='EEXIST';
if(error?.killed)failure.message='SMB 操作超时,请检查服务器和网络。';
reject(failure);
});
child.stdin.on('error',()=>{});child.stdin.end(JSON.stringify({operation,...input}));
});
}
async function connect(server){
if(process.platform!=='win32')throw Object.assign(new Error('SMB 连接需要在 Windows 部署机运行。'),{status:503});
await native('connect',{remote:`\\\\${server.host}\\${server.share}`,username:server.username,password:server.password});
}
async function publishExclusive(source,target){
if(process.platform==='win32')return native('publish',{source,target});
await fs.link(source,target);await fs.unlink(source);
}
module.exports={connect,publishExclusive};
+26
View File
@@ -0,0 +1,26 @@
'use strict';
const {secureBpmTransport}=require('./bpm-api.cjs');
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
function payload(body,keys){if(!body||Object.keys(body).some(k=>!keys.includes(k)))fail('存储操作参数无效。');}
async function storageApi({storage,workspace,user,url,route,method,body,request,response,reply,trustedProxy}){
if(!route.startsWith('/api/storage'))return false;if(!storage)fail('存储服务暂不可用。',503);
const audit=(action,detail)=>workspace?.record(user,action,detail);
if(route==='/api/storage'&&method==='GET'){reply(200,{servers:storage.store.servers(),settings:storage.store.settings(),archives:storage.store.archives()});return true;}
if(user.role==='viewer')fail('仅管理员和操作员可以操作归档文件。',403);
if(route==='/api/storage/servers'&&method==='POST'){
if(user.role!=='admin')fail('仅管理员可以维护存储服务器。',403);
if(!secureBpmTransport(request,trustedProxy))fail('请在部署机本地或 HTTPS 页面维护存储账号。',403);
const saved=storage.saveServer(body);audit('保存存储服务器',saved.name);reply(body.id?200:201,saved);return true;
}
if(route==='/api/storage/settings'&&method==='POST'){if(user.role!=='admin')fail('仅管理员可以修改自动归档设置。',403);payload(body,['serverId','enabled']);const saved=storage.saveSettings(body);audit('保存自动归档设置',saved.enabled?'已启用':'已暂停');reply(200,saved);return true;}
const match=/^\/api\/storage\/servers\/([\w-]+)\/(check|files|folders|archive|file)$/.exec(route);
if(match){const [,id,action]=match;
if(action==='check'&&method==='POST'){if(user.role!=='admin')fail('仅管理员可以检查存储服务器。',403);payload(body,[]);const checked=await storage.check(id);audit('检查存储服务器',checked.name);reply(200,checked);return true;}
if(action==='files'&&method==='GET'){reply(200,await storage.list(id,url.searchParams.get('path')||''));return true;}
if(action==='folders'&&method==='POST'){payload(body,['path']);const result=await storage.mkdir(id,body.path);audit('创建归档目录',result.path);reply(201,result);return true;}
if(action==='archive'&&method==='POST'){payload(body,['jobId','directory']);const result=await storage.archive(id,body.jobId,body.directory??'',user.username);audit('PDF 归档完成',result.relativePath);reply(200,result);return true;}
if(action==='file'&&method==='GET'){const file=await storage.readPdf(id,url.searchParams.get('path')||'');response.writeHead(200,{'Content-Type':'application/pdf','Content-Disposition':"attachment; filename*=UTF-8''"+encodeURIComponent(file.filename)});response.end(file.bytes);return true;}
}
fail('没有找到此存储操作。',404);
}
module.exports={storageApi};
+67
View File
@@ -0,0 +1,67 @@
'use strict';
const fs=require('node:fs/promises');
const path=require('node:path');
const crypto=require('node:crypto');
const native=require('./smb-native.cjs');
const MAX_FILE=64*1024*1024;
const fail=(message,status=400)=>Object.assign(new Error(message),{status});
function segments(relative=''){
if(typeof relative!=='string'||relative.length>1500||/^[\\/]|[<>:"|?*\x00-\x1f]/.test(relative))throw fail('请使用归档目录内的相对路径。');
if(!relative)return [];
const parts=relative.replace(/\\/g,'/').split('/');
if(parts.some(p=>!p||p==='.'||p==='..'||/[. ]$/.test(p)||/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/i.test(p)||p.length>200))throw fail('目录或文件名无效,不能跳转到归档根目录之外。');
return parts;
}
function inside(root,file){const rel=path.relative(root,file);return !path.isAbsolute(rel)&&rel!=='..'&&!rel.startsWith('..'+path.sep);}
function digest(bytes){return crypto.createHash('sha256').update(bytes).digest('hex');}
async function pdf(file){const info=await fs.stat(file);if(!info.isFile()||info.size>MAX_FILE)throw fail('PDF 必须为不超过 64 MiB 的文件。');const bytes=await fs.readFile(file);if(bytes.length>MAX_FILE||bytes.subarray(0,5).toString()!=='%PDF-')throw fail('文件不是有效的 PDF。');return bytes;}
class FileArea{
constructor(root,{boundary=root}={}){this.root=path.resolve(root);this.boundary=path.resolve(boundary);if(!inside(this.boundary,this.root))throw fail('归档根目录超出共享目录。');}
async resolve(relative='',create=false){
const prefix=segments(path.relative(this.boundary,this.root)),parts=[...prefix,...segments(relative)];let current=this.boundary;
const rootInfo=await fs.lstat(current);if(rootInfo.isSymbolicLink()||!rootInfo.isDirectory())throw fail('归档根目录不可用或为目录链接。');
const realRoot=await fs.realpath(current);
for(const [index,part]of parts.entries()){
current=path.join(current,part);
if(create&&index>=prefix.length)try{await fs.mkdir(current);}catch(e){if(e.code!=='EEXIST')throw e;}
const info=await fs.lstat(current);if(info.isSymbolicLink())throw fail('不能访问目录链接。');
if(!inside(realRoot,await fs.realpath(current)))throw fail('路径超出归档根目录。');
}
return current;
}
async list(relative=''){
const directory=await this.resolve(relative),entries=[];let truncated=false;
const iterator=await fs.opendir(directory);
for await(const entry of iterator){if(entry.name.startsWith('.order-'))continue;if(entries.length>=500){truncated=true;break;}entries.push({name:entry.name,type:entry.isSymbolicLink()?'blocked':entry.isDirectory()?'directory':'file'});}
entries.sort((a,b)=>(a.type==='directory'?0:1)-(b.type==='directory'?0:1)||a.name.localeCompare(b.name,'zh-CN'));
return {path:segments(relative).join('/'),entries,truncated};
}
async mkdir(relative){if(!segments(relative).length)throw fail('请输入要创建的目录名称。');await this.resolve(relative,true);return {path:segments(relative).join('/')};}
async check(){
const root=await this.resolve(''),file=path.join(root,'.order-probe-'+crypto.randomUUID()),bytes=crypto.randomBytes(32);let owned=false;
try{await fs.writeFile(file,bytes,{flag:'wx'});owned=true;if(!(await fs.readFile(file)).equals(bytes))throw fail('共享目录读写校验失败。',502);}finally{if(owned)await fs.unlink(file);}
return {readable:true,writable:true};
}
async readPdf(relative){if(path.extname(relative).toLowerCase()!=='.pdf')throw fail('仅支持下载归档 PDF。');const file=await this.resolve(relative);return {bytes:await pdf(file),filename:path.basename(file)};}
async archive(source,filename,relative=''){
if(segments(filename).length!==1||path.extname(filename).toLowerCase()!=='.pdf')throw fail('归档文件名必须为 PDF 文件名。');
const bytes=await pdf(source),sha256=digest(bytes),directory=await this.resolve(relative,true);
const same=async target=>{try{return digest(await pdf(target))===sha256;}catch(e){if(e.code==='ENOENT')return false;if(e.status===400)return false;throw e;}};
const candidateNames=[filename,filename.slice(0,-4).slice(0,130)+'_'+sha256+'.pdf'];
for(const name of candidateNames){
const target=path.join(directory,name);const result={filename:name,relativePath:[...segments(relative),name].join('/'),bytes:bytes.length,sha256};
try{const stat=await fs.lstat(target);if(stat.isSymbolicLink())throw fail('目标文件为链接,不能归档。');if(await same(target))return result;continue;}catch(e){if(e.code!=='ENOENT')throw e;}
const temp=path.join(directory,'.order-upload-'+crypto.randomUUID());
try{
await fs.writeFile(temp,bytes,{flag:'wx'});if(!await same(temp))throw fail('上传后校验失败,请重试。',502);
try{await native.publishExclusive(temp,target);}catch(e){if(e.code!=='EEXIST')throw e;if(!await same(target))continue;}
if(!await same(target))throw fail('归档文件校验失败,请检查服务器。',502);return result;
}finally{await fs.unlink(temp).catch(e=>{if(e.code!=='ENOENT')throw e;});}
}
throw fail('存在同名文件且内容不同,请选择其他归档目录。',409);
}
}
class SmbClient{
async area(server){await native.connect(server);const boundary=path.win32.join('\\\\'+server.host,server.share),root=path.win32.join(boundary,...segments(server.directory));return new FileArea(root,{boundary});}
}
module.exports={FileArea,SmbClient,segments,inside,MAX_FILE};
+33
View File
@@ -0,0 +1,33 @@
'use strict';
const fs=require('node:fs/promises');const path=require('node:path');
const {SmbClient,segments,inside}=require('./storage-files.cjs');
const fail=(message,status=400)=>Object.assign(new Error(message),{status});
const safe=e=>e.status?e:fail(({ENOENT:'找不到文件或归档目录,请检查路径。',EACCES:'没有共享目录访问权限。',EPERM:'没有共享目录操作权限。',ENOSPC:'存储服务器空间不足。',ENOTDIR:'指定路径不是目录。'})[e.code]||'存储操作未完成,请检查服务器与网络。',502);
class StorageService{
constructor({store,jobs,outputDir,client=new SmbClient()}){this.store=store;this.jobs=jobs;this.outputDir=outputDir;this.client=client;this.running=new Map();this.stopped=false;}
busy(id){return this.running.has(id);}
saveServer(input){if(input?.id&&this.busy(input.id))throw fail('此服务器正在执行操作,请稍后保存。',409);return this.store.saveServer(input);}
saveSettings(input){if(input?.enabled){const server=this.store.publicServer(input.serverId);if(!server.enabled||!server.state.readable||!server.state.writable)throw fail('请先启用服务器并检查读写成功。',409);}return this.store.saveSettings(input);}
run(id,work){
if(this.stopped)return Promise.reject(fail('存储服务正在停止。',503));
const previous=this.running.get(id)||Promise.resolve();
const task=previous.catch(()=>{}).then(async()=>{const server=this.store.secret(id);if(!server.enabled)throw fail('此存储服务器已停用。',409);try{return await work(server);}catch(e){throw safe(e);}});
this.running.set(id,task);task.finally(()=>{if(this.running.get(id)===task)this.running.delete(id);}).catch(()=>{});return task;
}
check(id){return this.run(id,async server=>{try{const area=await this.client.area(server),result=await area.check();const state={...result,checkedAt:new Date().toISOString(),message:'共享目录读写正常'};this.store.setState(id,server.version,state);return this.store.publicServer(id);}catch(e){const error=safe(e);this.store.setState(id,server.version,{readable:false,writable:false,checkedAt:new Date().toISOString(),message:error.message});throw error;}});}
list(id,relative){return this.run(id,async server=>(await this.client.area(server)).list(relative));}
mkdir(id,relative){return this.run(id,async server=>(await this.client.area(server)).mkdir(relative));}
readPdf(id,relative){return this.run(id,async server=>(await this.client.area(server)).readPdf(relative));}
archive(id,jobId,directory='',actor='自动归档'){
return this.run(id,async server=>{
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 record=this.store.beginArchive(id,jobId,actor,directory);
try{const [root,file]=await Promise.all([fs.realpath(this.outputDir),fs.realpath(job.path)]);if(!inside(root,file)||file===root||path.extname(file).toLowerCase()!=='.pdf')throw fail('PDF 不在本工具输出目录内。');const area=await this.client.area(server),result=await area.archive(file,path.basename(file),directory);return this.store.finishArchive(record.id,'success',{...result,serverName:server.name});}
catch(e){const error=safe(e);this.store.finishArchive(record.id,'error',{error:error.message,serverName:server.name});throw error;}
});
}
async automatic(job){const settings=this.store.settings();if(!settings.enabled||job.status!=='success'||!job.createdAt||job.createdAt<settings.since)return null;return this.archive(settings.serverId,job.jobId,'','自动归档');}
async stop(){this.stopped=true;await Promise.allSettled([...this.running.values()]);}
}
module.exports={StorageService};
+51
View File
@@ -0,0 +1,51 @@
'use strict';
const fs=require('node:fs');
const path=require('node:path');
const crypto=require('node:crypto');
const {DatabaseSync}=require('node:sqlite');
const {BpmVault}=require('./bpm-vault.cjs');
const {segments}=require('./storage-files.cjs');
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
const text=(v,label,max=200)=>{if(typeof v!=='string'||!v.trim()||v.length>max||/[\x00-\x1f]/.test(v))fail(label+'格式不正确。');return v.trim();};
const now=()=>new Date().toISOString();
class StorageStore{
constructor(dir){
fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});
this.db=new DatabaseSync(path.join(dir,'storage.sqlite'));this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
CREATE TABLE IF NOT EXISTS servers(id TEXT PRIMARY KEY,version INTEGER NOT NULL,payload BLOB NOT NULL,state TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS settings(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL);
INSERT OR IGNORE INTO settings VALUES(1,'{"serverId":"","enabled":false,"since":null}');
CREATE TABLE IF NOT EXISTS archives(id TEXT PRIMARY KEY,server_id TEXT NOT NULL,job_id TEXT NOT NULL,status TEXT NOT NULL,value TEXT NOT NULL,UNIQUE(server_id,job_id));
UPDATE archives SET status='interrupted' WHERE status='running';`);
}
row(id){if(typeof id!=='string')fail('请选择存储服务器。');const row=this.db.prepare('SELECT * FROM servers WHERE id=?').get(id);if(!row)fail('存储服务器不存在。',404);return row;}
secret(id){const row=this.row(id);try{return {...this.vault.decode(id,row.payload),id,version:row.version,state:JSON.parse(row.state)};}catch{fail('存储凭据无法解密,请联系管理员。',503);}}
publicServer(id){const {password,...server}=this.secret(id);return {...server,hasPassword:!!password};}
servers(){return this.db.prepare('SELECT id FROM servers ORDER BY rowid').all().map(r=>this.publicServer(r.id));}
saveServer(input){
const fields=['id','version','name','host','share','directory','username','password','enabled','state','hasPassword','createdAt','updatedAt'];
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!fields.includes(k)))fail('存储服务器配置无效。');
const old=input.id?this.secret(input.id):null;if(old&&input.version!==old.version)fail('服务器已被修改,请刷新后重试。',409);
const host=text(input.host,'服务器地址',253).toLowerCase();if(!/^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$/.test(host)||host.includes('..'))fail('服务器地址只填写主机名或 IPv4 地址。');
const share=text(input.share,'共享名称',80);if(segments(share).length!==1)fail('共享名称不能包含路径。');
const username=text(input.username,'登录账号',200),directory=segments(input.directory).join('/');
if(typeof input.enabled!=='boolean')fail('请选择服务器是否启用。');
if(old&&input.password===''&&(host!==old.host||share!==old.share||username!==old.username))fail('更换服务器、共享或登录账号时,请重新填写密码。');
const password=input.password===''&&old?old.password:input.password;if(typeof password!=='string'||!password||password.length>2048)fail('请输入 SMB 登录密码。');
const id=old?.id||crypto.randomUUID(),saved={name:text(input.name,'服务器名称',80),host,share,directory,username,password,enabled:input.enabled,createdAt:old?.createdAt||now(),updatedAt:now()};
let payload;try{payload=this.vault.encode(id,saved);}catch{fail('存储凭据加密不可用,请联系管理员。',503);}
const changed=!old||['host','share','directory','username','password'].some(k=>saved[k]!==old[k]);
const state=changed?{checkedAt:null,readable:false,writable:false,message:'待检查连接'}:old.state;
this.db.prepare('INSERT INTO servers VALUES(?,?,?,?) ON CONFLICT(id) DO UPDATE SET version=excluded.version,payload=excluded.payload,state=excluded.state').run(id,(old?.version||0)+1,payload,JSON.stringify(state));
if(old&&(!saved.enabled||changed)&&this.settings().serverId===id)this.saveSettings({serverId:id,enabled:false});
return this.publicServer(id);
}
setState(id,version,state){if(this.row(id).version!==version)fail('服务器配置已变化,请重试。',409);this.db.prepare('UPDATE servers SET state=? WHERE id=?').run(JSON.stringify(state),id);}
settings(){return JSON.parse(this.db.prepare('SELECT value FROM settings WHERE id=1').get().value);}
saveSettings(input){if(!input||Object.keys(input).some(k=>!['serverId','enabled'].includes(k))||typeof input.serverId!=='string'||typeof input.enabled!=='boolean')fail('自动归档设置无效。');if(input.serverId)this.row(input.serverId);if(input.enabled&&!input.serverId)fail('请选择自动归档服务器。');const old=this.settings();const saved={...input,since:input.enabled?(old.enabled&&old.serverId===input.serverId?old.since:now()):null};this.db.prepare('UPDATE settings SET value=? WHERE id=1').run(JSON.stringify(saved));return saved;}
beginArchive(serverId,jobId,actor,directory){const prior=this.db.prepare('SELECT id,value FROM archives WHERE server_id=? AND job_id=?').get(serverId,jobId),id=prior?.id||crypto.randomUUID();const value={...(prior?JSON.parse(prior.value):{}),actor,directory,startedAt:now(),finishedAt:null,error:null};this.db.prepare('INSERT INTO archives VALUES(?,?,?,?,?) ON CONFLICT(server_id,job_id) DO UPDATE SET status=excluded.status,value=excluded.value').run(id,serverId,jobId,'running',JSON.stringify(value));return {id,serverId,jobId,status:'running',...value};}
finishArchive(id,status,patch){const row=this.db.prepare('SELECT value FROM archives WHERE id=?').get(id);const value={...JSON.parse(row.value),...patch,finishedAt:now()};const saved=this.db.prepare('UPDATE archives SET status=?,value=? WHERE id=? RETURNING id,server_id AS serverId,job_id AS jobId,status').get(status,JSON.stringify(value),id);return {...value,...saved};}
archives(){return this.db.prepare("SELECT id,server_id AS serverId,job_id AS jobId,status,value FROM archives ORDER BY COALESCE(json_extract(value,'$.finishedAt'),json_extract(value,'$.startedAt')) DESC,rowid DESC LIMIT 100").all().map(({value,...r})=>({...JSON.parse(value),...r}));}
close(){if(this.db){this.db.close();this.db=null;}this.vault.destroy();}
}
module.exports={StorageStore};