using DigitalData.Core.Abstraction.Application.Repository; using DigitalData.EmailProfilerDispatcher.Abstraction.Entities; using EnvelopeGenerator.Application.Configurations; using EnvelopeGenerator.Domain.Constants; using EnvelopeGenerator.Domain.Entities; using MediatR; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace EnvelopeGenerator.Application.Notifications; /// /// /// public interface ISendMailNotification : INotification { /// /// /// public EmailTemplateType TemplateType { get; } /// /// /// public string EmailAddress { get; } } /// /// /// public abstract class SendMailHandler : INotificationHandler where TNotification : ISendMailNotification { /// /// /// protected readonly IRepository TempRepo; /// /// /// protected readonly IRepository EmailOutRepo; /// /// /// protected virtual Dictionary PlaceHolders { get; } = new(); /// /// /// protected readonly MailParams MailParams; /// /// /// protected readonly DispatcherParams DispatcherParams; /// /// /// /// /// protected abstract void ConfigEmailOut(TNotification notification, EmailOut emailOut); /// /// /// /// /// /// /// protected SendMailHandler(IRepository tempRepo, IRepository emailOutRepo, IOptions mailParamsOptions, IOptions dispatcherParamsOptions) { TempRepo = tempRepo; EmailOutRepo = emailOutRepo; MailParams = mailParamsOptions.Value; DispatcherParams = dispatcherParamsOptions.Value; } /// /// /// /// /// /// /// public async Task Handle(TNotification notification, CancellationToken cancel) { var temp = await TempRepo .ReadOnly() .SingleOrDefaultAsync(x => x.Name == notification.TemplateType.ToString(), cancel) ?? throw new InvalidOperationException($"Receiver information is missing in the notification." + $"{typeof(TNotification)}:\n {JsonConvert.SerializeObject(notification, Format.Json.ForDiagnostics)}"); temp.Subject = ReplacePlaceHolders(temp.Subject, PlaceHolders, MailParams.Placeholders); temp.Body = ReplacePlaceHolders(temp.Body, PlaceHolders, MailParams.Placeholders); var emailOut = new EmailOut { EmailAddress = notification.EmailAddress, EmailBody = temp.Body, EmailSubj = temp.Subject, AddedWhen = DateTime.UtcNow, AddedWho = DispatcherParams.AddedWho, SendingProfile = DispatcherParams.SendingProfile, ReminderTypeId = DispatcherParams.ReminderTypeId, EmailAttmt1 = DispatcherParams.EmailAttmt1, WfId = (int)EnvelopeStatus.MessageConfirmationSent, }; ConfigEmailOut(notification, emailOut); await EmailOutRepo.CreateAsync(emailOut, cancel); } private static string ReplacePlaceHolders(string text, params Dictionary[] placeHoldersList) { foreach (var placeHolders in placeHoldersList) foreach (var ph in placeHolders) text = text.Replace(ph.Key, ph.Value); return text; } }