using Quartz; using eprintServer.Data; using eprintServer.Enums; using eprintServer.Entities; using Microsoft.EntityFrameworkCore; namespace eprintServer.Services; public class ReportSchedulerJob : IJob { private readonly IServiceProvider _serviceProvider; public ReportSchedulerJob(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public async Task Execute(IJobExecutionContext context) { // 1. Get the report type from the Quartz job data map var reportTypeStr = context.MergedJobDataMap.GetString("ReportType"); if (!Enum.TryParse(reportTypeStr, out var reportType)) return; using (var scope = _serviceProvider.CreateScope()) { var reportSettingsService = scope.ServiceProvider.GetRequiredService(); var statsService = scope.ServiceProvider.GetRequiredService(); var logger = scope.ServiceProvider.GetRequiredService>(); var settings = await reportSettingsService.GetOrInitializeSettingsAsync(); // 3. Check if the specific report toggle is enabled bool isEnabled = reportType switch { ReportDateEum.DAILY => settings.DailyReports, ReportDateEum.WEEKLY => settings.WeeklyReports, ReportDateEum.MONTHLY => settings.MonthlyReports, ReportDateEum.YEARLY => settings.YearlyReports, _ => false }; if (!isEnabled) { logger.LogInformation($"{reportType} reports are disabled in Admin Settings. Skipping."); return; } // 4. Validate the email list if (settings.AdminEmailList == null || !settings.AdminEmailList.Any()) { logger.LogWarning($"The Admin Email List is empty. No {reportType} reports sent."); return; } // 5. Loop through the list from settings and send foreach (var email in settings.AdminEmailList) { try { await statsService.ProcessAndSendReport(reportType, email); logger.LogInformation($"Successfully sent {reportType} report to {email}"); } catch (Exception ex) { logger.LogError(ex, $"Failed to send {reportType} report to {email}"); } } } } }