Files
parr_api/PARR.EsppScheduleSync/ScheduleSyncher.cs
2023-11-24 16:52:56 +10:00

267 lines
11 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Microsoft.Extensions.Logging;
using PARR.BLL.Services.Interfaces;
using PARR.DAL.Contracts;
using PARR.DAL.Models;
using PARR.EsppScheduleSync.Domain;
using PARR.EsppScheduleSync.Settings;
using PARR.EsppSync;
namespace PARR.EsppScheduleSync
{
internal class ScheduleSyncher : IScheduleSyncher
{
private readonly ILogger<ScheduleSyncher> logger;
private readonly GlobalSettings globalSettings;
private readonly IMqService mqService;
private readonly ISyncService<EsppObjectSchedule> syncService;
private readonly SettingsFromDb settingsFromDb;
public ScheduleSyncher(
ILogger<ScheduleSyncher> logger,
GlobalSettings globalSettings,
IMqService mqService,
ISyncService<EsppObjectSchedule> syncService,
SettingsFromDb settingsFromDb
)
{
this.logger = logger;
this.globalSettings = globalSettings;
this.mqService = mqService;
this.syncService = syncService;
this.settingsFromDb = settingsFromDb;
if (globalSettings.MqSettings == null)
{
logger.LogError("Нет секции настроек хранилища. MqSettings, EsppTemplates");
throw new Exception("Нет секции настроек хранилища. MqSettings, EsppTemplates");
}
}
public void Start()
{
var isConnected = mqService.InitConsumer(globalSettings!.MqSettings!, SyncScheduleAsync);
if (!isConnected)
throw new Exception("Ошибка при подключении к RabbitMq");
logger.LogInformation($"Запущена проверка очереди {globalSettings.MqSettings!.QueueName}.");
}
public void Stop()
{
mqService.Dispose();
logger.LogInformation($"=== === === Соединение с очередью {globalSettings.MqSettings!.QueueName} закрыто === === ===");
}
private async Task SyncScheduleAsync(string str)
{
await syncService.SyncEsppObjectAsync(str, ParseStrToEsppObject, ConvertDbObjToEsppObj);
}
/// <summary>
/// Преобразование модели БД в модель для сравнения
/// </summary>
/// <param name="template"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
private EsppObjectSchedule ConvertDbObjToEsppObj(Template template)
{
//todo:
throw new NotImplementedException();
}
/// <summary>
/// Парсинг из строки в модель для сравнения
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
private EsppObjectSchedule? ParseStrToEsppObject(string str)
{
var splittedContent = str.Split(globalSettings.ParsingSeparator);
if (splittedContent.Length != 23)
{
logger.LogError($"Входная строка после сплита не содержит 23 объекта (факт: {splittedContent.Length}).");
return null;
}
var templateName = splittedContent[6];
var scheduleName = splittedContent[2];
if (!IsValidName(templateName) || !IsValidName(scheduleName))
return null;
bool.TryParse(splittedContent[1].Trim(), out var isActive);
var esppObject = new EsppObjectSchedule
{
TemplateName = templateName,
Code = splittedContent[0],
ScheduleName = scheduleName,
IsActive = isActive,
ResponseArea = splittedContent[5],
WorkGroup = splittedContent[3],
//TODO:!!!
//TypeSchedule = splittedContent[7],
Interval = splittedContent[8],
Dayofweek = splittedContent[15],
Dayofmonth = splittedContent[14],
Md1 = splittedContent[16],
Md2 = splittedContent[17],
Annualm = splittedContent[13],
Annualday = splittedContent[12],
An1 = splittedContent[9],
An2 = splittedContent[10],
An3 = splittedContent[11],
TypeV60calendar = splittedContent[21],
Scheduled = splittedContent[4],
Timezone = splittedContent[18],
TerminationType = splittedContent[19],
CompleteAfter = splittedContent[20],
V60calendar = splittedContent[22]
};
return ClearOptionalFields(esppObject);
}
/// <summary>
/// Проверка имени шаблона и расписание на соответствие префиксу из настроек
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
private bool IsValidName(string name)
{
var currentCulture = Thread.CurrentThread.CurrentCulture;
if (!string.IsNullOrEmpty(settingsFromDb.TemplatePrefixName) && name.StartsWith(settingsFromDb.TemplatePrefixName, true, currentCulture))
return true;
logger.LogWarning($"Имя шаблона или расписания не соответствует обязательному префиксу({settingsFromDb.TemplatePrefixName}). {name} игнорирован");
return false;
}
/// <summary>
/// Очистка полей которые не нуждаются в синхронизации
/// </summary>
/// <param name="esppObject"></param>
/// <returns></returns>
private EsppObjectSchedule ClearOptionalFields(EsppObjectSchedule esppObject)
{
esppObject.Code = string.Empty;
esppObject.ScheduleName = string.Empty;
esppObject.ResponseArea = string.Empty;
esppObject.WorkGroup = string.Empty;
esppObject.CompleteAfter = string.Empty;
// В ЕСПП, при изменении "Повторять задачу", остаются предыдущие значения, их не нужно синхронизировать (касается только данных полученных из ЕСПП, в БД все ок)
// т.е. если стояло Ежедненвно:понедельник, а изменили например на Еженедельно..., то в ежедневно значения останутся, но будут отрабатывать значения из Еженедельно.
// Т е значения из Ежедненвно проверять не нужно, вот их и будем очищать
//TODO: сделать миграцию в БД: Еженежельно
//TODO:!!!
////Regularly, Регулярно (значение в ЕСПП и в БД не совпадают, в бд Regularly, в ЕСПП simple)
//if (esppObject.TypeSchedule.ToLower() == "simple" || esppObject.TypeSchedule.ToLower() == EsppSchTypeScheduleEnum.Regularly.ToString().ToLower())
//{
// //esppObject.Interval = string.Empty;
// esppObject.Dayofweek = string.Empty;
// esppObject.Dayofmonth = string.Empty;
// esppObject.Md1 = string.Empty;
// esppObject.Md2 = string.Empty;
// esppObject.Annualm = string.Empty;
// esppObject.Annualday = string.Empty;
// esppObject.An1 = string.Empty;
// esppObject.An2 = string.Empty;
// esppObject.An3 = string.Empty;
//}
////Weekly, Еженедельно
//if (esppObject.TypeSchedule == "weekly")
//{
// esppObject.Interval = string.Empty;
// //esppObject.Dayofweek = string.Empty;
// esppObject.Dayofmonth = string.Empty;
// esppObject.Md1 = string.Empty;
// esppObject.Md2 = string.Empty;
// esppObject.Annualm = string.Empty;
// esppObject.Annualday = string.Empty;
// esppObject.An1 = string.Empty;
// esppObject.An2 = string.Empty;
// esppObject.An3 = string.Empty;
//}
////Monthly, Ежемесячно
//if (esppObject.TypeSchedule == "monthly")
//{
// esppObject.Interval = string.Empty;
// esppObject.Dayofweek = string.Empty;
// //esppObject.Dayofmonth = string.Empty;
// esppObject.Md1 = string.Empty;
// esppObject.Md2 = string.Empty;
// esppObject.Annualm = string.Empty;
// esppObject.Annualday = string.Empty;
// esppObject.An1 = string.Empty;
// esppObject.An2 = string.Empty;
// esppObject.An3 = string.Empty;
//}
////Monthly2, Ежемесячно-2
//if (esppObject.TypeSchedule == "monthly2")
//{
// esppObject.Interval = string.Empty;
// esppObject.Dayofweek = string.Empty;
// esppObject.Dayofmonth = string.Empty;
// //esppObject.Md1 = string.Empty;
// //esppObject.Md2 = string.Empty;
// esppObject.Annualm = string.Empty;
// esppObject.Annualday = string.Empty;
// esppObject.An1 = string.Empty;
// esppObject.An2 = string.Empty;
// esppObject.An3 = string.Empty;
//}
////Annually, Ежегодно
//if (esppObject.TypeSchedule == "annually")
//{
// esppObject.Interval = string.Empty;
// esppObject.Dayofweek = string.Empty;
// esppObject.Dayofmonth = string.Empty;
// esppObject.Md1 = string.Empty;
// esppObject.Md2 = string.Empty;
// //esppObject.Annualm = string.Empty;
// //esppObject.Annualday = string.Empty;
// esppObject.An1 = string.Empty;
// esppObject.An2 = string.Empty;
// esppObject.An3 = string.Empty;
//}
////Annually2, Ежегодно-2
//if (esppObject.TypeSchedule == "annually2")
//{
// esppObject.Interval = string.Empty;
// esppObject.Dayofweek = string.Empty;
// esppObject.Dayofmonth = string.Empty;
// esppObject.Md1 = string.Empty;
// esppObject.Md2 = string.Empty;
// esppObject.Annualm = string.Empty;
// esppObject.Annualday = string.Empty;
// //esppObject.An1 = string.Empty;
// //esppObject.An2 = string.Empty;
// //esppObject.An3 = string.Empty;
//}
return esppObject;
}
}
}