Files
parr_api/PARR.EsppTemplateSync/TemplateMQSyncer.cs

188 lines
8.1 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.DomainServices;
using PARR.DAL.Extensions;
using PARR.DAL.Models;
using PARR.EsppSync;
using PARR.EsppTemplateSync.Domain;
using PARR.EsppTemplateSync.Settings;
using System.Threading.Tasks;
namespace PARR.EsppTemplateSync
{
internal class TemplateMQSyncer : ITemplateSyncer
{
private readonly ILogger<TemplateMQSyncer> logger;
private readonly GlobalSettings globalSettings;
private readonly IMqService mqService;
private readonly ISyncService<EsppObjectTemplate> syncService;
private readonly SettingsFromDb settingsFromDb;
private readonly IShortcodesService shortcodesService;
public TemplateMQSyncer(
ILogger<TemplateMQSyncer> logger,
GlobalSettings globalSettings,
IMqService mqService,
ISyncService<EsppObjectTemplate> syncService,
SettingsFromDb settingsFromDb,
IShortcodesService shortcodesService
)
{
this.logger = logger;
this.globalSettings = globalSettings;
this.mqService = mqService;
this.syncService = syncService;
this.settingsFromDb = settingsFromDb;
this.shortcodesService = shortcodesService;
if (globalSettings.MqSettings == null)
{
logger.LogError("Нет секции настроек хранилища. MqSettings, EsppTemplates");
throw new Exception("Нет секции настроек хранилища. MqSettings, EsppTemplates");
}
}
public void Start()
{
var isConnected = mqService.InitConsumer(globalSettings!.MqSettings!, SyncTemplateAsync);
if (!isConnected)
throw new Exception("Ошибка при подключении к RabbitMq");
logger.LogInformation($"Запущена проверка очереди {globalSettings.MqSettings!.QueueName}.");
}
public void Stop()
{
mqService.Dispose();
logger.LogInformation($"=== === === Соединение с очередью {globalSettings.MqSettings!.QueueName} закрыто === === ===");
}
private async Task SyncTemplateAsync(string str)
{
await syncService.SyncEsppObjectAsync(str, ParseStrToEsppObject, ConvertDbObjToEsppObjAsync);
}
/// <summary>
/// Преобразование модели БД в модель для сравнения
/// </summary>
/// <param name="template">template должен обязательно содержать в себе информацию о Job+Group и Unit+BaseFields</param>
/// <returns></returns>
private async Task<EsppObjectTemplate> ConvertDbObjToEsppObjAsync(Template template)
{
var templateFromDb = new EsppObjectTemplate
{
TemplateName = template.Name,
IsActive = template.IsActiveTemplate,
//WorkGroup = template.Host!.WorkGroup!,
WorkGroup = template.Unit!.BaseFields!.WorkGroup!,
//ShortDescription = Normalize(template.Job.Group.ShortDescription.ApplyShortcode(Constants.Shortcodes.ShortcodeEnum.EK,template.Unit.Name)),
ShortDescription = Normalize(await shortcodesService.ApplyShortcodesAsync(template.Job!.Group!.ShortDescription,template.UnitId,template.JobId)),//TODO Вынести в переменную
//ResponseArea = template.Host!.ResponseArea!.Name,
//ЗО берем РГ а не хоста
ResponseArea = template.Unit.BaseFields.ResponseArea!,
Duration = template.Job.Group.TemplateDuration,
EK = template.Unit.Name,
FullDescription = Normalize(template.Job.Group.FullDescription),
Solution = Normalize(template.Job.Group.Solution),
Process = template.Job.Tnk!.Subprocess!.Process!.Name,
SubProcess = template.Job.Tnk.Subprocess.Name,
//TNK = template.Job.Tnk.Name.ApplyShortcode(Constants.Shortcodes.ShortcodeEnum.EK, template.Unit.Name),
TNK = Normalize(await shortcodesService.ApplyShortcodesAsync(template.Job.Tnk.Name, template.UnitId, template.JobId)),
Work = Normalize(await shortcodesService.ApplyShortcodesAsync(template.Job.WorkName, template.UnitId, template.JobId)),
Initiator = settingsFromDb.Initiator
};
return templateFromDb;
}
/// <summary>
/// Парсинг из строки в модель для сравнения
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private EsppObjectTemplate? ParseStrToEsppObject(string str)
{
var splittedContent = str.Split(globalSettings.ParsingSeparator);
if (splittedContent.Length != 17)
{
logger.LogError($"Входная строка после сплита не содержит 17 объектов (факт: {splittedContent.Length}).");
return null;
}
var templateName = splittedContent[0].Trim();
var currentCulture = Thread.CurrentThread.CurrentCulture;
//if (!string.IsNullOrEmpty(settingsFromDb.TemplatePrefixName) || !templateName.StartsWith(settingsFromDb.TemplatePrefixName, true, currentCulture))
if (string.IsNullOrEmpty(settingsFromDb.TemplatePrefixWithoutVariable) || !templateName.Contains(settingsFromDb.TemplatePrefixWithoutVariable)) // , StringComparison.CurrentCultureIgnoreCase
{
logger.LogWarning($"Имя шаблона не соответствует обязательному префиксу({settingsFromDb.TemplatePrefixWithoutVariable}). Шаблон {templateName} игнорирован");
return null;
}
bool.TryParse(splittedContent[1].Trim(), out var isActive);
var workGroup = splittedContent[2].Trim();
var shortDescription = splittedContent[3].Trim();
var category = splittedContent[4].Trim();
var responseArea = splittedContent[5].Trim();
var duration = splittedContent[6].Trim();
var ek = splittedContent[7].Trim();
var initiator = splittedContent[8].Trim();
var fullDescription = splittedContent[9].Trim();
var closingCode = splittedContent[10].Trim();
var solution = splittedContent[11].Trim();
var process = splittedContent[12].Trim();
var subProcess = splittedContent[13].Trim();
var tnk = splittedContent[14].Trim();
var work = splittedContent[15].Trim();
var worker = splittedContent[16].Trim();
var templateFromEspp = new EsppObjectTemplate
{
TemplateName = templateName,
IsActive = isActive,
WorkGroup = workGroup,
ShortDescription = Normalize(shortDescription),
//Category = category,
ResponseArea = responseArea,
Duration = duration,
EK = ek,
Initiator = initiator,
FullDescription = Normalize(fullDescription),
//ClosingCode = closingCode,
Solution = Normalize(solution),
Process = process,
SubProcess = subProcess,
TNK = tnk,
Work = work
//Worker = worker
};
return templateFromEspp;
}
/// <summary>
/// Удаляет ненужные символы из строки
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private string Normalize(string str)
{
str = str.Replace("\r", string.Empty);
str = str.Replace("\n", string.Empty);
str = str.Replace(" ", string.Empty);
return str;
}
}
}