using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using PARR.BLL.Services.Interfaces; using PARR.Common.Domain; using PARR.Constants; using PARR.NextRun.Services; using PARR.NextRun.Settings; namespace PARR.NextRun { /// /// Расчет nextRun по интервалу /// internal class NextRunIntervalService : INextRunIntervalService { private readonly WorkerSettings workerSettings; private readonly ILogger logger; private readonly IIntervalService intervalService; private readonly IServiceProvider serviceProvider; public NextRunIntervalService( WorkerSettings workerSettings, ILogger logger, IIntervalService intervalService, IServiceProvider serviceProvider ) { this.workerSettings = workerSettings; this.logger = logger; this.intervalService = intervalService; this.serviceProvider = serviceProvider; } public async Task StartAsync() { logger.LogInformation("Запуск сервиса рассчета времени следующего создания наряда (nextRun)"); await intervalService.IntervalInitAsync(async () => { using (var scope = serviceProvider.CreateScope()) { var nextRunUpdateService = scope.ServiceProvider.GetRequiredService(); await nextRunUpdateService.UpdateNextRunForTemplatesAsync( // фильтр, только просроченные шаблоны query => query.Where(t => t.NextRun < DateTimeOffset.UtcNow), () => new HistoryInitiator { InitiatorComment = "Обновлён NextRun (интервал)", InitiatorParrComponentId = ParrComponentsEnum.NextRun }, "Интервал" ); //var templateService = scope.ServiceProvider.GetRequiredService(); //var nextRunService = scope.ServiceProvider.GetRequiredService(); //var robotConfigurationService = scope.ServiceProvider.GetRequiredService(); //await HandlerAsync(templateService, nextRunService, robotConfigurationService); } }, workerSettings.RepeatEvery); } ///// ///// Рассчет следующей даты срабатываения ///// ///// //private async Task HandlerAsync(ITemplateService templateService, INextRunService nextRunService, IRobotConfigurationService robotConfigurationService) //{ // logger.LogInformation("Начинаю обновлять NextRun по расписанию"); // await UpdateNextRunAsync(templateService, nextRunService, robotConfigurationService); // logger.LogInformation($"Завершено обновление полей NextRun."); //} //private async Task UpdateNextRunAsync(ITemplateService templateService, INextRunService nextRunService, IRobotConfigurationService robotConfigurationService) //{ // // выбираем все шаблоны с просроченным nextRun в статусе Used // var templatesForUpdate = await templateService.Get() // .Include(t => t.RobotConfigurations) // .Where(t => // t.StatusTypeId == TemplateStatusTypeEnum.Used // && t.NextRun < DateTimeOffset.UtcNow // ).ToListAsync(); // logger.LogInformation("Найдено шаблонов в статусе Used с просроченным NextRun {count} шт.", templatesForUpdate.Count); // if (!templatesForUpdate.Any()) // return; // foreach (var template in templatesForUpdate) // { // var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false); // if (newNextRun.HasValue) // { // template.LastRun = template.NextRun; // template.NextRun = newNextRun.Value; // //так как nextRun обновился, пробуем поставить задание на обновление // var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, template); // robotConfigurationService.SetUpdateTaskStatusIfAllow(config); // } // else // { // logger.LogError("При расчете nextRun для шаблона {templateId}, '{templateName}', nextRun=null. Это значит что при расчете возникла ошибка.", template.Id, template.Name); // } // } // if (await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Обновлён NextRun", InitiatorParrComponentId = ParrComponentsEnum.NextRun })) // { // logger.LogInformation("Обновлены значения полей NextRun для шаблонов в статусе Used, {count} шт.", templatesForUpdate.Count); // } // else // { // logger.LogError("Ошибка при обновлении значений полей NextRun, для шаблонов в статусе Used, {count} шт.", templatesForUpdate.Count); // } //} } }