78 lines
2.2 KiB
C#
78 lines
2.2 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public interface ISendMailNotification : INotification
|
|
{
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public EmailTemplateType TemplateType { get; }
|
|
}
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
public abstract class SendMailHandler<TNotification> : INotificationHandler<TNotification>
|
|
where TNotification : ISendMailNotification
|
|
{
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
protected readonly IRepository<EmailTemplate> TempRepo;
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
protected virtual Dictionary<string, string> BodyPlaceHolders { get; } = new();
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
protected virtual Dictionary<string, string> SubjectPlaceHolders { get; } = new();
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="tempRepo"></param>
|
|
protected SendMailHandler(IRepository<EmailTemplate> tempRepo)
|
|
{
|
|
TempRepo = tempRepo;
|
|
}
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="notification"></param>
|
|
/// <param name="cancel"></param>
|
|
/// <returns></returns>
|
|
/// <exception cref="NotImplementedException"></exception>
|
|
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<string, string> placeHolders)
|
|
{
|
|
foreach (var ph in placeHolders)
|
|
text = text.Replace(ph.Key, ph.Value);
|
|
return text;
|
|
}
|
|
}
|