feat(dal, esppSync, nextRun): При синхронизации расписаний и шаблонов, при расчете nextRun в NextRunWorker - установить задание на обновление объекта, можно только если объект в статусе Ок. NextRunWorker - рефакторинг.

This commit is contained in:
Mikhail Trubnikov
2026-03-11 12:10:11 +10:00
parent 8cfccd7671
commit b9d1f923b3
10 changed files with 359 additions and 175 deletions

View File

@@ -500,7 +500,8 @@ namespace PARR.DAL.Context
new() { Id = ParrComponentsEnum.Master, Name = ParrComponentsEnum.Master.ToString(), Description = "Связывание нарядов ЕСПП с ПАРР (шаблонами, агентами)" }, new() { Id = ParrComponentsEnum.Master, Name = ParrComponentsEnum.Master.ToString(), Description = "Связывание нарядов ЕСПП с ПАРР (шаблонами, агентами)" },
new() { Id = ParrComponentsEnum.NextRun, Name = ParrComponentsEnum.NextRun.ToString(), Description = "Рассчет даты следующего срабатывания" }, new() { Id = ParrComponentsEnum.NextRun, Name = ParrComponentsEnum.NextRun.ToString(), Description = "Рассчет даты следующего срабатывания" },
new() { Id = ParrComponentsEnum.TemplateActivator, Name = ParrComponentsEnum.TemplateActivator.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 = "Генератор шаблонов" }
); );
}); });

View File

