using DigitalData.Core.Abstraction.Application.Repository;
using EnvelopeGenerator.Domain.Constants;
using EnvelopeGenerator.Domain.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
namespace EnvelopeGenerator.Application.Notifications;
///
///
///
public interface ISendMailNotification : INotification
{
///
///
///
public EmailTemplateType TemplateType { get; }
}
///
///
///
public abstract class SendMailHandler : INotificationHandler
where TNotification : ISendMailNotification
{
///
///
///
protected readonly IRepository TempRepo;
///
///
///
protected virtual Dictionary BodyPlaceHolders { get; } = new();
///
///
///
protected virtual Dictionary SubjectPlaceHolders { get; } = new();
///
///
///
///
protected SendMailHandler(IRepository tempRepo)
{
TempRepo = tempRepo;
}
///
///
///
///
///
///
///
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, SubjectPlaceHolders);
temp.Body = ReplacePlaceHolders(temp.Body, BodyPlaceHolders);
}
private static string ReplacePlaceHolders(string text, Dictionary placeHolders)
{
foreach (var ph in placeHolders)
text = text.Replace(ph.Key, ph.Value);
return text;
}
}