const crypto = require('node:crypto'); const fs = require('node:fs/promises'); const path = require('node:path'); const os = require('node:os'); const { Store } = require('../modules/dashboard/store.cjs'); const { createDashboard } = require('./dashboard.cjs'); const { startService } = require('./bridge.cjs'); const { acquireInstanceLock } = require('../platform/service/instance-lock.cjs'); const { WorkspaceStore } = require('../modules/workspace/store.cjs'); const { BpmSessionManager } = require('../modules/bpm/session-manager.cjs'); const { BpmCustodian } = require('../modules/bpm/custodian.cjs'); const { MailStore } = require('../modules/mail/store.cjs'); const { MailService } = require('../modules/mail/service.cjs'); const { BpmScanStore } = require('../modules/bpm/scan-store.cjs'); const { BpmScanner } = require('../modules/bpm/scanner.cjs'); const {BpmAccessClient}=require('../modules/bpm/access-client.cjs'); const {BpmArrivalMonitor}=require('../modules/bpm/arrival-monitor.cjs'); const { AssistantStore } = require('../modules/assistant/store.cjs'); const { AssistantService } = require('../modules/assistant/service.cjs'); const { DshRuntime } = require('../modules/assistant/dsh-runtime.cjs'); const { OperationJournal } = require('../modules/assistant/operation-journal.cjs'); const { RuntimeHealth } = require('../modules/health/runtime-health.cjs'); const { StorageStore } = require('../modules/storage/store.cjs'); const { StorageService } = require('../modules/storage/service.cjs'); const { NotificationHistory } = require('../modules/notifications/history.cjs'); const { RuleStore } = require('../modules/order-rules/store.cjs'); const { OrderRuleDispatcher } = require('../modules/order-rules/dispatcher.cjs'); const { BpmOrderProvider } = require('../modules/bpm/order-provider.cjs'); const { OrderArchiveProvider } = require('../modules/storage/order-archive.cjs'); const { OrderExecutionCoordinator } = require('../modules/order-execution/coordinator.cjs'); async function closeServer(server){ if(!server)return; // An unbound dashboard still owns its session DB. if(!server.listening){await server.drainExports?.();server.closeSessionStore?.();return;} await new Promise((resolve,reject)=>server.close(error=>error?reject(error):resolve())); } async function resolveOutputDir(root,stateDir,config){ if(Object.hasOwn(config,'outputDir'))return path.resolve(root,config.outputDir||'output/pdf'); let restored;try{restored=JSON.parse(await fs.readFile(path.join(stateDir,'restore-config.json'),'utf8'));}catch(e){if(e.code==='ENOENT')return path.resolve(root,'output/pdf');throw e;} if(restored.outputDir!=='restored-pdf')throw Error('恢复输出目录必须位于新状态目录内。'); const resolved=path.resolve(stateDir,restored.outputDir),relative=path.relative(path.resolve(stateDir),resolved);if(!relative||relative.startsWith('..')||path.isAbsolute(relative))throw Error('恢复输出目录必须位于新状态目录内。'); const [realState,realOutput]=await Promise.all([fs.realpath(stateDir),fs.realpath(resolved)]),realRelative=path.relative(realState,realOutput);if(!realRelative||path.isAbsolute(realRelative)||realRelative==='..'||realRelative.startsWith('..'+path.sep)||(await fs.lstat(resolved)).isSymbolicLink())throw Error('恢复输出目录不能是链接。');return resolved; } async function main(options = {}) { const startedAt=new Date().toISOString(),watchdog={token:process.env.ORDER_SUPERVISOR_TOKEN,instanceId:process.env.ORDER_SUPERVISOR_INSTANCE,startedAt}; const root = require('../shared/paths.cjs').PROJECT_ROOT; let config = options.config; if(!config){ config={}; try { config = JSON.parse(await fs.readFile(path.join(root,'config.json'),'utf8')); } catch(error) { if(error.code !== 'ENOENT') throw error; } } const port = config.port || 18765; if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error('端口需为 1024–65535。'); const stateDir = options.stateDir || path.join(process.env.LOCALAPPDATA || os.homedir(),'OrderNotificationAutomation'); const ownership=await acquireInstanceLock(stateDir); const cleanup=[]; let stopping; const stop=()=>stopping ||= (async()=>{ server?.stopAcceptingExports?.(); const errors=[]; // Stop producers before closing stores. Every teardown gets an attempt, even after a failure. for(const close of cleanup)try{await close();}catch(error){errors.push(error);} try{await ownership.release();}catch(error){errors.push(error);} if(errors.length)throw new AggregateError(errors,'关闭服务时部分资源清理失败。'); })(); let server,dashboard,store,workspace,bpmSessions,custodian; let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,orderRules,orderDispatcher,orderExecution,orderProvider,orderArchive,assistantStore,assistantJournal,assistant,health,bpmMonitor; try { const tokenPath = path.join(stateDir,'pairing.key'); let token; try { token = (await fs.readFile(tokenPath,'utf8')).trim(); } catch(error) { if(error.code !== 'ENOENT') throw error; token=crypto.randomBytes(32).toString('hex'); await fs.writeFile(tokenPath,token,{mode:0o600}); } if (!/^[a-f0-9]{64}$/.test(token)) throw new Error('本地配对文件损坏,请删除 pairing.key 后重启。'); const outputDir = await resolveOutputDir(root,stateDir,config); const installedExtension = path.join(stateDir,'extension'); const dashboardConfig=config.dashboard || {}; const dashboardPort=dashboardConfig.port ?? 18766; const dashboardHost=dashboardConfig.host || '0.0.0.0'; if(!Number.isInteger(dashboardPort) || dashboardPort<1024 || dashboardPort>65535 || dashboardPort===port)throw new Error('Web 看板端口需为 1024–65535,且不能与扩展服务相同。'); if(!['0.0.0.0','127.0.0.1'].includes(dashboardHost))throw new Error('Web 看板 host 请设置为 0.0.0.0(局域网)或 127.0.0.1(仅本机)。'); if(dashboardConfig.trustedProxy!==undefined && typeof dashboardConfig.trustedProxy!=='boolean')throw new Error('dashboard.trustedProxy 必须为布尔值。'); store=new Store(path.join(stateDir,'dashboard')); workspace=new WorkspaceStore(path.join(stateDir,'workspace')); // Register conditional closures before constructing later resources; partial startup follows the same path. cleanup.push(()=>closeServer(server)); cleanup.push(()=>bpmMonitor?.stop(),()=>health?.close(),()=>assistant?.stop(),()=>orderDispatcher?.stop(),()=>orderExecution?.stop(),()=>storage?.stop(),()=>scanner?.stop(),()=>mail?.stop(),()=>custodian?.stop(),()=>bpmSessions?.shutdown()); cleanup.push(()=>closeServer(dashboard),()=>workspace.close()); cleanup.push(()=>mailStore?.close(),()=>scanStore?.close(),()=>storageStore?.close(),()=>notificationStore?.close(),()=>orderRules?.close(),()=>assistantStore?.close(),()=>assistantJournal?.close()); bpmSessions=new BpmSessionManager({stateDir:path.join(stateDir,'bpm-sessions'),accessClient:new BpmAccessClient()}); custodian=new BpmCustodian({workspace,manager:bpmSessions}); mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore,beforeSend:()=>{if(!orderRules)throw Object.assign(Error('通知业务状态尚未就绪。'),{status:503});require('../modules/order-rules/stability-period.cjs').assertActive(orderRules);}}); 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 NotificationHistory(path.join(stateDir,'notifications'));notifications={store:notificationStore,historyOnly:true}; orderRules=new RuleStore(path.join(stateDir,'order-rules'),{schedule:()=>store.settings().schedule,calendar:()=>workspace.meta('calendar').overrides}); orderProvider=new BpmOrderProvider({manager:bpmSessions});orderArchive=new OrderArchiveProvider({storage,outputDir,journal:orderRules}); orderExecution=new OrderExecutionCoordinator({store:orderRules,workspace,provider:orderProvider,archive:orderArchive,mail,dashboard:store,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides,systemPrincipal:custodian.principal}); orderDispatcher=new OrderRuleDispatcher({store:orderRules,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides,providersReady:()=>{const cap=orderExecution.snapshot().capabilities;return ['liveTodo','pdfExport','automaticArchive'].every(key=>cap?.[key]===true);},templateResolver:(categoryId,rule,mode='normal')=>require('../modules/mail/rule-template.cjs').ruleTemplate(mailStore,categoryId,rule,mode),attachmentReader:file=>orderArchive.read(file)}); orderRules.deliveryBlockers=allowed=>scanStore.deliveries.pendingSources().filter(allowed); bpmMonitor=new BpmArrivalMonitor({workspace,manager:bpmSessions,scanner,provider:orderProvider,settings:()=>store.settings(),onTodoReconciled:payload=>orderExecution.notifyDiscovery(payload)}); assistantStore=new AssistantStore(path.join(stateDir,'assistant'));assistantStore.recover();assistantJournal=new OperationJournal({file:path.join(stateDir,'assistant','operations.sqlite')});assistantJournal.recoverRunning();assistant=new AssistantService({store:assistantStore,journal:assistantJournal,runtime:new DshRuntime({stateDir:path.join(stateDir,'assistant','runtime')}),dashboard:store,workspace,scanner,storage,orderRules,orderExecution}); health=new RuntimeHealth({stateDir,startedAt,instanceId:watchdog.instanceId,workspace,scanner,storage,mail,execution:orderExecution,monitor:bpmMonitor,bpmSessions}); await bpmSessions.migrateAccounts(workspace.snapshot().connections); workspace.markSessionChecksPending(); server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage,watchdog,renderSnapshot:options.renderSnapshot}); dashboard=createDashboard({store,workspace,outputDir,bpmSessions,bpmMonitor,mail,scanner,storage,notifications,orderRules,orderExecution,orderDispatcher,assistant,health,watchdog,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();bpmMonitor.start(); health.start(); orderExecution.start(); orderDispatcher.start(); if(!options.quiet){ console.log('订单通知中心已启动。\nWeb 工作台支持业务日历、异常待办与转交、BPM 连接管理。\n在 Chrome 订单页仍可点击扩展中的“导出当前订单”。'); console.log(`首次使用:Chrome 扩展管理 → 开发者模式 → 加载已解压的扩展程序\n选择目录:${installedExtension}\n输出目录:${outputDir}\n本地服务:http://127.0.0.1:${port}`); console.log(`Web 看板:http://127.0.0.1:${dashboardPort}\n${store.users().length?'使用已创建的工作台账号登录。':'首次请在部署机创建管理员。'}`); if(dashboardHost==='0.0.0.0')for(const list of Object.values(os.networkInterfaces()))for(const address of list || [])if(address.family==='IPv4' && !address.internal)console.log(`局域网地址:http://${address.address}:${dashboardPort}`); } return {server,dashboard,workspace,bpmSessions,bpmMonitor,custodian,mail,scanner,storage,notifications,orderRules,orderDispatcher,orderExecution,assistant,health,stop}; }catch(error){try{await stop();}catch(cleanupError){error.cleanupError=cleanupError;}throw error;} } module.exports={main,resolveOutputDir};