@@ -51,7 +51,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("TemplateId"); b.HasIndex("TemplateId");
b.ToTable("AgentHistories"); b.ToTable("AgentHistories", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.AgentHistoryLevel", b => modelBuilder.Entity("PARR.DAL.Models.AgentHistoryLevel", b =>
@@ -72,7 +72,7 @@ namespace PARR.DAL.Migrations
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("AgentHistoryLevels"); b.ToTable("AgentHistoryLevels", (string)null);
b.HasData( b.HasData(
new new
@@ -101,7 +101,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("WorkGroupId"); b.HasIndex("WorkGroupId");
b.ToTable("AppInWorkInWorkGroups"); b.ToTable("AppInWorkInWorkGroups", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.Application", b => modelBuilder.Entity("PARR.DAL.Models.Application", b =>
@@ -130,7 +130,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("Name", "ApplicationTypeId") b.HasIndex("Name", "ApplicationTypeId")
.IsUnique(); .IsUnique();
b.ToTable("Applications"); b.ToTable("Applications", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.ApplicationInHost", b => modelBuilder.Entity("PARR.DAL.Models.ApplicationInHost", b =>
@@ -157,7 +157,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("HostId"); b.HasIndex("HostId");
b.ToTable("ApplicationsInHost"); b.ToTable("ApplicationsInHost", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.ApplicationType", b => modelBuilder.Entity("PARR.DAL.Models.ApplicationType", b =>
@@ -181,7 +181,7 @@ namespace PARR.DAL.Migrations
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("ApplicationTypes"); b.ToTable("ApplicationTypes", (string)null);
b.HasData( b.HasData(
new new
@@ -294,7 +294,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("WorkId", "ApplicationId") b.HasIndex("WorkId", "ApplicationId")
.IsUnique(); .IsUnique();
b.ToTable("ApplicationsInWorks"); b.ToTable("ApplicationsInWorks", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.DistributionPeriod", b => modelBuilder.Entity("PARR.DAL.Models.DistributionPeriod", b =>
@@ -397,7 +397,7 @@ namespace PARR.DAL.Migrations
b.HasKey("Code"); b.HasKey("Code");
b.ToTable("EkStatuses"); b.ToTable("EkStatuses", (string)null);
b.HasData( b.HasData(
new new
@@ -1516,7 +1516,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("WorkGroupId"); b.HasIndex("WorkGroupId");
b.ToTable("Hosts"); b.ToTable("Hosts", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.Job.Job", b => modelBuilder.Entity("PARR.DAL.Models.Job.Job", b =>
@@ -1909,7 +1909,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("TemplateId"); b.HasIndex("TemplateId");
b.ToTable("Orders"); b.ToTable("Orders", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.OrderStatus", b => modelBuilder.Entity("PARR.DAL.Models.OrderStatus", b =>
@@ -1930,7 +1930,7 @@ namespace PARR.DAL.Migrations
b.HasKey("Code"); b.HasKey("Code");
b.ToTable("OrderStatuses"); b.ToTable("OrderStatuses", (string)null);
b.HasData( b.HasData(
new new
@@ -1983,7 +1983,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("Name") b.HasIndex("Name")
.IsUnique(); .IsUnique();
b.ToTable("ParrComponents"); b.ToTable("ParrComponents", (string)null);
b.HasData( b.HasData(
new new
@@ -2090,7 +2090,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("EsppId") b.HasIndex("EsppId")
.IsUnique(); .IsUnique();
b.ToTable("Processes"); b.ToTable("Processes", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.ResponseArea", b => modelBuilder.Entity("PARR.DAL.Models.ResponseArea", b =>
@@ -2107,7 +2107,7 @@ namespace PARR.DAL.Migrations
b.HasKey("Code"); b.HasKey("Code");
b.ToTable("ResponseAreas"); b.ToTable("ResponseAreas", (string)null);
b.HasData( b.HasData(
new new
@@ -2233,7 +2233,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("Name") b.HasIndex("Name")
.IsUnique(); .IsUnique();
b.ToTable("Robots"); b.ToTable("Robots", (string)null);
b.HasData( b.HasData(
new new
@@ -2292,7 +2292,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("TemplateId", "TaskStatusCode"); b.HasIndex("TemplateId", "TaskStatusCode");
b.ToTable("RobotConfigurations"); b.ToTable("RobotConfigurations", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.RobotHistory", b => modelBuilder.Entity("PARR.DAL.Models.RobotHistory", b =>
@@ -2330,7 +2330,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("TaskStatusCode"); b.HasIndex("TaskStatusCode");
b.ToTable("RobotHistories"); b.ToTable("RobotHistories", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.RobotHistoryLevel", b => modelBuilder.Entity("PARR.DAL.Models.RobotHistoryLevel", b =>
@@ -2351,7 +2351,7 @@ namespace PARR.DAL.Migrations
b.HasKey("Level"); b.HasKey("Level");
b.ToTable("RobotHistoryLevels"); b.ToTable("RobotHistoryLevels", (string)null);
b.HasData( b.HasData(
new new
@@ -2398,7 +2398,7 @@ namespace PARR.DAL.Migrations
b.HasKey("Code"); b.HasKey("Code");
b.ToTable("RobotStatuses"); b.ToTable("RobotStatuses", (string)null);
b.HasData( b.HasData(
new new
@@ -2446,7 +2446,7 @@ namespace PARR.DAL.Migrations
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("Roles"); b.ToTable("Roles", (string)null);
b.HasData( b.HasData(
new new
@@ -2615,7 +2615,7 @@ namespace PARR.DAL.Migrations
b.HasKey("Name"); b.HasKey("Name");
b.ToTable("Settings"); b.ToTable("Settings", (string)null);
b.HasData( b.HasData(
new new
@@ -2739,7 +2739,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("ProcessId"); b.HasIndex("ProcessId");
b.ToTable("Subprocesses"); b.ToTable("Subprocesses", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.TaskStatus", b => modelBuilder.Entity("PARR.DAL.Models.TaskStatus", b =>
@@ -2760,7 +2760,7 @@ namespace PARR.DAL.Migrations
b.HasKey("Code"); b.HasKey("Code");
b.ToTable("TaskStatuses"); b.ToTable("TaskStatuses", (string)null);
b.HasData( b.HasData(
new new
@@ -2846,7 +2846,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("Name", "Index") b.HasIndex("Name", "Index")
.IsUnique(); .IsUnique();
b.ToTable("Templates"); b.ToTable("Templates", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.TemplateHistory", b => modelBuilder.Entity("PARR.DAL.Models.TemplateHistory", b =>
@@ -2899,7 +2899,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("ParentId"); b.HasIndex("ParentId");
b.ToTable("TemplateHistories"); b.ToTable("TemplateHistories", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.TemplateStatusType", b => modelBuilder.Entity("PARR.DAL.Models.TemplateStatusType", b =>
@@ -2917,7 +2917,7 @@ namespace PARR.DAL.Migrations
b.HasKey("Id"); b.HasKey("Id");
b.ToTable("TemplateStatusTypes", t => b.ToTable("TemplateStatusTypes", null, t =>
{ {
t.HasComment("Таблица описания критериев выборки аттрибутов ЭК"); t.HasComment("Таблица описания критериев выборки аттрибутов ЭК");
}); });
@@ -2978,7 +2978,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("SubprocessId"); b.HasIndex("SubprocessId");
b.ToTable("Tnks"); b.ToTable("Tnks", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.Unit.Unit", b => modelBuilder.Entity("PARR.DAL.Models.Unit.Unit", b =>
@@ -3244,7 +3244,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("Ip") b.HasIndex("Ip")
.IsUnique(); .IsUnique();
b.ToTable("Users"); b.ToTable("Users", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.UsersInRole", b => modelBuilder.Entity("PARR.DAL.Models.UsersInRole", b =>
@@ -3259,7 +3259,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("UserId"); b.HasIndex("UserId");
b.ToTable("UsersInRoles"); b.ToTable("UsersInRoles", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.WeekendDay", b => modelBuilder.Entity("PARR.DAL.Models.WeekendDay", b =>
@@ -3299,7 +3299,7 @@ namespace PARR.DAL.Migrations
b.HasIndex("ResponseAreaCode"); b.HasIndex("ResponseAreaCode");
b.ToTable("WorkGroups"); b.ToTable("WorkGroups", (string)null);
}); });
modelBuilder.Entity("PARR.DAL.Models.AgentHistory", b => modelBuilder.Entity("PARR.DAL.Models.AgentHistory", b =>

View File

@@ -53,13 +53,14 @@ namespace PARR.DAL.Services.Implementations
// ставить статус Updating можно только если текущий статус == Ok // ставить статус Updating можно только если текущий статус == Ok
if (configuration.TaskStatusCode != (int)TaskStatusEnum.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; return false;
} }
// Статус ОК, можно ставить Updating // Статус ОК, можно ставить Updating
ChangeTaskStatus(updatingStatus, configuration); ChangeTaskStatus(updatingStatus, configuration);
logger.LogDebug("Установлен статус {newStatus} для конфигурации {configurationId}", updatingStatus, configuration.Id); logger.LogInformation("Установлен статус {newStatus} для конфигурации {configurationId}, templateId: {templateId}", updatingStatus, configuration.Id, configuration.TemplateId);
return true; return true;
} }

View File

@@ -138,7 +138,7 @@ namespace PARR.EsppScheduleSync
} }
else else
{ {
//ScheduleEsppId не нулл и не пустой, поизем по нему тоже //ScheduleEsppId не нулл и не пустой, поищем по нему тоже
query = query.Where(t => t.Name == esppTemplateName || t.ScheduleEsppId == esppScheduleId); query = query.Where(t => t.Name == esppTemplateName || t.ScheduleEsppId == esppScheduleId);
} }
@@ -163,7 +163,8 @@ namespace PARR.EsppScheduleSync
var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.TemplateOrder, templateByScheduleId); var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.TemplateOrder, templateByScheduleId);
logger.LogDebug("Текущий статус задания {taskStatusCode} шаблона {templateId}", config.TaskStatusCode, templateByScheduleId.Id); 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 = "Расхождение привязки, расписание из ЕСПП не соответствует имени шаблона в БД" })) if (!await templateService.CommitAsync(new HistoryInitiator { InitiatorParrComponentId = ParrComponentsEnum.EsppScheduleSync, InitiatorComment = "Расхождение привязки, расписание из ЕСПП не соответствует имени шаблона в БД" }))

View File

@@ -1,6 +1,7 @@
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using PARR.Common.Domain;
using PARR.Constants; using PARR.Constants;
using PARR.DAL.Contracts; using PARR.DAL.Contracts;
using PARR.DAL.DomainServices.Shortcodes; using PARR.DAL.DomainServices.Shortcodes;
@@ -153,13 +154,21 @@ namespace PARR.EsppSync
// пусть даже Create завершился с ошибками, но раз он уже есть в ЕСПП, то изменим на Update, сбросим все счетчики и пусть попробует обновить и исправить все // пусть даже Create завершился с ошибками, но раз он уже есть в ЕСПП, то изменим на Update, сбросим все счетчики и пусть попробует обновить и исправить все
if (config.TaskStatusCode != (int)TaskStatusEnum.Updating) if (config.TaskStatusCode != (int)TaskStatusEnum.Updating)
{ {
SetUpdateStatus(ref template, robotConfigurationService, esppObject.Robot); //SetUpdateStatus(ref template, robotConfigurationService, esppObject.Robot);
//todo: инициатор!!! var isChangedStatus = robotConfigurationService.SetUpdateTaskStatusIfAllow(config);
if (!await templateService.CommitAsync())
logger.LogError("Не удалось изменить запись Template {TemplateName}, Robot: {Robot}", template.Name, esppObject.Robot); 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 else
logger.LogInformation("Установлен принудительный статус {TaskStatus}, Template {TemplateName}, Robot: {Robot}", TaskStatusEnum.Updating, template.Name, esppObject.Robot); {
logger.LogInformation("Нельзя установить статус Updating для шаблона {templateName}, так как текущий статус это запрещает.", template.Name);
}
} }
else else
{ {
@@ -178,7 +187,7 @@ namespace PARR.EsppSync
if (robotConfig.TaskStatusCode != (int)TaskStatusEnum.Ok) if (robotConfig.TaskStatusCode != (int)TaskStatusEnum.Ok)
{ {
robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Ok, robotConfig); robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Ok, robotConfig);
if (!await templateService.CommitAsync()) if (!await templateService.CommitAsync(GetInitiator()))
logger.LogError("Не удалось изменить запись Template {TemplateName}, Robot: {Robot}", template.Name, esppObject.Robot); logger.LogError("Не удалось изменить запись Template {TemplateName}, Robot: {Robot}", template.Name, esppObject.Robot);
else else
logger.LogInformation("Установлен принудительный статус {TaskStatus}, Template {TemplateName}, Robot: {Robot}", TaskStatusEnum.Ok, template.Name, esppObject.Robot); logger.LogInformation("Установлен принудительный статус {TaskStatus}, Template {TemplateName}, Robot: {Robot}", TaskStatusEnum.Ok, template.Name, esppObject.Robot);
@@ -193,6 +202,20 @@ namespace PARR.EsppSync
} }
/// <summary>
/// Получить инициатора изменений для сохранения в БД
/// </summary>
/// <returns></returns>
private IHistoryInitiator GetInitiator()
{
return new HistoryInitiator
{
InitiatorComment = "Обновление статуса синхронизации, SyncService.",
InitiatorParrComponentId = typeof(EsppObject).Name.Contains("Template") ? ParrComponentsEnum.EsppTemplateSync : ParrComponentsEnum.EsppScheduleSync
};
}
/// <summary> /// <summary>
/// Применяем шорткоды /// Применяем шорткоды
/// </summary> /// </summary>
@@ -221,17 +244,17 @@ namespace PARR.EsppSync
} }
/// <summary> ///// <summary>
/// Установить статус - Обновить ///// Установить статус - Обновить
/// </summary> ///// </summary>
/// <param name="template"></param> ///// <param name="template"></param>
/// <param name="robotConfigurationService"></param> ///// <param name="robotConfigurationService"></param>
/// <param name="robot"></param> ///// <param name="robot"></param>
private void SetUpdateStatus(ref Template template, IRobotConfigurationService robotConfigurationService, RobotsEnum robot) //private void SetUpdateStatus(ref Template template, IRobotConfigurationService robotConfigurationService, RobotsEnum robot)
{ //{
var robotConfig = robotConfigurationService.GetFromTemplateByRobotCode(robot, template); // var robotConfig = robotConfigurationService.GetFromTemplateByRobotCode(robot, template);
robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, robotConfig); // robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, robotConfig);
} //}
/// <summary> /// <summary>

View File

@@ -2,6 +2,7 @@
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using PARR.BLL; using PARR.BLL;
using PARR.DAL; using PARR.DAL;
using PARR.NextRun.Services;
using PARR.NextRun.Settings; using PARR.NextRun.Settings;
namespace PARR.NextRun namespace PARR.NextRun
@@ -19,6 +20,7 @@ namespace PARR.NextRun
services.AddTransient<INextRunIntervalService, NextRunIntervalService>(); services.AddTransient<INextRunIntervalService, NextRunIntervalService>();
services.AddTransient<INextRunRabbitService, NextRunRabbitService>(); services.AddTransient<INextRunRabbitService, NextRunRabbitService>();
services.AddTransient<INextRunUpdateService, NextRunUpdateService>();
} }

View File

@@ -1,12 +1,9 @@
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using PARR.BLL.Services.Interfaces; using PARR.BLL.Services.Interfaces;
using PARR.Common.Domain; using PARR.Common.Domain;
using PARR.Constants; using PARR.Constants;
using PARR.DAL.NextRunServices; using PARR.NextRun.Services;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
using PARR.NextRun.Settings; using PARR.NextRun.Settings;
namespace PARR.NextRun namespace PARR.NextRun
@@ -42,76 +39,89 @@ namespace PARR.NextRun
{ {
using (var scope = serviceProvider.CreateScope()) using (var scope = serviceProvider.CreateScope())
{ {
//var appInWorkService = scope.ServiceProvider.GetService<IApplicationsInWorkService>(); var nextRunUpdateService = scope.ServiceProvider.GetRequiredService<INextRunUpdateService>();
//var esppSchService = scope.ServiceProvider.GetService<IEsppScheduleTransformService>();
var templateService = scope.ServiceProvider.GetService<ITemplateService>();
var jobGroupService = scope.ServiceProvider.GetService<IJobGroupService>();
var nextRunService = scope.ServiceProvider.GetService<INextRunService>();
if (templateService == null || nextRunService == null || jobGroupService == null) await nextRunUpdateService.UpdateNextRunForTemplatesAsync(
throw new Exception($"Не смог получить серивс {nameof(ITemplateService)} или {nameof(INextRunService)} или {nameof(IJobGroupService)}"); // фильтр, только просроченные шаблоны
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<ITemplateService>();
//var nextRunService = scope.ServiceProvider.GetRequiredService<INextRunService>();
//var robotConfigurationService = scope.ServiceProvider.GetRequiredService<IRobotConfigurationService>();
//await HandlerAsync(templateService, nextRunService, robotConfigurationService);
} }
}, workerSettings.RepeatEvery); }, workerSettings.RepeatEvery);
} }
/// <summary> ///// <summary>
/// Рассчет следующей даты срабатываения ///// Рассчет следующей даты срабатываения
/// </summary> ///// </summary>
/// <returns></returns> ///// <returns></returns>
private async Task HandlerAsync(ITemplateService templateService, INextRunService nextRunService, IJobGroupService jobGroupService) //private async Task HandlerAsync(ITemplateService templateService, INextRunService nextRunService, IRobotConfigurationService robotConfigurationService)
{ //{
logger.LogInformation("Начинаю обновлять NextRun по расписанию"); // 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) //private async Task UpdateNextRunAsync(ITemplateService templateService, INextRunService nextRunService, IRobotConfigurationService robotConfigurationService)
{ //{
// выбираем все шаблоны с просроченным nextRun в статусе Used // // выбираем все шаблоны с просроченным nextRun в статусе Used
var templatesForUpdate = await templateService.Get() // var templatesForUpdate = await templateService.Get()
.Where(t => // .Include(t => t.RobotConfigurations)
t.StatusTypeId == TemplateStatusTypeEnum.Used // .Where(t =>
&& t.NextRun < DateTimeOffset.UtcNow // t.StatusTypeId == TemplateStatusTypeEnum.Used
).ToListAsync(); // && t.NextRun < DateTimeOffset.UtcNow
// ).ToListAsync();
logger.LogInformation("Найдено шаблонов в статусе Used с просроченным NextRun {count} шт.", templatesForUpdate.Count); // logger.LogInformation("Найдено шаблонов в статусе Used с просроченным NextRun {count} шт.", templatesForUpdate.Count);
if (!templatesForUpdate.Any()) // if (!templatesForUpdate.Any())
return; // return;
foreach (var template in templatesForUpdate) // foreach (var template in templatesForUpdate)
{ // {
var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false); // var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
if (newNextRun.HasValue) // if (newNextRun.HasValue)
{ // {
template.LastRun = template.NextRun; // template.LastRun = template.NextRun;
template.NextRun = newNextRun.Value; // template.NextRun = newNextRun.Value;
}
else
{
logger.LogError("При расчете nextRun для шаблона {templateId}, '{templateName}', nextRun=null. Это значит что при расчете возникла ошибка.", template.Id, template.Name);
}
}
if (await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Обновлён NextRun", InitiatorParrComponentId = ParrComponentsEnum.NextRun })) // //так как nextRun обновился, пробуем поставить задание на обновление
{ // var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, template);
logger.LogInformation("Обновлены значения полей NextRun для шаблонов в статусе Used, {count} шт.", templatesForUpdate.Count); // robotConfigurationService.SetUpdateTaskStatusIfAllow(config);
} // }
else // else
{ // {
logger.LogError("Ошибка при обновлении значений полей NextRun, для шаблонов в статусе Used, {count} шт.", templatesForUpdate.Count); // 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);
// }
//}

View File

@@ -3,11 +3,8 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using PARR.BLL.Domain.Mq; using PARR.BLL.Domain.Mq;
using PARR.BLL.Services.Interfaces; 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.DAL.Services.Interfaces.Job;
using PARR.NextRun.Services;
using PARR.NextRun.Settings; using PARR.NextRun.Settings;
namespace PARR.NextRun namespace PARR.NextRun
@@ -61,17 +58,29 @@ namespace PARR.NextRun
{ {
logger.LogInformation("Получили запрос: {message}", msg); logger.LogInformation("Получили запрос: {message}", msg);
var query = transformService.GetModelFromJson<NextRunUpdateMq>(msg); var queryMq = transformService.GetModelFromJson<NextRunUpdateMq>(msg);
if (query == null) if (queryMq == null)
return; return;
if (!await IsValidJobGroupAsync(query.JobGroupId)) if (!await IsValidJobGroupAsync(queryMq.JobGroupId))
{ {
logger.LogError("Не найдена группа работ с id: {jobGroupId}", query.JobGroupId); logger.LogError("Не найдена группа работ с id: {jobGroupId}", queryMq.JobGroupId);
return; return;
} }
await UpdateNextRunAsync(query); using (var scope = serviceProvider.CreateScope())
{
var nextRunUpdateService = scope.ServiceProvider.GetRequiredService<INextRunUpdateService>();
await nextRunUpdateService.UpdateNextRunForTemplatesAsync(
// фильтр по JobGroupId
query => query.Where(t => t.Job!.GroupId == queryMq.JobGroupId),
() => queryMq.Initiator,
$"RabbitMq_JobGroupId_{queryMq.JobGroupId}"
);
}
//await UpdateNextRunAsync(query);
} }
/// <summary> /// <summary>
@@ -90,74 +99,80 @@ namespace PARR.NextRun
} }
/// <summary> ///// <summary>
/// Обновить все NextRun в JobGroup ///// Обновить все NextRun в JobGroup
/// </summary> ///// </summary>
/// <param name="jobGroupId"></param> ///// <param name="jobGroupId"></param>
/// <returns></returns> ///// <returns></returns>
private async Task UpdateNextRunAsync(NextRunUpdateMq queryMq) //private async Task UpdateNextRunAsync(NextRunUpdateMq queryMq)
{ //{
using var scope = serviceProvider.CreateScope(); // using var scope = serviceProvider.CreateScope();
var templateService = scope.ServiceProvider.GetRequiredService<ITemplateService>(); // var templateService = scope.ServiceProvider.GetRequiredService<ITemplateService>();
var nextRunService = scope.ServiceProvider.GetRequiredService<INextRunService>(); // var nextRunService = scope.ServiceProvider.GetRequiredService<INextRunService>();
// var robotConfigurationService = scope.ServiceProvider.GetRequiredService<IRobotConfigurationService>();
// Берем шаблоны только в статусе Used // // Берем шаблоны только в статусе Used
var templates = await templateService.Get() // var templates = await templateService.Get()
.Where(t => // .Include(t => t.RobotConfigurations)
t.Job!.GroupId == queryMq.JobGroupId // .Where(t =>
&& t.StatusTypeId == TemplateStatusTypeEnum.Used // t.Job!.GroupId == queryMq.JobGroupId
).ToListAsync(); // && 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()) // if (!templates.Any())
return; // return;
var updatedTemplates = 0; // var updatedTemplates = 0;
foreach (var template in templates) // foreach (var template in templates)
{ // {
var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false); // var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
if (newNextRun == null) // if (newNextRun == null)
{ // {
logger.LogError("При расчете nextRun для шаблона {templateId}, {templateName} вернулся null", template.Id, template.Name); // logger.LogError("При расчете nextRun для шаблона {templateId}, {templateName} вернулся null", template.Id, template.Name);
continue; // continue;
} // }
if (template.NextRun != newNextRun) // if (template.NextRun != newNextRun)
{ // {
logger.LogInformation("Обновлен nextRun для шаблона {templateId}, {templateName}, newNextRun: {newNextRun}, oldNextRun: {oldNextRun}", // logger.LogInformation("Обновлен nextRun для шаблона {templateId}, {templateName}, newNextRun: {newNextRun}, oldNextRun: {oldNextRun}",
template.Id, template.Name, newNextRun, template.NextRun); // template.Id, template.Name, newNextRun, template.NextRun);
template.LastRun = template.NextRun; // template.LastRun = template.NextRun;
template.NextRun = newNextRun.Value; // template.NextRun = newNextRun.Value;
updatedTemplates++; // //так как nextRun обновился, пробуем поставить задание на обновление
} // var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, template);
else // robotConfigurationService.SetUpdateTaskStatusIfAllow(config);
{
logger.LogDebug("Не требуется обновлять nextRun для шаблона {templateId}, {templateName}. Рассчитанный и исходный равны. NextRun: {NextRun}",
template.Id, template.Name, template.NextRun);
}
}
if (updatedTemplates > 0) // updatedTemplates++;
{ // }
if (await templateService.CommitAsync(queryMq.Initiator)) // else
{ // {
logger.LogInformation("Успешно обновлены nextRun у {count} шаблонов, группа работ: {jobGroupId}", updatedTemplates, queryMq.JobGroupId); // logger.LogDebug("Не требуется обновлять nextRun для шаблона {templateId}, {templateName}. Рассчитанный и исходный равны. NextRun: {NextRun}",
} // template.Id, template.Name, template.NextRun);
else // }
{ // }
logger.LogError("При сохранении nextRun для шаблонов {count} шт, произошла ошибка при сохранении в БД. JobGroupId: {jobGroupId}", updatedTemplates, queryMq.JobGroupId);
} // if (updatedTemplates > 0)
} // {
else // if (await templateService.CommitAsync(queryMq.Initiator))
{ // {
logger.LogInformation("Для группы работ {jobGroupId}, все nextRun актуальны. Нечего обновлять.", queryMq.JobGroupId); // 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);
// }
//}
} }
} }

View File

@@ -0,0 +1,17 @@
using PARR.Common.Domain;
using PARR.DAL.Models;
namespace PARR.NextRun.Services
{
internal interface INextRunUpdateService
{
/// <summary>
/// Обновить NextRun для списка шаблонов
/// </summary>
/// <param name="filter">Фильтр выборки шаблонов</param>
/// <param name="getInitiator"></param>
/// <param name="operationName"></param>
/// <returns></returns>
Task UpdateNextRunForTemplatesAsync(Func<IQueryable<Template>, IQueryable<Template>> filter, Func<IHistoryInitiator> getInitiator, string operationName);
}
}

View File

@@ -0,0 +1,114 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Common.Domain;
using PARR.Constants;
using PARR.DAL.Models;
using PARR.DAL.NextRunServices;
using PARR.DAL.Services.Interfaces;
namespace PARR.NextRun.Services
{
internal class NextRunUpdateService : INextRunUpdateService
{
private readonly ILogger<NextRunUpdateService> logger;
private readonly ITemplateService templateService;
private readonly INextRunService nextRunService;
private readonly IRobotConfigurationService robotConfigurationService;
public NextRunUpdateService(
ILogger<NextRunUpdateService> logger,
ITemplateService templateService,
INextRunService nextRunService,
IRobotConfigurationService robotConfigurationService
)
{
this.logger = logger;
this.templateService = templateService;
this.nextRunService = nextRunService;
this.robotConfigurationService = robotConfigurationService;
}
public async Task UpdateNextRunForTemplatesAsync(Func<IQueryable<Template>, IQueryable<Template>> filter, Func<IHistoryInitiator> getInitiator, string operationName)
{
var query = templateService.Get()
.Include(t => t.RobotConfigurations)
.Where(t => t.StatusTypeId == TemplateStatusTypeEnum.Used);
var templates = await filter(query).ToListAsync();
logger.LogInformation("[{operationName}] Найдено шаблонов в статусе Used для обработки: {count}", operationName, templates.Count);
if (!templates.Any())
{
logger.LogInformation("[{operationName}] Шаблоны не найдены, выходим", operationName);
return;
}
var updatedCount = 0;
foreach (var template in templates)
{
var wasUpdated = await UpdateNextRunAsync(template);
if (wasUpdated)
updatedCount++;
}
if (updatedCount == 0)
{
logger.LogInformation("[{operationName}] Нет изменённых nextRun, сохранение не требуется", operationName);
return;
}
var initiator = getInitiator();
var commitResult = await templateService.CommitAsync(initiator);
if (commitResult)
logger.LogInformation("[{operationName}] Успешно обновлено {count} шаблонов", operationName, updatedCount);
else
logger.LogError("[{operationName}] Ошибка при сохранении {count} шаблонов в БД", operationName, updatedCount);
}
/// <summary>
/// Обновляет если надо nextRun для одного шаблона, если может, ставит задание на обновление
/// </summary>
/// <param name="template"></param>
/// <param name="nextRunService"></param>
/// <param name="robotConfigurationService"></param>
/// <param name="templateName"></param>
/// <param name="logger"></param>
/// <returns></returns>
private async Task<bool> UpdateNextRunAsync(Template template)
{
var newNextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
if (!newNextRun.HasValue)
{
logger.LogError("При расчете nextRun для шаблона {templateId}, '{templateName}' вернулся null. Это значит что при расчете возникла ошибка.", template.Id, template.Name);
return false;
}
if (template.NextRun == newNextRun.Value)
{
logger.LogDebug("NextRun для шаблона {templateId}, '{templateName}' не изменился: {nextRun}", template.Id, template.Name, newNextRun.Value);
return false;
}
logger.LogInformation("Обновление NextRun: шаблон {templateId}, '{templateName}'. Было: {oldNextRun}, стало: {newNextRun}", template.Id, template.Name, template.NextRun, newNextRun.Value);
template.LastRun = template.NextRun;
template.NextRun = newNextRun.Value;
//так как nextRun обновился, пробуем поставить задание на обновление
var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, template);
robotConfigurationService.SetUpdateTaskStatusIfAllow(config);
//шаблон изменен и нужен Commit
return true;
}
}
}