feat(dal, templateMatcher): изменена логика работы Shortcodes сервиса в сторону самостоятельной дозагрузки данных из БД, в Template сервис добавлен метод атомарного резервирования шаблона для TemplateMatcher
This commit is contained in:
@@ -521,6 +521,10 @@
|
|||||||
public const string GetAll = Base + "/shortcodes/";
|
public const string GetAll = Base + "/shortcodes/";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public static class ShortcodeApply
|
||||||
|
{
|
||||||
|
public const string Apply = Base + "/shortcodes/apply";
|
||||||
|
}
|
||||||
public static class RegionalEkPtkGroup
|
public static class RegionalEkPtkGroup
|
||||||
{
|
{
|
||||||
public const string GetAll = Base + "/regional-ek-ptk-groups/";
|
public const string GetAll = Base + "/regional-ek-ptk-groups/";
|
||||||
|
|||||||
8
PARR.API/Contracts/V1/Requests/ShortcodeApplyRequest.cs
Normal file
8
PARR.API/Contracts/V1/Requests/ShortcodeApplyRequest.cs
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
namespace PARR.API.Contracts.V1.Requests
|
||||||
|
{
|
||||||
|
public class ShortcodeApplyRequest
|
||||||
|
{
|
||||||
|
public Guid TemplateId { get; set; }
|
||||||
|
public required string Content { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
namespace PARR.API.Contracts.V1.Responses
|
||||||
|
{
|
||||||
|
public class ShortcodeApplyResponse
|
||||||
|
{
|
||||||
|
public required string Content { get; set; }
|
||||||
|
}
|
||||||
|
}
|
||||||
60
PARR.API/Controllers/V1/ShortcodeApplyController.cs
Normal file
60
PARR.API/Controllers/V1/ShortcodeApplyController.cs
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using PARR.API.Contracts.V1;
|
||||||
|
using PARR.API.Contracts.V1.Requests;
|
||||||
|
using PARR.API.Contracts.V1.Responses;
|
||||||
|
using PARR.API.Contracts.V1.Responses.Base;
|
||||||
|
using PARR.API.Controllers.V1.Base;
|
||||||
|
using PARR.DAL.DomainServices.Shortcodes;
|
||||||
|
using PARR.DAL.Services.Interfaces;
|
||||||
|
|
||||||
|
namespace PARR.API.Controllers.V1
|
||||||
|
{
|
||||||
|
public class ShortcodeApplyController : BaseApiController
|
||||||
|
{
|
||||||
|
private readonly ILogger<ShortcodeController> logger;
|
||||||
|
private readonly IShortcodesService shortcodesService;
|
||||||
|
private readonly ITemplateService templateService;
|
||||||
|
|
||||||
|
public ShortcodeApplyController(
|
||||||
|
ILogger<ShortcodeController> logger,
|
||||||
|
IShortcodesService shortcodesService,
|
||||||
|
ITemplateService templateService
|
||||||
|
)
|
||||||
|
{
|
||||||
|
this.logger = logger;
|
||||||
|
this.shortcodesService = shortcodesService;
|
||||||
|
this.templateService = templateService;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Получить список всех переменных составляющих
|
||||||
|
/// </summary>
|
||||||
|
/// <returns></returns>
|
||||||
|
[HttpPost(ApiRoutes.ShortcodeApply.Apply)]
|
||||||
|
public async Task<IActionResult> Apply([FromBody] ShortcodeApplyRequest request)
|
||||||
|
{
|
||||||
|
var template = await templateService.Get()
|
||||||
|
.Include(t => t.Unit)
|
||||||
|
.Include(t => t.UnitsInTemplate)
|
||||||
|
.Include(t => t.Unit)
|
||||||
|
.Include(t => t.Job)
|
||||||
|
.ThenInclude(t => t!.Group)
|
||||||
|
.ThenInclude(t => t!.GroupType)
|
||||||
|
.Include(t => t.Job)
|
||||||
|
.ThenInclude(t => t!.Tnk)
|
||||||
|
.AsNoTracking()
|
||||||
|
.FirstOrDefaultAsync(t => t.Id == request.TemplateId);
|
||||||
|
|
||||||
|
if (template == null)
|
||||||
|
return BadRequest(new Response(false, new List<ErrorModel> { new ErrorModel { FieldName = nameof(request.TemplateId), Message = $"Шаблон имеющий Id = {request.TemplateId} не найден" } }));
|
||||||
|
|
||||||
|
var aplyingShortCodes = await shortcodesService.ApplyShortcodesAsync(request.Content, template);
|
||||||
|
|
||||||
|
var response = new ShortcodeApplyResponse { Content = aplyingShortCodes };
|
||||||
|
|
||||||
|
return Ok(new Response<ShortcodeApplyResponse>(response, true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,8 +6,10 @@ namespace PARR.Constants
|
|||||||
public enum ShortcodeTypeEnum
|
public enum ShortcodeTypeEnum
|
||||||
{
|
{
|
||||||
Static,
|
Static,
|
||||||
Standart,
|
Standard,
|
||||||
Relationship,
|
Relationship,
|
||||||
FieldValue
|
FieldValue,
|
||||||
|
GroupValue,
|
||||||
|
Transform
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ namespace PARR.DAL.DomainServices.Implementations
|
|||||||
internal class UnitFilterService : IUnitFilterService
|
internal class UnitFilterService : IUnitFilterService
|
||||||
{
|
{
|
||||||
#if DEBUG
|
#if DEBUG
|
||||||
private readonly Guid targetUnitId = Guid.Parse("6c019569-ecba-4d9a-9cdf-cdc1dea93925");
|
private readonly Guid targetUnitId = Guid.Parse("87fc4c36-1ea8-4163-983f-1605fee1de99");
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
private readonly ILogger<UnitFilterService> logger;
|
private readonly ILogger<UnitFilterService> logger;
|
||||||
|
|||||||
@@ -1,16 +1,12 @@
|
|||||||
using PARR.DAL.DomainModels;
|
using PARR.DAL.DomainModels;
|
||||||
using PARR.DAL.DomainServices.Shortcodes.Models;
|
|
||||||
using PARR.DAL.Models;
|
using PARR.DAL.Models;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
namespace PARR.DAL.DomainServices.Shortcodes
|
namespace PARR.DAL.DomainServices.Shortcodes
|
||||||
{
|
{
|
||||||
public interface IShortcodesService
|
public interface IShortcodesService
|
||||||
{
|
{
|
||||||
Task<string> ApplyShortcodesAsync(string str, TemplateForShortcodes template);
|
Task<string> ApplyShortcodesAsync(string str, Template template, [CallerMemberName] string? caller = null);
|
||||||
|
|
||||||
Task<string> ApplyShortcodesAsync(string str, Template template);
|
|
||||||
|
|
||||||
// bool IsAnyShortcodes(string str);
|
|
||||||
|
|
||||||
Task<List<ShortcodeInfoDto>> GetAvailableShortcodesAsync();
|
Task<List<ShortcodeInfoDto>> GetAvailableShortcodesAsync();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +0,0 @@
|
|||||||
namespace PARR.DAL.DomainServices.Shortcodes.Models
|
|
||||||
{
|
|
||||||
public class JobForShortcodes
|
|
||||||
{
|
|
||||||
public JobGroupForShortcodes? Group { get; set; }
|
|
||||||
public TnkForShortcodes? Tnk { get; set; }
|
|
||||||
public string WorkName { get; set; } = string.Empty;
|
|
||||||
public string Name { get; set; } = string.Empty;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
namespace PARR.DAL.DomainServices.Shortcodes.Models
|
|
||||||
{
|
|
||||||
public class JobGroupForShortcodes
|
|
||||||
{
|
|
||||||
public Guid Id { get; set; }
|
|
||||||
public Guid? GroupingUnitFieldId { get; set; }
|
|
||||||
public JobGroupTypeForShortcodes? GroupType { get; set; }
|
|
||||||
public string GroupName { get; set; } = string.Empty;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
using PARR.DAL.Contracts;
|
|
||||||
|
|
||||||
namespace PARR.DAL.DomainServices.Shortcodes.Models
|
|
||||||
{
|
|
||||||
public class JobGroupTypeForShortcodes
|
|
||||||
{
|
|
||||||
public JobGroupTypesEnum Code { get; set; }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
namespace PARR.DAL.DomainServices.Shortcodes.Models
|
|
||||||
{
|
|
||||||
public class TemplateForShortcodes
|
|
||||||
{
|
|
||||||
public Guid Id { get; set; }
|
|
||||||
public int? Index { get; set; }
|
|
||||||
public Guid JobId { get; set; }
|
|
||||||
public Guid UnitId { get; set; }
|
|
||||||
|
|
||||||
public JobForShortcodes? Job { get; set; }
|
|
||||||
public List<UnitInTemplateForShortcodes> UnitsInTemplate { get; set; } = new();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
namespace PARR.DAL.DomainServices.Shortcodes.Models
|
|
||||||
{
|
|
||||||
public class TnkForShortcodes
|
|
||||||
{
|
|
||||||
public string Name { get; set; } = string.Empty;
|
|
||||||
public string ShortName { get; set; } = string.Empty;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
namespace PARR.DAL.DomainServices.Shortcodes.Models
|
|
||||||
{
|
|
||||||
public class UnitInTemplateForShortcodes
|
|
||||||
{
|
|
||||||
public Guid UnitId { get; set; }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -7,23 +7,42 @@ using PARR.DAL.DomainModels;
|
|||||||
using PARR.DAL.DomainServices.Interfaces;
|
using PARR.DAL.DomainServices.Interfaces;
|
||||||
using PARR.DAL.DomainServices.Shortcodes.Models;
|
using PARR.DAL.DomainServices.Shortcodes.Models;
|
||||||
using PARR.DAL.Models;
|
using PARR.DAL.Models;
|
||||||
using PARR.DAL.Models.Unit;
|
using PARR.DAL.Models.Job;
|
||||||
using PARR.DAL.Services.Interfaces;
|
using PARR.DAL.Services.Interfaces;
|
||||||
using PARR.DAL.Services.Interfaces.Job;
|
using PARR.DAL.Services.Interfaces.Job;
|
||||||
using PARR.DAL.Services.Interfaces.Unit;
|
using PARR.DAL.Services.Interfaces.Unit;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
using System.Text.RegularExpressions;
|
using System.Text.RegularExpressions;
|
||||||
|
|
||||||
namespace PARR.DAL.DomainServices.Shortcodes
|
namespace PARR.DAL.DomainServices.Shortcodes
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Сервис для подстановки шорткодов в строке на основе данных шаблона.
|
||||||
|
/// </summary>
|
||||||
internal class ShortcodesService : IShortcodesService
|
internal class ShortcodesService : IShortcodesService
|
||||||
{
|
{
|
||||||
private const string shortcodePattern = "%[^%\\s]+%";
|
private const string MissingJobWarningMsg =
|
||||||
private const string maxShortcodePattern = @"%МАКС:([а-яА-Яa-zA-Z0-9_]+)%";
|
"[{Caller}] Шаблон {TemplateId} не содержит Job в переданных данных. Данные будут догружены из БД. " +
|
||||||
private const string lettersShortcodePattern = @"%БУКВЫ:([^%]+)%";
|
"Рекомендуется обновить запрос шаблона с Include(j => j.Job).";
|
||||||
|
|
||||||
private static readonly HashSet<string> SupportedShortcodes = new(StringComparer.OrdinalIgnoreCase)
|
private const string MissingIncludesWarningMsg =
|
||||||
|
"[{Caller}] Шаблон {TemplateId} содержит Job, но не хватает данных для шорткодов: {Shortcodes}. " +
|
||||||
|
"Отсутствуют Include: {MissingIncludes}. Данные будут догружены из БД. " +
|
||||||
|
"Рекомендуется обновить запрос шаблона.";
|
||||||
|
|
||||||
|
private const string MissingUnitNameWarningMsg =
|
||||||
|
"[{Caller}] Шаблон {TemplateId} не содержит Unit.Name в переданных данных. Данные будут догружены из БД. " +
|
||||||
|
"Рекомендуется обновить запрос шаблона с Include(t => t.Unit).";
|
||||||
|
|
||||||
|
private const int MaxIterations = 3;
|
||||||
|
private const string NoContent = "Нет данных";
|
||||||
|
private static readonly Regex GeneralShortcodeRegex = new(@"%[^%\s]+%", RegexOptions.Compiled);
|
||||||
|
private static readonly Regex MaxShortcodeRegex = new(@"%МАКС:([а-яА-Яa-zA-Z0-9_]+)%", RegexOptions.Compiled);
|
||||||
|
private static readonly Regex LettersShortcodeRegex = new(@"%БУКВЫ:([^%]+)%", RegexOptions.Compiled);
|
||||||
|
|
||||||
|
private static readonly HashSet<string> SupportedStandardShortcodes = new(StringComparer.OrdinalIgnoreCase)
|
||||||
{
|
{
|
||||||
"%ЭК%", "%ГРУППА_РАБОТ%", "%РАБОТА%", "%ТНК%", "%СВЯЗИ%", "%ТНК-КРАТКО%", "%СВЯЗИ-ПН%", "%ИНДЕКС%"
|
"%ЭК%", "%ГРУППА_РАБОТ%", "%РАБОТА%", "%ТНК%", "%ТНК-КРАТКО%", "%ТИКТАК%"
|
||||||
};
|
};
|
||||||
|
|
||||||
private readonly ILogger<ShortcodesService> logger;
|
private readonly ILogger<ShortcodesService> logger;
|
||||||
@@ -36,6 +55,43 @@ namespace PARR.DAL.DomainServices.Shortcodes
|
|||||||
private readonly IRedisCacheService cacheService;
|
private readonly IRedisCacheService cacheService;
|
||||||
private readonly IUnitFilterService unitFilterService;
|
private readonly IUnitFilterService unitFilterService;
|
||||||
|
|
||||||
|
// Используем record struct вместо class
|
||||||
|
private record class TemplateForShortcodes(
|
||||||
|
Guid Id,
|
||||||
|
int? Index,
|
||||||
|
Guid JobId,
|
||||||
|
Guid UnitId,
|
||||||
|
JobForShortcodes? Job,
|
||||||
|
List<UnitInTemplateForShortcodes> UnitsInTemplate
|
||||||
|
);
|
||||||
|
|
||||||
|
private record class JobForShortcodes(
|
||||||
|
JobGroupForShortcodes? Group,
|
||||||
|
TnkForShortcodes? Tnk,
|
||||||
|
string WorkName,
|
||||||
|
string Name
|
||||||
|
);
|
||||||
|
|
||||||
|
private record class JobGroupForShortcodes(
|
||||||
|
Guid Id,
|
||||||
|
Guid? GroupingUnitFieldId,
|
||||||
|
JobGroupTypeForShortcodes? GroupType,
|
||||||
|
string GroupName
|
||||||
|
);
|
||||||
|
|
||||||
|
private record class JobGroupTypeForShortcodes(
|
||||||
|
JobGroupTypesEnum Code
|
||||||
|
);
|
||||||
|
|
||||||
|
private record class TnkForShortcodes(
|
||||||
|
string Name,
|
||||||
|
string ShortName
|
||||||
|
);
|
||||||
|
|
||||||
|
private record class UnitInTemplateForShortcodes(
|
||||||
|
Guid UnitId
|
||||||
|
);
|
||||||
|
|
||||||
public ShortcodesService(
|
public ShortcodesService(
|
||||||
ILogger<ShortcodesService> logger,
|
ILogger<ShortcodesService> logger,
|
||||||
SettingsFromDb settingsFromDb,
|
SettingsFromDb settingsFromDb,
|
||||||
@@ -59,229 +115,380 @@ namespace PARR.DAL.DomainServices.Shortcodes
|
|||||||
this.unitFilterService = unitFilterService;
|
this.unitFilterService = unitFilterService;
|
||||||
}
|
}
|
||||||
|
|
||||||
public Task<string> ApplyShortcodesAsync(string str, Template template)
|
/// <summary>
|
||||||
|
/// Подставляет шорткоды в строке на основе данных шаблона.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="str">Строка с шорткодами</param>
|
||||||
|
/// <param name="template">Шаблон, из которого берутся данные</param>
|
||||||
|
/// <returns>Строка с подставленными значениями</returns>
|
||||||
|
public async Task<string> ApplyShortcodesAsync(string str, Template template, [CallerMemberName] string? caller = null)
|
||||||
{
|
{
|
||||||
// Построим TemplateForShortcodes из уже загруженного template
|
if (string.IsNullOrEmpty(str)) return str;
|
||||||
var templateForShortcodes = new TemplateForShortcodes
|
if (template == null) throw new ArgumentNullException(nameof(template));
|
||||||
{
|
|
||||||
Id = template.Id,
|
|
||||||
Index = template.Index,
|
|
||||||
JobId = template.JobId,
|
|
||||||
UnitId = template.UnitId,
|
|
||||||
Job = template.Job == null ? null : new JobForShortcodes
|
|
||||||
{
|
|
||||||
Group = template.Job.Group == null ? null : new JobGroupForShortcodes
|
|
||||||
{
|
|
||||||
Id = template.Job.GroupId,
|
|
||||||
GroupingUnitFieldId = template.Job.Group.GroupingUnitFieldId,
|
|
||||||
GroupType = template.Job.Group.GroupType == null ? null : new JobGroupTypeForShortcodes
|
|
||||||
{
|
|
||||||
Code = template.Job.Group.GroupType.Code
|
|
||||||
},
|
|
||||||
GroupName = template.Job.Group.GroupName
|
|
||||||
},
|
|
||||||
Tnk = template.Job.Tnk == null ? null : new TnkForShortcodes
|
|
||||||
{
|
|
||||||
Name = template.Job.Tnk.Name,
|
|
||||||
ShortName = template.Job.Tnk.ShortName
|
|
||||||
},
|
|
||||||
WorkName = template.Job.WorkName,
|
|
||||||
Name = template.Job.Name
|
|
||||||
},
|
|
||||||
UnitsInTemplate = template.UnitsInTemplate?.Select(uit => new UnitInTemplateForShortcodes { UnitId = uit.UnitId }).ToList() ?? new List<UnitInTemplateForShortcodes>()
|
|
||||||
};
|
|
||||||
|
|
||||||
return ApplyShortcodesAsync(str, templateForShortcodes);
|
var callerName = caller ?? "Unknown";
|
||||||
}
|
|
||||||
|
|
||||||
|
logger.LogDebug("[{Caller}] Начата подстановка шорткодов. Вход: '{Input}', templateId={TemplateId}", callerName, str, template.Id);
|
||||||
|
|
||||||
//todo: сделать private в перспективе
|
var result = str;
|
||||||
public async Task<string> ApplyShortcodesAsync(string str, TemplateForShortcodes template)
|
|
||||||
{
|
|
||||||
if (!IsAnyShortcodes(str))
|
|
||||||
{
|
|
||||||
logger.LogDebug("Строка не содержит шорткодов: {str}", str);
|
|
||||||
return str;
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.LogDebug("Начата подстановка шорткодов. Вход: '{Input}', templateId={TemplateId}, index={Index}", str, template.Id, template.Index);
|
|
||||||
|
|
||||||
var job = template.Job;
|
|
||||||
if (job == null)
|
|
||||||
{
|
|
||||||
logger.LogError("Шаблон {TemplateId} не содержит Job. Подстановка прервана.", template.Id);
|
|
||||||
return str;
|
|
||||||
}
|
|
||||||
|
|
||||||
var unit = await unitService.Get().AsNoTracking().FirstOrDefaultAsync(u => u.Id == template.UnitId);
|
|
||||||
|
|
||||||
if (unit == null || string.IsNullOrEmpty(str))
|
|
||||||
{
|
|
||||||
logger.LogError("Переданы некорректные данные для подстановки динамических записей");
|
|
||||||
return str;
|
|
||||||
}
|
|
||||||
|
|
||||||
var resultName = str;
|
|
||||||
var shortcodesInMask = GetShortCodes(resultName);
|
|
||||||
|
|
||||||
// 1. Статические константы
|
|
||||||
var nameConstants = settingsFromDb.TemplateNameConstantPartsList;
|
|
||||||
if (shortcodesInMask.Any(m => nameConstants.Any(c => $"%{c.Name}%".Equals(m.Value, StringComparison.OrdinalIgnoreCase))))
|
|
||||||
{
|
|
||||||
resultName = ReplaceConstants(nameConstants, resultName);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. Стандартные шорткоды — с поддержкой вложенных (%РАБОТА% → "Мониторинг | %ЭК%")
|
|
||||||
const int MaxStandardIterations = 3;
|
|
||||||
var iteration = 0;
|
var iteration = 0;
|
||||||
|
|
||||||
while (iteration < MaxStandardIterations)
|
while (iteration < MaxIterations)
|
||||||
{
|
{
|
||||||
var remainingShortcodes = GetShortCodes(resultName)
|
var shortcodes = GetShortCodes(result).Select(m => m.Value).ToList();
|
||||||
.Select(m => m.Value)
|
if (!shortcodes.Any()) break;
|
||||||
.Where(s => SupportedShortcodes.Contains(s))
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
if (!remainingShortcodes.Any())
|
// Подготавливаем данные с догрузкой при необходимости
|
||||||
break;
|
var data = await PrepareTemplateDataAsync(template, shortcodes, callerName).ConfigureAwait(false);
|
||||||
|
|
||||||
|
var oldResult = result;
|
||||||
|
|
||||||
|
// Подстановка всех типов шорткодов
|
||||||
|
result = await ApplyAllShortcodesOnceAsync(result, data, shortcodes, callerName).ConfigureAwait(false);
|
||||||
|
|
||||||
var oldResult = resultName;
|
|
||||||
resultName = ReplaceStandardShortcodes(job, unit, resultName, template.Index);
|
|
||||||
iteration++;
|
iteration++;
|
||||||
|
|
||||||
if (resultName == oldResult)
|
if (result == oldResult) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.LogDebug("[{Caller}] Подстановка завершена. Результат: '{Result}'", callerName, result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<TemplateForShortcodes> PrepareTemplateDataAsync(Template template, List<string> shortcodes, string caller)
|
||||||
|
{
|
||||||
|
var data = new TemplateForShortcodes(
|
||||||
|
Id: template.Id,
|
||||||
|
Index: template.Index,
|
||||||
|
JobId: template.JobId,
|
||||||
|
UnitId: template.UnitId,
|
||||||
|
Job: null,
|
||||||
|
UnitsInTemplate: template.UnitsInTemplate?.Select(uit => new UnitInTemplateForShortcodes(uit.UnitId)).ToList() ?? new List<UnitInTemplateForShortcodes>()
|
||||||
|
);
|
||||||
|
|
||||||
|
// Загружаем Unit.Name
|
||||||
|
var unitName = template.Unit?.Name ?? await GetUnitNameAsyncWithWarning(template, shortcodes, caller).ConfigureAwait(false);
|
||||||
|
|
||||||
|
// Проверяем, нужны ли данные Job
|
||||||
|
if (!NeedsJobForShortcodes(shortcodes))
|
||||||
|
{
|
||||||
|
// Всё равно создаём пустой JobForShortcodes, чтобы не было null
|
||||||
|
data = data with { Job = new JobForShortcodes(null, null, string.Empty, string.Empty) };
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (template.Job == null)
|
||||||
|
{
|
||||||
|
logger.LogWarning(MissingJobWarningMsg, caller, template.Id);
|
||||||
|
var jobData = await LoadJobForShortcodesAsync(template.JobId, shortcodes, caller).ConfigureAwait(false);
|
||||||
|
return data with { Job = jobData };
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var missingIncludes = GetMissingIncludesForShortcodes(shortcodes, template.Job);
|
||||||
|
if (missingIncludes.Any())
|
||||||
{
|
{
|
||||||
logger.LogDebug("Замена стандартных шорткодов не изменила строку на итерации {Iteration}. Останов.", iteration);
|
var problematicShortcodes = shortcodes.Where(sc =>
|
||||||
break;
|
(sc.Equals("%ГРУППА_РАБОТ%", StringComparison.OrdinalIgnoreCase) && template.Job.Group == null) ||
|
||||||
}
|
(sc.StartsWith("%МАКС:", StringComparison.OrdinalIgnoreCase) && template.Job.Group?.GroupType == null) ||
|
||||||
}
|
(sc.Equals("%ГР_ПОЛЕ-ПН%", StringComparison.OrdinalIgnoreCase) && template.Job.Group?.GroupType == null) ||
|
||||||
|
(sc.Equals("%ИНДЕКС%", StringComparison.OrdinalIgnoreCase) && template.Job.Group?.GroupType == null) ||
|
||||||
|
((sc.Equals("%ТНК%", StringComparison.OrdinalIgnoreCase) || sc.Equals("%ТНК-КРАТКО%", StringComparison.OrdinalIgnoreCase)) && template.Job.Tnk == null)
|
||||||
|
).ToList();
|
||||||
|
|
||||||
if (iteration >= MaxStandardIterations)
|
logger.LogWarning(MissingIncludesWarningMsg, caller, template.Id, string.Join(", ", problematicShortcodes), string.Join(" ", missingIncludes));
|
||||||
{
|
|
||||||
logger.LogWarning(
|
|
||||||
"Достигнуто максимальное число итераций ({Max}) при замене стандартных шорткодов. Текущий результат: {Result}",
|
|
||||||
MaxStandardIterations, resultName);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2.5. %МАКС:FIELD% — только для групповых job (JobGroup.Type == Group)
|
var jobData = await LoadJobForShortcodesAsync(template.JobId, shortcodes, caller).ConfigureAwait(false);
|
||||||
if (job.Group != null && job.Group.GroupType != null && job.Group.GroupType!.Code == JobGroupTypesEnum.Group)
|
return data with { Job = jobData };
|
||||||
{
|
|
||||||
var maxShortcodes = Regex.Matches(resultName, maxShortcodePattern);
|
|
||||||
if (maxShortcodes.Count > 0)
|
|
||||||
{
|
|
||||||
resultName = await ReplaceMaxShortcodesAsync(job.Group.Id, template.UnitId, resultName, maxShortcodes);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2.6. %БУКВЫ:FIELD% — извлекает только буквы из значения поля
|
|
||||||
var lettersShortcodes = Regex.Matches(resultName, lettersShortcodePattern);
|
|
||||||
if (lettersShortcodes.Count > 0)
|
|
||||||
{
|
|
||||||
resultName = await ReplaceLettersShortcodesAsync(template.UnitId, resultName, lettersShortcodes);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2.7. %ГР_ПОЛЕ-ПН% — нумерованный список UnitsInTemplate с GroupingUnitFieldId, отсортированный по имени юнита
|
|
||||||
if (shortcodesInMask.Any(m => string.Equals(m.Value, "%ГР_ПОЛЕ-ПН%", StringComparison.OrdinalIgnoreCase)))
|
|
||||||
{
|
|
||||||
var unitsInTemplate = template.UnitsInTemplate;
|
|
||||||
if (unitsInTemplate == null || !unitsInTemplate.Any())
|
|
||||||
{
|
|
||||||
logger.LogDebug("Шаблон {TemplateId} не содержит UnitsInTemplate. %ГР_ПОЛЕ-ПН% заменён на пустую строку.", template.Id);
|
|
||||||
resultName = Regex.Replace(resultName, "%ГР_ПОЛЕ-ПН%", "", RegexOptions.IgnoreCase);
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
var unitIds = unitsInTemplate.Select(uit => uit.UnitId).ToList();
|
var jobData = MapJobForShortcodes(template.Job);
|
||||||
|
return data with { Job = jobData };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var units = await unitService.Get()
|
private static bool NeedsJobForShortcodes(List<string> shortcodes)
|
||||||
.AsNoTracking()
|
{
|
||||||
.Where(u => unitIds.Contains(u.Id))
|
return shortcodes.Any(sc =>
|
||||||
.ToListAsync();
|
sc != "%ЭК%" && // %ЭК% не требует Job
|
||||||
|
(SupportedStandardShortcodes.Contains(sc) ||
|
||||||
|
sc.StartsWith("%МАКС:", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
sc.Equals("%ГР_ПОЛЕ-ПН%", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
sc.Equals("%ИНДЕКС%", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
sc.Equals("%СВЯЗИ%", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
sc.Equals("%СВЯЗИ-ПН%", StringComparison.OrdinalIgnoreCase)));
|
||||||
|
}
|
||||||
|
|
||||||
// Словарь: UnitId -> Unit (для быстрого поиска)
|
private static List<string> GetMissingIncludesForShortcodes(List<string> shortcodes, Job? job)
|
||||||
var unitDict = units.ToDictionary(u => u.Id, u => u);
|
{
|
||||||
|
var missing = new List<string>();
|
||||||
|
|
||||||
var groupingFieldId = job.Group?.GroupingUnitFieldId;
|
if (shortcodes.Any(sc =>
|
||||||
Dictionary<Guid, string> valuesByUnit = new();
|
sc.Equals("%ГРУППА_РАБОТ%", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
sc.StartsWith("%МАКС:", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
sc.Equals("%ГР_ПОЛЕ-ПН%", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
sc.Equals("%ИНДЕКС%", StringComparison.OrdinalIgnoreCase))
|
||||||
|
&& job?.Group == null)
|
||||||
|
{
|
||||||
|
missing.Add(".Include(j => j.Group)");
|
||||||
|
}
|
||||||
|
|
||||||
if (groupingFieldId.HasValue)
|
if (shortcodes.Any(sc =>
|
||||||
{
|
sc.StartsWith("%МАКС:", StringComparison.OrdinalIgnoreCase) ||
|
||||||
var fieldValues = await unitInValueService.Get()
|
sc.Equals("%ГР_ПОЛЕ-ПН%", StringComparison.OrdinalIgnoreCase) ||
|
||||||
.AsNoTracking()
|
sc.Equals("%ИНДЕКС%", StringComparison.OrdinalIgnoreCase))
|
||||||
.Include(uv => uv.Value)
|
&& job?.Group?.GroupType == null)
|
||||||
.Where(uv =>
|
{
|
||||||
uv.FieldId == groupingFieldId.Value &&
|
missing.Add(".ThenInclude(g => g.GroupType)");
|
||||||
unitIds.Contains(uv.UnitId) &&
|
}
|
||||||
uv.Value != null &&
|
|
||||||
!string.IsNullOrWhiteSpace(uv.Value.Value))
|
|
||||||
.Select(uv => new { uv.UnitId, Value = uv.Value!.Value })
|
|
||||||
.ToListAsync();
|
|
||||||
|
|
||||||
valuesByUnit = fieldValues
|
if (shortcodes.Any(sc =>
|
||||||
.GroupBy(x => x.UnitId)
|
sc.Equals("%ТНК%", StringComparison.OrdinalIgnoreCase) ||
|
||||||
.ToDictionary(
|
sc.Equals("%ТНК-КРАТКО%", StringComparison.OrdinalIgnoreCase))
|
||||||
g => g.Key,
|
&& job?.Tnk == null)
|
||||||
g => string.Join(", ", g.Select(v => v.Value).OrderBy(v => v))
|
{
|
||||||
);
|
missing.Add(".Include(j => j.Tnk)");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Сортируем UnitsInTemplate по имени юнита
|
return missing;
|
||||||
var sortedUnitsInTemplate = unitsInTemplate
|
}
|
||||||
.OrderBy(uit => unitDict.TryGetValue(uit.UnitId, out var unit) ? unit.Name : $"(UnitId={uit.UnitId})")
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
var lines = sortedUnitsInTemplate
|
private async Task<string> GetUnitNameAsyncWithWarning(Template template, List<string> shortcodes, string caller)
|
||||||
.Select((uit, indexInList) =>
|
{
|
||||||
{
|
if (shortcodes.Any(sc => sc.Equals("%ЭК%", StringComparison.OrdinalIgnoreCase)))
|
||||||
var unitInList = unitDict.TryGetValue(uit.UnitId, out var unit) ? unit : null;
|
{
|
||||||
var unitName = unitInList?.Name ?? $"(UnitId={uit.UnitId})";
|
logger.LogWarning(MissingUnitNameWarningMsg, caller, template.Id);
|
||||||
var valuesStr = valuesByUnit.TryGetValue(uit.UnitId, out var vals) ? vals : "";
|
}
|
||||||
return $"{indexInList + 1}. {unitName} ({valuesStr})";
|
|
||||||
})
|
|
||||||
.ToList();
|
|
||||||
|
|
||||||
var resultText = string.Join("\n", lines);
|
var unit = await unitService.Get().AsNoTracking().FirstOrDefaultAsync(u => u.Id == template.UnitId).ConfigureAwait(false);
|
||||||
resultName = Regex.Replace(resultName, "%ГР_ПОЛЕ-ПН%", resultText, RegexOptions.IgnoreCase);
|
if (unit == null || string.IsNullOrEmpty(unit.Name))
|
||||||
|
throw new InvalidOperationException($"Unit {template.UnitId} не найден или не содержит Name.");
|
||||||
|
|
||||||
|
return unit.Name;
|
||||||
|
}
|
||||||
|
|
||||||
|
private JobForShortcodes MapJobForShortcodes(Job job)
|
||||||
|
{
|
||||||
|
return new JobForShortcodes(
|
||||||
|
Group: job.Group == null ? null : new JobGroupForShortcodes(
|
||||||
|
Id: job.Group.Id,
|
||||||
|
GroupingUnitFieldId: job.Group.GroupingUnitFieldId,
|
||||||
|
GroupName: job.Group.GroupName ?? string.Empty,
|
||||||
|
GroupType: job.Group.GroupType == null ? null : new JobGroupTypeForShortcodes(job.Group.GroupType.Code)
|
||||||
|
),
|
||||||
|
Tnk: job.Tnk == null ? null : new TnkForShortcodes(
|
||||||
|
Name: job.Tnk.Name ?? string.Empty,
|
||||||
|
ShortName: job.Tnk.ShortName ?? string.Empty
|
||||||
|
),
|
||||||
|
WorkName: job.WorkName ?? string.Empty,
|
||||||
|
Name: job.Name ?? string.Empty
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<JobForShortcodes> LoadJobForShortcodesAsync(Guid jobId, List<string> shortcodes, string caller)
|
||||||
|
{
|
||||||
|
var query = jobService.Get().AsNoTracking();
|
||||||
|
|
||||||
|
// Всегда загружаем Group и GroupType, если нужны групповые шорткоды
|
||||||
|
if (shortcodes.Any(sc =>
|
||||||
|
sc.StartsWith("%МАКС:", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
sc.Equals("%ГР_ПОЛЕ-ПН%", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
sc.Equals("%ИНДЕКС%", StringComparison.OrdinalIgnoreCase)))
|
||||||
|
{
|
||||||
|
query = query
|
||||||
|
.Include(j => j.Group)
|
||||||
|
.ThenInclude(g => g!.GroupType);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Для стандартных шорткодов тоже может понадобиться Group.GroupName
|
||||||
|
if (shortcodes.Any(sc => sc.Equals("%ГРУППА_РАБОТ%", StringComparison.OrdinalIgnoreCase)))
|
||||||
|
{
|
||||||
|
query = query
|
||||||
|
.Include(j => j.Group);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Для Tnk
|
||||||
|
if (shortcodes.Any(sc =>
|
||||||
|
sc.Equals("%ТНК%", StringComparison.OrdinalIgnoreCase) ||
|
||||||
|
sc.Equals("%ТНК-КРАТКО%", StringComparison.OrdinalIgnoreCase)))
|
||||||
|
{
|
||||||
|
query = query
|
||||||
|
.Include(j => j.Tnk);
|
||||||
|
}
|
||||||
|
|
||||||
|
var job = await query.FirstOrDefaultAsync(j => j.Id == jobId).ConfigureAwait(false);
|
||||||
|
if (job == null)
|
||||||
|
throw new InvalidOperationException($"Job {jobId} не найден.");
|
||||||
|
|
||||||
|
return MapJobForShortcodes(job);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<string> ApplyAllShortcodesOnceAsync(string str, TemplateForShortcodes data, List<string> shortcodesInMask, string caller)
|
||||||
|
{
|
||||||
|
var result = str;
|
||||||
|
|
||||||
|
// 1. Константы
|
||||||
|
var nameConstants = settingsFromDb.TemplateNameConstantPartsList;
|
||||||
|
if (shortcodesInMask.Any(m => nameConstants.Any(c => $"%{c.Name}%".Equals(m, StringComparison.OrdinalIgnoreCase))))
|
||||||
|
{
|
||||||
|
result = ReplaceConstants(nameConstants, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Стандартные
|
||||||
|
var hasStandardShortcodes = shortcodesInMask.Any(m => SupportedStandardShortcodes.Contains(m));
|
||||||
|
if (hasStandardShortcodes)
|
||||||
|
{
|
||||||
|
var unitName = await GetUnitNameForTemplateAsync(data.UnitId).ConfigureAwait(false);
|
||||||
|
result = ReplaceStandardShortcodes(data.Job, unitName, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. GroupJob: %ИНДЕКС%, %МАКС:..., %ГР_ПОЛЕ-ПН%
|
||||||
|
if (shortcodesInMask.Any(m => string.Equals(m, "%ИНДЕКС%", StringComparison.OrdinalIgnoreCase)))
|
||||||
|
{
|
||||||
|
result = ReplaceSingleShortcode(result, "%ИНДЕКС%", data.Index?.ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.Job?.Group?.GroupType?.Code == JobGroupTypesEnum.Group)
|
||||||
|
{
|
||||||
|
var maxShortcodes = MaxShortcodeRegex.Matches(result);
|
||||||
|
if (maxShortcodes.Count > 0)
|
||||||
|
{
|
||||||
|
result = await ReplaceMaxShortcodesAsync(data.Job.Group.Id, data.UnitId, result, maxShortcodes, caller).ConfigureAwait(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. %СВЯЗИ% или %СВЯЗИ-ПН% (если всё ещё зависят от jobId/unitId)
|
if (shortcodesInMask.Any(m => string.Equals(m, "%ГР_ПОЛЕ-ПН%", StringComparison.OrdinalIgnoreCase)))
|
||||||
|
{
|
||||||
|
if (data.Job?.Group == null)
|
||||||
|
{
|
||||||
|
logger.LogWarning("[{Caller}] Job не содержит Group, необходимый для %ГР_ПОЛЕ-ПН%. Шорткод пропущен.", caller);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
List<Guid> unitIds;
|
||||||
|
bool wasLoadedFromDb = false;
|
||||||
|
|
||||||
|
if (data.UnitsInTemplate.Count == 0)
|
||||||
|
{
|
||||||
|
logger.LogWarning(
|
||||||
|
"[{Caller}] Template {TemplateId} не содержит UnitsInTemplate. Данные будут догружены из БД. " +
|
||||||
|
"Рекомендуется обновить запрос с Include(t => t.UnitsInTemplate).",
|
||||||
|
caller, data.Id);
|
||||||
|
|
||||||
|
var fullTemplate = await templateService.Get()
|
||||||
|
.AsNoTracking()
|
||||||
|
.Include(t => t.UnitsInTemplate)
|
||||||
|
.FirstOrDefaultAsync(t => t.Id == data.Id)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
|
||||||
|
unitIds = fullTemplate?.UnitsInTemplate?.Select(uit => uit.UnitId).ToList() ?? new List<Guid>();
|
||||||
|
wasLoadedFromDb = true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
unitIds = data.UnitsInTemplate.Select(uit => uit.UnitId).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (unitIds.Count == 0)
|
||||||
|
{
|
||||||
|
logger.LogDebug("[{Caller}] Нет UnitsInTemplate для шаблона {TemplateId}. %ГР_ПОЛЕ-ПН% заменён на пустую строку.", caller, data.Id);
|
||||||
|
result = Regex.Replace(result, "%ГР_ПОЛЕ-ПН%", "", RegexOptions.IgnoreCase);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var units = await unitService.Get()
|
||||||
|
.AsNoTracking()
|
||||||
|
.Where(u => unitIds.Contains(u.Id))
|
||||||
|
.ToDictionaryAsync(u => u.Id, u => u).ConfigureAwait(false);
|
||||||
|
|
||||||
|
var groupingFieldId = data.Job.Group.GroupingUnitFieldId;
|
||||||
|
Dictionary<Guid, string> valuesByUnit = new();
|
||||||
|
|
||||||
|
if (groupingFieldId.HasValue)
|
||||||
|
{
|
||||||
|
var fieldValues = await unitInValueService.Get()
|
||||||
|
.AsNoTracking()
|
||||||
|
.Include(uv => uv.Value)
|
||||||
|
.Where(uv =>
|
||||||
|
uv.FieldId == groupingFieldId.Value &&
|
||||||
|
unitIds.Contains(uv.UnitId) &&
|
||||||
|
uv.Value != null &&
|
||||||
|
!string.IsNullOrWhiteSpace(uv.Value.Value))
|
||||||
|
.Select(uv => new { uv.UnitId, Value = uv.Value!.Value })
|
||||||
|
.ToListAsync().ConfigureAwait(false);
|
||||||
|
|
||||||
|
valuesByUnit = fieldValues
|
||||||
|
.GroupBy(x => x.UnitId)
|
||||||
|
.ToDictionary(g => g.Key, g => string.Join(", ", g.OrderBy(v => v.Value).Select(v => v.Value)));
|
||||||
|
}
|
||||||
|
|
||||||
|
var actualUnitsInTemplate = unitIds.Select(id => new UnitInTemplateForShortcodes(id)).ToList();
|
||||||
|
|
||||||
|
var sortedUnitsInTemplate = actualUnitsInTemplate
|
||||||
|
.OrderBy(uit => units.TryGetValue(uit.UnitId, out var u) ? u.Name : uit.UnitId.ToString())
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
var lines = sortedUnitsInTemplate
|
||||||
|
.Select((uit, i) =>
|
||||||
|
{
|
||||||
|
var unitName = units.TryGetValue(uit.UnitId, out var u) ? u.Name : $"(UnitId={uit.UnitId})";
|
||||||
|
var valuesStr = valuesByUnit.TryGetValue(uit.UnitId, out var vals) ? vals : "";
|
||||||
|
return $"{i + 1}. {unitName} ({valuesStr})";
|
||||||
|
});
|
||||||
|
|
||||||
|
result = Regex.Replace(result, "%ГР_ПОЛЕ-ПН%", string.Join("\n", lines), RegexOptions.IgnoreCase);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Transform: %БУКВЫ:...
|
||||||
|
var lettersShortcodes = LettersShortcodeRegex.Matches(result);
|
||||||
|
if (lettersShortcodes.Count > 0)
|
||||||
|
{
|
||||||
|
result = await ReplaceLettersShortcodesAsync(data.UnitId, result, lettersShortcodes, caller).ConfigureAwait(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. %СВЯЗИ% и %СВЯЗИ-ПН%
|
||||||
List<string>? relatedUnitNames = null;
|
List<string>? relatedUnitNames = null;
|
||||||
|
if (shortcodesInMask.Any(m => string.Equals(m, "%СВЯЗИ%", StringComparison.OrdinalIgnoreCase)))
|
||||||
if (shortcodesInMask.Any(m => string.Equals(m.Value, "%СВЯЗИ%", StringComparison.OrdinalIgnoreCase)))
|
|
||||||
{
|
{
|
||||||
relatedUnitNames ??= await unitFilterService.GetRelatedUnitNamesAsync(template.JobId, template.UnitId);
|
if (data.Job != null)
|
||||||
var linksText = string.Join("\n", relatedUnitNames);
|
{
|
||||||
resultName = Regex.Replace(resultName, "%СВЯЗИ%", linksText, RegexOptions.IgnoreCase);
|
relatedUnitNames ??= await unitFilterService.GetRelatedUnitNamesAsync(data.JobId, data.UnitId).ConfigureAwait(false);
|
||||||
|
result = Regex.Replace(result, "%СВЯЗИ%", string.Join("\n", relatedUnitNames), RegexOptions.IgnoreCase);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (shortcodesInMask.Any(m => string.Equals(m, "%СВЯЗИ-ПН%", StringComparison.OrdinalIgnoreCase)))
|
||||||
|
{
|
||||||
|
if (data.Job != null)
|
||||||
|
{
|
||||||
|
relatedUnitNames ??= await unitFilterService.GetRelatedUnitNamesAsync(data.JobId, data.UnitId).ConfigureAwait(false);
|
||||||
|
var numbered = relatedUnitNames.Select((name, i) => $"{i + 1}. {name}");
|
||||||
|
result = Regex.Replace(result, "%СВЯЗИ-ПН%", string.Join("\n", numbered), RegexOptions.IgnoreCase);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (shortcodesInMask.Any(m => string.Equals(m.Value, "%СВЯЗИ-ПН%", StringComparison.OrdinalIgnoreCase)))
|
// 6. Поля
|
||||||
{
|
var fieldShortcodes = GetShortCodes(result);
|
||||||
relatedUnitNames ??= await unitFilterService.GetRelatedUnitNamesAsync(template.JobId, template.UnitId);
|
if (fieldShortcodes.Count > 0)
|
||||||
var linksText = string.Join("\n", relatedUnitNames.Select((name, i) => $"{i + 1}. {name}"));
|
result = await ReplaceFieldValues(data.UnitId, result, fieldShortcodes).ConfigureAwait(false);
|
||||||
resultName = Regex.Replace(resultName, "%СВЯЗИ-ПН%", linksText, RegexOptions.IgnoreCase);
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. Поля (оставшиеся %FIELD_NAME%)
|
return result;
|
||||||
shortcodesInMask = GetShortCodes(resultName);
|
|
||||||
if (shortcodesInMask.Count > 0)
|
|
||||||
resultName = await ReplaceFieldValues(template.UnitId, resultName, shortcodesInMask);
|
|
||||||
|
|
||||||
logger.LogDebug("Подстановка завершена. Результат: '{Result}'", resultName);
|
|
||||||
|
|
||||||
return resultName;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool IsAnyShortcodes(string str)
|
private async Task<string> GetUnitNameForTemplateAsync(Guid unitId)
|
||||||
{
|
{
|
||||||
return Regex.IsMatch(str, shortcodePattern) ||
|
var unit = await unitService.Get().AsNoTracking().FirstOrDefaultAsync(u => u.Id == unitId).ConfigureAwait(false);
|
||||||
Regex.IsMatch(str, maxShortcodePattern) ||
|
if (unit == null || string.IsNullOrEmpty(unit.Name))
|
||||||
Regex.IsMatch(str, lettersShortcodePattern);
|
throw new InvalidOperationException($"Unit {unitId} не найден или не содержит Name.");
|
||||||
|
return unit.Name;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static List<Match> GetShortCodes(string resultName)
|
private static List<Match> GetShortCodes(string resultName)
|
||||||
{
|
{
|
||||||
var shortcodesInMask = Regex.Matches(resultName, shortcodePattern).ToList();
|
var shortcodesInMask = GeneralShortcodeRegex.Matches(resultName).ToList();
|
||||||
return shortcodesInMask;
|
return shortcodesInMask;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -305,32 +512,48 @@ namespace PARR.DAL.DomainServices.Shortcodes
|
|||||||
{
|
{
|
||||||
new ShortcodeInfoDto { Shortcode = "%ЭК%",
|
new ShortcodeInfoDto { Shortcode = "%ЭК%",
|
||||||
Description = "Наименование ЭК(Код поиска)",
|
Description = "Наименование ЭК(Код поиска)",
|
||||||
Type = ShortcodeTypeEnum.Standart },
|
Type = ShortcodeTypeEnum.Standard },
|
||||||
new ShortcodeInfoDto { Shortcode = "%ГРУППА_РАБОТ%",
|
new ShortcodeInfoDto { Shortcode = "%ГРУППА_РАБОТ%",
|
||||||
Description = "Наименование группы работ",
|
Description = "Наименование группы работ",
|
||||||
Type = ShortcodeTypeEnum.Standart },
|
Type = ShortcodeTypeEnum.Standard },
|
||||||
new ShortcodeInfoDto { Shortcode = "%РАБОТА%",
|
new ShortcodeInfoDto { Shortcode = "%РАБОТА%",
|
||||||
Description = "Наименование работы в АСУ ЕСПП",
|
Description = "Наименование работы в АСУ ЕСПП",
|
||||||
Type = ShortcodeTypeEnum.Standart },
|
Type = ShortcodeTypeEnum.Standard },
|
||||||
new ShortcodeInfoDto { Shortcode = "%ТНК%",
|
new ShortcodeInfoDto { Shortcode = "%ТНК%",
|
||||||
Description = "Полное наименование ТНК",
|
Description = "Полное наименование ТНК",
|
||||||
Type = ShortcodeTypeEnum.Standart },
|
Type = ShortcodeTypeEnum.Standard },
|
||||||
new ShortcodeInfoDto { Shortcode = "%ТНК-КРАТКО%",
|
new ShortcodeInfoDto { Shortcode = "%ТНК-КРАТКО%",
|
||||||
Description = "Краткое наименование ТНК",
|
Description = "Краткое наименование ТНК",
|
||||||
Type = ShortcodeTypeEnum.Standart },
|
Type = ShortcodeTypeEnum.Standard },
|
||||||
new ShortcodeInfoDto { Shortcode = "%ИНДЕКС%",
|
new ShortcodeInfoDto { Shortcode = "%ТИКТАК%",
|
||||||
Description = "Порядковый индекс шаблона для групповых работ",
|
Description = "Текущее время в формате Unix timestamp (секунды с 1970-01-01 UTC)",
|
||||||
Type = ShortcodeTypeEnum.Standart },
|
Type = ShortcodeTypeEnum.Standard
|
||||||
new ShortcodeInfoDto { Shortcode = "%МАКС:ИМЯ АТРИБУТА%",
|
|
||||||
Description = "Используется только с групповым типом работ. Наиболее часто встречающееся значение поля в группе (игнорирует пустые). Пример: %МАКС:РАБОЧАЯ_ГР_ОТВ_ЗА_ЭК%",
|
|
||||||
Type = ShortcodeTypeEnum.Standart },
|
|
||||||
new ShortcodeInfoDto{ Shortcode = "%БУКВЫ:ИМЯ АТРИБУТА%",
|
|
||||||
Description = "Извлекает только буквы из значения поля. Пример: %БУКВЫ:ЗОНА_ОТВЕТСТВЕННОСТИ% → ПРИВ",
|
|
||||||
Type = ShortcodeTypeEnum.Standart
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// 3. Связи
|
// 3. Групповые шорткоды
|
||||||
|
result.AddRange(new[]
|
||||||
|
{
|
||||||
|
new ShortcodeInfoDto { Shortcode = "%ИНДЕКС%",
|
||||||
|
Description = "Порядковый индекс шаблона для групповых работ",
|
||||||
|
Type = ShortcodeTypeEnum.GroupValue },
|
||||||
|
new ShortcodeInfoDto { Shortcode = "%МАКС:ИМЯ АТРИБУТА%",
|
||||||
|
Description = "Используется только с групповым типом работ. Наиболее часто встречающееся значение поля в группе (игнорирует пустые). Пример: %МАКС:РАБОЧАЯ_ГР_ОТВ_ЗА_ЭК%",
|
||||||
|
Type = ShortcodeTypeEnum.GroupValue },
|
||||||
|
new ShortcodeInfoDto { Shortcode = "%ГР_ПОЛЕ-ПН%",
|
||||||
|
Description = "Нумерованный список unit-ов из шаблона: 1. ЭК-123 (Значение1, Значение2). Использует GroupingUnitFieldId из JobGroup.",
|
||||||
|
Type = ShortcodeTypeEnum.GroupValue },
|
||||||
|
});
|
||||||
|
|
||||||
|
// 4. Трансформирующие шорткоды
|
||||||
|
result.Add(new ShortcodeInfoDto
|
||||||
|
{
|
||||||
|
Shortcode = "%БУКВЫ:ИМЯ АТРИБУТА%",
|
||||||
|
Description = "Извлекает только буквы из значения поля. Пример: %БУКВЫ:ЗОНА_ОТВЕТСТВЕННОСТИ% → ПРИВ",
|
||||||
|
Type = ShortcodeTypeEnum.Transform
|
||||||
|
});
|
||||||
|
|
||||||
|
// 5. Связи
|
||||||
result.AddRange(new[]
|
result.AddRange(new[]
|
||||||
{
|
{
|
||||||
new ShortcodeInfoDto { Shortcode = "%СВЯЗИ%",
|
new ShortcodeInfoDto { Shortcode = "%СВЯЗИ%",
|
||||||
@@ -339,13 +562,10 @@ namespace PARR.DAL.DomainServices.Shortcodes
|
|||||||
new ShortcodeInfoDto { Shortcode = "%СВЯЗИ-ПН%",
|
new ShortcodeInfoDto { Shortcode = "%СВЯЗИ-ПН%",
|
||||||
Description = "Связанные ЭК с нумерацией (1. ..., 2. ...), выбираются только при настроенном фильтре по полям в связанных ЭК",
|
Description = "Связанные ЭК с нумерацией (1. ..., 2. ...), выбираются только при настроенном фильтре по полям в связанных ЭК",
|
||||||
Type = ShortcodeTypeEnum.Relationship },
|
Type = ShortcodeTypeEnum.Relationship },
|
||||||
new ShortcodeInfoDto { Shortcode = "%ГР_ПОЛЕ-ПН%",
|
|
||||||
Description = "Нумерованный список unit-ов из шаблона: 1. ЭК-123 (Значение1, Значение2). Использует GroupingUnitFieldId из JobGroup.",
|
|
||||||
Type = ShortcodeTypeEnum.Relationship },
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// 4. Все доступные поля из UnitField
|
// 6. Все доступные поля из UnitField
|
||||||
var fieldNames = await unitFieldService.Get().AsNoTracking().Select(t => new { t.AihitName, t.DisplayName }).ToListAsync();
|
var fieldNames = await unitFieldService.Get().AsNoTracking().Select(t => new { t.AihitName, t.DisplayName }).ToListAsync().ConfigureAwait(false);
|
||||||
foreach (var fieldName in fieldNames.OrderBy(n => n.AihitName))
|
foreach (var fieldName in fieldNames.OrderBy(n => n.AihitName))
|
||||||
{
|
{
|
||||||
result.Add(new ShortcodeInfoDto
|
result.Add(new ShortcodeInfoDto
|
||||||
@@ -367,7 +587,7 @@ namespace PARR.DAL.DomainServices.Shortcodes
|
|||||||
if (requiredFieldNames.Count == 0)
|
if (requiredFieldNames.Count == 0)
|
||||||
return resultName;
|
return resultName;
|
||||||
|
|
||||||
var fieldValues = await unitInValueService.GetFieldValuesAsync(unitId, requiredFieldNames);
|
var fieldValues = await unitInValueService.GetFieldValuesAsync(unitId, requiredFieldNames).ConfigureAwait(false);
|
||||||
|
|
||||||
var fieldValuesMap = fieldValues
|
var fieldValuesMap = fieldValues
|
||||||
.GroupBy(x => x.FieldName, StringComparer.OrdinalIgnoreCase)
|
.GroupBy(x => x.FieldName, StringComparer.OrdinalIgnoreCase)
|
||||||
@@ -395,15 +615,56 @@ namespace PARR.DAL.DomainServices.Shortcodes
|
|||||||
return resultName;
|
return resultName;
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string ReplaceStandardShortcodes(JobForShortcodes job, Unit unit, string input, int? index = null)
|
private static string ReplaceStandardShortcodes(JobForShortcodes? job, string unitName, string input)
|
||||||
{
|
{
|
||||||
return input
|
var result = input;
|
||||||
.Replace("%ЭК%", unit.Name, StringComparison.OrdinalIgnoreCase)
|
|
||||||
.Replace("%ГРУППА_РАБОТ%", job.Group?.GroupName ?? "", StringComparison.OrdinalIgnoreCase)
|
// %ЭК% — заменяем, только если есть в строке
|
||||||
.Replace("%РАБОТА%", job.WorkName, StringComparison.OrdinalIgnoreCase)
|
if (result.Contains("%ЭК%", StringComparison.OrdinalIgnoreCase))
|
||||||
.Replace("%ТНК%", job.Tnk?.Name ?? "", StringComparison.OrdinalIgnoreCase)
|
{
|
||||||
.Replace("%ТНК-КРАТКО%", job.Tnk?.ShortName ?? "", StringComparison.OrdinalIgnoreCase)
|
result = ReplaceSingleShortcode(result, "%ЭК%", unitName);
|
||||||
.Replace("%ИНДЕКС%", index?.ToString() ?? "", StringComparison.OrdinalIgnoreCase);
|
}
|
||||||
|
|
||||||
|
// %ТИКТАК% — не зависит от Job или Unit
|
||||||
|
if (result.Contains("%ТИКТАК%", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
result = ReplaceSingleShortcode(result, "%ТИКТАК%", DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString());
|
||||||
|
}
|
||||||
|
|
||||||
|
if (job != null)
|
||||||
|
{
|
||||||
|
if (result.Contains("%РАБОТА%", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
result = ReplaceSingleShortcode(result, "%РАБОТА%", job.WorkName);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.Contains("%ГРУППА_РАБОТ%", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
result = ReplaceSingleShortcode(result, "%ГРУППА_РАБОТ%", job.Group?.GroupName);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.Contains("%ТНК%", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
result = ReplaceSingleShortcode(result, "%ТНК%", job.Tnk?.Name);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.Contains("%ТНК-КРАТКО%", StringComparison.OrdinalIgnoreCase))
|
||||||
|
{
|
||||||
|
result = ReplaceSingleShortcode(result, "%ТНК-КРАТКО%", job.Tnk?.ShortName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string ReplaceSingleShortcode(string input, string shortcode, string? replacement)
|
||||||
|
{
|
||||||
|
if (replacement == null)
|
||||||
|
{
|
||||||
|
throw new InvalidOperationException($"Шорткод '{shortcode}' требует непустое значение, но подставляемое значение равно null.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return input.Replace(shortcode, replacement, StringComparison.OrdinalIgnoreCase);
|
||||||
}
|
}
|
||||||
|
|
||||||
private static string ReplaceConstants(List<BLL.Domain.TemplateNameConstantPart> nameConstants, string resultName)
|
private static string ReplaceConstants(List<BLL.Domain.TemplateNameConstantPart> nameConstants, string resultName)
|
||||||
@@ -414,17 +675,17 @@ namespace PARR.DAL.DomainServices.Shortcodes
|
|||||||
return resultName;
|
return resultName;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<string> ReplaceMaxShortcodesAsync(Guid jobGroupId, Guid unitId, string input, MatchCollection maxShortcodes)
|
private async Task<string> ReplaceMaxShortcodesAsync(Guid jobGroupId, Guid unitId, string input, MatchCollection maxShortcodes, string caller)
|
||||||
{
|
{
|
||||||
if (jobGroupId == Guid.Empty)
|
if (jobGroupId == Guid.Empty)
|
||||||
{
|
{
|
||||||
logger.LogWarning("jobGroupId не задан. Пропускаем обработку %МАКС:...%");
|
logger.LogWarning("[{Caller}] jobGroupId не задан. Пропускаем обработку %МАКС:...%", caller);
|
||||||
return input;
|
return input;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (unitId == Guid.Empty)
|
if (unitId == Guid.Empty)
|
||||||
{
|
{
|
||||||
logger.LogWarning("unitId не задан. Пропускаем обработку %МАКС:...%");
|
logger.LogWarning("[{Caller}] unitId не задан. Пропускаем обработку %МАКС:...%", caller);
|
||||||
return input;
|
return input;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -439,10 +700,10 @@ namespace PARR.DAL.DomainServices.Shortcodes
|
|||||||
var matches = kvp.Value;
|
var matches = kvp.Value;
|
||||||
var fieldName = fullShortcode.Trim('%').Split(':', 2)[1].Trim();
|
var fieldName = fullShortcode.Trim('%').Split(':', 2)[1].Trim();
|
||||||
|
|
||||||
logger.LogDebug("Обработка {Shortcode} для JobGroup {JobGroupId}, Template.UnitId {UnitId}, fieldName {FieldName}",
|
logger.LogDebug("[{Caller}] Обработка {Shortcode} для JobGroup {JobGroupId}, Template.UnitId {UnitId}, fieldName {FieldName}",
|
||||||
fullShortcode, jobGroupId, unitId, fieldName);
|
caller, fullShortcode, jobGroupId, unitId, fieldName);
|
||||||
|
|
||||||
var mostFrequentValue = await GetMaxShortCodeFromCacheOrDbAsync(jobGroupId, unitId, fullShortcode, fieldName);
|
var mostFrequentValue = await GetMaxShortCodeFromCacheOrDbAsync(jobGroupId, unitId, fullShortcode, fieldName, caller).ConfigureAwait(false);
|
||||||
|
|
||||||
foreach (var match in matches)
|
foreach (var match in matches)
|
||||||
input = input.Replace(match.Value, mostFrequentValue);
|
input = input.Replace(match.Value, mostFrequentValue);
|
||||||
@@ -451,30 +712,30 @@ namespace PARR.DAL.DomainServices.Shortcodes
|
|||||||
return input;
|
return input;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<string> GetMaxShortCodeFromCacheOrDbAsync(Guid jobGroupId, Guid unitId, string fullShortcode, string fieldName)
|
private async Task<string> GetMaxShortCodeFromCacheOrDbAsync(Guid jobGroupId, Guid unitId, string fullShortcode, string fieldName, string caller)
|
||||||
{
|
{
|
||||||
if (jobGroupId == Guid.Empty)
|
if (jobGroupId == Guid.Empty)
|
||||||
{
|
{
|
||||||
logger.LogWarning("jobGroupId не задан. Пропускаем обработку шорткода {Shortcode}", fullShortcode);
|
logger.LogWarning("[{Caller}] jobGroupId не задан. Пропускаем обработку шорткода {Shortcode}", caller, fullShortcode);
|
||||||
return "Нет данных";
|
return NoContent;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (unitId == Guid.Empty)
|
if (unitId == Guid.Empty)
|
||||||
{
|
{
|
||||||
logger.LogWarning("unitId не задан. Пропускаем обработку шорткода {Shortcode}", fullShortcode);
|
logger.LogWarning("[{Caller}] unitId не задан. Пропускаем обработку шорткода {Shortcode}", caller, fullShortcode);
|
||||||
return "Нет данных";
|
return NoContent;
|
||||||
}
|
}
|
||||||
|
|
||||||
var cacheKey = $"gr_shcd_{jobGroupId:N}_{unitId:N}_{ComputeHash(fullShortcode)}";
|
var cacheKey = $"gr_shcd_{jobGroupId:N}_{unitId:N}_{ComputeHash(fullShortcode)}";
|
||||||
|
|
||||||
var cachedData = await cacheService.GetCachedDataAsync<CachedGroupedShortCode>(cacheKey);
|
var cachedData = await cacheService.GetCachedDataAsync<CachedGroupedShortCode>(cacheKey).ConfigureAwait(false);
|
||||||
if (cachedData != null)
|
if (cachedData != null)
|
||||||
{
|
{
|
||||||
logger.LogDebug("Кэш попал для GroupedShortCode '{Name}': {Value}", fullShortcode, cachedData.Value);
|
logger.LogDebug("[{Caller}] Кэш попал для GroupedShortCode '{Name}': {Value}", caller, fullShortcode, cachedData.Value);
|
||||||
return cachedData.Value;
|
return cachedData.Value;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.LogDebug("Кэш промахнут для GroupedShortCode '{Name}'. Запрашиваем из БД.", fullShortcode);
|
logger.LogDebug("[{Caller}] Кэш промахнут для GroupedShortCode '{Name}'. Запрашиваем из БД.", caller, fullShortcode);
|
||||||
|
|
||||||
// Загружаем юниты из БД
|
// Загружаем юниты из БД
|
||||||
var effectiveUnitIds = await jobService.Get()
|
var effectiveUnitIds = await jobService.Get()
|
||||||
@@ -490,14 +751,14 @@ namespace PARR.DAL.DomainServices.Shortcodes
|
|||||||
.SelectMany(template => template.UnitsInTemplate)
|
.SelectMany(template => template.UnitsInTemplate)
|
||||||
.Select(uit => uit.UnitId)
|
.Select(uit => uit.UnitId)
|
||||||
.Distinct()
|
.Distinct()
|
||||||
.ToListAsync();
|
.ToListAsync().ConfigureAwait(false);
|
||||||
|
|
||||||
logger.LogDebug("EffectiveUnitIds: [{Ids}], Count: {Count}", string.Join(", ", effectiveUnitIds), effectiveUnitIds.Count);
|
logger.LogDebug("[{Caller}] EffectiveUnitIds: [{Ids}], Count: {Count}", caller, string.Join(", ", effectiveUnitIds), effectiveUnitIds.Count);
|
||||||
|
|
||||||
// Вызываем метод из сервиса
|
// Вызываем метод из сервиса
|
||||||
var mostFrequentValue = await unitInValueService.GetMostFrequentValueForFieldAsync(effectiveUnitIds, fieldName);
|
var mostFrequentValue = await unitInValueService.GetMostFrequentValueForFieldAsync(effectiveUnitIds, fieldName).ConfigureAwait(false);
|
||||||
|
|
||||||
logger.LogDebug("Результат GetMostFrequentValueForFieldAsync: {Result}, для поля {FieldName}, unitIds: [{Ids}]", mostFrequentValue, fieldName, string.Join(", ", effectiveUnitIds));
|
logger.LogDebug("[{Caller}] Результат GetMostFrequentValueForFieldAsync: {Result}, для поля {FieldName}, unitIds: [{Ids}]", caller, mostFrequentValue, fieldName, string.Join(", ", effectiveUnitIds));
|
||||||
|
|
||||||
// Не кэшируем пустые значения
|
// Не кэшируем пустые значения
|
||||||
if (!string.IsNullOrEmpty(mostFrequentValue))
|
if (!string.IsNullOrEmpty(mostFrequentValue))
|
||||||
@@ -506,18 +767,18 @@ namespace PARR.DAL.DomainServices.Shortcodes
|
|||||||
{
|
{
|
||||||
Value = mostFrequentValue,
|
Value = mostFrequentValue,
|
||||||
Timestamp = DateTimeOffset.UtcNow,
|
Timestamp = DateTimeOffset.UtcNow,
|
||||||
Source = GetType().Name,
|
Source = typeof(ShortcodesService).Name,
|
||||||
Version = 1
|
Version = 1
|
||||||
};
|
};
|
||||||
|
|
||||||
await cacheService.SetCachedDataAsync(cacheKey, toCache, TimeSpan.FromHours(1));
|
await cacheService.SetCachedDataAsync(cacheKey, toCache, TimeSpan.FromHours(1)).ConfigureAwait(false);
|
||||||
return mostFrequentValue;
|
return mostFrequentValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
return "Нет данных";
|
return NoContent;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async Task<string> ReplaceLettersShortcodesAsync(Guid unitId, string input, MatchCollection lettersShortcodes)
|
private async Task<string> ReplaceLettersShortcodesAsync(Guid unitId, string input, MatchCollection lettersShortcodes, string caller)
|
||||||
{
|
{
|
||||||
var shortcodeToMatches = lettersShortcodes
|
var shortcodeToMatches = lettersShortcodes
|
||||||
.Cast<Match>()
|
.Cast<Match>()
|
||||||
@@ -526,30 +787,29 @@ namespace PARR.DAL.DomainServices.Shortcodes
|
|||||||
|
|
||||||
foreach (var kvp in shortcodeToMatches)
|
foreach (var kvp in shortcodeToMatches)
|
||||||
{
|
{
|
||||||
var fullShortcode = kvp.Key; // например, "%БУКВЫ:ЗОНА_ОТВЕТСТВЕННОСТИ%"
|
var fullShortcode = kvp.Key;
|
||||||
var matches = kvp.Value;
|
var matches = kvp.Value;
|
||||||
var fieldName = fullShortcode.Trim('%').Split(':', 2)[1].Trim(); // "ЗОНА_ОТВЕТСТВЕННОСТИ"
|
var fieldName = fullShortcode.Trim('%').Split(':', 2)[1].Trim();
|
||||||
|
|
||||||
logger.LogDebug("Обработка {Shortcode} для unitId {UnitId}, fieldName {FieldName}", fullShortcode, unitId, fieldName);
|
logger.LogDebug("[{Caller}] Обработка {Shortcode} для unitId {UnitId}, fieldName {FieldName}", caller, fullShortcode, unitId, fieldName);
|
||||||
|
|
||||||
// Получаем значение поля через unitInValueService.GetFieldValuesAsync
|
var fieldValues = await unitInValueService.GetFieldValuesAsync(unitId, new List<string> { fieldName }).ConfigureAwait(false);
|
||||||
var fieldValues = await unitInValueService.GetFieldValuesAsync(unitId, new List<string> { fieldName });
|
|
||||||
|
|
||||||
string extractedLetters = string.Empty;
|
string extractedLetters = string.Empty;
|
||||||
|
|
||||||
if (fieldValues.Any())
|
if (fieldValues.Any())
|
||||||
{
|
{
|
||||||
var value = fieldValues.First().Value; // Берём первое значение, если несколько
|
var value = fieldValues.First().Value;
|
||||||
if (value != null)
|
if (value != null)
|
||||||
{
|
{
|
||||||
extractedLetters = ExtractLettersOnly(value);
|
extractedLetters = ExtractLettersOnly(value);
|
||||||
logger.LogDebug("Извлечены буквы: '{Letters}' из значения '{Value}'", extractedLetters, value);
|
logger.LogDebug("[{Caller}] Извлечены буквы: '{Letters}' из значения '{Value}'", caller, extractedLetters, value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (string.IsNullOrEmpty(extractedLetters))
|
if (string.IsNullOrEmpty(extractedLetters))
|
||||||
{
|
{
|
||||||
logger.LogDebug("Для шорткода {Shortcode} не найдено подходящее значение или из него нельзя извлечь буквы", fullShortcode);
|
logger.LogDebug("[{Caller}] Для шорткода {Shortcode} не найдено подходящее значение или из него нельзя извлечь буквы", caller, fullShortcode);
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var match in matches)
|
foreach (var match in matches)
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Configuration;
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.DependencyInjection;
|
using Microsoft.Extensions.DependencyInjection;
|
||||||
using PARR.DAL.Cache.Services;
|
|
||||||
using PARR.DAL.Cache.Services.Base;
|
using PARR.DAL.Cache.Services.Base;
|
||||||
using PARR.DAL.Configurations.DbSettings;
|
using PARR.DAL.Configurations.DbSettings;
|
||||||
using PARR.DAL.Context;
|
using PARR.DAL.Context;
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Npgsql;
|
||||||
|
using PARR.Common.Domain;
|
||||||
using PARR.Constants;
|
using PARR.Constants;
|
||||||
using PARR.DAL.Context;
|
using PARR.DAL.Context;
|
||||||
using PARR.DAL.Contracts;
|
using PARR.DAL.Contracts;
|
||||||
@@ -46,7 +48,7 @@ namespace PARR.DAL.Services.Implementations
|
|||||||
.ThenInclude(p => p!.Process)
|
.ThenInclude(p => p!.Process)
|
||||||
.Include(t => t.Job)
|
.Include(t => t.Job)
|
||||||
.ThenInclude(t => t!.Group)
|
.ThenInclude(t => t!.Group)
|
||||||
.ThenInclude(t=>t.GroupType);
|
.ThenInclude(t => t!.GroupType);
|
||||||
}
|
}
|
||||||
|
|
||||||
public override Task<bool> CreateAsync(Template obj)
|
public override Task<bool> CreateAsync(Template obj)
|
||||||
@@ -82,5 +84,46 @@ namespace PARR.DAL.Services.Implementations
|
|||||||
|
|
||||||
return base.CreateAsync(obj);
|
return base.CreateAsync(obj);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
public async Task<Guid?> ReserveUnusedTemplateAsync(Guid newUnitId, HistoryInitiator initiator)
|
||||||
|
{
|
||||||
|
var sql = @"
|
||||||
|
UPDATE ""Templates""
|
||||||
|
SET ""StatusTypeId"" = @NewStatus,
|
||||||
|
""DateModified"" = @DateModified,
|
||||||
|
""InitiatorIp"" = @InitiatorIp,
|
||||||
|
""InitiatorParrComponentId"" = @InitiatorComponent,
|
||||||
|
""InitiatorComment"" = @InitiatorComment
|
||||||
|
WHERE ""Id"" = (
|
||||||
|
SELECT ""Id""
|
||||||
|
FROM ""Templates""
|
||||||
|
WHERE ""StatusTypeId"" = @OldStatus
|
||||||
|
AND ""UnitId"" != @NewUnitId
|
||||||
|
ORDER BY ""DateCreated"" ASC
|
||||||
|
LIMIT 1
|
||||||
|
)
|
||||||
|
RETURNING ""Id"";";
|
||||||
|
|
||||||
|
var parameters = new[]
|
||||||
|
{
|
||||||
|
new NpgsqlParameter("@NewStatus", (int)TemplateStatusTypeEnum.Updating),
|
||||||
|
new NpgsqlParameter("@DateModified", DateTimeOffset.UtcNow),
|
||||||
|
new NpgsqlParameter("@InitiatorIp", initiator.InitiatorIp ?? (object)DBNull.Value),
|
||||||
|
new NpgsqlParameter("@InitiatorComponent",
|
||||||
|
initiator.InitiatorParrComponentId.HasValue
|
||||||
|
? (object)(int)initiator.InitiatorParrComponentId.Value
|
||||||
|
: DBNull.Value),
|
||||||
|
new NpgsqlParameter("@InitiatorComment", initiator.InitiatorComment ?? (object)DBNull.Value),
|
||||||
|
new NpgsqlParameter("@OldStatus", (int)TemplateStatusTypeEnum.Unused),
|
||||||
|
new NpgsqlParameter("@NewUnitId", newUnitId)
|
||||||
|
};
|
||||||
|
|
||||||
|
var result = await dataContext.Database
|
||||||
|
.SqlQueryRaw<Guid>(sql, parameters)
|
||||||
|
.ToListAsync();
|
||||||
|
|
||||||
|
return result.FirstOrDefault();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
using PARR.DAL.Contracts;
|
using PARR.Common.Domain;
|
||||||
using PARR.DAL.Models;
|
using PARR.DAL.Models;
|
||||||
using PARR.DAL.Services.Interfaces.Base;
|
using PARR.DAL.Services.Interfaces.Base;
|
||||||
|
|
||||||
@@ -8,6 +8,8 @@ namespace PARR.DAL.Services.Interfaces
|
|||||||
{
|
{
|
||||||
Task<Template?> GetTemplateByNameAsync(string name);
|
Task<Template?> GetTemplateByNameAsync(string name);
|
||||||
|
|
||||||
|
Task<Guid?> ReserveUnusedTemplateAsync(Guid newUnitId, HistoryInitiator initiator);
|
||||||
|
|
||||||
IQueryable<Template> GetWithIncludes();
|
IQueryable<Template> GetWithIncludes();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ using Microsoft.Extensions.Logging;
|
|||||||
using PARR.Constants;
|
using PARR.Constants;
|
||||||
using PARR.DAL.Contracts;
|
using PARR.DAL.Contracts;
|
||||||
using PARR.DAL.DomainServices.Shortcodes;
|
using PARR.DAL.DomainServices.Shortcodes;
|
||||||
using PARR.DAL.DomainServices.Shortcodes.Models;
|
|
||||||
using PARR.DAL.Models;
|
using PARR.DAL.Models;
|
||||||
using PARR.DAL.Services.Interfaces;
|
using PARR.DAL.Services.Interfaces;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
@@ -90,51 +89,20 @@ namespace PARR.EsppSync
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Построим TemplateForShortcodes из уже загруженного template
|
|
||||||
var templateForShortcodes = new TemplateForShortcodes
|
|
||||||
{
|
|
||||||
Id = template.Id,
|
|
||||||
Index = template.Index,
|
|
||||||
JobId = template.JobId,
|
|
||||||
UnitId = template.UnitId,
|
|
||||||
Job = template.Job == null ? null : new JobForShortcodes
|
|
||||||
{
|
|
||||||
Group = template.Job.Group == null ? null : new JobGroupForShortcodes
|
|
||||||
{
|
|
||||||
Id = template.Job.GroupId,
|
|
||||||
GroupingUnitFieldId = template.Job.Group.GroupingUnitFieldId,
|
|
||||||
GroupType = template.Job.Group.GroupType == null ? null : new JobGroupTypeForShortcodes
|
|
||||||
{
|
|
||||||
Code = template.Job.Group.GroupType.Code
|
|
||||||
},
|
|
||||||
GroupName = template.Job.Group.GroupName
|
|
||||||
},
|
|
||||||
Tnk = template.Job.Tnk == null ? null : new TnkForShortcodes
|
|
||||||
{
|
|
||||||
Name = template.Job.Tnk.Name,
|
|
||||||
ShortName = template.Job.Tnk.ShortName
|
|
||||||
},
|
|
||||||
WorkName = template.Job.WorkName,
|
|
||||||
Name = template.Job.Name
|
|
||||||
},
|
|
||||||
UnitsInTemplate = template.UnitsInTemplate?.Select(uit => new UnitInTemplateForShortcodes { UnitId = uit.UnitId }).ToList() ?? new List<UnitInTemplateForShortcodes>()
|
|
||||||
};
|
|
||||||
|
|
||||||
var dbObjectInEsppObject = converterToEsppObject.Invoke(template);
|
var dbObjectInEsppObject = converterToEsppObject.Invoke(template);
|
||||||
|
|
||||||
//Проверяем наличие Shortcode в полях объекта из БД
|
// Проверяем наличие Shortcode в полях объекта из БД
|
||||||
var properties = dbObjectInEsppObject.GetType().GetProperties();
|
var properties = dbObjectInEsppObject.GetType().GetProperties();
|
||||||
|
|
||||||
foreach (PropertyInfo property in properties)
|
foreach (PropertyInfo property in properties)
|
||||||
{
|
{
|
||||||
var type = property.PropertyType;
|
if (property.PropertyType == typeof(string))
|
||||||
if(type == typeof(string)){
|
{
|
||||||
// только для стрингов проверяем шорткоды
|
|
||||||
var value = property.GetValue(dbObjectInEsppObject)?.ToString();
|
var value = property.GetValue(dbObjectInEsppObject)?.ToString();
|
||||||
|
if (!string.IsNullOrEmpty(value))
|
||||||
if (value != null)
|
|
||||||
{
|
{
|
||||||
var processedValue = await shortcodesService.ApplyShortcodesAsync(value, templateForShortcodes);
|
// Передаём исходный template — он уже загружен с Include
|
||||||
|
var processedValue = await shortcodesService.ApplyShortcodesAsync(value, template);
|
||||||
property.SetValue(dbObjectInEsppObject, processedValue);
|
property.SetValue(dbObjectInEsppObject, processedValue);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -66,6 +66,8 @@ namespace PARR.TemplateGeneratorWorker
|
|||||||
var job = await jobService
|
var job = await jobService
|
||||||
.Get().AsNoTracking()
|
.Get().AsNoTracking()
|
||||||
.Include(t => t.Group)
|
.Include(t => t.Group)
|
||||||
|
.ThenInclude(g => g!.GroupType)
|
||||||
|
.Include(t => t.Tnk)
|
||||||
.FirstOrDefaultAsync(t => t.Id == query.JobId);
|
.FirstOrDefaultAsync(t => t.Id == query.JobId);
|
||||||
|
|
||||||
if (job == null)
|
if (job == null)
|
||||||
@@ -80,36 +82,20 @@ namespace PARR.TemplateGeneratorWorker
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var templateForShortcodes = new TemplateForShortcodes
|
// === Создаём временный Template для подстановки шорткодов ===
|
||||||
|
var tempTemplateForShortcodes = new Template
|
||||||
{
|
{
|
||||||
Id = Guid.Empty, // шаблон ещё не создан
|
Id = Guid.Empty, // ещё не создан
|
||||||
Index = query.Index,
|
Name = "", // не используется
|
||||||
JobId = query.JobId,
|
JobId = query.JobId,
|
||||||
UnitId = query.UnitId,
|
UnitId = query.UnitId,
|
||||||
Job = job == null ? null : new JobForShortcodes
|
Index = query.Index,
|
||||||
{
|
Job = job,
|
||||||
Group = job.Group == null ? null : new JobGroupForShortcodes
|
Unit = null, // ShortcodesService сам догрузит при необходимости
|
||||||
{
|
UnitsInTemplate = query.UnitsInTemplate?.Select(unitId => new UnitsInTemplate { UnitId = unitId }).ToList() ?? new List<UnitsInTemplate>()
|
||||||
Id = job.GroupId,
|
|
||||||
GroupingUnitFieldId = job.Group.GroupingUnitFieldId,
|
|
||||||
GroupType = job.Group.GroupType == null ? null : new JobGroupTypeForShortcodes
|
|
||||||
{
|
|
||||||
Code = job.Group.GroupType.Code
|
|
||||||
},
|
|
||||||
GroupName = job.Group.GroupName
|
|
||||||
},
|
|
||||||
Tnk = job.Tnk == null ? null : new TnkForShortcodes
|
|
||||||
{
|
|
||||||
Name = job.Tnk.Name,
|
|
||||||
ShortName = job.Tnk.ShortName
|
|
||||||
},
|
|
||||||
WorkName = job.WorkName,
|
|
||||||
Name = job.Name
|
|
||||||
},
|
|
||||||
UnitsInTemplate = query.UnitsInTemplate?.Select(guid => new UnitInTemplateForShortcodes { UnitId = guid }).ToList() ?? new List<UnitInTemplateForShortcodes>()
|
|
||||||
};
|
};
|
||||||
|
|
||||||
var templateName = await shortcodesService.ApplyShortcodesAsync(job!.TemplateNameMask!, templateForShortcodes);
|
var templateName = await shortcodesService.ApplyShortcodesAsync(job.TemplateNameMask!, tempTemplateForShortcodes);
|
||||||
|
|
||||||
var nextRun = await esppScheduleTransformService.GetNextDateAsync(job.GroupId, job.Group!.ReferenceDate);
|
var nextRun = await esppScheduleTransformService.GetNextDateAsync(job.GroupId, job.Group!.ReferenceDate);
|
||||||
|
|
||||||
@@ -125,20 +111,10 @@ namespace PARR.TemplateGeneratorWorker
|
|||||||
StatusTypeId = TemplateStatusTypeEnum.Used,
|
StatusTypeId = TemplateStatusTypeEnum.Used,
|
||||||
InitiatorComment = query.HistoryInitiator?.InitiatorComment,
|
InitiatorComment = query.HistoryInitiator?.InitiatorComment,
|
||||||
InitiatorParrComponentId = query.HistoryInitiator?.InitiatorParrComponentId,
|
InitiatorParrComponentId = query.HistoryInitiator?.InitiatorParrComponentId,
|
||||||
Index = query.Index
|
Index = query.Index,
|
||||||
|
UnitsInTemplate = query.UnitsInTemplate?.Select(unitId => new UnitsInTemplate { UnitId = unitId }).ToList() ?? new List<UnitsInTemplate>()
|
||||||
};
|
};
|
||||||
|
|
||||||
// Устанавливаем UnitsInTemplate
|
|
||||||
if (query.UnitsInTemplate != null && query.UnitsInTemplate.Any())
|
|
||||||
{
|
|
||||||
template.UnitsInTemplate = query.UnitsInTemplate.Select(unitId => new UnitsInTemplate { UnitId = unitId }).ToList();
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
// Если список пуст, все равно инициализируем коллекцию, чтобы избежать NullReferenceException при сохранении (если это не nullable)
|
|
||||||
template.UnitsInTemplate = new List<UnitsInTemplate>();
|
|
||||||
}
|
|
||||||
|
|
||||||
if (await templateService.CreateAsync(template) && await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Запрос на генерацию с тестового шаблона", InitiatorParrComponentId = ParrComponentsEnum.TemplateTaskGenerator }))
|
if (await templateService.CreateAsync(template) && await templateService.CommitAsync(new HistoryInitiator { InitiatorComment = "Запрос на генерацию с тестового шаблона", InitiatorParrComponentId = ParrComponentsEnum.TemplateTaskGenerator }))
|
||||||
{
|
{
|
||||||
logger.LogInformation("Создан шаблон: Id={TemplateId}, Name={Name}, Job={JobId}, Unit={UnitId}, Index={Index}, UnitsInTemplateCount={UnitsCount}",
|
logger.LogInformation("Создан шаблон: Id={TemplateId}, Name={Name}, Job={JobId}, Unit={UnitId}, Index={Index}, UnitsInTemplateCount={UnitsCount}",
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ namespace PARR.TemplateMatcher.Services.Implementations;
|
|||||||
internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
||||||
{
|
{
|
||||||
#if DEBUG
|
#if DEBUG
|
||||||
private readonly Guid targetUnitId = Guid.Parse("d4322a08-246b-4380-8953-8ce4a8446235");
|
private readonly Guid targetUnitId = Guid.Parse("87fc4c36-1ea8-4163-983f-1605fee1de99");
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
private const bool DefaultUsedTemplateState = false;
|
private const bool DefaultUsedTemplateState = false;
|
||||||
@@ -163,7 +163,6 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
logger.LogDebug("Юнит {TargetUnitId} НЕ найден в expectedUnitIds.", targetUnitId);
|
logger.LogDebug("Юнит {TargetUnitId} НЕ найден в expectedUnitIds.", targetUnitId);
|
||||||
//return; // ❌ юнит отсеялся на этом этапе
|
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@@ -179,7 +178,6 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
// Загрузить UnitValues для юнитов из expectedUnitIds, чтобы проверить GroupingUnitFieldId
|
// Загрузить UnitValues для юнитов из expectedUnitIds, чтобы проверить GroupingUnitFieldId
|
||||||
var expectedUnitsWithGroupingField = await unitService.Get()
|
var expectedUnitsWithGroupingField = await unitService.Get()
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
.AsSplitQuery() // Для Unit -> UnitValues
|
|
||||||
.Include(u => u.UnitValues)
|
.Include(u => u.UnitValues)
|
||||||
.ThenInclude(uv => uv.Value)
|
.ThenInclude(uv => uv.Value)
|
||||||
.Where(u => expectedUnitIds.Contains(u.Id))
|
.Where(u => expectedUnitIds.Contains(u.Id))
|
||||||
@@ -199,7 +197,6 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
logger.LogDebug("Юнит {TargetUnitId} НЕ найден в unitIdsWithValidGroupingFieldSet.", targetUnitId);
|
logger.LogDebug("Юнит {TargetUnitId} НЕ найден в unitIdsWithValidGroupingFieldSet.", targetUnitId);
|
||||||
//return; // ❌ юнит отсеялся на этом этапе
|
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@@ -212,15 +209,12 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
}
|
}
|
||||||
|
|
||||||
// --- Дополнительная фильтрация по "РАБОЧАЯ_ГР_ОТВ_ЗА_ЭК" ---
|
// --- Дополнительная фильтрация по "РАБОЧАЯ_ГР_ОТВ_ЗА_ЭК" ---
|
||||||
var unitIdsWithValidWorkGroupFieldSet = expectedUnitsWithGroupingField
|
var unitIdsWithValidWorkGroupFieldSet = await FilterByWorkGroupFieldAsync(
|
||||||
.Where(u => unitIdsWithValidGroupingFieldSet.Contains(u.Id) && // Убедимся, что юнит уже прошёл фильтр по GroupingFieldId
|
expectedUnitsWithGroupingField,
|
||||||
u.UnitValues.Any(uv =>
|
unitIdsWithValidGroupingFieldSet,
|
||||||
uv.FieldId == workGroupFieldId && // Поле "РАБОЧАЯ_ГР_ОТВ_ЗА_ЭК"
|
workGroupFieldId,
|
||||||
uv.Value != null && // Значение существует
|
regionalGroupValueIds
|
||||||
regionalGroupValueIds.Contains(uv.Value.Id) // Значение в списке разрешённых
|
);
|
||||||
))
|
|
||||||
.Select(u => u.Id) // Выбираем Id юнита
|
|
||||||
.ToHashSet(); // И снова в HashSet
|
|
||||||
|
|
||||||
#if DEBUG
|
#if DEBUG
|
||||||
// Отладка: проверить, есть ли юнит в unitIdsWithValidWorkGroupFieldSet
|
// Отладка: проверить, есть ли юнит в unitIdsWithValidWorkGroupFieldSet
|
||||||
@@ -231,7 +225,6 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
logger.LogDebug("Юнит {TargetUnitId} НЕ найден в unitIdsWithValidWorkGroupFieldSet.", targetUnitId);
|
logger.LogDebug("Юнит {TargetUnitId} НЕ найден в unitIdsWithValidWorkGroupFieldSet.", targetUnitId);
|
||||||
//return; // ❌ юнит отсеялся на этом этапе
|
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@@ -266,7 +259,6 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
logger.LogDebug("Юнит {TargetUnitId} НЕ участвует в потенциальных связях UnitInUnit.", targetUnitId);
|
logger.LogDebug("Юнит {TargetUnitId} НЕ участвует в потенциальных связях UnitInUnit.", targetUnitId);
|
||||||
// ❌ юнит отсеялся на этом этапе, если связи не требовались
|
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@@ -343,7 +335,6 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
logger.LogDebug("Юнит {TargetUnitId} НЕ участвует в отфильтрованных связях UnitInUnit.", targetUnitId);
|
logger.LogDebug("Юнит {TargetUnitId} НЕ участвует в отфильтрованных связях UnitInUnit.", targetUnitId);
|
||||||
// ❌ юнит отсеялся на этом этапе, если связи требовались
|
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@@ -386,7 +377,6 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
logger.LogDebug("Юнит {TargetUnitId} НЕ найден в groupedRelationships.Values до разрешения конфликтов.", targetUnitId);
|
logger.LogDebug("Юнит {TargetUnitId} НЕ найден в groupedRelationships.Values до разрешения конфликтов.", targetUnitId);
|
||||||
// ❌ юнит отсеялся на этапе группировки
|
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.LogDebug("Содержимое groupedRelationships до разрешения конфликтов: [{Groups}]", string.Join(", ", groupedRelationships.Select(kvp => $"Key: {kvp.Key}, Values: [{string.Join(", ", kvp.Value)}]")));
|
logger.LogDebug("Содержимое groupedRelationships до разрешения конфликтов: [{Groups}]", string.Join(", ", groupedRelationships.Select(kvp => $"Key: {kvp.Key}, Values: [{string.Join(", ", kvp.Value)}]")));
|
||||||
@@ -477,7 +467,6 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
else
|
else
|
||||||
{
|
{
|
||||||
logger.LogDebug("Юнит {TargetUnitId} НЕ найден в groupedRelationships.Values после разрешения конфликтов.", targetUnitId);
|
logger.LogDebug("Юнит {TargetUnitId} НЕ найден в groupedRelationships.Values после разрешения конфликтов.", targetUnitId);
|
||||||
// юнит отсеялся на этапе разрешения конфликтов
|
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
@@ -504,11 +493,18 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
continue;
|
continue;
|
||||||
|
|
||||||
#if DEBUG
|
#if DEBUG
|
||||||
// Отладка: проверить, есть ли ВРТ-AOS-05-ДВС в childUnitIds
|
// === Безопасная асинхронная загрузка имён для отладки ===
|
||||||
var childUnitNamesForDebug = childUnitIds.Select(id => unitService.Get().AsNoTracking().Where(u => u.Id == id).Select(u => u.Name).FirstOrDefaultAsync().GetAwaiter().GetResult() ?? id.ToString()).ToList();
|
var debugUnitIds = childUnitIds.Concat(new[] { relationshipUnitId }).Distinct().ToList();
|
||||||
|
var debugUnits = await unitService.Get()
|
||||||
|
.AsNoTracking()
|
||||||
|
.Where(u => debugUnitIds.Contains(u.Id))
|
||||||
|
.ToDictionaryAsync(u => u.Id, u => u.Name);
|
||||||
|
|
||||||
|
var childUnitNamesForDebug = childUnitIds.Select(id => debugUnits.GetValueOrDefault(id, id.ToString())).ToList();
|
||||||
|
var relationshipUnitName = debugUnits.GetValueOrDefault(relationshipUnitId, relationshipUnitId.ToString());
|
||||||
|
|
||||||
if (childUnitNamesForDebug.Contains("ВРТ-AOS-05-ДВС"))
|
if (childUnitNamesForDebug.Contains("ВРТ-AOS-05-ДВС"))
|
||||||
{
|
{
|
||||||
var relationshipUnitName = await unitService.Get().AsNoTracking().Where(u => u.Id == relationshipUnitId).Select(u => u.Name).FirstOrDefaultAsync();
|
|
||||||
logger.LogDebug("Группа с ключом {Key} (название: {Name}) содержит юнит 'ВРТ-AOS-05-ДВС' в childUnitIds: [{ChildUnitNames}]", relationshipUnitId, relationshipUnitName, string.Join(", ", childUnitNamesForDebug));
|
logger.LogDebug("Группа с ключом {Key} (название: {Name}) содержит юнит 'ВРТ-AOS-05-ДВС' в childUnitIds: [{ChildUnitNames}]", relationshipUnitId, relationshipUnitName, string.Join(", ", childUnitNamesForDebug));
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@@ -553,6 +549,12 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
|
|
||||||
// 9. Загрузить существующие шаблоны для targetJob, связанные с relationshipUnitId
|
// 9. Загрузить существующие шаблоны для targetJob, связанные с relationshipUnitId
|
||||||
var existingTemplatesForRelationship = await templateService.Get()
|
var existingTemplatesForRelationship = await templateService.Get()
|
||||||
|
.Include(t => t.Unit)
|
||||||
|
.Include(t => t.Job)
|
||||||
|
.ThenInclude(t => t!.Tnk)
|
||||||
|
.Include(t => t.Job)
|
||||||
|
.ThenInclude(t => t.Group)
|
||||||
|
.ThenInclude(t => t.GroupType)
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
.Include(t => t.UnitsInTemplate)
|
.Include(t => t.UnitsInTemplate)
|
||||||
.Where(t => t.JobId == targetJob.Id && t.UnitId == relationshipUnitId && t.Index == i && t.StatusTypeId == TemplateStatusTypeEnum.Used)
|
.Where(t => t.JobId == targetJob.Id && t.UnitId == relationshipUnitId && t.Index == i && t.StatusTypeId == TemplateStatusTypeEnum.Used)
|
||||||
@@ -570,8 +572,8 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
{
|
{
|
||||||
logger.LogDebug("Шаблон {TemplateId} (Job {JobId}, Relationship {RelationshipId}, Index {Index}) актуален по юнитам.", existingTemplateForSubGroup.Id, targetJob.Id, relationshipUnitId, i);
|
logger.LogDebug("Шаблон {TemplateId} (Job {JobId}, Relationship {RelationshipId}, Index {Index}) актуален по юнитам.", existingTemplateForSubGroup.Id, targetJob.Id, relationshipUnitId, i);
|
||||||
|
|
||||||
// Проверить, изменилось ли имя шаблона (например, из-за %МАКС:...% или %ТНК-КРАТКО%)
|
// Проверить, изменилось ли имя шаблона
|
||||||
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(targetJob, relationshipUnitId, i, subGroup);
|
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(existingTemplateForSubGroup);
|
||||||
if (!string.Equals(existingTemplateForSubGroup.Name, expectedName, StringComparison.OrdinalIgnoreCase))
|
if (!string.Equals(existingTemplateForSubGroup.Name, expectedName, StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
logger.LogDebug("Шаблон {TemplateId} требует обновления имени: старое = '{OldName}', новое = '{NewName}'", existingTemplateForSubGroup.Id, existingTemplateForSubGroup.Name, expectedName);
|
logger.LogDebug("Шаблон {TemplateId} требует обновления имени: старое = '{OldName}', новое = '{NewName}'", existingTemplateForSubGroup.Id, existingTemplateForSubGroup.Name, expectedName);
|
||||||
@@ -625,7 +627,20 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
{
|
{
|
||||||
logger.LogInformation("Переиспользован шаблон {TemplateId} для Job {JobId}, связанного юнита {RelationshipId}, Index {Index}.", reusableTemplate.Id, targetJob.Id, relationshipUnitId, i);
|
logger.LogInformation("Переиспользован шаблон {TemplateId} для Job {JobId}, связанного юнита {RelationshipId}, Index {Index}.", reusableTemplate.Id, targetJob.Id, relationshipUnitId, i);
|
||||||
|
|
||||||
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(targetJob, relationshipUnitId, i, subGroup);
|
// === Создаём временный Template для нормализации имени ===
|
||||||
|
var tempTemplateForName = new Template
|
||||||
|
{
|
||||||
|
Id = reusableTemplate.Id,
|
||||||
|
Name = reusableTemplate.Name,
|
||||||
|
JobId = targetJob.Id,
|
||||||
|
UnitId = relationshipUnitId,
|
||||||
|
Index = i,
|
||||||
|
Job = targetJob,
|
||||||
|
Unit = reusableTemplate.Unit,
|
||||||
|
UnitsInTemplate = subGroup.Select(id => new UnitsInTemplate { UnitId = id }).ToList()
|
||||||
|
};
|
||||||
|
|
||||||
|
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(tempTemplateForName);
|
||||||
var nextRun = await GetNextRunAsync(targetJob);
|
var nextRun = await GetNextRunAsync(targetJob);
|
||||||
|
|
||||||
var updateRequest = new TemplateUpdaterMq
|
var updateRequest = new TemplateUpdaterMq
|
||||||
@@ -719,13 +734,28 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
|
|
||||||
// --- Вспомогательные методы ---
|
// --- Вспомогательные методы ---
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Фильтрует юниты по полю "РАБОЧАЯ_ГР_ОТВ_ЗА_ЭК"
|
||||||
|
/// </summary>
|
||||||
|
private async Task<HashSet<Guid>> FilterByWorkGroupFieldAsync(
|
||||||
|
List<Unit> units,
|
||||||
|
HashSet<Guid> candidateUnitIds,
|
||||||
|
Guid workGroupFieldId,
|
||||||
|
List<Guid> regionalGroupValueIds)
|
||||||
|
{
|
||||||
|
return units
|
||||||
|
.Where(u => candidateUnitIds.Contains(u.Id) &&
|
||||||
|
u.UnitValues.Any(uv =>
|
||||||
|
uv.FieldId == workGroupFieldId &&
|
||||||
|
uv.Value != null &&
|
||||||
|
regionalGroupValueIds.Contains(uv.Value.Id)))
|
||||||
|
.Select(u => u.Id)
|
||||||
|
.ToHashSet();
|
||||||
|
}
|
||||||
|
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Выбирает Job, соответствующий размеру подгруппы
|
/// Выбирает Job, соответствующий размеру подгруппы
|
||||||
/// </summary>
|
/// </summary>
|
||||||
/// <param name="jobsInGroup">Список Job'ов в группе</param>
|
|
||||||
/// <param name="subGroupSize">Размер подгруппы</param>
|
|
||||||
/// <param name="maxJob">Job с максимальным MaxValueRelationships</param>
|
|
||||||
/// <returns>Найденный Job или maxJob, если не найден подходящий</returns>
|
|
||||||
private Job SelectTargetJob(List<Job> jobsInGroup, int subGroupSize, Job maxJob)
|
private Job SelectTargetJob(List<Job> jobsInGroup, int subGroupSize, Job maxJob)
|
||||||
{
|
{
|
||||||
Job? targetJob = jobsInGroup
|
Job? targetJob = jobsInGroup
|
||||||
@@ -742,7 +772,7 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
|
|
||||||
if (targetJob == null)
|
if (targetJob == null)
|
||||||
{
|
{
|
||||||
targetJob = maxJob; // maxJob уже проверен на null ранее
|
targetJob = maxJob;
|
||||||
logger.LogDebug("Для подгруппы размером {Size} не найден подходящий Job, используем maxJob {MaxJobId}.", subGroupSize, maxJob.Id);
|
logger.LogDebug("Для подгруппы размером {Size} не найден подходящий Job, используем maxJob {MaxJobId}.", subGroupSize, maxJob.Id);
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@@ -764,7 +794,20 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(targetJob, template.UnitId, template.Index, newUnitIds);
|
// === Создаём временный Template для нормализации имени ===
|
||||||
|
var tempTemplateForName = new Template
|
||||||
|
{
|
||||||
|
Id = template.Id,
|
||||||
|
Name = template.Name,
|
||||||
|
JobId = targetJob.Id,
|
||||||
|
UnitId = template.UnitId,
|
||||||
|
Index = template.Index,
|
||||||
|
Job = targetJob,
|
||||||
|
Unit = template.Unit,
|
||||||
|
UnitsInTemplate = newUnitIds.Select(id => new UnitsInTemplate { UnitId = id }).ToList()
|
||||||
|
};
|
||||||
|
|
||||||
|
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(tempTemplateForName);
|
||||||
var nextRun = await GetNextRunAsync(targetJob, template.NextRun);
|
var nextRun = await GetNextRunAsync(targetJob, template.NextRun);
|
||||||
|
|
||||||
var updateRequest = new TemplateUpdaterMq
|
var updateRequest = new TemplateUpdaterMq
|
||||||
@@ -793,9 +836,9 @@ internal class GroupedTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
var mqRequest = new TemplateGeneratorMq
|
var mqRequest = new TemplateGeneratorMq
|
||||||
{
|
{
|
||||||
JobId = jobId,
|
JobId = jobId,
|
||||||
UnitId = relationshipUnitId, // UnitId шаблона
|
UnitId = relationshipUnitId,
|
||||||
UnitsInTemplate = unitIds, // Юниты для UnitsInTemplate
|
UnitsInTemplate = unitIds,
|
||||||
Index = index, // Индекс шаблона
|
Index = index,
|
||||||
HistoryInitiator = initiator
|
HistoryInitiator = initiator
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ using PARR.Common.Domain;
|
|||||||
using PARR.Constants;
|
using PARR.Constants;
|
||||||
using PARR.DAL.DomainServices.Interfaces;
|
using PARR.DAL.DomainServices.Interfaces;
|
||||||
using PARR.DAL.DomainServices.Shortcodes;
|
using PARR.DAL.DomainServices.Shortcodes;
|
||||||
|
using PARR.DAL.Models;
|
||||||
using PARR.DAL.Models.Job;
|
using PARR.DAL.Models.Job;
|
||||||
using PARR.DAL.Services.Interfaces;
|
using PARR.DAL.Services.Interfaces;
|
||||||
using PARR.DAL.Services.Interfaces.Job;
|
using PARR.DAL.Services.Interfaces.Job;
|
||||||
@@ -127,6 +128,12 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
|
|
||||||
var existingTemplates = await templateService.Get()
|
var existingTemplates = await templateService.Get()
|
||||||
.Include(t => t.UnitsInTemplate)
|
.Include(t => t.UnitsInTemplate)
|
||||||
|
.Include(t => t.Job)
|
||||||
|
.ThenInclude(t => t!.Group)
|
||||||
|
.ThenInclude(t => t.GroupType)
|
||||||
|
.Include(t => t.Job)
|
||||||
|
.ThenInclude(t => t!.Tnk)
|
||||||
|
.Include(t => t.Unit)
|
||||||
.Where(t => t.JobId == jobId)
|
.Where(t => t.JobId == jobId)
|
||||||
.ToListAsync();
|
.ToListAsync();
|
||||||
|
|
||||||
@@ -147,12 +154,24 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
foreach (var unitId in newUnitIds)
|
foreach (var unitId in newUnitIds)
|
||||||
{
|
{
|
||||||
var reusableTemplate = await templateReuser.TryReuseOneUnusedTemplateAsync(jobId, unitId, initiator);
|
var reusableTemplate = await templateReuser.TryReuseOneUnusedTemplateAsync(jobId, unitId, initiator);
|
||||||
|
|
||||||
if (reusableTemplate != null)
|
if (reusableTemplate != null)
|
||||||
{
|
{
|
||||||
logger.LogInformation("Переиспользован шаблон {TemplateId} для Job {JobId}, UnitId {UnitId}.", reusableTemplate.Id, jobId, unitId);
|
logger.LogInformation("Переиспользован шаблон {TemplateId} для Job {JobId}, UnitId {UnitId}.", reusableTemplate.Id, jobId, unitId);
|
||||||
|
|
||||||
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(job, unitId);
|
// === Создаём временный Template для нормализации имени ===
|
||||||
|
var tempTemplateForName = new Template
|
||||||
|
{
|
||||||
|
Id = reusableTemplate.Id,
|
||||||
|
Name = reusableTemplate.Name,
|
||||||
|
JobId = jobId,
|
||||||
|
UnitId = unitId,
|
||||||
|
Index = reusableTemplate.Index,
|
||||||
|
Job = job, // загруженный job
|
||||||
|
Unit = reusableTemplate.Unit, // может быть null — нормально
|
||||||
|
UnitsInTemplate = new List<UnitsInTemplate>() // для простого шаблона
|
||||||
|
};
|
||||||
|
|
||||||
|
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(tempTemplateForName);
|
||||||
var nextRun = await GetNextRunAsync(job);
|
var nextRun = await GetNextRunAsync(job);
|
||||||
|
|
||||||
var updateRequest = new TemplateUpdaterMq
|
var updateRequest = new TemplateUpdaterMq
|
||||||
@@ -183,7 +202,7 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
{
|
{
|
||||||
if (unitIds.Contains(template.UnitId))
|
if (unitIds.Contains(template.UnitId))
|
||||||
{
|
{
|
||||||
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(job, template.UnitId);
|
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(template);
|
||||||
if (!string.Equals(template.Name, expectedName, StringComparison.OrdinalIgnoreCase))
|
if (!string.Equals(template.Name, expectedName, StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
logger.LogDebug("Шаблон {TemplateId} требует обновления имени: старое = '{OldName}', новое = '{NewName}'", template.Id, template.Name, expectedName);
|
logger.LogDebug("Шаблон {TemplateId} требует обновления имени: старое = '{OldName}', новое = '{NewName}'", template.Id, template.Name, expectedName);
|
||||||
@@ -267,7 +286,13 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
|
|
||||||
var existingTemplates = await templateService.Get()
|
var existingTemplates = await templateService.Get()
|
||||||
.AsNoTracking()
|
.AsNoTracking()
|
||||||
|
.Include(t => t.Unit)
|
||||||
.Include(t => t.UnitsInTemplate)
|
.Include(t => t.UnitsInTemplate)
|
||||||
|
.Include(t => t.Job)
|
||||||
|
.ThenInclude(t => t!.Group)
|
||||||
|
.ThenInclude(t => t!.GroupType)
|
||||||
|
.Include(t => t.Job)
|
||||||
|
.ThenInclude(t => t!.Tnk)
|
||||||
.Where(t => t.JobId == jobId && t.StatusTypeId == TemplateStatusTypeEnum.Used)
|
.Where(t => t.JobId == jobId && t.StatusTypeId == TemplateStatusTypeEnum.Used)
|
||||||
.ToListAsync();
|
.ToListAsync();
|
||||||
|
|
||||||
@@ -275,7 +300,7 @@ internal class SimpleTemplateSynchronizer : ITemplateSynchronizer
|
|||||||
{
|
{
|
||||||
if (unitIds.Contains(template.UnitId))
|
if (unitIds.Contains(template.UnitId))
|
||||||
{
|
{
|
||||||
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(job, template.UnitId);
|
var expectedName = await templateNameNormalizer.GetNormalizedTemplateNameAsync(template);
|
||||||
if (!string.Equals(template.Name, expectedName, StringComparison.OrdinalIgnoreCase))
|
if (!string.Equals(template.Name, expectedName, StringComparison.OrdinalIgnoreCase))
|
||||||
{
|
{
|
||||||
logger.LogDebug("Шаблон {TemplateId} требует обновления имени: старое = '{OldName}', новое = '{NewName}'", template.Id, template.Name, expectedName);
|
logger.LogDebug("Шаблон {TemplateId} требует обновления имени: старое = '{OldName}', новое = '{NewName}'", template.Id, template.Name, expectedName);
|
||||||
|
|||||||
@@ -76,8 +76,20 @@ internal class TemplateDeactivator : ITemplateDeactivator
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Вычисляем имя шаблона с новым Job
|
// === Создаём временный Template для нормализации имени ===
|
||||||
var expectedName = await namenormalizer.GetNormalizedTemplateNameAsync(unusedJob, template.UnitId);
|
var tempTemplateForName = new Template
|
||||||
|
{
|
||||||
|
Id = template.Id,
|
||||||
|
Name = template.Name,
|
||||||
|
JobId = unusedJob.Id,
|
||||||
|
UnitId = template.UnitId,
|
||||||
|
Index = template.Index,
|
||||||
|
Job = unusedJob,
|
||||||
|
Unit = template.Unit,
|
||||||
|
UnitsInTemplate = new List<UnitsInTemplate>()
|
||||||
|
};
|
||||||
|
|
||||||
|
var expectedName = await namenormalizer.GetNormalizedTemplateNameAsync(tempTemplateForName);
|
||||||
|
|
||||||
var updateRequest = new TemplateUpdaterMq
|
var updateRequest = new TemplateUpdaterMq
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
using PARR.DAL.DomainServices.Shortcodes;
|
using PARR.DAL.DomainServices.Shortcodes;
|
||||||
using PARR.DAL.DomainServices.Shortcodes.Models;
|
using PARR.DAL.Models;
|
||||||
using PARR.DAL.Models.Job;
|
|
||||||
using PARR.TemplateMatcher.Services.Interfaces;
|
using PARR.TemplateMatcher.Services.Interfaces;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
namespace PARR.TemplateMatcher.Services.Implementations;
|
namespace PARR.TemplateMatcher.Services.Implementations;
|
||||||
|
|
||||||
@@ -14,38 +14,15 @@ internal class TemplateNameNormalizer : ITemplateNameNormalizer
|
|||||||
this.shortcodesService = shortcodesService;
|
this.shortcodesService = shortcodesService;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<string> GetNormalizedTemplateNameAsync(Job job, Guid unitId, int? index = null, List<Guid>? templateUnitIds = null)
|
public async Task<string> GetNormalizedTemplateNameAsync(Template template, [CallerMemberName] string? caller = null)
|
||||||
{
|
{
|
||||||
var templateForShortcodes = new TemplateForShortcodes
|
var callerName = caller ?? "Unknown";
|
||||||
{
|
|
||||||
Id = Guid.Empty,
|
if (template.Job == null)
|
||||||
Index = (index != null) ? index + 1 : index,
|
throw new ArgumentNullException(nameof(template.Job));
|
||||||
JobId = job.Id,
|
|
||||||
UnitId = unitId,
|
var rawName = await shortcodesService.ApplyShortcodesAsync(template.Job.TemplateNameMask, template, callerName);
|
||||||
Job = new JobForShortcodes
|
|
||||||
{
|
|
||||||
Group = job.Group != null ? new JobGroupForShortcodes
|
|
||||||
{
|
|
||||||
Id = job.Group.Id,
|
|
||||||
GroupingUnitFieldId = job.Group.GroupingUnitFieldId,
|
|
||||||
GroupType = job.Group.GroupType != null ? new JobGroupTypeForShortcodes
|
|
||||||
{
|
|
||||||
Code = job.Group.GroupType.Code
|
|
||||||
} : null,
|
|
||||||
GroupName = job.Group.GroupName
|
|
||||||
} : null,
|
|
||||||
Tnk = job.Tnk != null ? new TnkForShortcodes
|
|
||||||
{
|
|
||||||
Name = job.Tnk.Name,
|
|
||||||
ShortName = job.Tnk.ShortName ?? ""
|
|
||||||
} : null,
|
|
||||||
WorkName = job.WorkName,
|
|
||||||
Name = job.Name
|
|
||||||
},
|
|
||||||
UnitsInTemplate = templateUnitIds?.Select(id => new UnitInTemplateForShortcodes { UnitId = id }).ToList() ?? new List<UnitInTemplateForShortcodes>()
|
|
||||||
};
|
|
||||||
|
|
||||||
var rawName = await shortcodesService.ApplyShortcodesAsync(job.TemplateNameMask, templateForShortcodes);
|
|
||||||
return rawName.ToUpper();
|
return rawName.ToUpper();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Logging;
|
||||||
using PARR.Common.Domain;
|
using PARR.Common.Domain;
|
||||||
using PARR.Constants;
|
|
||||||
using PARR.DAL.Models;
|
using PARR.DAL.Models;
|
||||||
using PARR.DAL.Services.Interfaces;
|
using PARR.DAL.Services.Interfaces;
|
||||||
using PARR.TemplateMatcher.Services.Interfaces;
|
using PARR.TemplateMatcher.Services.Interfaces;
|
||||||
@@ -10,8 +9,6 @@ namespace PARR.TemplateMatcher.Services.Implementations;
|
|||||||
|
|
||||||
internal class TemplateReuser : ITemplateReuser
|
internal class TemplateReuser : ITemplateReuser
|
||||||
{
|
{
|
||||||
private const int UnusedCandidateBatchSize = 10;
|
|
||||||
|
|
||||||
private readonly ILogger<TemplateReuser> logger;
|
private readonly ILogger<TemplateReuser> logger;
|
||||||
private readonly ITemplateService templateService;
|
private readonly ITemplateService templateService;
|
||||||
|
|
||||||
@@ -25,7 +22,7 @@ internal class TemplateReuser : ITemplateReuser
|
|||||||
|
|
||||||
public async Task<Template?> TryReuseOneUnusedTemplateAsync(
|
public async Task<Template?> TryReuseOneUnusedTemplateAsync(
|
||||||
Guid jobId,
|
Guid jobId,
|
||||||
Guid unitId,
|
Guid unitId,
|
||||||
HistoryInitiator initiator,
|
HistoryInitiator initiator,
|
||||||
int maxAttempts = 3)
|
int maxAttempts = 3)
|
||||||
{
|
{
|
||||||
@@ -33,57 +30,47 @@ internal class TemplateReuser : ITemplateReuser
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var unusedCandidates = await templateService.Get()
|
// Атомарно резервируем один шаблон через DAL
|
||||||
.Where(t => t.StatusTypeId == TemplateStatusTypeEnum.Unused)
|
var templateId = await templateService.ReserveUnusedTemplateAsync(unitId, initiator);
|
||||||
.OrderBy(t => t.DateModified ?? t.DateCreated)
|
|
||||||
.Take(UnusedCandidateBatchSize)
|
|
||||||
.ToListAsync();
|
|
||||||
|
|
||||||
if (!unusedCandidates.Any())
|
if (templateId == null)
|
||||||
{
|
{
|
||||||
logger.LogDebug("Нет Unused-шаблонов (попытка {Attempt}).", attempt);
|
logger.LogDebug("Нет доступных Unused-шаблонов для переиспользования (попытка {Attempt}).", attempt);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
foreach (var candidate in unusedCandidates)
|
// Загружаем зарезервированный шаблон
|
||||||
|
var template = await templateService.Get()
|
||||||
|
.AsNoTracking()
|
||||||
|
.Include(t=>t.Unit)
|
||||||
|
.Include(t=>t.Job)
|
||||||
|
.ThenInclude(t=>t!.Tnk)
|
||||||
|
.Include(t => t.Job)
|
||||||
|
.ThenInclude(t => t!.Group)
|
||||||
|
.ThenInclude(t=>t!.GroupType)
|
||||||
|
.FirstOrDefaultAsync(t => t.Id == templateId);
|
||||||
|
|
||||||
|
if (template == null)
|
||||||
{
|
{
|
||||||
var originalStatus = candidate.StatusTypeId;
|
logger.LogWarning("Зарезервированный шаблон {TemplateId} не найден при загрузке.", templateId);
|
||||||
var originalModified = candidate.DateModified;
|
continue;
|
||||||
|
|
||||||
try
|
|
||||||
{
|
|
||||||
candidate.StatusTypeId = TemplateStatusTypeEnum.Updating;
|
|
||||||
candidate.DateModified = DateTimeOffset.UtcNow;
|
|
||||||
|
|
||||||
if (await templateService.CommitAsync(initiator))
|
|
||||||
{
|
|
||||||
logger.LogInformation("Успешно захвачен шаблон {TemplateId} для переиспользования (попытка {Attempt}).",
|
|
||||||
candidate.Id, attempt);
|
|
||||||
return candidate; // Возвращаем захваченный шаблон
|
|
||||||
}
|
|
||||||
|
|
||||||
// Откат при неудаче
|
|
||||||
candidate.StatusTypeId = originalStatus;
|
|
||||||
candidate.DateModified = originalModified;
|
|
||||||
}
|
|
||||||
catch (Exception ex) when (
|
|
||||||
ex is DbUpdateException ||
|
|
||||||
ex.InnerException?.Message.Contains("deadlock", StringComparison.OrdinalIgnoreCase) == true ||
|
|
||||||
ex.InnerException?.Message.Contains("timeout", StringComparison.OrdinalIgnoreCase) == true)
|
|
||||||
{
|
|
||||||
logger.LogWarning(ex, "Конфликт при захвате шаблона {TemplateId} (попытка {Attempt}).", candidate.Id, attempt);
|
|
||||||
candidate.StatusTypeId = originalStatus;
|
|
||||||
candidate.DateModified = originalModified;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (attempt < maxAttempts)
|
logger.LogInformation(
|
||||||
await Task.Delay(Random.Shared.Next(5, 15) * attempt);
|
"Успешно захвачен шаблон {TemplateId} (старый Job {OldJobId}) для нового Job {NewJobId}, Unit {UnitId} (попытка {Attempt}).",
|
||||||
|
template.Id, template.JobId, jobId, unitId, attempt);
|
||||||
|
|
||||||
|
return template;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
logger.LogError(ex, "Ошибка в попытке захвата (попытка {Attempt}).", attempt);
|
logger.LogError(ex, "Ошибка при попытке захвата шаблона (попытка {Attempt}).", attempt);
|
||||||
if (attempt == maxAttempts) throw;
|
|
||||||
|
if (attempt == maxAttempts)
|
||||||
|
throw;
|
||||||
|
|
||||||
|
// Небольшая задержка перед повтором
|
||||||
|
await Task.Delay(Random.Shared.Next(10, 50));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
using PARR.DAL.Models.Job;
|
using PARR.DAL.Models;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
|
|
||||||
namespace PARR.TemplateMatcher.Services.Interfaces
|
namespace PARR.TemplateMatcher.Services.Interfaces
|
||||||
{
|
{
|
||||||
public interface ITemplateNameNormalizer
|
public interface ITemplateNameNormalizer
|
||||||
{
|
{
|
||||||
Task<string> GetNormalizedTemplateNameAsync(Job job, Guid unitId, int? index = null, List<Guid>? templateUnitIds = null);
|
Task<string> GetNormalizedTemplateNameAsync(Template template, [CallerMemberName] string? caller = null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user