69 lines
2.4 KiB
C#
69 lines
2.4 KiB
C#
using Heimdall.Application.Services;
|
|||
|
|
using Heimdall.Infrastructure.Data;
|
||
|
|
using Microsoft.EntityFrameworkCore;
|
||
|
|
using Microsoft.Extensions.Logging;
|
||
|
|
|
||
|
|
namespace Heimdall.Infrastructure.Jobs;
|
||
|
|
|
||
|
|
/// <summary>
|
||
|
|
/// Hangfire recurring job that sends a weekly digest email to users who have it enabled.
|
||
|
|
/// Scheduled Monday at 8:00.
|
||
|
|
/// Uses IDbContextFactory to avoid sharing a DbContext across Hangfire worker threads.
|
||
|
|
/// </summary>
|
||
|
|
public class WeeklyDigestJob
|
||
|
|
{
|
||
|
|
private readonly IDbContextFactory<AppDbContext> _dbFactory;
|
||
|
|
private readonly IEmailService _emailService;
|
||
|
|
private readonly ILogger<WeeklyDigestJob> _logger;
|
||
|
|
|
||
|
|
public WeeklyDigestJob(
|
||
|
|
IDbContextFactory<AppDbContext> dbFactory,
|
||
|
|
IEmailService emailService,
|
||
|
|
ILogger<WeeklyDigestJob> logger)
|
||
|
|
{
|
||
|
|
_dbFactory = dbFactory;
|
||
|
|
_emailService = emailService;
|
||
|
|
_logger = logger;
|
||
|
|
}
|
||
|
|
|
||
|
|
public async Task ExecuteAsync(CancellationToken ct = default)
|
||
|
|
{
|
||
|
|
_logger.LogInformation("Starting weekly digest job");
|
||
|
|
|
||
|
|
await using var db = await _dbFactory.CreateDbContextAsync(ct);
|
||
|
|
|
||
|
|
var configs = await db.UserNotificationConfigs
|
||
|
|
.Where(c => c.WeeklyDigest && c.EmailEnabled && c.EmailAddress != null)
|
||
|
|
.ToListAsync(ct);
|
||
|
|
|
||
|
|
var lastWeek = DateTime.UtcNow.Date.AddDays(-7);
|
||
|
|
|
||
|
|
foreach (var config in configs)
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var eventCount = await db.CameraEvents
|
||
|
|
.CountAsync(e => e.CreatedAt >= lastWeek, ct);
|
||
|
|
|
||
|
|
var subject = "Heimdall — Résumé hebdomadaire";
|
||
|
|
var body = $"""
|
||
|
|
<h2>Résumé hebdomadaire Heimdall</h2>
|
||
|
|
<p>Bonjour,</p>
|
||
|
|
<ul>
|
||
|
|
<li>Événements détectés cette semaine : <strong>{eventCount}</strong></li>
|
||
|
|
</ul>
|
||
|
|
<p>Cordialement,<br/>L'équipe Heimdall</p>
|
||
|
|
""";
|
||
|
|
|
||
|
|
await _emailService.SendEmailAsync(config.EmailAddress!, subject, body, ct);
|
||
|
|
_logger.LogDebug("Weekly digest sent to {Email}", config.EmailAddress);
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
_logger.LogError(ex, "Failed to send weekly digest to {Email}", config.EmailAddress);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
_logger.LogInformation("Weekly digest completed: {Count} emails sent", configs.Count);
|
||
|
|
}
|
||
|
|
}
|