refactor: organize source web and tests by business module
This commit is contained in:
1 parent
9854d2d5c2
commit
2aed328774
113 files changed
+189
-183
No files matched your search
@@ -0,0 +1,143 @@
|
||||
const http=require('node:http');const fs=require('node:fs');const path=require('node:path');
|
||||
const {nextSlots}=require('../shared/schedule.cjs');
|
||||
const {workspaceApi}=require('../modules/workspace/api.cjs');
|
||||
const {bpmApi}=require('../modules/bpm/api.cjs');
|
||||
const {mailApi}=require('../modules/mail/api.cjs');
|
||||
const {bpmScanApi}=require('../modules/bpm/scan-api.cjs');
|
||||
const {storageApi}=require('../modules/storage/api.cjs');
|
||||
const {notificationApi}=require('../modules/notifications/api.cjs');
|
||||
const {assistantApi}=require('../modules/assistant/api.cjs');
|
||||
const {respondToPing}=require('../platform/service/ping.cjs');
|
||||
const {previewAsset,PREVIEW_CSP}=require('../modules/storage/preview-assets.cjs');
|
||||
const {SessionStore,SESSION_MS}=require('../modules/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,storage,notifications,assistant,health,watchdog,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})(?:;|$)');
|
||||
const webRoot=require('../shared/paths.cjs').WEB_ROOT;
|
||||
const assets={
|
||||
'/':{path:path.join(webRoot,'index.html'),type:'text/html'},
|
||||
'/app.js':{path:path.join(webRoot,'app.js'),type:'text/javascript'},
|
||||
'/workspace.js':{path:path.join(webRoot,'modules/workspace/view.js'),type:'text/javascript'},
|
||||
'/bpm.js':{path:path.join(webRoot,'modules/bpm/view.js'),type:'text/javascript'},
|
||||
'/mail.js':{path:path.join(webRoot,'modules/mail/view.js'),type:'text/javascript'},
|
||||
'/orders.js':{path:path.join(webRoot,'modules/bpm/arrivals.js'),type:'text/javascript'},
|
||||
'/storage.js':{path:path.join(webRoot,'modules/storage/view.js'),type:'text/javascript'},
|
||||
'/storage-preview.html':{path:path.join(webRoot,'modules/storage/preview.html'),type:'text/html',preview:true},
|
||||
'/storage-preview.js':{path:path.join(webRoot,'modules/storage/preview.js'),type:'text/javascript',preview:true},
|
||||
'/storage-preview-office.js':{path:path.join(webRoot,'modules/storage/preview-office.js'),type:'text/javascript',preview:true},
|
||||
'/storage-preview-host.js':{path:path.join(webRoot,'modules/storage/preview-host.js'),type:'text/javascript'},
|
||||
'/storage-preview.css':{path:path.join(webRoot,'modules/storage/preview.css'),type:'text/css',preview:true},
|
||||
'/notifications.js':{path:path.join(webRoot,'modules/notifications/view.js'),type:'text/javascript'},
|
||||
'/assistant.js':{path:path.join(webRoot,'modules/assistant/view.js'),type:'text/javascript'},
|
||||
'/health.js':{path:path.join(webRoot,'modules/health/view.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'}
|
||||
};
|
||||
const server=http.createServer(async(request,response)=>{
|
||||
if(respondToPing(request,response,watchdog))return;
|
||||
const encryptedTransport=Boolean(request.socket.encrypted || (trustedProxy && isLoopback(request.socket.remoteAddress) && request.headers['x-forwarded-proto']==='https'));
|
||||
response.setHeader('X-Content-Type-Options','nosniff');response.setHeader('Referrer-Policy','same-origin');
|
||||
response.setHeader('Content-Security-Policy',"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'");
|
||||
response.setHeader('Cache-Control','no-store');
|
||||
const reply=(status,body)=>{response.writeHead(status,{'Content-Type':'application/json; charset=utf-8'});response.end(JSON.stringify(body));};
|
||||
const fail=(status,message)=>{throw Object.assign(new Error(message),{status});};
|
||||
try {
|
||||
const url=new URL(request.url,'http://localhost');const route=url.pathname;
|
||||
const asset=assets[route]||previewAsset(route);
|
||||
if(/^\/vendor\/(embedpdf|photoswipe|docx|jszip|exceljs)\//.test(route)&&!asset)fail(404,'资源不存在。');
|
||||
if(request.method==='GET' && asset) {
|
||||
let bytes;try{bytes=await fs.promises.readFile(asset.path);}catch(error){if(error.code==='ENOENT')fail(404,'资源不存在。');throw error;}
|
||||
if(asset.preview){response.setHeader('Content-Security-Policy',PREVIEW_CSP);response.setHeader('Access-Control-Allow-Origin','*');}
|
||||
response.writeHead(200,{'Content-Type':asset.type+(asset.binary?'':'; charset=utf-8')});response.end(bytes);return;
|
||||
}
|
||||
const sameOrigin=request.headers.origin===`http://${request.headers.host}` || request.headers.origin===`https://${request.headers.host}`;
|
||||
if(!['GET','HEAD'].includes(request.method) && !sameOrigin)fail(403,'请在看板页面中执行操作。');
|
||||
let body;
|
||||
if(request.method==='POST') {
|
||||
if(!/^application\/json(?:;|$)/i.test(request.headers['content-type'] || ''))fail(415,'需要 JSON 数据。');
|
||||
if(Number(request.headers['content-length'] || 0)>128*1024){request.resume();fail(413,'提交内容过大。');}
|
||||
const chunks=[];let size=0;
|
||||
for await(const chunk of request){size+=chunk.length;if(size>128*1024)fail(413,'提交内容过大。');chunks.push(chunk);}
|
||||
try{body=JSON.parse(Buffer.concat(chunks).toString('utf8'));if(!body || Array.isArray(body) || typeof body!=='object')throw new Error();}catch{fail(400,'数据格式不正确。');}
|
||||
}
|
||||
const host=(request.headers.host || '').split(':')[0];
|
||||
const canSetup=isLoopback(request.socket.remoteAddress) && ['localhost','127.0.0.1'].includes(host);
|
||||
const preview=Boolean(previewUserId && canSetup && store.user(previewUserId));
|
||||
if(route==='/api/bootstrap/status' && request.method==='GET')return reply(200,{required:store.users().length===0,canSetup,preview});
|
||||
function signIn(user) {
|
||||
const {token}=sessions.issue(user.id);
|
||||
response.setHeader('Set-Cookie',`${sessionCookieName}=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=${SESSION_MS/1000}${encryptedTransport?'; Secure':''}`);
|
||||
return user;
|
||||
}
|
||||
if(route==='/api/bootstrap' && request.method==='POST') {
|
||||
if(!canSetup)fail(403,'请在部署机访问 http://127.0.0.1:18766 创建管理员。');
|
||||
return reply(201,{user:signIn(store.bootstrap(body.username,body.password))});
|
||||
}
|
||||
if(route==='/api/preview-login' && request.method==='POST') {
|
||||
if(!previewUserId)fail(404,'没有找到此页面或操作。');
|
||||
if(!preview)fail(403,'演示登录仅允许在部署机本地访问。');
|
||||
return reply(200,{user:signIn(store.user(previewUserId)),preview:true});
|
||||
}
|
||||
if(route==='/api/login' && request.method==='POST') {
|
||||
const address=request.socket.remoteAddress;const now=Date.now();
|
||||
for(const [key,value] of failures)if(now-value.since>900000)failures.delete(key);
|
||||
if(failures.get(address)?.count>=10)fail(429,'登录失败次数过多,请 15 分钟后重试。');
|
||||
const user=store.authenticate(body.username,body.password);
|
||||
if(!user){if(failures.size>1000)failures.clear();const previous=failures.get(address);failures.set(address,{since:previous?.since || now,count:(previous?.count || 0)+1});fail(401,'账号或密码不正确。');}
|
||||
failures.delete(address);return reply(200,{user:signIn(user)});
|
||||
}
|
||||
const token=sessionCookiePattern.exec(request.headers.cookie || '')?.[1];
|
||||
const session=sessions.lookup(token);const user=session?store.user(session.userId):null;
|
||||
if(!user)fail(401,'请先登录。');
|
||||
if(session.renewed)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 reply(200,{user,preview});
|
||||
if(route==='/api/health' && request.method==='GET'){if(!health)fail(503,'健康状态服务未启动。');return reply(200,health.snapshot(user));}
|
||||
if(route==='/api/logout' && request.method==='POST'){sessions.revoke(token);response.setHeader('Set-Cookie',`${sessionCookieName}=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0${encryptedTransport?'; Secure':''}`);if(bpmSessions)try{await bpmSessions.releaseSession(token);}catch{fail(502,'登录窗口关闭失败,请稍后重试。');}return reply(200,{ok:true});}
|
||||
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(await assistantApi({assistant,workspace,user,sessionId:token,route,method:request.method,body,request,reply,trustedProxy}))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:'待核实并接入 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());
|
||||
if(request.method==='POST'){if(user.role!=='admin')fail(403,'仅管理员可以修改配置。');return reply(200,store.saveSettings(body,body.version,user.username));}
|
||||
}
|
||||
if(route==='/api/jobs' && request.method==='GET')return reply(200,{jobs:store.jobs().map(publicJob)});
|
||||
if(route==='/api/audit' && request.method==='GET')return reply(200,{audit:store.audit()});
|
||||
if(route==='/api/users') {
|
||||
if(user.role!=='admin')fail(403,'仅管理员可以管理账号。');
|
||||
if(request.method==='GET')return reply(200,{users:store.users()});
|
||||
if(request.method==='POST')return reply(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]);
|
||||
if(!job || job.status!=='success' || !job.path)fail(404,'文件不可用。');
|
||||
let realRoot,realFile;
|
||||
try{[realRoot,realFile]=await Promise.all([fs.promises.realpath(outputDir),fs.promises.realpath(job.path)]);}catch{fail(404,'文件不存在。');}
|
||||
const relative=path.relative(realRoot,realFile);
|
||||
if(!relative || relative.startsWith('..'+path.sep) || relative==='..' || path.isAbsolute(relative) || path.extname(realFile).toLowerCase()!=='.pdf')fail(404,'文件不可用。');
|
||||
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;
|
||||
}
|
||||
fail(404,'没有找到此页面或操作。');
|
||||
}catch(error){if(!response.headersSent){if(!error.status)console.error('看板处理失败:',error.message);reply(error.status || 500,{error:error.status?error.message:'处理失败,请检查服务日志。'});}else response.end();}
|
||||
});
|
||||
server.once('close',()=>sessions.close());server.once('error',()=>{if(!server.listening)sessions.close();});
|
||||
return server;
|
||||
}
|
||||
module.exports={createDashboard};
|
||||
Reference in new issue
Block a user