Merge branch 'robot-tasks' into dev
This commit is contained in:
@@ -7,6 +7,8 @@ using PARR.Core.Common.Interfaces;
|
||||
using PARR.Core.Services.MatchingStatusService;
|
||||
using PARR.Core.Services.NextRunServices;
|
||||
using PARR.Core.Services.NextRunServices.Subservices;
|
||||
using PARR.Core.Services.RobotTask.Implementations;
|
||||
using PARR.Core.Services.RobotTask.Interfaces;
|
||||
using PARR.Core.Services.Shortcodes;
|
||||
using PARR.Core.Services.Shortcodes.Handlers;
|
||||
using PARR.Core.Services.TaskServices.Handlers;
|
||||
@@ -78,8 +80,6 @@ namespace PARR.Core
|
||||
|
||||
#endregion
|
||||
|
||||
#region Services
|
||||
|
||||
#region Shortсodes
|
||||
|
||||
services.AddScoped<IShortcodeHandler, ConstantsShortcodeHandler>();
|
||||
@@ -97,10 +97,13 @@ namespace PARR.Core
|
||||
services.AddScoped<IShortcodesService, ShortcodesService>();
|
||||
#endregion
|
||||
|
||||
#region Services
|
||||
|
||||
services.AddTransient<IMatchingStatusService, MatchingStatusService>();
|
||||
|
||||
//services.AddScoped<IUserService, UserService>();
|
||||
services.AddScoped<IRobotTaskService, RobotTaskService>();
|
||||
|
||||
//services.AddScoped<IUserService, UserService>();
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
using AutoMapper;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PARR.Core.Repositories.Interfaces.Schedule;
|
||||
using PARR.Domain.DTOs.RobotTask;
|
||||
using PARR.Domain.Entities;
|
||||
|
||||
namespace PARR.Core.Infrastructure.Mapping.RobotTask.Resolvers
|
||||
{
|
||||
public class RobotTaskScheduleSchResolver : IValueResolver<RobotConfiguration, RobotTaskSchedule, List<RobotTaskScheduleSch>?>
|
||||
{
|
||||
private readonly IEsppSchTypeConfigRepository esppConfigRepository;
|
||||
private readonly ILogger<RobotTaskScheduleSchResolver> logger;
|
||||
|
||||
public RobotTaskScheduleSchResolver(
|
||||
IEsppSchTypeConfigRepository esppConfigRepository,
|
||||
ILogger<RobotTaskScheduleSchResolver> logger
|
||||
)
|
||||
{
|
||||
this.esppConfigRepository = esppConfigRepository;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
public List<RobotTaskScheduleSch>? Resolve(RobotConfiguration source, RobotTaskSchedule destination, List<RobotTaskScheduleSch>? destMember, ResolutionContext context)
|
||||
{
|
||||
var jobGroupId = source.Template!.Job!.GroupId;
|
||||
|
||||
var schedule = esppConfigRepository.GetEsppScheduleDto(jobGroupId);
|
||||
|
||||
if (schedule == null)
|
||||
{
|
||||
logger.LogError("RobotTaskScheduleSchResolver: Не смог замапить расписание для робота, так как оно null. JobGroupId: {JobGroupId}", jobGroupId);
|
||||
return null;
|
||||
}
|
||||
|
||||
var response = schedule.Values.Select(t => new RobotTaskScheduleSch
|
||||
{
|
||||
Order = t.Order,
|
||||
Type = t.Type.Name,
|
||||
TypeCode = t.Type.Id,
|
||||
Value = t.Value.Value
|
||||
}).OrderBy(t => t.Order).ToList();
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
using AutoMapper;
|
||||
using PARR.Core.Infrastructure.Mapping.RobotTask.Resolvers;
|
||||
using PARR.Domain.DTOs.RobotTask;
|
||||
using PARR.Domain.Entities;
|
||||
using PARR.Domain.Settings;
|
||||
|
||||
namespace PARR.Core.Infrastructure.Mapping.RobotTask
|
||||
{
|
||||
/// <summary>
|
||||
/// Маппинг RobotTask
|
||||
/// </summary>
|
||||
internal class RobotTaskMappingProfile : Profile
|
||||
{
|
||||
public RobotTaskMappingProfile()
|
||||
{
|
||||
|
||||
CreateMap<RobotConfiguration, RobotTaskBase>()
|
||||
.Include<RobotConfiguration, RobotTaskTemplate>()
|
||||
.Include<RobotConfiguration, RobotTaskSchedule>()
|
||||
.ForMember(d => d.TaskId, o => o.MapFrom(s => s.Id));
|
||||
|
||||
// Задание роботам, шаблоны
|
||||
CreateMap<RobotConfiguration, RobotTaskTemplate>()
|
||||
.ForMember(d => d.IsActive, o => o.MapFrom(s => s.Template!.IsActiveTemplate))
|
||||
//.ForMember(d => d.ClosingCode, o => o.MapFrom<RobotTaskTemplateClosingCodeResolver>())
|
||||
.ForMember(d => d.FullDescription, o => o.MapFrom(s => s.Template!.Job!.Group!.FullDescription))
|
||||
.ForMember(d => d.ShortDescription, o => o.MapFrom(s => s.Template!.Job!.Group!.ShortDescription))
|
||||
.ForMember(d => d.Solution, o => o.MapFrom(s => s.Template!.Job!.Group!.Solution))
|
||||
//ЗО берем у группы а не у хоста
|
||||
.ForMember(d => d.ResponseArea, o => o.MapFrom(s => s.Template!.Unit!.BaseFields!.ResponseArea))
|
||||
.ForMember(d => d.TemplateDuration, o => o.MapFrom(s => s.Template!.Job!.Group!.TemplateDuration))
|
||||
//.ForMember(d => d.Initiator, o => o.MapFrom<RobotTaskTemplateInitiatorResolver>())
|
||||
//.ForMember(d => d.Category, o => o.MapFrom<RobotTaskTemplateCategoryResolver>())
|
||||
.ForMember(d => d.WorkGroup, o => o.MapFrom(s => s.Template!.Job!.WorkGroupMask))
|
||||
.ForMember(d => d.Ek, o => o.MapFrom(s => s.Template!.Unit!.Name))
|
||||
.ForMember(d => d.Name, o => o.MapFrom(s => s.Template!.Name))
|
||||
.ForMember(d => d.ProcessName, o => o.MapFrom(s => s.Template!.Job!.Tnk!.Subprocess!.Process!.Name))
|
||||
.ForMember(d => d.ProcessEsppId, o => o.MapFrom(s => s.Template!.Job!.Tnk!.Subprocess!.Process!.EsppId))
|
||||
.ForMember(d => d.SubprocessName, o => o.MapFrom(s => s.Template!.Job!.Tnk!.Subprocess!.Name))
|
||||
.ForMember(d => d.SubprocessEsppId, o => o.MapFrom(s => s.Template!.Job!.Tnk!.Subprocess!.EsppId))
|
||||
.ForMember(d => d.TnkName, o => o.MapFrom(s => s.Template!.Job!.Tnk!.Name))
|
||||
.ForMember(d => d.TnkEsppId, o => o.MapFrom(s =>
|
||||
s.Template!.Job!.Tnk!.EsppId.HasValue
|
||||
? s.Template!.Job!.Tnk!.EsppId.Value.ToString()
|
||||
: string.Empty
|
||||
))
|
||||
.ForMember(d => d.WorkName, o => o.MapFrom(s => s.Template!.Job!.WorkName))
|
||||
.ForMember(d => d.ScheduleEsppId, o => o.MapFrom(s => s.Template!.ScheduleEsppId));
|
||||
|
||||
|
||||
// Задание роботам, расписания
|
||||
CreateMap<RobotConfiguration, RobotTaskSchedule>()
|
||||
.ForMember(d => d.EsppId, o => o.MapFrom(s => s.Template!.ScheduleEsppId))
|
||||
.ForMember(d => d.ScheduleName, o => o.MapFrom(s => s.Template!.Name))
|
||||
.ForMember(d => d.IsActive, o => o.MapFrom(s => s.Template!.IsActiveSchedule))
|
||||
.ForMember(d => d.ResponseArea, o => o.MapFrom(s => s.Template!.Unit!.BaseFields!.ResponseArea))
|
||||
.ForMember(d => d.TemplateName, o => o.MapFrom(s => s.Template!.Name))
|
||||
.ForMember(d => d.TemplateId, o => o.MapFrom(s => s.Template!.Id))
|
||||
.ForMember(d => d.WorkGroup, o => o.MapFrom(s => s.Template!.Job!.WorkGroupMask))
|
||||
.ForMember(d => d.Exclude, o => o.MapFrom(s => s.Template!.Job!.Group!.ScheduleExcludeType!.EsppName))
|
||||
.ForMember(d => d.ExcludeCalendar, o => o.MapFrom(s => s.Template!.Job!.Group!.ScheduleExcludeTypeCalendar != null ? s.Template!.Job!.Group!.ScheduleExcludeTypeCalendar.EsppName : null))
|
||||
//.ForMember(d => d.RepeatRange, o => o.MapFrom<RobotTaskScheduleRepeatRangeResolver>())
|
||||
.ForMember(d => d.ScheduleType, o => o.MapFrom(s =>
|
||||
s.Template!.Job!.Group!.EsppSchValues!.First()!.EsppSchTypeConfig!.EsppSchTypeSchedule!.Description))
|
||||
.ForMember(d => d.ScheduleTypeCode, o => o.MapFrom(s =>
|
||||
s.Template!.Job!.Group!.EsppSchValues!.First()!.EsppSchTypeConfig!.EsppSchTypeSchedule!.Id))
|
||||
.ForMember(d => d.Schedule, o => o.MapFrom<RobotTaskScheduleSchResolver>());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ namespace PARR.Core.Repositories.Interfaces
|
||||
/// <param name="robotAttemptsNumber"></param>
|
||||
/// <param name="robotWaitTime"></param>
|
||||
/// <returns></returns>
|
||||
Task FindUnfulfilledTaskAndSetRobotErrorStatusAsync(int robotAttemptsNumber, TimeSpan robotWaitTime);
|
||||
Task MarkExpiredTasksAsFailedAsync(int robotAttemptsNumber, TimeSpan robotWaitTime);
|
||||
|
||||
/// <summary>
|
||||
/// Получить конфигурацию из шаблона по RobotCode. У шаблона обязательно должен быть Include таблицы RobotConfiguration
|
||||
@@ -42,5 +42,12 @@ namespace PARR.Core.Repositories.Interfaces
|
||||
/// <param name="configuration"></param>
|
||||
/// <returns>true - если изменил статус, false - нельзя изменить статус</returns>
|
||||
bool SetUpdateTaskStatusIfAllow(RobotConfiguration configuration);
|
||||
|
||||
/// <summary>
|
||||
/// Атомарно установить статус задачи "В работе" если текущий статус "В ожидании".
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <returns></returns>
|
||||
Task<bool> SetInProgressStatusAsync(Guid id);
|
||||
}
|
||||
}
|
||||
|
||||
387
PARR.Core/Services/RobotTask/Implementations/RobotTaskService.cs
Normal file
387
PARR.Core/Services/RobotTask/Implementations/RobotTaskService.cs
Normal file
@@ -0,0 +1,387 @@
|
||||
using AutoMapper;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using PARR.BLL.Helpers;
|
||||
using PARR.Core.Repositories.Interfaces;
|
||||
using PARR.Core.Services.NextRunServices;
|
||||
using PARR.Core.Services.RobotTask.Interfaces;
|
||||
using PARR.Core.Services.Shortcodes;
|
||||
using PARR.Domain.DTOs.RobotTask;
|
||||
using PARR.Domain.Entities;
|
||||
using PARR.Domain.Entities.Base.History;
|
||||
using PARR.Domain.Enums;
|
||||
using PARR.Domain.Exceptions;
|
||||
using PARR.Domain.Settings;
|
||||
|
||||
namespace PARR.Core.Services.RobotTask.Implementations
|
||||
{
|
||||
internal class RobotTaskService : IRobotTaskService
|
||||
{
|
||||
/// <summary>
|
||||
/// Количество заданий которые рассматриваем для взятия в работу.
|
||||
/// </summary>
|
||||
private readonly int TakeTasks = 10;
|
||||
|
||||
private readonly ILogger<RobotTaskService> logger;
|
||||
private readonly IRobotConfigurationRepository robotConfigurationRepository;
|
||||
private readonly SettingsFromDb settingsFromDb;
|
||||
private readonly IRobotHistoryRepository robotHistoryRepository;
|
||||
private readonly IMapper mapper;
|
||||
private readonly IShortcodesService shortcodesService;
|
||||
private readonly INextRunService nextRunService;
|
||||
|
||||
public RobotTaskService(
|
||||
ILogger<RobotTaskService> logger,
|
||||
IRobotConfigurationRepository robotConfigurationRepository,
|
||||
SettingsFromDb settingsFromDb,
|
||||
IRobotHistoryRepository robotHistoryRepository,
|
||||
IMapper mapper,
|
||||
IShortcodesService shortcodesService,
|
||||
INextRunService nextRunService
|
||||
)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.robotConfigurationRepository = robotConfigurationRepository;
|
||||
this.settingsFromDb = settingsFromDb;
|
||||
this.robotHistoryRepository = robotHistoryRepository;
|
||||
this.mapper = mapper;
|
||||
this.shortcodesService = shortcodesService;
|
||||
this.nextRunService = nextRunService;
|
||||
}
|
||||
|
||||
|
||||
public async Task<RobotTaskTemplate> GetTemplateTaskAsync(TaskStatusEnum taskStatusCode, bool acquireTask, string? robotIp, string? robotId)
|
||||
{
|
||||
var templateTask = await GetTaskAsync(RobotsEnum.TemplateOrder, taskStatusCode, acquireTask, robotIp, robotId);
|
||||
|
||||
var task = mapper.Map<RobotTaskTemplate>(templateTask);
|
||||
|
||||
task = task with { FullDescription = NormalizeLineEndingsToCrlf(await shortcodesService.ApplyShortcodesAsync(task.FullDescription, templateTask.Template!)) };
|
||||
task = task with { ShortDescription = await shortcodesService.ApplyShortcodesAsync(task.ShortDescription, templateTask.Template!) };
|
||||
task = task with { Solution = NormalizeLineEndingsToCrlf(await shortcodesService.ApplyShortcodesAsync(task.Solution, templateTask.Template!)) };
|
||||
task = task with { TnkName = await shortcodesService.ApplyShortcodesAsync(task.TnkName, templateTask.Template!) };
|
||||
task = task with { WorkName = await shortcodesService.ApplyShortcodesAsync(task.WorkName, templateTask.Template!) };
|
||||
task = task with { WorkGroup = await shortcodesService.ApplyShortcodesAsync(task.WorkGroup, templateTask.Template!) };
|
||||
task = task with { ResponseArea = await shortcodesService.ApplyShortcodesAsync(task.ResponseArea, templateTask.Template!) };
|
||||
|
||||
task = task with { ClosingCode = settingsFromDb.ClosingCode };
|
||||
task = task with { Initiator = settingsFromDb.Initiator };
|
||||
task = task with { Category = settingsFromDb.Category };
|
||||
|
||||
return task;
|
||||
}
|
||||
|
||||
|
||||
public async Task<RobotTaskSchedule> GetScheduleTaskAsync(TaskStatusEnum taskStatusCode, bool acquireTask, string? robotIp, string? robotId, IHistoryInitiator historyInitiator)
|
||||
{
|
||||
var scheduleTask = await GetTaskAsync(RobotsEnum.ScheduleOrder, taskStatusCode, acquireTask, robotIp, robotId);
|
||||
|
||||
// Проверяем nextRun, lastRun, обновляем их
|
||||
|
||||
var resultUpdateNextRun = await UpdateNextRunAsync(scheduleTask, historyInitiator);
|
||||
if (!resultUpdateNextRun)
|
||||
{
|
||||
logger.LogError("Ошибка при расчете NextRun для templateId: {templateId}", scheduleTask.TemplateId);
|
||||
throw new NextRunException($"Ошибка при расчете NextRun для templateId: {scheduleTask.TemplateId}");
|
||||
}
|
||||
|
||||
var task = mapper.Map<RobotTaskSchedule>(scheduleTask);
|
||||
|
||||
task = task with { Timezone = settingsFromDb.EsppScheduleTimezone };
|
||||
task = task with { WorkGroup = await shortcodesService.ApplyShortcodesAsync(task.WorkGroup, scheduleTask.Template!) };
|
||||
task = task with { ResponseArea = await shortcodesService.ApplyShortcodesAsync(task.ResponseArea, scheduleTask.Template!) };
|
||||
|
||||
//nextRun в часовой зоне УЗ Робота ЕСПП
|
||||
var nextRunWithRobotTz = scheduleTask.Template!.NextRun.Add(nextRunService.GetEsppAccountOffset());
|
||||
//на всякий случай еще раз проверяем, что дата не устарела и отправляем задание
|
||||
if (nextRunWithRobotTz < DateTimeOffset.UtcNow)
|
||||
{
|
||||
logger.LogError("Ошибка при расчете NextRun для templateId: {templateId}, итоговое значение для робота, меньше чем сейчас {nextRunWithRobotTz}<{now}",
|
||||
task.TemplateId, nextRunWithRobotTz, DateTimeOffset.UtcNow);
|
||||
throw new NextRunException($"Ошибка при расчете NextRun для templateId: {scheduleTask.TemplateId}");
|
||||
}
|
||||
|
||||
task = task with { NextStart = EsppScheduleHelpers.GetNextRun(nextRunWithRobotTz) };
|
||||
task = task with { GenerationTime = EsppScheduleHelpers.GetGenerationTime(nextRunWithRobotTz) };
|
||||
|
||||
task = task with { RepeatRange = settingsFromDb.ScheduleRepeatRange };
|
||||
task = task with { };
|
||||
|
||||
return task;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Получить задачу для робота.
|
||||
/// Метод может генерировать исключения.
|
||||
/// </summary>
|
||||
/// <param name="robotCode"></param>
|
||||
/// <param name="taskStatusCode"></param>
|
||||
/// <param name="acquireTask">Взять в работу</param>
|
||||
/// <param name="robotIp"></param>
|
||||
/// <returns></returns>
|
||||
/// <exception cref="NotFoundException"></exception>
|
||||
private async Task<RobotConfiguration> GetTaskAsync(RobotsEnum robotCode, TaskStatusEnum taskStatusCode, bool acquireTask, string? robotIp, string? robotId)
|
||||
{
|
||||
// 1. Ищем все задания с превышенным кол-вом попыток и просроченным временем, ставим им статус ошибки
|
||||
await robotConfigurationRepository.MarkExpiredTasksAsFailedAsync(settingsFromDb.RobotAttemptsNumber, settingsFromDb.RobotWaitTime);
|
||||
|
||||
|
||||
// 2. Ищем доступные задания
|
||||
var availableTasks = await GetAvailableTasksAsync(robotCode, taskStatusCode);
|
||||
|
||||
if (availableTasks.Count == 0)
|
||||
throw new NotFoundException("Нет доступных заданий для робота");
|
||||
|
||||
Guid? acquiredTaskId = null;
|
||||
|
||||
if (acquireTask)
|
||||
{
|
||||
// Берем задание в работу, устанавливаем ей статус "В работе"
|
||||
acquiredTaskId = await AcquireTaskAsync(availableTasks, robotIp, robotId);
|
||||
|
||||
if (acquiredTaskId == null)
|
||||
throw new Exception($"Не удалось взять ни одну из доступных задач ({availableTasks.Count}) в работу");
|
||||
}
|
||||
else
|
||||
{
|
||||
// Берем первую задачу из списка доступных
|
||||
acquiredTaskId = availableTasks.First();
|
||||
logger.LogDebug("Задача не требует захвата, взята первая из доступных: {TaskId}", acquiredTaskId);
|
||||
}
|
||||
|
||||
|
||||
//3. Получаем задачу со всеми нужными инклудами в зависимости от типа робота
|
||||
var task = await GetTaskWithAllDataAsync(acquiredTaskId.Value, robotCode);
|
||||
|
||||
return task;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Получить список возможных заданий для взятия в работу.
|
||||
/// Кол-во заданй ограничено переменной TakeTasks
|
||||
/// </summary>
|
||||
/// <param name="robotCode"></param>
|
||||
/// <param name="taskStatusCode"></param>
|
||||
/// <returns></returns>
|
||||
private async Task<List<Guid>> GetAvailableTasksAsync(RobotsEnum robotCode, TaskStatusEnum taskStatusCode)
|
||||
{
|
||||
var query = robotConfigurationRepository.Get()
|
||||
.AsNoTracking()
|
||||
.Where(t => t.RobotCode == (int)robotCode && t.TaskStatusCode == (int)taskStatusCode);
|
||||
|
||||
// Если это задание для робота расписаний
|
||||
if (robotCode == RobotsEnum.ScheduleOrder)
|
||||
{
|
||||
// Выбираем только записи с созданными шаблонами (у которых статус 30), а только потом ищем у них расписания
|
||||
var createdTemplates = robotConfigurationRepository.Get()
|
||||
.Where(t => t.RobotCode == (int)RobotsEnum.TemplateOrder && t.TaskStatusCode == (int)TaskStatusEnum.Ok)
|
||||
.Select(t => t.TemplateId);
|
||||
|
||||
query = query.Where(t => createdTemplates.Contains(t.TemplateId));
|
||||
}
|
||||
|
||||
// Сортируем по nextRun, чтобы те, у кого nextRun ближе к текущей, выполнились скорее
|
||||
query = query.OrderBy(t => t.Template!.NextRun).ThenBy(t => t.Template!.IsActiveSchedule).ThenBy(t => t.Template!.IsActiveTemplate);
|
||||
|
||||
// Кандидаты заданий
|
||||
var tasks = new List<Guid>();
|
||||
|
||||
// Ещем первые 10 заданий в статусе ОЖИДАНИЕ
|
||||
tasks = await query.Where(t => t.RobotStatusCode == (int)RobotStatusEnum.Wait).Take(TakeTasks).Select(t => t.Id).ToListAsync();
|
||||
|
||||
logger.LogDebug("Найдено заданий в статусе 'Ожидание' {Count} шт. Робот '{Robot}'", tasks.Count, robotCode.ToString());
|
||||
|
||||
if (tasks.Count == 0)
|
||||
{
|
||||
// Ищем задания в статусе В РАБОТЕ, которые можно перезапустить
|
||||
// Поиск по `RobotStatusCode` = 22.
|
||||
// Далее проверяется `LastStatusUpdated`, что время последнего смены статуса не превышает допустимого(берется из настроек, поле `RobotWaitTime`)
|
||||
// и что текущая попытка не больше разрешенной(берется из настроек, поле `RobotAttemptsNumber`) - если это так, берется эта запись.
|
||||
|
||||
var endDate = DateTimeOffset.UtcNow.Add(-settingsFromDb.RobotWaitTime);
|
||||
|
||||
tasks = await query.Where(t => t.RobotStatusCode == (int)RobotStatusEnum.InProgress
|
||||
&& t.AttemptsNumber < settingsFromDb.RobotAttemptsNumber
|
||||
&& t.LastRobotStatusUpdated < endDate)
|
||||
.Take(TakeTasks)
|
||||
.Select(t => t.Id)
|
||||
.ToListAsync();
|
||||
|
||||
logger.LogDebug("Найдено заданий в статусе 'В работе' {Count} шт. Робот '{Robot}'", tasks.Count, robotCode.ToString());
|
||||
}
|
||||
|
||||
return tasks;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Взять задачу в работу
|
||||
/// </summary>
|
||||
/// <param name="taskId"></param>
|
||||
/// <returns></returns>
|
||||
private async Task<Guid?> AcquireTaskAsync(List<Guid> tasks, string? robotIp, string? robotId)
|
||||
{
|
||||
foreach (var taskId in tasks)
|
||||
{
|
||||
var isChangedStatus = await robotConfigurationRepository.SetInProgressStatusAsync(taskId);
|
||||
if (isChangedStatus)
|
||||
{
|
||||
logger.LogDebug("Захвачена задача {TaskId}", taskId);
|
||||
|
||||
var task = await robotConfigurationRepository.Get()
|
||||
.AsNoTracking()
|
||||
.FirstAsync(t => t.Id == taskId);
|
||||
|
||||
// пишем в историю робота
|
||||
var history = new RobotHistory
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
HistoryLevel = (int)RobotHistoryLevelEnum.Start,
|
||||
TaskStatusCode = task.TaskStatusCode,
|
||||
RobotConfigurationId = taskId,
|
||||
RobotIp = robotIp,
|
||||
RobotId = robotId
|
||||
};
|
||||
|
||||
if (!await robotHistoryRepository.CreateAsync(history) || !await robotHistoryRepository.CommitAsync())
|
||||
throw new DbErrorException("Ошибка при добавлении истории робота, при взятии задания в работу.");
|
||||
|
||||
return taskId;
|
||||
}
|
||||
else
|
||||
{
|
||||
logger.LogDebug("Не удалось захватить задачу {TaskId}", taskId);
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogDebug("Не удалось захватить ни одну из доступных задач для робота");
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Получить задачу со всем необходимыми полями
|
||||
/// </summary>
|
||||
/// <param name="taskId"></param>
|
||||
/// <param name="robotCode"></param>
|
||||
/// <returns></returns>
|
||||
private async Task<RobotConfiguration> GetTaskWithAllDataAsync(Guid taskId, RobotsEnum robotCode)
|
||||
{
|
||||
IQueryable<RobotConfiguration> query = robotConfigurationRepository.Get()
|
||||
//.AsNoTracking() // нужно обязательно трекать, так как может измениться nextRun и его нужно будет сохранить
|
||||
.AsSingleQuery()
|
||||
// Общие инклуды для шаблонов и расписаний
|
||||
// Units
|
||||
.Include(t => t.Template)
|
||||
.ThenInclude(t => t!.Unit)
|
||||
.ThenInclude(t => t!.UnitValues)
|
||||
.ThenInclude(t => t!.Field)
|
||||
.Include(t => t.Template)
|
||||
.ThenInclude(t => t!.Unit)
|
||||
.ThenInclude(t => t!.UnitValues)
|
||||
.ThenInclude(t => t!.Value)
|
||||
.Include(t => t.Template)
|
||||
.ThenInclude(t => t!.UnitsInTemplate)
|
||||
// Группа с типом
|
||||
.Include(t => t.Template)
|
||||
.ThenInclude(t => t!.Job)
|
||||
.ThenInclude(t => t!.Group)
|
||||
.ThenInclude(t => t!.GroupType)
|
||||
// ТНК
|
||||
.Include(t => t.Template)
|
||||
.ThenInclude(t => t!.Job)
|
||||
.ThenInclude(t => t!.Tnk)
|
||||
.ThenInclude(t => t!.Subprocess)
|
||||
.ThenInclude(t => t!.Process);
|
||||
|
||||
if (robotCode == RobotsEnum.ScheduleOrder)
|
||||
{
|
||||
// Инклуды только для расписаний
|
||||
query = query
|
||||
// Расписание
|
||||
.Include(t => t.Template)
|
||||
.ThenInclude(t => t!.Job)
|
||||
.ThenInclude(t => t!.Group)
|
||||
.ThenInclude(t => t!.EsppSchValues)
|
||||
.ThenInclude(t => t!.EsppSchTypeConfig)
|
||||
.ThenInclude(t => t!.EsppSchTypeSchedule)
|
||||
// Исключения по типу
|
||||
.Include(t => t.Template)
|
||||
.ThenInclude(t => t!.Job)
|
||||
.ThenInclude(t => t!.Group)
|
||||
.ThenInclude(t => t!.ScheduleExcludeType)
|
||||
// Исключения по календарю
|
||||
.Include(t => t.Template)
|
||||
.ThenInclude(t => t!.Job)
|
||||
.ThenInclude(t => t!.Group)
|
||||
.ThenInclude(t => t!.ScheduleExcludeTypeCalendar);
|
||||
}
|
||||
|
||||
return await query.FirstAsync(t => t.Id == taskId);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Приводит переносы строк в тексте к формату CRLF (\r\n)
|
||||
/// </summary>
|
||||
/// <param name="text">Исходный текст</param>
|
||||
/// <returns>Текст с унифицированными переносами строк</returns>
|
||||
private string NormalizeLineEndingsToCrlf(string? text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
return string.Empty;
|
||||
|
||||
// Заменяем любые варианты переносов (\r\n, \r, \n) на единый \r\n
|
||||
return System.Text.RegularExpressions.Regex.Replace(text, @"\r\n|\r|\n", "\r\n");
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Обоновить NextRun если он устарел
|
||||
/// </summary>
|
||||
/// <param name="task"></param>
|
||||
/// <returns></returns>
|
||||
private async Task<bool> UpdateNextRunAsync(RobotConfiguration task, IHistoryInitiator historyInitiator)
|
||||
{
|
||||
var template = task.Template!;
|
||||
|
||||
//var nextRun = await esppScheduleTransformService.GetNextDateAsync(template.Job!.GroupId, template!.Job!.Group!.ReferenceDate);
|
||||
var nextRun = await nextRunService.GetNextRunForTemplateAsync(template.Id, false);
|
||||
|
||||
if (!nextRun.HasValue)
|
||||
{
|
||||
logger.LogError("При обновлении nextRun для шаблона {templateId}, расчитанный nextRun=null, ошибка в расчетах.", template.Id);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (nextRun.Value < DateTimeOffset.UtcNow)
|
||||
{
|
||||
logger.LogError("При обновлении nextRun для шаблона {templateId}, расчитанный nextRun<Now [{nextRun}<{now}], ошибка в расчетах.", template.Id, nextRun.Value, DateTimeOffset.UtcNow);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (nextRun != template.NextRun)
|
||||
{
|
||||
logger.LogDebug($"Для шаблона id {template.Id} обновляю nextRun, новое значение {nextRun}, старое значение {template.NextRun}");
|
||||
|
||||
template.LastRun = template.NextRun;
|
||||
template.NextRun = nextRun.Value;
|
||||
|
||||
var suffix = "При получении задания роботом, обновил NextRun";
|
||||
historyInitiator.InitiatorComment =
|
||||
string.IsNullOrEmpty(historyInitiator.InitiatorComment)
|
||||
? suffix
|
||||
: $"{historyInitiator.InitiatorComment}. {suffix}";
|
||||
|
||||
if (!await robotConfigurationRepository.CommitAsync(historyInitiator))
|
||||
throw new DbErrorException("Ошибка при сохранении изменения NextRun");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
35
PARR.Core/Services/RobotTask/Interfaces/IRobotTaskService.cs
Normal file
35
PARR.Core/Services/RobotTask/Interfaces/IRobotTaskService.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using PARR.Domain.DTOs.RobotTask;
|
||||
using PARR.Domain.Entities.Base.History;
|
||||
using PARR.Domain.Enums;
|
||||
|
||||
namespace PARR.Core.Services.RobotTask.Interfaces
|
||||
{
|
||||
/// <summary>
|
||||
/// Управление заданиями роботам
|
||||
/// </summary>
|
||||
public interface IRobotTaskService
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// Получить задание роботу - шаблоны.
|
||||
/// </summary>
|
||||
/// <param name="taskStatusCode"></param>
|
||||
/// <param name="acquireTask"></param>
|
||||
/// <param name="robotIp"></param>
|
||||
/// <param name="robotId"></param>
|
||||
/// <returns></returns>
|
||||
Task<RobotTaskTemplate> GetTemplateTaskAsync(TaskStatusEnum taskStatusCode, bool acquireTask, string? robotIp, string? robotId);
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Получить задание роботу - расписания.
|
||||
/// </summary>
|
||||
/// <param name="taskStatusCode"></param>
|
||||
/// <param name="acquireTask"></param>
|
||||
/// <param name="robotIp"></param>
|
||||
/// <param name="robotId"></param>
|
||||
/// <param name="historyInitiator"></param>
|
||||
/// <returns></returns>
|
||||
Task<RobotTaskSchedule> GetScheduleTaskAsync(TaskStatusEnum taskStatusCode, bool acquireTask, string? robotIp, string? robotId, IHistoryInitiator historyInitiator);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user