'use strict'; const fs=require('node:fs/promises'); const path=require('node:path'); const crypto=require('node:crypto'); const {nextSlots}=require('../../shared/schedule.cjs'); const {windowForCutoff}=require('./window.cjs'); function sameWindow(batch,cutoff,window){ return batch.status==='prepared'&&Date.parse(batch.cutoff)===Date.parse(cutoff)&&batch.window?.start===window.start&&batch.window?.end===window.end&&batch.window?.startInclusive===true&&batch.window?.endInclusive===false; } function freeze(value){ if(value&&typeof value==='object'){for(const item of Object.values(value))freeze(item);Object.freeze(value);} return value; } class OrderRuleDispatcher{ constructor({store,mail,settings,calendar=()=>[],clock=()=>new Date(),providersReady=()=>false}){ this.store=store;this.mail=mail;this.settings=settings;this.calendar=calendar;this.clock=clock;this.providersReady=providersReady; this.running=null;this.stopped=false;this.schedule=null;this.timer=null; } ready(){ const config=this.store.settings(),cap=this.store.snapshot().capabilities; return !this.stopped&&config.enabled===true&&this.providersReady()===true&&cap?.liveTodo===true&&cap?.pdfExport===true&&cap?.automaticArchive===true; } tick(now=this.clock()){ if(this.stopped||this.running)return this.running||Promise.resolve(); const task=this.perform(new Date(now));this.running=task; task.finally(()=>{if(this.running===task)this.running=null;}).catch(()=>{}); return task; } async perform(now){ if(!this.ready())return; const config=freeze(structuredClone(this.store.settings())); const schedule=this.settings()?.schedule,calendar=this.calendar(); if(!schedule?.times?.length)return; const signature=JSON.stringify([schedule,calendar]); if(!this.schedule||this.schedule.signature!==signature){this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};return;} if(!this.schedule.next||Date.parse(this.schedule.next)>now.getTime())return; const cutoff=this.schedule.next; if(now.getTime()-Date.parse(cutoff)>60000){this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};return;} if(!this.ready())return; try{ await this.mail.exclusive(config.channelId,async()=>{ if(!this.ready())return; // A busy mailbox cannot consume the slot or reserve any orders. Recovery // applies only to this exact business window, never to earlier history. const window=windowForCutoff(cutoff,schedule,calendar); const existing=(this.store.snapshot().batches||[]).filter(batch=>sameWindow(batch,cutoff,window)); const fresh=this.store.prepare(cutoff,'系统调度',window).filter(batch=>sameWindow(batch,cutoff,window)); const batches=[...new Map([...existing,...fresh].map(batch=>[batch.id,freeze(structuredClone(batch))])).values()]; let interrupted=false; for(const batch of batches){ if(!this.ready()){interrupted=true;break;} if(batch.status!=='prepared')continue; await this.dispatch(batch,config); } if(!interrupted)this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]}; }); }catch(error){if(error.status!==409)throw error;} } async attachments(batch,config){ const result=[];let total=0; for(const file of batch.attachments||[]){ if(!file||typeof file.path!=='string'||!(path.isAbsolute(file.path)||path.win32.isAbsolute(file.path))||/^[a-z]+:\/\//i.test(file.path)||!/^[a-f\d]{64}$/i.test(file.sha256)||!Number.isSafeInteger(file.size)||file.size<0)throw Error('归档文件证据无效。'); total+=file.size; if(total>(config.maxMessageBytes||20971520))throw Error('归档文件超过邮件大小限制。'); const stat=await fs.stat(file.path); if(!stat.isFile()||stat.size!==file.size)throw Error('归档文件大小发生变化。'); const content=await fs.readFile(file.path); if(content.length!==file.size||crypto.createHash('sha256').update(content).digest('hex')!==file.sha256.toLowerCase())throw Error('归档文件校验失败。'); result.push({filename:file.name,content,contentType:file.kind==='pdf'?'application/pdf':'application/octet-stream',contentDisposition:'attachment'}); } return result; } async dispatch(batch,config){ let transport,sending=false; try{ if(batch.channelId&&batch.channelId!==config.channelId){ this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。');return; } const attachments=await this.attachments(batch,config); if(this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。'); const channel=freeze(structuredClone(this.mail.store.channelSecret(config.channelId))); if(channel.readOnly)throw Error('只读邮箱不能用于分类通知发送。'); transport=this.mail.smtpFactory(channel.smtp); this.mail.clients?.add(transport); await transport.verify(); if(!this.ready()||this.store.settings().channelId!==config.channelId)throw Error('发送已暂停或配置已变更。'); if(this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。'); this.mail.store.guard(channel.id,channel.version); this.store.beginSending(batch.id);sending=true; const result=await transport.sendMail({from:{address:channel.email,name:channel.name},to:[...batch.to],cc:[...batch.cc],subject:batch.subject,text:batch.text,html:batch.html,attachments,messageId:`<${batch.id}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true}); const accepted=new Set((result?.accepted||[]).map(address=>String(address.address||address).toLowerCase())); const partial=result?.rejected?.length||[...batch.to,...batch.cc].some(address=>!accepted.has(address.toLowerCase())); this.store.finishSending(batch.id,partial?'unknown':'sent',partial?'部分收件人未被服务器接受,请核对邮件记录后处理。':'邮件服务器已接受全部收件人;最终送达请以邮件记录为准。'); }catch(error){ this.store.finishSending(batch.id,sending?'unknown':'failed',sending?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${error.code==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`); }finally{ try{transport?.close?.();}finally{if(transport)this.mail.clients?.delete(transport);} } } start(){ if(this.timer||this.stopped)return; this.timer=setInterval(()=>this.tick().catch(()=>{}),30000);this.timer.unref?.(); } async stop(){ this.stopped=true;clearInterval(this.timer);this.timer=null; if(this.running)await this.running.catch(()=>{}); } } module.exports={OrderRuleDispatcher};