230 lines
11 KiB
C#
230 lines
11 KiB
C#
using AutoMapper;
|
||
using Microsoft.AspNetCore.Mvc;
|
||
using Microsoft.EntityFrameworkCore;
|
||
using PARR.API.Contracts.V1;
|
||
using PARR.API.Contracts.V1.Requests;
|
||
using PARR.API.Contracts.V1.Requests.Queries;
|
||
using PARR.API.Contracts.V1.Responses;
|
||
using PARR.API.Contracts.V1.Responses.Base;
|
||
using PARR.API.Controllers.V1.Base;
|
||
using PARR.API.Extensions;
|
||
using PARR.BLL.Helpers;
|
||
using PARR.Constants;
|
||
using PARR.DAL.Contracts;
|
||
using PARR.DAL.DomainModels;
|
||
using PARR.DAL.Models;
|
||
using PARR.DAL.Services.Interfaces;
|
||
|
||
namespace PARR.API.Controllers.V1
|
||
{
|
||
public class TemplateController : BaseApiController
|
||
{
|
||
private readonly IMapper mapper;
|
||
private readonly ITemplateService templateService;
|
||
private readonly SettingsFromDb settingsFromDb;
|
||
private readonly IRobotConfigurationService robotConfigurationService;
|
||
|
||
public TemplateController(
|
||
IMapper mapper,
|
||
ITemplateService templateService,
|
||
SettingsFromDb settingsFromDb,
|
||
IRobotConfigurationService robotConfigurationService
|
||
)
|
||
{
|
||
this.mapper = mapper;
|
||
this.templateService = templateService;
|
||
this.settingsFromDb = settingsFromDb;
|
||
this.robotConfigurationService = robotConfigurationService;
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// Получить список всех шаблонов постранично
|
||
/// </summary>
|
||
/// <param name="paginationQuery"></param>
|
||
/// <returns></returns>
|
||
[HttpGet(ApiRoutes.Template.GetAll)]
|
||
public async Task<IActionResult> GetAll([FromQuery] PaginationQuery paginationQuery, [FromQuery] TemplateQuery filter)
|
||
{
|
||
var paginationFilter = mapper.Map<PaginationFilter>(paginationQuery);
|
||
|
||
IQueryable<Template> query = templateService.GetWithIncludes()
|
||
.Include(t => t.RobotConfigurations).ThenInclude(t => t.Robot)
|
||
.Include(t => t.RobotConfigurations).ThenInclude(t => t.TaskStatus)
|
||
.Include(t => t.RobotConfigurations).ThenInclude(t => t.RobotStatus)
|
||
.OrderBy(t => t.Name)
|
||
.AsSplitQuery();
|
||
|
||
|
||
if (!string.IsNullOrEmpty(filter.Mask))
|
||
query = query.Where(t => EF.Functions.Like(t.Name.ToLower(), SqlHelpers.RegexToLike(filter.Mask)));
|
||
|
||
var templates = await templateService.GetPage(query, paginationFilter).ToListAsync();
|
||
|
||
if (!templates.Any())
|
||
return NoContent();
|
||
|
||
var templateResponse = mapper.Map<List<TemplateResponse>>(templates);
|
||
var paginationResponse = new PagedResponse<TemplateResponse>(templateResponse, true).GetPaginatedProps(paginationFilter, query);
|
||
|
||
return Ok(paginationResponse);
|
||
}
|
||
|
||
/// <summary>
|
||
/// Получить шаблон по id
|
||
/// </summary>
|
||
/// <param name="id"></param>
|
||
/// <returns></returns>
|
||
[HttpGet(ApiRoutes.Template.Get)]
|
||
public async Task<IActionResult> GetById([FromRoute] Guid id)
|
||
{
|
||
var template = await templateService.GetWithIncludes()
|
||
.Include(t => t.RobotConfigurations).ThenInclude(t => t.Robot)
|
||
.Include(t => t.RobotConfigurations).ThenInclude(t => t.TaskStatus)
|
||
.Include(t => t.RobotConfigurations).ThenInclude(t => t.RobotStatus)
|
||
.AsSplitQuery()
|
||
.FirstOrDefaultAsync(t => t.Id == id);
|
||
|
||
if (template == null)
|
||
return NotFound();
|
||
|
||
var response = mapper.Map<TemplateResponse>(template);
|
||
|
||
return Ok(new Response<TemplateResponse>(response, true));
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// Изменить статус у шаблона по ИД (активировать/деактивировать)
|
||
/// </summary>
|
||
/// <param name="id">ИД шаблона</param>
|
||
/// <returns></returns>
|
||
[HttpPut(ApiRoutes.Template.ChangeState)]
|
||
public async Task<IActionResult> ChangeState([FromRoute] Guid id, [FromBody] TemplateChangeStateRequest request)
|
||
{
|
||
var template = await templateService.GetWithIncludes()
|
||
.Include(t => t.RobotConfigurations).ThenInclude(t => t.Robot)
|
||
.Include(t => t.RobotConfigurations).ThenInclude(t => t.TaskStatus)
|
||
.Include(t => t.RobotConfigurations).ThenInclude(t => t.RobotStatus)
|
||
.AsSplitQuery()
|
||
.FirstOrDefaultAsync(t => t.Id == id);
|
||
|
||
if (template == null)
|
||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Не найден шаблона с id: {id}" } }));
|
||
|
||
if (template.IsActiveTemplate != request.IsActiveTemplate)
|
||
{
|
||
template.IsActiveTemplate = request.IsActiveTemplate;
|
||
//необходимо обновить шаблон
|
||
var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.TemplateOrder, ref template);
|
||
robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, ref config);
|
||
}
|
||
|
||
if (template.IsActiveSchedule != request.IsActiveSchedule)
|
||
{
|
||
template.IsActiveSchedule = request.IsActiveSchedule;
|
||
//необходимо обновить расписание
|
||
var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.ScheduleOrder, ref template);
|
||
robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, ref config);
|
||
}
|
||
|
||
if (!await templateService.CommitAsync())
|
||
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = "Ошибка при изменении шаблона." } }));
|
||
|
||
var templateToResponse = await templateService.GetWithIncludes()
|
||
.Include(t => t.RobotConfigurations).ThenInclude(t => t.Robot)
|
||
.Include(t => t.RobotConfigurations).ThenInclude(t => t.TaskStatus)
|
||
.Include(t => t.RobotConfigurations).ThenInclude(t => t.RobotStatus)
|
||
.AsSplitQuery()
|
||
.FirstOrDefaultAsync(t => t.Id == id);
|
||
|
||
var response = mapper.Map<TemplateResponse>(templateToResponse);
|
||
|
||
return Ok(new Response<TemplateResponse>(response, true));
|
||
}
|
||
|
||
/// <summary>
|
||
/// Получить один шаблон по заданному статусу
|
||
/// </summary>
|
||
/// <param name="statusCode"></param>
|
||
/// <returns></returns>
|
||
//[HttpGet(ApiRoutes.Template.GetByStatusCode)]
|
||
//public async Task<IActionResult> GetByStatus([FromRoute] int statusCode, [FromQuery] RobinQuery query)
|
||
//{
|
||
// Template? template = null;
|
||
|
||
// //1.Ищем `RobotStatusCode` = 22 и `RobotLastStatusUpdated` истекло и `RobotAttemptsNumber` >= допустимого значения из настроек,
|
||
// //ставим всем этим записям `RobotStatusCode`= 33
|
||
// //2.Поиск шаблонов со `StatusCode` 10 или 20 и `RobotStatusCode` = 11.Находим, **выбрали эту запись, конец**.
|
||
// //3.Поиск шаблонов со `StatusCode` 10 или 20 и `RobotStatusCode` = 22.
|
||
// //Далее проверяется `RobotLastStatusUpdated`, что время последнего смены статуса не превышает допустимого(берется из настроек, поле `RobotWaitTime`)
|
||
// //и что текущая попытка не больше разрешенной(берется из настроек, поле `RobotAttemptsNumber`) - если это так, берется эта запись.
|
||
|
||
// //1.
|
||
// await templateService.CheckAndSetErrorRobotStatusAsync(settingsFromDb.RobotAttemptsNumber, settingsFromDb.RobotWaitTime);
|
||
|
||
|
||
// //2.
|
||
// template = await templateService.GetWithIncludes()
|
||
// .AsSplitQuery()
|
||
// .FirstOrDefaultAsync(t => t.StatusCode == statusCode && t.RobotStatusCode == (int)RobotStatusEnum.Wait);
|
||
|
||
// //3.
|
||
// if (template == null)
|
||
// {
|
||
// var endDate = DateTimeOffset.UtcNow.Add(-settingsFromDb.RobotWaitTime);
|
||
// template = await templateService.GetWithIncludes()
|
||
// .AsSplitQuery()
|
||
// .FirstOrDefaultAsync(t =>
|
||
// t.StatusCode == statusCode
|
||
// && t.RobotStatusCode == (int)RobotStatusEnum.InProgress
|
||
// && t.RobotAttemptsNumber < settingsFromDb.RobotAttemptsNumber
|
||
// && t.RobotLastStatusUpdated < endDate
|
||
// );
|
||
// }
|
||
|
||
|
||
// if (template == null)
|
||
// return NotFound();
|
||
|
||
// var response = mapper.Map<TemplateResponse>(template);
|
||
|
||
// if (query.Robin == true)
|
||
// {
|
||
// var stringResponse = mapper.Map<TemplateStringResponse>(response);
|
||
// return Ok(stringResponse);
|
||
// }
|
||
|
||
// return Ok(new Response<TemplateResponse>(response, true));
|
||
//}
|
||
|
||
|
||
/// <summary>
|
||
/// Установить статус ОК для шаблона с id
|
||
/// </summary>
|
||
/// <param name="id"></param>
|
||
/// <returns></returns>
|
||
//[HttpPut(ApiRoutes.Template.SetOkStatus)]
|
||
//public async Task<IActionResult> SetOkStatus([FromRoute] Guid id)
|
||
//{
|
||
// var template = await templateService.GetWithIncludes()
|
||
// .AsSplitQuery()
|
||
// .FirstOrDefaultAsync(t => t.Id == id);
|
||
|
||
// if (template == null)
|
||
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Не найден шаблон с id: {id}" } }));
|
||
|
||
// template.StatusCode = (int)TaskStatusEnum.Ok;
|
||
|
||
// if (!await templateService.CommitAsync())
|
||
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при изменении статуса у шаблона с id: {id}" } }));
|
||
|
||
// var response = mapper.Map<TemplateResponse>(template);
|
||
|
||
// return Ok(new Response<TemplateResponse>(response, true));
|
||
//}
|
||
|
||
|
||
}
|
||
}
|