const fs=require('node:fs'); 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,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) { const schedule=settings.schedule; if(!schedule || !Array.isArray(schedule.times) || schedule.times.length!==2 || new Set(schedule.times).size!==2)fail('请设置两个不同的发送时间。'); if(schedule.times.some(time=>typeof time!=='string' || !/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(time)))fail('时间必须为有效的 HH:MM。'); if(typeof schedule.weekends!=='boolean' || !['product_line','order'].includes(schedule.mode) || !['next_window','skip'].includes(schedule.missed))fail('发送计划选项不正确。'); if(schedule.timezone!=='Asia/Shanghai')fail('时区必须为 Asia/Shanghai。'); if(!settings.templates || typeof settings.templates.subject!=='string' || typeof settings.templates.body!=='string' || settings.templates.subject.length>300 || settings.templates.body.length>20000)fail('模板标题最多 300 字,正文最多 20000 字。'); if(!Array.isArray(settings.groups) || settings.groups.length>100)fail('收件群组格式不正确。'); const names=new Set(); for(const group of settings.groups) { if(!group || typeof group.productLine!=='string' || !group.productLine.trim() || group.productLine.length>100 || names.has(group.productLine.trim()))fail('产品线名称不能为空或重复。'); names.add(group.productLine.trim()); for(const field of ['to','cc']) { if(!Array.isArray(group[field]) || group[field].length>50 || group[field].some(email=>typeof email!=='string' || email.length>254 || !/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(email)))fail('请填写有效的收件邮箱,使用逗号分隔。'); } if(group.to.length===0)fail('每个产品线至少需要一个收件人。'); } } class Store { constructor(dir) { fs.mkdirSync(dir,{recursive:true});this.file=path.join(dir,'state.sqlite'); this.data=this.database(db=>{ db.exec('CREATE TABLE IF NOT EXISTS dashboard_state(id INTEGER PRIMARY KEY CHECK(id=1),value TEXT NOT NULL)'); const stored=db.prepare('SELECT value FROM dashboard_state WHERE id=1').get(); if(stored){const data=JSON.parse(stored.value);if(data.schema!==1)fail('状态文件版本不支持。',500);return data;} let data; try{data=JSON.parse(fs.readFileSync(path.join(dir,'state.json'),'utf8'));if(data.schema!==1)fail('状态文件版本不支持。',500);} catch(error){if(error.code!=='ENOENT')throw error;data={schema:1,users:[],settings:{version:1,schedule:{times:['09:00','17:00'],timezone:'Asia/Shanghai',weekends:false,mode:'product_line',missed:'next_window'},templates:{subject:'',body:''},groups:[]},jobs:[],audit:[]};} // A single SQLite statement publishes the imported snapshot atomically. // Retain legacy JSON unchanged for backups; SQLite is authoritative thereafter. 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,mutateDatabase) { const draft=copy(this.data);const result=mutator(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);} settings(){return copy(this.data.settings);} saveSettings(patch,version,actor) { return this.commit(draft=>{ if(version!==draft.settings.version)fail('配置已被其他人更新,请刷新后重试。',409); const updated={...draft.settings}; for(const key of ['schedule','templates','groups'])if(Object.hasOwn(patch,key))updated[key]=copy(patch[key]); validateSettings(updated); updated.schedule={times:[...updated.schedule.times].sort(),timezone:'Asia/Shanghai',weekends:updated.schedule.weekends,mode:updated.schedule.mode,missed:updated.schedule.missed}; updated.templates={subject:updated.templates.subject,body:updated.templates.body}; updated.groups=updated.groups.map(group=>({productLine:group.productLine.trim(),to:group.to,cc:group.cc})); updated.version++;draft.settings=updated; this.addAudit(draft,actor,'保存配置','发送计划 / 模板 / 产品线群组');return updated; }); } users(){return this.data.users.map(safeUser);} user(id){const user=this.data.users.find(user=>user.id===id);return user?safeUser(user):null;} makeUser(username,password,role) { if(typeof username!=='string' || !/^[a-zA-Z0-9_.-]{3,40}$/.test(username))fail('账号需为 3–40 位英文、数字、点、下划线或短横线。'); 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,enabled:true,version:1,createdAt:new Date().toISOString(),passwordHash:hashPassword(password)}; } bootstrap(username,password) { if(this.data.users.length)fail('管理员已经创建,请登录。',409); const user=this.makeUser(username,password,'admin'); return this.commit(draft=>{draft.users.push(user);this.addAudit(draft,username,'创建管理员');return safeUser(user);}); } addUser(input,actor) { const user=this.makeUser(input.username,input.password,input.role); return this.commit(draft=>{draft.users.push(user);this.addAudit(draft,actor,'创建账号',user.username+' / '+user.role);return safeUser(user);}); } 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 || 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('新密码不能与原密码相同。'); const passwordHash=hashPassword(password); return this.commit(draft=>{ const target=draft.users.find(user=>user.id===id);target.passwordHash=passwordHash; target.passwordVersion=(target.passwordVersion||0)+1; this.addAudit(draft,actor.username,actor.id===id?'修改密码':'重置密码',target.username); return safeUser(target); }); } recordJob(record) { 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)); } 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() { 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};