feat(esppScheduleSync, esppSync): вынесена логика сравнения nextRun из EsppSync в EsppScheduleSync. Рефакторинг EsppScheduleSync - логика проверки имени шаблона

This commit is contained in:
Mikhail Trubnikov
2026-02-18 11:40:25 +10:00
parent d17f6cf409
commit 517d446bcf
6 changed files with 272 additions and 255 deletions

View File

@@ -3,6 +3,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using PARR.BLL.Helpers;
using PARR.BLL.Services.Interfaces;
using PARR.Common.Domain;
using PARR.Constants;
using PARR.DAL.Contracts;
using PARR.DAL.Models;
@@ -12,6 +13,7 @@ using PARR.DAL.Services.Interfaces.Schedule;
using PARR.EsppScheduleSync.Settings;
using PARR.EsppSync;
using PARR.EsppSync.Domain;
using PARR.EsppSync.Helpers;
namespace PARR.EsppScheduleSync
{
@@ -23,7 +25,6 @@ namespace PARR.EsppScheduleSync
private readonly ISyncService<EsppObjectSchedule> syncService;
private readonly SettingsFromDb settingsFromDb;
private readonly IServiceProvider serviceProvider;
private readonly IScheduleResponseAreaTimeOffsetService scheduleResponseAreaTimeOffsetService;
private string noneExcludeCalendarEsppValue;
@@ -33,8 +34,7 @@ namespace PARR.EsppScheduleSync
IMqService mqService,
ISyncService<EsppObjectSchedule> syncService,
SettingsFromDb settingsFromDb,
IServiceProvider serviceProvider,
IScheduleResponseAreaTimeOffsetService scheduleResponseAreaTimeOffsetService
IServiceProvider serviceProvider
)
{
this.logger = logger;
@@ -43,7 +43,6 @@ namespace PARR.EsppScheduleSync
this.syncService = syncService;
this.settingsFromDb = settingsFromDb;
this.serviceProvider = serviceProvider;
this.scheduleResponseAreaTimeOffsetService = scheduleResponseAreaTimeOffsetService;
this.noneExcludeCalendarEsppValue = string.Empty;
if (globalSettings.MqSettings == null)
@@ -74,7 +73,19 @@ namespace PARR.EsppScheduleSync
}
public async Task StopAsync()
{
await mqService.DisposeAsync();
logger.LogInformation("=== === === Соединение с очередью {QueueName} закрыто === === ===", globalSettings.MqSettings!.QueueName);
}
/// <summary>
/// Получение типа исключения
/// </summary>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
private async Task GetNoneExcludeCalendarEsppValueAsync()
{
using var scope = serviceProvider.CreateScope();
@@ -88,153 +99,98 @@ namespace PARR.EsppScheduleSync
noneExcludeCalendarEsppValue = noneExcludeType.EsppValue;
}
public async Task StopAsync()
{
await mqService.DisposeAsync();
logger.LogInformation("=== === === Соединение с очередью {QueueName} закрыто === === ===", globalSettings.MqSettings!.QueueName);
}
/// <summary>
/// Старт синхронизации, получили сообщение
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private async Task SyncScheduleAsync(string str)
{
try
await syncService.SyncEsppObjectAsync(str, ParseStrToEsppObject, ConvertDbObjToEsppObj, CustomComparisionCheckAsyncHandler, AfterParseStringToEsppObjectAsyncHandler);
}
/// <summary>
/// Выполняется после парсинга строки в объект ЕСПП.
/// Проверка, есть ли у расписания шаблон. Если имена шаблона и расписания не совпадают, установить шаблону статус обновления.
/// </summary>
/// <param name="esppObject"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
private async Task AfterParseStringToEsppObjectAsyncHandler(EsppObjectSchedule esppObject)
{
var esppScheduleId = esppObject.Code;
var esppTemplateName = esppObject.TemplateName;
using var scope = serviceProvider.CreateScope();
var templateService = scope.ServiceProvider.GetRequiredService<ITemplateService>();
var candidates = await templateService.Get()
.Include(t => t.RobotConfigurations)
.Where(t => t.Name == esppTemplateName || t.ScheduleEsppId == esppScheduleId)
.ToListAsync();
var templateByName = candidates.FirstOrDefault(t => t.Name == esppTemplateName);
var templateByScheduleId = candidates.FirstOrDefault(t => t.ScheduleEsppId == esppScheduleId);
if (templateByName == null && templateByScheduleId == null)
{
const int expectedParts = 24;
var separator = globalSettings.ParsingSeparator;
var parts = str.Split(separator);
if (parts.Length != expectedParts)
{
logger.LogWarning("Некорректное количество полей в строке расписания: {Actual} (ожидается {Expected})", parts.Length, expectedParts);
await syncService.SyncEsppObjectAsync(str, ParseStrToEsppObject, ConvertDbObjToEsppObj);
return;
}
var esppScheduleId = parts[0]; // ScheduleEsppId из ЕСПП
var templateNameRaw = parts[6];
var templateName = templateNameRaw.ToUpper();
// Проверка префикса (как в ParseStrToEsppObject)
if (string.IsNullOrEmpty(settingsFromDb.TemplatePrefixWithoutVariable) ||
!templateName.Contains(settingsFromDb.TemplatePrefixWithoutVariable))
{
logger.LogWarning("Имя шаблона '{TemplateName}' не соответствует префиксу '{Prefix}'. Пропущено.", templateName, settingsFromDb.TemplatePrefixWithoutVariable);
await syncService.SyncEsppObjectAsync(str, ParseStrToEsppObject, ConvertDbObjToEsppObj);
return;
}
// === ЕДИНЫЙ ЗАПРОС: ищем по имени ИЛИ по ScheduleEsppId ===
using var scope = serviceProvider.CreateScope();
var templateService = scope.ServiceProvider.GetRequiredService<ITemplateService>();
var candidates = await templateService.Get()
.Include(t => t.RobotConfigurations)
.Where(t => t.Name == templateName || t.ScheduleEsppId == esppScheduleId)
.ToListAsync();
var templateByName = candidates.FirstOrDefault(t => t.Name == templateName);
var templateByScheduleId = candidates.FirstOrDefault(t => t.ScheduleEsppId == esppScheduleId);
if (templateByName == null && templateByScheduleId == null)
{
// Нет ни по имени, ни по ID
logger.LogWarning(
"Расписание из ЕСПП не привязано ни к одному шаблону: TemplateName='{TemplateName}', ScheduleEsppId='{EsppId}'",
templateName,
esppScheduleId
);
}
else if (templateByName == null && templateByScheduleId != null)
{
// Есть только по ID → имя не совпадает
logger.LogWarning(
"Расхождение привязки: расписание из ЕСПП с ScheduleEsppId='{EsppId}' и TemplateName='{TemplateName}' " +
"соответствует шаблону в БД с именем '{DbTemplateName}', Id='{TemplateId}'.",
esppScheduleId,
templateName,
templateByScheduleId.Name,
templateByScheduleId.Id
);
// Принудительно выставляем статус обновления шаблона, так как имя в ЕСПП изменилось
try
{
var robotConfigurationService = scope.ServiceProvider.GetRequiredService<IRobotConfigurationService>();
var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.TemplateOrder, templateByScheduleId);
robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, config);
// Сохраняем изменения в базу данных
if (!await robotConfigurationService.CommitAsync())
{
logger.LogError("Не удалось сохранить изменения статуса задачи для шаблона Id='{TemplateId}'", templateByScheduleId.Id);
}
else
{
logger.LogDebug($"Для шаблона {nameof(templateByScheduleId.Id)}:{templateByScheduleId.Id} установлен статус {RobotStatusEnum.Wait.ToString()} при обнаружении расхождения имени с ЕСПП");
}
}
catch (Exception updateEx)
{
logger.LogError(updateEx, "Ошибка при установке статуса обновления для шаблона Id='{TemplateId}'", templateByScheduleId.Id);
}
}
else if (templateByName != null)
{
var dbScheduleId = templateByName.ScheduleEsppId ?? string.Empty;
if (string.IsNullOrEmpty(dbScheduleId))
{
// Утерян ID в БД
logger.LogWarning(
"У шаблона '{TemplateName}' (Id='{TemplateId}') отсутствует ScheduleEsppId в БД, но в ЕСПП он равен '{EsppId}'",
templateName,
templateByName.Id,
esppScheduleId
);
}
else if (dbScheduleId != esppScheduleId)
{
// ID не совпадают — проверяем, не занят ли esppScheduleId другим шаблоном
var conflictingTemplate = candidates.FirstOrDefault(t =>
t.Id != templateByName.Id && t.ScheduleEsppId == esppScheduleId);
if (conflictingTemplate != null)
{
logger.LogWarning(
"Конфликт ScheduleEsppId: расписание '{EsppId}' из ЕСПП с именем '{TemplateName}' " +
"уже привязано к другому шаблону '{OtherTemplateName}' (Id='{OtherTemplateId}') в БД.",
esppScheduleId,
templateName,
conflictingTemplate.Name,
conflictingTemplate.Id
);
}
else
{
logger.LogWarning(
"Несовпадение ScheduleEsppId для шаблона '{TemplateName}' (Id='{TemplateId}'): в БД='{DbId}', в ЕСПП='{EsppId}'",
templateName,
templateByName.Id,
dbScheduleId,
esppScheduleId
);
}
}
}
// Передаём оригинальную строку в стандартный синхронизатор
await syncService.SyncEsppObjectAsync(str, ParseStrToEsppObject, ConvertDbObjToEsppObj);
// Нет ни по имени, ни по ID
logger.LogWarning("Расписание из ЕСПП не привязано ни к одному шаблону: TemplateName='{TemplateName}', ScheduleEsppId='{EsppId}'", esppTemplateName, esppScheduleId);
}
catch (Exception ex)
else if (templateByName == null && templateByScheduleId != null)
{
logger.LogError(ex, "Ошибка при синхронизации расписания из строки: {InputString}", str);
// Есть только по ID → имя не совпадает
logger.LogWarning("Расхождение привязки: расписание из ЕСПП с ScheduleEsppId='{EsppId}' и TemplateName='{TemplateName}' соответствует шаблону в БД с именем '{DbTemplateName}', Id='{TemplateId}'.",
esppScheduleId, esppTemplateName, templateByScheduleId.Name, templateByScheduleId.Id);
// Принудительно выставляем статус обновления шаблона, так как имя в ЕСПП изменилось
var robotConfigurationService = scope.ServiceProvider.GetRequiredService<IRobotConfigurationService>();
var config = robotConfigurationService.GetFromTemplateByRobotCode(RobotsEnum.TemplateOrder, templateByScheduleId);
logger.LogDebug("Текущий статус задания {taskStatusCode} шаблона {templateId}", config.TaskStatusCode, templateByScheduleId.Id);
robotConfigurationService.ChangeTaskStatus(TaskStatusEnum.Updating, config);
// Сохраняем изменения в базу данных
if (!await templateService.CommitAsync(new HistoryInitiator { InitiatorParrComponentId = ParrComponentsEnum.EsppScheduleSync, InitiatorComment = "Расхождение привязки, расписание из ЕСПП не соответствует имени шаблона в БД" }))
{
logger.LogError("Не удалось сохранить изменения статуса задачи для шаблона Id='{TemplateId}'", templateByScheduleId.Id);
}
else
{
logger.LogDebug("Для шаблона {templateId} установлен статус задания {taskStatus} при обнаружении расхождения имени с ЕСПП",
templateByScheduleId.Id, TaskStatusEnum.Updating.ToString());
}
}
else if (templateByName != null)
{
var dbScheduleId = templateByName.ScheduleEsppId ?? string.Empty;
if (string.IsNullOrEmpty(dbScheduleId))
{
// Утерян ID в БД
logger.LogWarning("У шаблона '{TemplateName}' (Id='{TemplateId}') отсутствует ScheduleEsppId в БД, но в ЕСПП он равен '{EsppId}'", esppTemplateName, templateByName.Id, esppScheduleId);
}
else if (dbScheduleId != esppScheduleId)
{
// ID не совпадают — проверяем, не занят ли esppScheduleId другим шаблоном
var conflictingTemplate = candidates.FirstOrDefault(t => t.Id != templateByName.Id && t.ScheduleEsppId == esppScheduleId);
if (conflictingTemplate != null)
{
logger.LogWarning("Конфликт ScheduleEsppId: расписание '{EsppId}' из ЕСПП с именем '{TemplateName}' уже привязано к другому шаблону '{OtherTemplateName}' (Id='{OtherTemplateId}') в БД.",
esppScheduleId, esppTemplateName, conflictingTemplate.Name, conflictingTemplate.Id);
}
else
{
logger.LogWarning("Несовпадение ScheduleEsppId для шаблона '{TemplateName}' (Id='{TemplateId}'): в БД='{DbId}', в ЕСПП='{EsppId}'",
esppTemplateName, templateByName.Id, dbScheduleId, esppScheduleId);
}
}
}
}
/// <summary>
/// Преобразование модели БД в модель для сравнения
/// </summary>
@@ -291,6 +247,85 @@ namespace PARR.EsppScheduleSync
return ClearOptionalFields(esppObjectFromDb);
}
/// <summary>
/// Кастомная дополнительная проверка полей
/// </summary>
/// <param name="esppObject"></param>
/// <param name="dbObject"></param>
/// <param name="templateId"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
private async Task<bool> CustomComparisionCheckAsyncHandler(EsppObjectSchedule esppObject, EsppObjectSchedule dbObject, Guid templateId)
{
// рассчитать nextRun, и сравнить все три nextRun, БД - ЕСПП - Расчитанное
// в часовой зоне робота
var calculatedNextRun = await CalcNextRunWithRobotTzAsync(templateId);
if (calculatedNextRun == null)
{
return false;
}
var scheduledCalculated = EsppScheduleHelpers.GetNextRun(calculatedNextRun.Value);
var basisTimeCalculated = EsppScheduleHelpers.GetGenerationTime(calculatedNextRun.Value);
logger.LogDebug("Рассчитанные значения для шаблона '{templateName}', {templateId}, следующее срабатывание {scheduledCalculated}, время создания наряда: {basisTimeCalculated}",
dbObject.TemplateName, templateId, scheduledCalculated, basisTimeCalculated);
if (EsppSyncHelpers.Normalize(dbObject.Scheduled) != EsppSyncHelpers.Normalize(esppObject.Scheduled) || EsppSyncHelpers.Normalize(dbObject.Scheduled) != scheduledCalculated || EsppSyncHelpers.Normalize(esppObject.Scheduled) != scheduledCalculated)
{
logger.LogInformation("Не совпадают поля ({propName}), dbValueStr: {dbValueStr}, esppValueStr: {esppValueStr}, scheduledCalculated: {scheduledCalculated}. Имя шаблона: {templateName}",
nameof(dbObject.Scheduled), dbObject.Scheduled, esppObject.Scheduled, scheduledCalculated, dbObject.TemplateName);
return false;
}
if (EsppSyncHelpers.Normalize(dbObject.BasisTime) != EsppSyncHelpers.Normalize(esppObject.BasisTime) || EsppSyncHelpers.Normalize(dbObject.BasisTime) != basisTimeCalculated || EsppSyncHelpers.Normalize(esppObject.BasisTime) != basisTimeCalculated)
{
logger.LogInformation("Не совпадают поля ({propName}), dbValueStr: {dbValueStr}, esppValueStr: {esppValueStr}, basisTimeCalculated: {basisTimeCalculated}. Имя шаблона: {templateName}",
nameof(dbObject.BasisTime), dbObject.BasisTime, esppObject.BasisTime, basisTimeCalculated, dbObject.TemplateName);
return false;
}
logger.LogDebug("Значения nextRun в БД, ЕСПП, расчитанное, все совпадают. Scheduled: {scheduled}, basisTime: {basisTime}", scheduledCalculated, basisTimeCalculated);
return true;
}
/// <summary>
/// Рассчитать nextRun в часовом поясе УЗ робота
/// </summary>
/// <param name="templateId"></param>
/// <returns></returns>
private async Task<DateTimeOffset?> CalcNextRunWithRobotTzAsync(Guid templateId)
{
using var scope = serviceProvider.CreateScope();
var nextRunService = scope.ServiceProvider.GetRequiredService<INextRunServiceV2>();
var nextRun = await nextRunService.GetNextRunForTemplateAsync(templateId, isNew: false);
if (nextRun.HasValue)
{
var nextRunWithEsppAccountTz = nextRun.Value.Add(nextRunService.GetEsppAccountOffset());
logger.LogDebug("Расчитанный nextRun для шаблона {templateId}, UTC: {nextRun}, EsppAccountTz: {nextRunWithEsppAccountTz}", templateId, nextRun, nextRunWithEsppAccountTz);
return nextRunWithEsppAccountTz;
}
else
{
logger.LogError("При расчете nextRun для templateId: {templateId} верунлся null", templateId);
return null;
}
}
/// <summary>
/// Получить "В каком часовом поясе"
/// </summary>
/// <returns></returns>
private string GetTimezone(/*Template template, string responseArea*/)
{
// договорились, что у роботоа ТЗ МСК