using Helpdesk.Application.Abstractions; using Helpdesk.Application.Common; using Helpdesk.Domain; using Helpdesk.Domain.Notifications; using Microsoft.EntityFrameworkCore; namespace Helpdesk.Application.Notifications; public sealed record NotificationDeliveryDto( int Id, int NotificationId, string Channel, string Status, int AttemptCount, string? LastError, DateTime? NextAttemptAt, DateTime? SentAt); public sealed class NotificationDeliveryService(IAppDbContext db, TimeProvider clock) { public async Task> ListAsync(string status, int page, int pageSize, CancellationToken ct) { if (!EnumCode.TryParse(status, out var deliveryStatus)) throw new BadRequestException("Neplatný stav doručení."); page = Math.Max(1, page); pageSize = Math.Clamp(pageSize, 1, 100); var query = db.NotificationDeliveries.AsNoTracking().Where(d => d.Status == deliveryStatus); var count = await query.CountAsync(ct); var offset = (long)(page - 1) * pageSize; if (offset >= count) return new PagedResult([], count, page, pageSize); var rows = await query.OrderByDescending(d => d.Id).Skip((int)offset).Take(pageSize).ToListAsync(ct); var items = rows.Select(d => new NotificationDeliveryDto(d.Id, d.NotificationId, d.Channel.ToCode(), d.Status.ToCode(), d.AttemptCount, d.LastError, d.NextAttemptAt, d.SentAt)).ToArray(); return new PagedResult(items, count, page, pageSize); } public async Task RetryAsync(int id, CancellationToken ct) { var now = clock.GetUtcNow().UtcDateTime; var delivery = db.NotificationDeliveries.Where(d => d.Id == id); var updated = await delivery.Where(d => d.Status == DeliveryStatus.Failed) .ExecuteUpdateAsync(setters => setters .SetProperty(d => d.Status, DeliveryStatus.Pending) .SetProperty(d => d.AttemptCount, 0) .SetProperty(d => d.NextAttemptAt, now) .SetProperty(d => d.LastError, (string?)null) .SetProperty(d => d.SentAt, (DateTime?)null), ct); if (updated == 1) return; if (!await delivery.AnyAsync(ct)) throw new NotFoundException("Doručení neexistuje."); throw new ConflictException("Zopakovat lze pouze neúspěšné doručení."); } }