diff --git a/PARR.DAL/Context/DataContext.cs b/PARR.DAL/Context/DataContext.cs index 3a90aeaf..6c7f2621 100644 --- a/PARR.DAL/Context/DataContext.cs +++ b/PARR.DAL/Context/DataContext.cs @@ -500,7 +500,8 @@ namespace PARR.DAL.Context new() { Id = ParrComponentsEnum.Master, Name = ParrComponentsEnum.Master.ToString(), Description = "Связывание нарядов ЕСПП с ПАРР (шаблонами, агентами)" }, new() { Id = ParrComponentsEnum.NextRun, Name = ParrComponentsEnum.NextRun.ToString(), Description = "Рассчет даты следующего срабатывания" }, new() { Id = ParrComponentsEnum.TemplateActivator, Name = ParrComponentsEnum.TemplateActivator.ToString(), Description = "Активатор шаблонов / расписаний" }, - new() { Id = ParrComponentsEnum.TemplateDistributor, Name = ParrComponentsEnum.TemplateDistributor.ToString(), Description = "Автораспределение РР" } + new() { Id = ParrComponentsEnum.TemplateDistributor, Name = ParrComponentsEnum.TemplateDistributor.ToString(), Description = "Автораспределение РР" }, + new() { Id = ParrComponentsEnum.TemplateTaskGenerator, Name = ParrComponentsEnum.TemplateTaskGenerator.ToString(), Description = "Генератор шаблонов" } ); }); diff --git a/PARR.DAL/Migrations/DataContextModelSnapshot.cs b/PARR.DAL/Migrations/DataContextModelSnapshot.cs index c012733a..ab7505ca 100644 --- a/PARR.DAL/Migrations/DataContextModelSnapshot.cs +++ b/PARR.DAL/Migrations/DataContextModelSnapshot.cs @@ -51,7 +51,7 @@ namespace PARR.DAL.Migrations b.HasIndex("TemplateId"); - b.ToTable("AgentHistories"); + b.ToTable("AgentHistories", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.AgentHistoryLevel", b => @@ -72,7 +72,7 @@ namespace PARR.DAL.Migrations b.HasKey("Id"); - b.ToTable("AgentHistoryLevels"); + b.ToTable("AgentHistoryLevels", (string)null); b.HasData( new @@ -101,7 +101,7 @@ namespace PARR.DAL.Migrations b.HasIndex("WorkGroupId"); - b.ToTable("AppInWorkInWorkGroups"); + b.ToTable("AppInWorkInWorkGroups", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.Application", b => @@ -130,7 +130,7 @@ namespace PARR.DAL.Migrations b.HasIndex("Name", "ApplicationTypeId") .IsUnique(); - b.ToTable("Applications"); + b.ToTable("Applications", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.ApplicationInHost", b => @@ -157,7 +157,7 @@ namespace PARR.DAL.Migrations b.HasIndex("HostId"); - b.ToTable("ApplicationsInHost"); + b.ToTable("ApplicationsInHost", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.ApplicationType", b => @@ -181,7 +181,7 @@ namespace PARR.DAL.Migrations b.HasKey("Id"); - b.ToTable("ApplicationTypes"); + b.ToTable("ApplicationTypes", (string)null); b.HasData( new @@ -294,7 +294,7 @@ namespace PARR.DAL.Migrations b.HasIndex("WorkId", "ApplicationId") .IsUnique(); - b.ToTable("ApplicationsInWorks"); + b.ToTable("ApplicationsInWorks", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.DistributionPeriod", b => @@ -397,7 +397,7 @@ namespace PARR.DAL.Migrations b.HasKey("Code"); - b.ToTable("EkStatuses"); + b.ToTable("EkStatuses", (string)null); b.HasData( new @@ -1516,7 +1516,7 @@ namespace PARR.DAL.Migrations b.HasIndex("WorkGroupId"); - b.ToTable("Hosts"); + b.ToTable("Hosts", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.Job.Job", b => @@ -1909,7 +1909,7 @@ namespace PARR.DAL.Migrations b.HasIndex("TemplateId"); - b.ToTable("Orders"); + b.ToTable("Orders", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.OrderStatus", b => @@ -1930,7 +1930,7 @@ namespace PARR.DAL.Migrations b.HasKey("Code"); - b.ToTable("OrderStatuses"); + b.ToTable("OrderStatuses", (string)null); b.HasData( new @@ -1983,7 +1983,7 @@ namespace PARR.DAL.Migrations b.HasIndex("Name") .IsUnique(); - b.ToTable("ParrComponents"); + b.ToTable("ParrComponents", (string)null); b.HasData( new @@ -2090,7 +2090,7 @@ namespace PARR.DAL.Migrations b.HasIndex("EsppId") .IsUnique(); - b.ToTable("Processes"); + b.ToTable("Processes", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.ResponseArea", b => @@ -2107,7 +2107,7 @@ namespace PARR.DAL.Migrations b.HasKey("Code"); - b.ToTable("ResponseAreas"); + b.ToTable("ResponseAreas", (string)null); b.HasData( new @@ -2233,7 +2233,7 @@ namespace PARR.DAL.Migrations b.HasIndex("Name") .IsUnique(); - b.ToTable("Robots"); + b.ToTable("Robots", (string)null); b.HasData( new @@ -2292,7 +2292,7 @@ namespace PARR.DAL.Migrations b.HasIndex("TemplateId", "TaskStatusCode"); - b.ToTable("RobotConfigurations"); + b.ToTable("RobotConfigurations", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.RobotHistory", b => @@ -2330,7 +2330,7 @@ namespace PARR.DAL.Migrations b.HasIndex("TaskStatusCode"); - b.ToTable("RobotHistories"); + b.ToTable("RobotHistories", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.RobotHistoryLevel", b => @@ -2351,7 +2351,7 @@ namespace PARR.DAL.Migrations b.HasKey("Level"); - b.ToTable("RobotHistoryLevels"); + b.ToTable("RobotHistoryLevels", (string)null); b.HasData( new @@ -2398,7 +2398,7 @@ namespace PARR.DAL.Migrations b.HasKey("Code"); - b.ToTable("RobotStatuses"); + b.ToTable("RobotStatuses", (string)null); b.HasData( new @@ -2446,7 +2446,7 @@ namespace PARR.DAL.Migrations b.HasKey("Id"); - b.ToTable("Roles"); + b.ToTable("Roles", (string)null); b.HasData( new @@ -2615,7 +2615,7 @@ namespace PARR.DAL.Migrations b.HasKey("Name"); - b.ToTable("Settings"); + b.ToTable("Settings", (string)null); b.HasData( new @@ -2739,7 +2739,7 @@ namespace PARR.DAL.Migrations b.HasIndex("ProcessId"); - b.ToTable("Subprocesses"); + b.ToTable("Subprocesses", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.TaskStatus", b => @@ -2760,7 +2760,7 @@ namespace PARR.DAL.Migrations b.HasKey("Code"); - b.ToTable("TaskStatuses"); + b.ToTable("TaskStatuses", (string)null); b.HasData( new @@ -2846,7 +2846,7 @@ namespace PARR.DAL.Migrations b.HasIndex("Name", "Index") .IsUnique(); - b.ToTable("Templates"); + b.ToTable("Templates", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.TemplateHistory", b => @@ -2899,7 +2899,7 @@ namespace PARR.DAL.Migrations b.HasIndex("ParentId"); - b.ToTable("TemplateHistories"); + b.ToTable("TemplateHistories", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.TemplateStatusType", b => @@ -2917,7 +2917,7 @@ namespace PARR.DAL.Migrations b.HasKey("Id"); - b.ToTable("TemplateStatusTypes", t => + b.ToTable("TemplateStatusTypes", null, t => { t.HasComment("Таблица описания критериев выборки аттрибутов ЭК"); }); @@ -2978,7 +2978,7 @@ namespace PARR.DAL.Migrations b.HasIndex("SubprocessId"); - b.ToTable("Tnks"); + b.ToTable("Tnks", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.Unit.Unit", b => @@ -3244,7 +3244,7 @@ namespace PARR.DAL.Migrations b.HasIndex("Ip") .IsUnique(); - b.ToTable("Users"); + b.ToTable("Users", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.UsersInRole", b => @@ -3259,7 +3259,7 @@ namespace PARR.DAL.Migrations b.HasIndex("UserId"); - b.ToTable("UsersInRoles"); + b.ToTable("UsersInRoles", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.WeekendDay", b => @@ -3299,7 +3299,7 @@ namespace PARR.DAL.Migrations b.HasIndex("ResponseAreaCode"); - b.ToTable("WorkGroups"); + b.ToTable("WorkGroups", (string)null); }); modelBuilder.Entity("PARR.DAL.Models.AgentHistory", b => diff --git a/PARR.DAL/Services/Implementations/RobotConfigurationService.cs b/PARR.DAL/Services/Implementations/RobotConfigurationService.cs index 17b81ad0..94815b9f 100644 --- a/PARR.DAL/Services/Implementations/RobotConfigurationService.cs +++ b/PARR.DAL/Services/Implementations/RobotConfigurationService.cs @@ -53,13 +53,14 @@ namespace PARR.DAL.Services.Implementations // ставить статус Updating можно только если текущий статус == Ok if (configuration.TaskStatusCode != (int)TaskStatusEnum.Ok) { - logger.LogDebug("Нельзя установить статус {newStatus} для конфигурации {configurationId}, так как текущий статус {currentStatus}", updatingStatus, configuration.Id, configuration.TaskStatusCode); + logger.LogInformation("Нельзя установить статус {newStatus} для конфигурации {configurationId}, templateId: {templateId}, так как текущий статус {currentStatus}", + updatingStatus, configuration.Id, configuration.TemplateId, configuration.TaskStatusCode); return false; } // Статус ОК, можно ставить Updating ChangeTaskStatus(updatingStatus, configuration); - logger.LogDebug("Установлен статус {newStatus} для конфигурации {configurationId}", updatingStatus, configuration.Id); + logger.LogInformation("Установлен статус {newStatus} для конфигурации {configurationId}, templateId: {templateId}", updatingStatus, configuration.Id, configuration.TemplateId); return true; } diff --git a/PARR.EsppScheduleSync/ScheduleSyncher.cs b/PARR.EsppScheduleSync/ScheduleSyncher.cs index 9477ef58..56617a03 100644 --- a/PARR.EsppScheduleSync/ScheduleSyncher.cs +++ b/PARR.EsppScheduleSync/ScheduleSyncher.cs @@ -138,7 +138,7 @@ namespace PARR.EsppScheduleSync } else { - //ScheduleEsppId не нулл и не пустой, поизем по нему тоже + //ScheduleEsppId не нулл и не пустой, поищем по нему тоже query = query.Where(t => t.Name == esppTemplateName || t.ScheduleEsppId == esppScheduleId); } @@ -163,7 +163,8 @@ namespace PARR.EsppScheduleSync var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.TemplateOrder, templateByScheduleId); logger.LogDebug("Текущий статус задания {taskStatusCode} шаблона {templateId}", config.TaskStatusCode, templateByScheduleId.Id); - robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, config); + //robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, config); + robotConfigurationService.SetUpdateTaskStatusIfAllow(config); // Сохраняем изменения в базу данных if (!await templateService.CommitAsync(new HistoryInitiator { InitiatorParrComponentId = ParrComponentsEnum.EsppScheduleSync, InitiatorComment = "Расхождение привязки, расписание из ЕСПП не соответствует имени шаблона в БД" })) diff --git a/PARR.EsppSync/SyncService.cs b/PARR.EsppSync/SyncService.cs index 63ac7379..d87f4d18 100644 --- a/PARR.EsppSync/SyncService.cs +++ b/PARR.EsppSync/SyncService.cs @@ -1,6 +1,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using PARR.Common.Domain; using PARR.Constants; using PARR.DAL.Contracts; using PARR.DAL.DomainServices.Shortcodes; @@ -153,13 +154,21 @@ namespace PARR.EsppSync // пусть даже Create завершился с ошибками, но раз он уже есть в ЕСПП, то изменим на Update, сбросим все счетчики и пусть попробует обновить и исправить все if (config.TaskStatusCode != (int)TaskStatusEnum.Updating) { - SetUpdateStatus(ref template, robotConfigurationService, esppObject.Robot); + //SetUpdateStatus(ref template, robotConfigurationService, esppObject.Robot); - //todo: инициатор!!! - if (!await templateService.CommitAsync()) - logger.LogError("Не удалось изменить запись Template {TemplateName}, Robot: {Robot}", template.Name, esppObject.Robot); + var isChangedStatus = robotConfigurationService.SetUpdateTaskStatusIfAllow(config); + + if (isChangedStatus) + { + if (!await templateService.CommitAsync(GetInitiator())) + logger.LogError("Не удалось изменить запись Template {TemplateName}, Robot: {Robot}", template.Name, esppObject.Robot); + else + logger.LogInformation("Установлен принудительный статус {TaskStatus}, Template {templateName}, Robot: {Robot}", TaskStatusEnum.Updating, template.Name, esppObject.Robot); + } else - logger.LogInformation("Установлен принудительный статус {TaskStatus}, Template {TemplateName}, Robot: {Robot}", TaskStatusEnum.Updating, template.Name, esppObject.Robot); + { + logger.LogInformation("Нельзя установить статус Updating для шаблона {templateName}, так как текущий статус это запрещает.", template.Name); + } } else { @@ -178,7 +187,7 @@ namespace PARR.EsppSync if (robotConfig.TaskStatusCode != (int)TaskStatusEnum.Ok) { robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Ok, robotConfig); - if (!await templateService.CommitAsync()) + if (!await templateService.CommitAsync(GetInitiator())) logger.LogError("Не удалось изменить запись Template {TemplateName}, Robot: {Robot}", template.Name, esppObject.Robot); else logger.LogInformation("Установлен принудительный статус {TaskStatus}, Template {TemplateName}, Robot: {Robot}", TaskStatusEnum.Ok, template.Name, esppObject.Robot); @@ -193,6 +202,20 @@ namespace PARR.EsppSync } + /// + /// Получить инициатора изменений для сохранения в БД + /// + /// + private IHistoryInitiator GetInitiator() + { + return new HistoryInitiator + { + InitiatorComment = "Обновление статуса синхронизации, SyncService.", + InitiatorParrComponentId = typeof(EsppObject).Name.Contains("Template") ? ParrComponentsEnum.EsppTemplateSync : ParrComponentsEnum.EsppScheduleSync + }; + } + + /// /// Применяем шорткоды /// @@ -221,17 +244,17 @@ namespace PARR.EsppSync } - /// - /// Установить статус - Обновить - /// - /// - /// - /// - private void SetUpdateStatus(ref Template template, IRobotConfigurationService robotConfigurationService, RobotsEnum robot) - { - var robotConfig = robotConfigurationService.GetFromTemplateByRobotCode(robot, template); - robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, robotConfig); - } + ///// + ///// Установить статус - Обновить + ///// + ///// + ///// + ///// + //private void SetUpdateStatus(ref Template template, IRobotConfigurationService robotConfigurationService, RobotsEnum robot) + //{ + // var robotConfig = robotConfigurationService.GetFromTemplateByRobotCode(robot, template); + // robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, robotConfig); + //} /// diff --git a/PARR.NextRun/NextRunInstaller.cs b/PARR.NextRun/NextRunInstaller.cs index 5a5bb1e2..8a3b03c5 100644 --- a/PARR.NextRun/NextRunInstaller.cs +++ b/PARR.NextRun/NextRunInstaller.cs @@ -2,6 +2,7 @@ using Microsoft.Extensions.DependencyInjection; using PARR.BLL; using PARR.DAL; +using PARR.NextRun.Services; using PARR.NextRun.Settings; namespace PARR.NextRun @@ -19,6 +20,7 @@ namespace PARR.NextRun services.AddTransient(); services.AddTransient(); + services.AddTransient(); } diff --git a/PARR.NextRun/NextRunIntervalService.cs b/PARR.NextRun/NextRunIntervalService.cs index 1eeba62b..094093e0 100644 --- a/PARR.NextRun/NextRunIntervalService.cs +++ b/PARR.NextRun/NextRunIntervalService.cs @@ -1,12 +1,9 @@ -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using PARR.BLL.Services.Interfaces; using PARR.Common.Domain; using PARR.Constants; -using PARR.DAL.NextRunServices; -using PARR.DAL.Services.Interfaces; -using PARR.DAL.Services.Interfaces.Job; +using PARR.NextRun.Services; using PARR.NextRun.Settings; namespace PARR.NextRun @@ -42,76 +39,89 @@ namespace PARR.NextRun { using (var scope = serviceProvider.CreateScope()) { - //var appInWorkService = scope.ServiceProvider.GetService(); - //var esppSchService = scope.ServiceProvider.GetService(); - var templateService = scope.ServiceProvider.GetService(); - var jobGroupService = scope.ServiceProvider.GetService(); - var nextRunService = scope.ServiceProvider.GetService(); + var nextRunUpdateService = scope.ServiceProvider.GetRequiredService(); - if (templateService == null || nextRunService == null || jobGroupService == null) - throw new Exception($"Не смог получить серивс {nameof(ITemplateService)} или {nameof(INextRunService)} или {nameof(IJobGroupService)}"); + await nextRunUpdateService.UpdateNextRunForTemplatesAsync( + // фильтр, только просроченные шаблоны + query => query.Where(t => t.NextRun < DateTimeOffset.UtcNow), + () => new HistoryInitiator + { + InitiatorComment = "Обновлён NextRun (интервал)", + InitiatorParrComponentId = ParrComponentsEnum.NextRun + }, + "Интервал" + ); - await HandlerAsync(templateService, nextRunService, jobGroupService); + //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, IJobGroupService jobGroupService) - { - logger.LogInformation("Начинаю обновлять NextRun по расписанию"); + ///// + ///// Рассчет следующей даты срабатываения + ///// + ///// + //private async Task HandlerAsync(ITemplateService templateService, INextRunService nextRunService, IRobotConfigurationService robotConfigurationService) + //{ + // logger.LogInformation("Начинаю обновлять NextRun по расписанию"); - await UpdateNextRunAsync(templateService, nextRunService, jobGroupService); + // await UpdateNextRunAsync(templateService, nextRunService, robotConfigurationService); - logger.LogInformation($"Завершено обновление полей NextRun."); - } + // logger.LogInformation($"Завершено обновление полей NextRun."); + //} - private async Task UpdateNextRunAsync(ITemplateService templateService, INextRunService nextRunService, IJobGroupService jobGroupService) - { - // выбираем все шаблоны с просроченным nextRun в статусе Used + //private async Task UpdateNextRunAsync(ITemplateService templateService, INextRunService nextRunService, IRobotConfigurationService robotConfigurationService) + //{ + // // выбираем все шаблоны с просроченным nextRun в статусе Used - var templatesForUpdate = await templateService.Get() - .Where(t => - t.StatusTypeId == TemplateStatusTypeEnum.Used - && t.NextRun < DateTimeOffset.UtcNow - ).ToListAsync(); + // 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); + // logger.LogInformation("Найдено шаблонов в статусе Used с просроченным NextRun {count} шт.", templatesForUpdate.Count); - if (!templatesForUpdate.Any()) - return; + // if (!templatesForUpdate.Any()) + // return; - foreach (var template in templatesForUpdate) - { - var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false); + // foreach (var template in templatesForUpdate) + // { + // var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false); - if (newNextRun.HasValue) - { - template.LastRun = template.NextRun; - template.NextRun = newNextRun.Value; - } - else - { - logger.LogError("При расчете nextRun для шаблона {templateId}, '{templateName}', nextRun=null. Это значит что при расчете возникла ошибка.", template.Id, template.Name); - } - } + // if (newNextRun.HasValue) + // { + // template.LastRun = template.NextRun; + // template.NextRun = newNextRun.Value; - 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); - } + // //так как 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); + // } + + //} diff --git a/PARR.NextRun/NextRunRabbitService.cs b/PARR.NextRun/NextRunRabbitService.cs index df58beb9..e5b9264c 100644 --- a/PARR.NextRun/NextRunRabbitService.cs +++ b/PARR.NextRun/NextRunRabbitService.cs @@ -3,11 +3,8 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using PARR.BLL.Domain.Mq; using PARR.BLL.Services.Interfaces; -using PARR.Common.Domain; -using PARR.Constants; -using PARR.DAL.NextRunServices; -using PARR.DAL.Services.Interfaces; using PARR.DAL.Services.Interfaces.Job; +using PARR.NextRun.Services; using PARR.NextRun.Settings; namespace PARR.NextRun @@ -61,17 +58,29 @@ namespace PARR.NextRun { logger.LogInformation("Получили запрос: {message}", msg); - var query = transformService.GetModelFromJson(msg); - if (query == null) + var queryMq = transformService.GetModelFromJson(msg); + if (queryMq == null) return; - if (!await IsValidJobGroupAsync(query.JobGroupId)) + if (!await IsValidJobGroupAsync(queryMq.JobGroupId)) { - logger.LogError("Не найдена группа работ с id: {jobGroupId}", query.JobGroupId); + logger.LogError("Не найдена группа работ с id: {jobGroupId}", queryMq.JobGroupId); return; } - await UpdateNextRunAsync(query); + using (var scope = serviceProvider.CreateScope()) + { + var nextRunUpdateService = scope.ServiceProvider.GetRequiredService(); + + await nextRunUpdateService.UpdateNextRunForTemplatesAsync( + // фильтр по JobGroupId + query => query.Where(t => t.Job!.GroupId == queryMq.JobGroupId), + () => queryMq.Initiator, + $"RabbitMq_JobGroupId_{queryMq.JobGroupId}" + ); + } + + //await UpdateNextRunAsync(query); } /// @@ -90,74 +99,80 @@ namespace PARR.NextRun } - /// - /// Обновить все NextRun в JobGroup - /// - /// - /// - private async Task UpdateNextRunAsync(NextRunUpdateMq queryMq) - { - using var scope = serviceProvider.CreateScope(); + ///// + ///// Обновить все NextRun в JobGroup + ///// + ///// + ///// + //private async Task UpdateNextRunAsync(NextRunUpdateMq queryMq) + //{ + // using var scope = serviceProvider.CreateScope(); - var templateService = scope.ServiceProvider.GetRequiredService(); - var nextRunService = scope.ServiceProvider.GetRequiredService(); + // var templateService = scope.ServiceProvider.GetRequiredService(); + // var nextRunService = scope.ServiceProvider.GetRequiredService(); + // var robotConfigurationService = scope.ServiceProvider.GetRequiredService(); - // Берем шаблоны только в статусе Used - var templates = await templateService.Get() - .Where(t => - t.Job!.GroupId == queryMq.JobGroupId - && t.StatusTypeId == TemplateStatusTypeEnum.Used - ).ToListAsync(); + // // Берем шаблоны только в статусе Used + // var templates = await templateService.Get() + // .Include(t => t.RobotConfigurations) + // .Where(t => + // t.Job!.GroupId == queryMq.JobGroupId + // && t.StatusTypeId == TemplateStatusTypeEnum.Used + // ).ToListAsync(); - logger.LogInformation("Найдено шаблонов {count} шт. в статусе Used в группе работ {jobGroupId}", templates.Count, queryMq.JobGroupId); + // logger.LogInformation("Найдено шаблонов {count} шт. в статусе Used в группе работ {jobGroupId}", templates.Count, queryMq.JobGroupId); - if (!templates.Any()) - return; + // if (!templates.Any()) + // return; - var updatedTemplates = 0; + // var updatedTemplates = 0; - foreach (var template in templates) - { - var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false); + // foreach (var template in templates) + // { + // var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false); - if (newNextRun == null) - { - logger.LogError("При расчете nextRun для шаблона {templateId}, {templateName} вернулся null", template.Id, template.Name); - continue; - } + // if (newNextRun == null) + // { + // logger.LogError("При расчете nextRun для шаблона {templateId}, {templateName} вернулся null", template.Id, template.Name); + // continue; + // } - if (template.NextRun != newNextRun) - { - logger.LogInformation("Обновлен nextRun для шаблона {templateId}, {templateName}, newNextRun: {newNextRun}, oldNextRun: {oldNextRun}", - template.Id, template.Name, newNextRun, template.NextRun); + // if (template.NextRun != newNextRun) + // { + // logger.LogInformation("Обновлен nextRun для шаблона {templateId}, {templateName}, newNextRun: {newNextRun}, oldNextRun: {oldNextRun}", + // template.Id, template.Name, newNextRun, template.NextRun); - template.LastRun = template.NextRun; - template.NextRun = newNextRun.Value; + // template.LastRun = template.NextRun; + // template.NextRun = newNextRun.Value; - updatedTemplates++; - } - else - { - logger.LogDebug("Не требуется обновлять nextRun для шаблона {templateId}, {templateName}. Рассчитанный и исходный равны. NextRun: {NextRun}", - template.Id, template.Name, template.NextRun); - } - } + // //так как nextRun обновился, пробуем поставить задание на обновление + // var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, template); + // robotConfigurationService.SetUpdateTaskStatusIfAllow(config); - if (updatedTemplates > 0) - { - if (await templateService.CommitAsync(queryMq.Initiator)) - { - logger.LogInformation("Успешно обновлены nextRun у {count} шаблонов, группа работ: {jobGroupId}", updatedTemplates, queryMq.JobGroupId); - } - else - { - logger.LogError("При сохранении nextRun для шаблонов {count} шт, произошла ошибка при сохранении в БД. JobGroupId: {jobGroupId}", updatedTemplates, queryMq.JobGroupId); - } - } - else - { - logger.LogInformation("Для группы работ {jobGroupId}, все nextRun актуальны. Нечего обновлять.", queryMq.JobGroupId); - } - } + // updatedTemplates++; + // } + // else + // { + // logger.LogDebug("Не требуется обновлять nextRun для шаблона {templateId}, {templateName}. Рассчитанный и исходный равны. NextRun: {NextRun}", + // template.Id, template.Name, template.NextRun); + // } + // } + + // if (updatedTemplates > 0) + // { + // if (await templateService.CommitAsync(queryMq.Initiator)) + // { + // logger.LogInformation("Успешно обновлены nextRun у {count} шаблонов, группа работ: {jobGroupId}", updatedTemplates, queryMq.JobGroupId); + // } + // else + // { + // logger.LogError("При сохранении nextRun для шаблонов {count} шт, произошла ошибка при сохранении в БД. JobGroupId: {jobGroupId}", updatedTemplates, queryMq.JobGroupId); + // } + // } + // else + // { + // logger.LogInformation("Для группы работ {jobGroupId}, все nextRun актуальны. Нечего обновлять.", queryMq.JobGroupId); + // } + //} } } diff --git a/PARR.NextRun/Services/INextRunUpdateService.cs b/PARR.NextRun/Services/INextRunUpdateService.cs new file mode 100644 index 00000000..9b0e58d1 --- /dev/null +++ b/PARR.NextRun/Services/INextRunUpdateService.cs @@ -0,0 +1,17 @@ +using PARR.Common.Domain; +using PARR.DAL.Models; + +namespace PARR.NextRun.Services +{ + internal interface INextRunUpdateService + { + /// + /// Обновить NextRun для списка шаблонов + /// + /// Фильтр выборки шаблонов + /// + /// + /// + Task UpdateNextRunForTemplatesAsync(Func, IQueryable