Files
components/LiteCharms.Features/Shop/Notifications/Events/Handlers/ProcessEmailNotificationsEventHandler.cs
T
2026-05-15 08:37:58 +02:00

107 lines
3.7 KiB
C#

using LiteCharms.Features.Email;
using LiteCharms.Features.Shop.Notifications.Models;
using LiteCharms.Features.Shop.Postgres;
namespace LiteCharms.Features.Shop.Notifications.Events.Handlers;
public class ProcessEmailNotificationsEventHandler(IDbContextFactory<ShopDbContext> contextFactory, ILogger<ProcessEmailNotificationsEvent> logger,
EmailService emailService) : INotificationHandler<ProcessEmailNotificationsEvent>
{
private bool dropBatch = false;
public async ValueTask Handle(ProcessEmailNotificationsEvent message, CancellationToken cancellationToken)
{
try
{
using var context = await contextFactory.CreateDbContextAsync(cancellationToken);
var notifications = await context.Notifications
.OrderByDescending(o => o.CreatedAt)
.ThenBy(o => o.Priority)
.Where(n => n.CorrelationIdType == CorrelationIdTypes.Email)
.Where(n => n.Direction == NotificationDirection.Outgoing)
.Take(message.MaxRecords)
.ToListAsync(cancellationToken);
foreach (var notification in notifications)
{
if (dropBatch || cancellationToken.IsCancellationRequested) break;
var sendResult = await SendEmailAsync(notification,emailService, cancellationToken);
if(sendResult.IsFailed)
{
var errors = new List<string>(1000);
errors.AddRange(sendResult.Errors.Select(e => e.Message));
if (sendResult.Reasons?.Count > 0)
errors.AddRange(sendResult.Reasons.Select(e => e.Message));
notification.HasError = true;
notification.Errors = [.. errors];
}
notification.Processed = true;
notification.UpdatedAt = DateTime.UtcNow;
}
await context.SaveChangesAsync(cancellationToken);
}
catch (Exception ex)
{
logger.LogError(ex, ex.Message);
}
}
private async Task<Result> SendEmailAsync(Notification notification, EmailService service, CancellationToken cancellationToken = default)
{
try
{
using Email.Models.Message message = CreateMessage(notification);
var sendResult = await service.SendEmailAsync(message, cancellationToken);
if (sendResult.IsFailed)
{
if (emailService.Status != EmailStatuses.Success && emailService.Status != EmailStatuses.Connected) dropBatch = true;
return Result.Fail(sendResult.Errors);
}
return sendResult.IsFailed
? Result.Fail(sendResult.Errors)
: Result.Ok();
}
catch (Exception ex)
{
return Result.Fail(new Error(ex.Message).CausedBy(ex));
}
}
private static Email.Models.Message CreateMessage(Notification notification) =>
new()
{
Sender = new Email.Models.Party
{
Name = notification.SenderName,
Address = notification.SenderAddress
},
Recipient = new Email.Models.Party
{
Name = notification.RecipientName,
Address = notification.RecipientAddress
},
Subject = notification.Subject,
Body = new Email.Models.Body
{
Properties = new Email.Models.BodyProperties
{
HasAttachments = false,
IsHtml = notification.IsHtml
},
Message = notification.Message
}
};
}