2023-09-15 16:32:46 +10:00
using AutoMapper ;
2023-12-04 10:16:00 +10:00
using Microsoft.AspNetCore.Authorization ;
2023-09-15 16:32:46 +10:00
using Microsoft.AspNetCore.Mvc ;
using Microsoft.EntityFrameworkCore ;
using PARR.API.Contracts.V1 ;
2023-10-13 14:21:49 +10:00
using PARR.API.Contracts.V1.Requests ;
2023-09-15 16:32:46 +10:00
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 ;
2023-09-26 12:26:37 +10:00
using PARR.BLL.Helpers ;
2023-11-22 12:04:33 +10:00
using PARR.Constants ;
2023-09-15 16:32:46 +10:00
using PARR.DAL.Contracts ;
using PARR.DAL.DomainModels ;
using PARR.DAL.Models ;
using PARR.DAL.Services.Interfaces ;
namespace PARR.API.Controllers.V1
{
2023-12-05 16:32:34 +10:00
/// <summary>
/// Шаблоны
/// </summary>
2023-12-04 10:16:00 +10:00
[Authorize(Roles = ParrRoles.Administrator.Role)]
2023-09-15 16:32:46 +10:00
public class TemplateController : BaseApiController
{
private readonly IMapper mapper ;
private readonly ITemplateService templateService ;
2023-10-04 12:00:43 +10:00
private readonly SettingsFromDb settingsFromDb ;
2023-10-13 14:21:49 +10:00
private readonly IRobotConfigurationService robotConfigurationService ;
2023-09-15 16:32:46 +10:00
public TemplateController (
IMapper mapper ,
2023-10-04 12:00:43 +10:00
ITemplateService templateService ,
2023-10-13 14:21:49 +10:00
SettingsFromDb settingsFromDb ,
IRobotConfigurationService robotConfigurationService
2023-09-15 16:32:46 +10:00
)
{
this . mapper = mapper ;
this . templateService = templateService ;
2023-10-04 12:00:43 +10:00
this . settingsFromDb = settingsFromDb ;
2023-10-13 14:21:49 +10:00
this . robotConfigurationService = robotConfigurationService ;
2023-09-15 16:32:46 +10:00
}
/// <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 ) ;
2023-09-19 16:42:06 +10:00
IQueryable < Template > query = templateService . GetWithIncludes ( )
2023-10-13 14:21:49 +10:00
. Include ( t = > t . RobotConfigurations ) . ThenInclude ( t = > t . Robot )
2023-10-06 15:13:40 +10:00
. Include ( t = > t . RobotConfigurations ) . ThenInclude ( t = > t . TaskStatus )
. Include ( t = > t . RobotConfigurations ) . ThenInclude ( t = > t . RobotStatus )
2023-09-26 12:26:37 +10:00
. OrderBy ( t = > t . Name )
. AsSplitQuery ( ) ;
2023-09-15 16:32:46 +10:00
2023-09-26 12:26:37 +10:00
if ( ! string . IsNullOrEmpty ( filter . Mask ) )
query = query . Where ( t = > EF . Functions . Like ( t . Name . ToLower ( ) , SqlHelpers . RegexToLike ( filter . Mask ) ) ) ;
2024-04-11 09:22:43 +10:00
if ( filter . AppInWorkId . HasValue )
query = query . Where ( t = > t . ApplicationInWorkId = = filter . AppInWorkId . Value ) ;
2023-09-15 16:32:46 +10:00
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>
2023-10-12 12:06:47 +10:00
[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 ) ;
2023-09-15 16:32:46 +10:00
2023-10-12 12:06:47 +10:00
if ( template = = null )
return NotFound ( ) ;
2023-09-15 16:32:46 +10:00
2023-10-12 12:06:47 +10:00
var response = mapper . Map < TemplateResponse > ( template ) ;
2023-09-15 16:32:46 +10:00
2023-10-12 12:06:47 +10:00
return Ok ( new Response < TemplateResponse > ( response , true ) ) ;
}
2023-09-15 16:32:46 +10:00
2023-10-13 14:21:49 +10:00
/// <summary>
/// Изменить статус у шаблона по ИД (активировать/деактивировать)
/// </summary>
2023-10-17 10:53:02 +10:00
/// <param name="id">ИД шаблона</param>
2023-10-13 14:21:49 +10:00
/// <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 ) ) ;
}
2023-09-15 16:32:46 +10:00
/// <summary>
/// Получить один шаблон по заданному статусу
/// </summary>
/// <param name="statusCode"></param>
/// <returns></returns>
2023-10-06 14:24:58 +10:00
//[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));
//}
2023-09-15 16:32:46 +10:00
/// <summary>
/// Установить статус О К для шаблона с id
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
2023-10-06 14:24:58 +10:00
//[HttpPut(ApiRoutes.Template.SetOkStatus)]
//public async Task<IActionResult> SetOkStatus([FromRoute] Guid id)
//{
// var template = await templateService.GetWithIncludes()
// .AsSplitQuery()
// .FirstOrDefaultAsync(t => t.Id == id);
2023-09-15 16:32:46 +10:00
2023-10-06 14:24:58 +10:00
// if (template == null)
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Н е найден шаблон с id: {id}" } }));
2023-09-15 16:32:46 +10:00
2023-10-06 14:24:58 +10:00
// template.StatusCode = (int)TaskStatusEnum.Ok;
2023-09-15 16:32:46 +10:00
2023-10-06 14:24:58 +10:00
// if (!await templateService.CommitAsync())
// return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { Message = $"Ошибка при изменении статуса у шаблона с id: {id}" } }));
2023-09-15 16:32:46 +10:00
2023-10-06 14:24:58 +10:00
// var response = mapper.Map<TemplateResponse>(template);
2023-09-15 16:32:46 +10:00
2023-10-06 14:24:58 +10:00
// return Ok(new Response<TemplateResponse>(response, true));
//}
2023-09-15 16:32:46 +10:00
}
}