'use strict'; const {today,AUTOMATIC_SNAPSHOT_LAST_SUCCESS,automaticSnapshotKey}=require('./ledger'); const TIME_ZONE='Asia/Shanghai',DAILY_TIME='23:50',RETRY_MS=60000; const recordDTO=value=>value&&typeof value.date==='string'&&typeof value.scheduledFor==='string'&&typeof value.savedAt==='string'?{date:value.date,scheduledFor:value.scheduledFor,savedAt:value.savedAt}:null; class InventorySnapshotScheduler{ constructor(ledger,{clock=()=>new Date(),logger=console.error,setTimer=setTimeout,clearTimer=clearTimeout}={}){ this.ledger=ledger;this.clock=clock;this.logger=logger;this.setTimer=setTimer;this.clearTimer=clearTimer; this.running=false;this.busy=false;this.timer=null;this.lastError=null;this.retry=null; } moment(){ const actual=new Date(this.clock()); if(!Number.isFinite(actual.getTime()))throw new Error('自动库存快照时钟无效'); const date=today(actual),scheduledFor=date+'T'+DAILY_TIME+':00+08:00'; return {actual,date,scheduledFor,dueAt:Date.parse(scheduledFor)}; } start(){if(this.running)return false;this.running=true;this.tick();this.arm();return true;} stop(){this.running=false;if(this.timer!==null)this.clearTimer(this.timer);this.timer=null;} arm(){ if(!this.running||this.timer!==null)return; const {actual,dueAt,date}=this.moment(),retryAt=this.retry?.date===date?this.retry.at:null; const target=actual.getTime()actual.getTime()?retryAt:actual.getTime()+RETRY_MS; this.timer=this.setTimer(()=>{this.timer=null;this.tick();this.arm();},Math.min(RETRY_MS,Math.max(1,target-actual.getTime()))); this.timer?.unref?.(); } tick(){ if(!this.running||this.busy)return {saved:false,reason:'stopped-or-busy'}; const {actual,date,dueAt}=this.moment(),instant=actual.getTime(); if(instant