import { DashboardsService } from '@app/event-emitter/dashboards/dashboards.service'; import { Dashboard, Widget } from '@app/event-emitter/models/dashboard'; import { Injectable, Logger } from '@nestjs/common'; import { Cron, SchedulerRegistry } from '@nestjs/schedule'; import { CronJob } from 'cron'; export type Params = { query: any; // TODO: add type schedule: string; }; export type Report = { id: string; name: string; datetime: number; datetimeFormatted: string; params: Params; // query?, schedule?, etc TODO data: any; }; export type Job = { id: string; params: Params; }; export const WIDGET_TYPE = 'daily-eccm-v2'; export const JOB_PREFIX = 'daily_eccm_v2'; @Injectable() export class DailyEccmV2ReportService { private logger = new Logger(DailyEccmV2ReportService.name); private dashboardsService: DashboardsService; constructor(private schedulerRegistry: SchedulerRegistry) {} @Cron('* * * * *') async autoScanJobs() { this.logger.debug('Auto scan jobs started'); const dbs = this.getDashboardsService(); if (!dbs) { this.logger.warn('Dashboards service not initialized'); this.logger.debug('Auto scan jobs finished'); return; } const dashboards = await dbs.findDashboardsByWidgetType(WIDGET_TYPE); for (let i = 0; i < dashboards.length; i++) { const dashboard: Dashboard = dashboards[i]; for (let j = 0; j < dashboard.data.widgets.length; j++) { const widget = dashboard.data.widgets[j]; if (widget.type === WIDGET_TYPE) { const jobId = `${JOB_PREFIX}_${dashboard.id}_${widget.id}`; let cronJob = this.schedulerRegistry.getCronJob(jobId); if (!cronJob) { cronJob = new CronJob( widget.dataLoaderParams.schedule, async () => { this.logger.debug(`Cron job ${jobId} started`); // const report = await dbs.getReport(dashboard.id, widget.id); this.logger.debug(`Cron job ${jobId} finished`); // return report; }, ); this.schedulerRegistry.addCronJob(jobId, cronJob); } } } } this.logger.debug('Auto scan jobs finished'); } getDashboardsService(): DashboardsService | null { if (!this.dashboardsService) { this.logger.warn('Dashboards service not initialized'); return null; } return this.dashboardsService; } setDashboardsService(dashboardsService: DashboardsService) { this.dashboardsService = dashboardsService; } private createJobHandler( jobId: string, dashboard: Dashboard, widget: Widget, ): () => void { return async () => { this.logger.debug(`Cron job ${jobId} started`); this.logger.debug(`Cron job ${jobId} finished`); }; } }