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 ;
2024-10-08 09:40:08 +10:00
using PARR.API.Services.Interfaces ;
2023-09-26 12:26:37 +10:00
using PARR.BLL.Helpers ;
2024-10-08 10:29:34 +10:00
using PARR.Common.Domain ;
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 ;
2026-01-13 14:36:07 +10:00
using PARR.DAL.DomainServices.Shortcodes ;
2023-09-15 16:32:46 +10:00
using PARR.DAL.Models ;
2026-02-03 16:15:19 +10:00
using PARR.DAL.NextRunServices ;
2023-09-15 16:32:46 +10:00
using PARR.DAL.Services.Interfaces ;
2026-02-04 09:50:30 +10:00
using PARR.DAL.Services.Interfaces.Schedule ;
2023-09-15 16:32:46 +10:00
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-13 14:21:49 +10:00
private readonly IRobotConfigurationService robotConfigurationService ;
2024-10-08 09:40:08 +10:00
private readonly IClientService clientService ;
2025-12-09 12:20:27 +10:00
private readonly ILogger < TemplateController > logger ;
2026-01-13 14:36:07 +10:00
private readonly IShortcodesService shortcodesService ;
2026-01-29 16:53:00 +10:00
private readonly IOrderService orderService ;
2026-02-03 16:15:19 +10:00
private readonly INextRunService nextRunService ;
2026-02-04 09:50:30 +10:00
private readonly SettingsFromDb settingsFromDb ;
private readonly IScheduleResponseAreaTimeOffsetService scheduleResponseAreaTimeOffsetService ;
2023-09-15 16:32:46 +10:00
public TemplateController (
IMapper mapper ,
2023-10-04 12:00:43 +10:00
ITemplateService templateService ,
2024-10-08 09:40:08 +10:00
IRobotConfigurationService robotConfigurationService ,
2025-12-09 12:20:27 +10:00
IClientService clientService ,
2026-01-13 14:36:07 +10:00
ILogger < TemplateController > logger ,
2026-01-29 16:53:00 +10:00
IShortcodesService shortcodesService ,
2026-02-03 16:15:19 +10:00
IOrderService orderService ,
2026-02-04 09:50:30 +10:00
INextRunService nextRunService ,
SettingsFromDb settingsFromDb ,
IScheduleResponseAreaTimeOffsetService scheduleResponseAreaTimeOffsetService
2023-09-15 16:32:46 +10:00
)
{
this . mapper = mapper ;
this . templateService = templateService ;
2023-10-13 14:21:49 +10:00
this . robotConfigurationService = robotConfigurationService ;
2024-10-08 09:40:08 +10:00
this . clientService = clientService ;
2025-12-09 12:20:27 +10:00
this . logger = logger ;
2026-01-13 14:36:07 +10:00
this . shortcodesService = shortcodesService ;
2026-01-29 16:53:00 +10:00
this . orderService = orderService ;
2026-02-03 16:15:19 +10:00
this . nextRunService = nextRunService ;
2026-02-04 09:50:30 +10:00
this . settingsFromDb = settingsFromDb ;
this . scheduleResponseAreaTimeOffsetService = scheduleResponseAreaTimeOffsetService ;
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 ) ;
2026-01-29 16:53:00 +10:00
//IQueryable<Template> query = templateService.GetWithIncludes().AsNoTracking()
// .Include(t => t.Unit).ThenInclude(t => t!.UnitValues).ThenInclude(t => t.Field)
// .Include(t => t.Unit).ThenInclude(t => t!.UnitValues).ThenInclude(t => t.Value)
// .Include(t => t.RobotConfigurations).ThenInclude(t => t.Robot)
// .Include(t => t.RobotConfigurations).ThenInclude(t => t.TaskStatus)
// .Include(t => t.RobotConfigurations).ThenInclude(t => t.RobotStatus)
// .Include(t => t.Orders)
// .Include(t => t.StatusType)
// .Include(t => t.Job).ThenInclude(t => t.Group).ThenInclude(t => t.ScheduleExcludeType)
// .Include(t => t.Job).ThenInclude(t => t.Group).ThenInclude(t => t.ScheduleExcludeTypeCalendar)
// .OrderBy(t => t.Name)
// .AsSplitQuery();
//var sw = Stopwatch.StartNew();
IQueryable < Template > query = templateService . Get ( )
. Include ( t = > t . Unit ) . ThenInclude ( t = > t ! . UnitValues ) . ThenInclude ( t = > t . Field )
. Include ( t = > t . Unit ) . ThenInclude ( t = > t ! . UnitValues ) . ThenInclude ( t = > t . Value )
. Include ( t = > t . StatusType )
. Include ( t = > t . Job ) . ThenInclude ( t = > t . Group )
. 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 )
. AsNoTracking ( ) ;
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 ) ) ) ;
2025-09-10 10:40:12 +10:00
if ( filter . JobId . HasValue )
query = query . Where ( t = > t . JobId = = filter . JobId ) ;
2024-04-11 09:22:43 +10:00
2025-12-02 09:49:08 +10:00
if ( filter . StatusTypeId . HasValue )
query = query . Where ( t = > t . StatusTypeId = = filter . StatusTypeId ) ;
2025-12-12 10:45:20 +10:00
#region С т а т у с с и н х р о н и з а ц и и
switch ( filter . SyncStatus )
{
case ( TemplateQuerySyncStatusEnum . Waiting ) :
query = query . Where ( t = > t . RobotConfigurations . Any ( x = > x . TaskStatusCode ! = ( int ) TaskStatusEnum . Ok ) ) ;
break ;
case ( TemplateQuerySyncStatusEnum . Complete ) :
query = query . Where ( t = > t . RobotConfigurations . All ( x = > x . TaskStatusCode = = ( int ) TaskStatusEnum . Ok ) ) ;
break ;
case ( TemplateQuerySyncStatusEnum . Error ) :
query = query . Where ( t = > t . RobotConfigurations . Any ( x = > x . RobotStatusCode = = ( int ) RobotStatusEnum . Error ) ) ;
break ;
default :
break ;
}
#endregion
2023-09-15 16:32:46 +10:00
var templates = await templateService . GetPage ( query , paginationFilter ) . ToListAsync ( ) ;
2026-01-29 16:53:00 +10:00
//logger.LogDebug("Загрузка шаблонов из БД: {ElapsedMs} мс", sw.ElapsedMilliseconds);
2023-09-15 16:32:46 +10:00
if ( ! templates . Any ( ) )
return NoContent ( ) ;
2026-01-29 16:53:00 +10:00
var templateResponse = mapper . Map < List < TemplateListResponse > > ( templates ) ;
// словари для быстрого поиска
var templatesDict = templates . ToDictionary ( t = > t . Id ) ;
var templateResponseDict = templateResponse . ToDictionary ( t = > t . Id ) ;
2026-02-03 16:15:19 +10:00
#region З а п о л н я е м ш о р т к о д ы и NextRunWithResponseAreaOffset
2026-01-29 16:53:00 +10:00
if ( filter . ApplyShortcode = = true )
2026-01-13 14:36:07 +10:00
{
2026-01-29 16:53:00 +10:00
//sw.Restart();
foreach ( var responseItem in templateResponse )
{
//await ApplyTemplateShortcodesAsync(responseItem, templates.First(t => t.Id == responseItem.Id));
await ApplyTemplateShortcodesAsync ( responseItem , templatesDict [ responseItem . Id ] ) ;
2026-02-04 09:11:35 +10:00
FillNextRunWithResponseAreaInLocal ( responseItem ) ;
2026-01-29 16:53:00 +10:00
}
//logger.LogDebug("Получение шорткодов: {ElapsedMs} мс", sw.ElapsedMilliseconds);
//sw.Stop();
2026-01-13 14:36:07 +10:00
}
2026-01-29 16:53:00 +10:00
#endregion
2026-01-13 14:36:07 +10:00
2026-01-29 16:53:00 +10:00
#region з а п о л н е н и е OrdersCount
var templatesWithOrdersCount = await GetOrdersCountAsync ( templates . Select ( t = > t . Id ) . ToList ( ) ) ;
foreach ( var ( templateId , orderCount ) in templatesWithOrdersCount )
{
if ( templateResponseDict . TryGetValue ( templateId , out var response ) )
response . OrderCount = orderCount ;
}
#endregion
var paginationResponse = new PagedResponse < TemplateListResponse > ( templateResponse , true ) . GetPaginatedProps ( paginationFilter , query ) ;
2023-09-15 16:32:46 +10:00
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 )
{
2025-06-27 13:42:13 +10:00
var template = await templateService . GetWithIncludes ( ) . AsNoTracking ( )
2023-10-12 12:06:47 +10:00
. Include ( t = > t . RobotConfigurations ) . ThenInclude ( t = > t . Robot )
. Include ( t = > t . RobotConfigurations ) . ThenInclude ( t = > t . TaskStatus )
. Include ( t = > t . RobotConfigurations ) . ThenInclude ( t = > t . RobotStatus )
2026-01-29 16:53:00 +10:00
//.Include(t => t.Orders)
2025-12-02 09:49:08 +10:00
. Include ( t = > t . StatusType )
2025-12-26 11:21:45 +10:00
. Include ( t = > t . Job ) . ThenInclude ( t = > t . Group ) . ThenInclude ( t = > t . ScheduleExcludeType )
. Include ( t = > t . Job ) . ThenInclude ( t = > t . Group ) . ThenInclude ( t = > t . ScheduleExcludeTypeCalendar )
2023-10-12 12:06:47 +10:00
. 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 ) ;
2026-01-13 14:36:07 +10:00
await ApplyTemplateShortcodesAsync ( response , template ) ;
2026-02-04 09:11:35 +10:00
FillNextRunWithResponseAreaInLocal ( response ) ;
2023-09-15 16:32:46 +10:00
2026-01-29 16:53:00 +10:00
var ordersCountResult = await GetOrdersCountAsync ( new List < Guid > { response . Id } ) ;
response . OrderCount = ordersCountResult . Count > 0 ? ordersCountResult . First ( ) . Value : 0 ;
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 )
{
2025-11-26 14:34:03 +10:00
//TODO:!!! Возможно тут не надо сразу менять, а отправить запрос в TemplateActivator и пусть он сам занимается своей работой!!!
2026-01-29 16:53:00 +10:00
#region old
//var template = await templateService.GetWithIncludes()
// //.Include(t => t.Unit).ThenInclude(t => t!.UnitValues).ThenInclude(t => t.Field)
// //.Include(t => t.Unit).ThenInclude(t => t!.UnitValues).ThenInclude(t => t.Value)
// .Include(t => t.RobotConfigurations).ThenInclude(t => t.Robot)
// .Include(t => t.RobotConfigurations).ThenInclude(t => t.TaskStatus)
// .Include(t => t.RobotConfigurations).ThenInclude(t => t.RobotStatus)
// .Include(t => t.Orders)
// .Include(t => t.StatusType)
// .Include(t => t.Job).ThenInclude(t => t.Group).ThenInclude(t => t.ScheduleExcludeType)
// .Include(t => t.Job).ThenInclude(t => t.Group).ThenInclude(t => t.ScheduleExcludeTypeCalendar)
// .AsSplitQuery()
// .FirstOrDefaultAsync(t => t.Id == id);
#endregion
2025-11-26 14:34:03 +10:00
2026-01-29 16:53:00 +10:00
var template = await templateService . Get ( )
. Include ( t = > t . RobotConfigurations )
. FirstOrDefaultAsync ( t = > t . Id = = id ) ;
2023-10-13 14:21:49 +10:00
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 ;
//необходимо обновить шаблон
2025-11-26 14:34:03 +10:00
var config = robotConfigurationService . GetFromTemplateByRobotCode ( RobotsEnum . TemplateOrder , template ) ;
robotConfigurationService . ChangeTaskStatus ( TaskStatusEnum . Updating , config ) ;
2023-10-13 14:21:49 +10:00
}
if ( template . IsActiveSchedule ! = request . IsActiveSchedule )
{
template . IsActiveSchedule = request . IsActiveSchedule ;
//необходимо обновить расписание
2025-11-26 14:34:03 +10:00
var config = robotConfigurationService . GetFromTemplateByRobotCode ( RobotsEnum . ScheduleOrder , template ) ;
robotConfigurationService . ChangeTaskStatus ( TaskStatusEnum . Updating , config ) ;
2023-10-13 14:21:49 +10:00
}
2024-10-08 10:29:34 +10:00
if ( ! await templateService . CommitAsync ( new HistoryInitiator { InitiatorComment = "Изменён статус шаблона/расписания" , InitiatorIp = clientService . GetClientIp ( ) ? . ToString ( ) , InitiatorParrComponentId = ParrComponentsEnum . Api } ) )
2023-10-13 14:21:49 +10:00
return BadRequest ( new Response ( false , new List < ErrorModel > { new ErrorModel { Message = "Ошибка при изменении шаблона." } } ) ) ;
2026-01-29 16:53:00 +10:00
#region old
//var templateToResponse = await templateService.GetWithIncludes().AsNoTracking()
// //.Include(t => t.Unit).ThenInclude(t => t.UnitValues).ThenInclude(t => t.Field)
// //.Include(t => t.Unit).ThenInclude(t => t.UnitValues).ThenInclude(t => t.Value)
// .Include(t => t.RobotConfigurations).ThenInclude(t => t.Robot)
// .Include(t => t.RobotConfigurations).ThenInclude(t => t.TaskStatus)
// .Include(t => t.RobotConfigurations).ThenInclude(t => t.RobotStatus)
// .Include(t => t.Orders)
// .Include(t => t.StatusType)
// .Include(t => t.Job).ThenInclude(t => t.Group).ThenInclude(t => t.ScheduleExcludeType)
// .Include(t => t.Job).ThenInclude(t => t.Group).ThenInclude(t => t.ScheduleExcludeTypeCalendar)
// .AsSplitQuery()
// .FirstAsync(t => t.Id == id);
//var response = mapper.Map<TemplateResponse>(templateToResponse);
//await ApplyTemplateShortcodesAsync(response, templateToResponse);
//return Ok(new Response<TemplateResponse>(response, true));
#endregion
var templateToResponse = await templateService . Get ( )
. AsNoTracking ( )
. Include ( t = > t . Unit ) . ThenInclude ( t = > t ! . UnitValues ) . ThenInclude ( t = > t . Field )
. Include ( t = > t . Unit ) . ThenInclude ( t = > t ! . UnitValues ) . ThenInclude ( t = > t . Value )
. Include ( t = > t . StatusType )
. Include ( t = > t . Job ) . ThenInclude ( t = > t . Group )
. Include ( t = > t . RobotConfigurations ) . ThenInclude ( t = > t . Robot )
. Include ( t = > t . RobotConfigurations ) . ThenInclude ( t = > t . TaskStatus )
. Include ( t = > t . RobotConfigurations ) . ThenInclude ( t = > t . RobotStatus )
. FirstAsync ( t = > t . Id = = id ) ;
var response = mapper . Map < TemplateListResponse > ( templateToResponse ) ;
2026-01-13 14:36:07 +10:00
await ApplyTemplateShortcodesAsync ( response , templateToResponse ) ;
2026-02-04 09:11:35 +10:00
FillNextRunWithResponseAreaInLocal ( response ) ;
2023-10-13 14:21:49 +10:00
2026-01-29 16:53:00 +10:00
var ordersCountResult = await GetOrdersCountAsync ( new List < Guid > { response . Id } ) ;
response . OrderCount = ordersCountResult . Count > 0 ? ordersCountResult . First ( ) . Value : 0 ;
return Ok ( new Response < TemplateListResponse > ( response , true ) ) ;
2023-10-13 14:21:49 +10:00
}
2026-01-13 14:36:07 +10:00
2026-01-29 16:53:00 +10:00
/// <summary>
/// Применить шорткоды
/// </summary>
/// <param name="response"></param>
/// <param name="template"></param>
/// <returns></returns>
private async Task ApplyTemplateShortcodesAsync ( TemplateBaseResponse response , Template template )
2026-01-13 14:36:07 +10:00
{
response . WorkGroup = await shortcodesService . ApplyShortcodesAsync ( template . Job . WorkGroupMask , template ) ;
response . ResponseArea = await shortcodesService . ApplyShortcodesAsync ( template . Job . ResponseAreaMask , template ) ;
}
2026-01-29 16:53:00 +10:00
/// <summary>
/// Получить кол-во нарядов для шаблонов
/// </summary>
/// <param name="templateIdList"></param>
/// <returns></returns>
private async Task < Dictionary < Guid , int > > GetOrdersCountAsync ( List < Guid > templateIdList )
{
if ( ! templateIdList . Any ( ) )
return new Dictionary < Guid , int > ( ) ;
var templateWithOrders = await orderService . Get ( )
. Where ( t = > t . TemplateId . HasValue & & templateIdList . Contains ( t . TemplateId . Value ) )
. GroupBy ( t = > t . TemplateId )
. Select ( t = > new { TemplateId = t . Key , OrderCount = t . Count ( ) } )
. AsNoTracking ( )
. ToListAsync ( ) ;
if ( templateWithOrders = = null )
return new Dictionary < Guid , int > ( ) ;
return templateWithOrders . ToDictionary ( t = > t . TemplateId ! . Value , t = > t . OrderCount ) ;
}
2026-02-03 16:15:19 +10:00
/// <summary>
2026-02-04 09:11:35 +10:00
/// Заполнить NextRunResponseAreaInLocal
2026-02-03 16:15:19 +10:00
/// </summary>
/// <param name="response"></param>
2026-02-04 09:11:35 +10:00
private void FillNextRunWithResponseAreaInLocal ( TemplateBaseResponse response )
2026-02-03 16:15:19 +10:00
{
2026-02-04 09:50:30 +10:00
var responseArea = response . IsResponseAreaTimezone & & ! string . IsNullOrEmpty ( response . ResponseArea )
? response . ResponseArea
: settingsFromDb . DefaultResponseAreaToTimeOffset ;
//response.NextRunResponseAreaInLocal = response.IsResponseAreaTimezone && !string.IsNullOrEmpty(response.ResponseArea)
// ? nextRunService.GetNextRunWithResponseAreaOffset(response.NextRun, response.ResponseArea)
// // возвращаем в дефолтной зоне
// : nextRunService.GetNextRunWithResponseAreaOffset(response.NextRun, settingsFromDb.DefaultResponseAreaToTimeOffset);
response . NextRunResponseAreaInLocal = nextRunService . GetNextRunWithResponseAreaOffset ( response . NextRun , responseArea ) ;
response . Timezone = mapper . Map < ScheduleResponseAreaTimeOffsetResponse > ( scheduleResponseAreaTimeOffsetService . GetByResponseAreaOrDefault ( responseArea ) ) ;
2026-02-03 16:15:19 +10:00
}
2023-09-15 16:32:46 +10:00
}
}