QrRapido/Services/HistoryCleanupService.cs
Ricardo Carneiro 2ccd35bb7d
Some checks failed
Deploy QR Rapido / test (push) Successful in 4m58s
Deploy QR Rapido / build-and-push (push) Failing after 1m39s
Deploy QR Rapido / deploy-staging (push) Has been skipped
Deploy QR Rapido / deploy-production (push) Has been skipped
first commit
2025-07-28 11:46:48 -03:00

70 lines
3.2 KiB
C#

using QRRapidoApp.Data;
using QRRapidoApp.Models;
using MongoDB.Driver;
namespace QRRapidoApp.Services
{
public class HistoryCleanupService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<HistoryCleanupService> _logger;
private readonly IConfiguration _configuration;
public HistoryCleanupService(IServiceScopeFactory scopeFactory, ILogger<HistoryCleanupService> logger, IConfiguration configuration)
{
_scopeFactory = scopeFactory;
_logger = logger;
_configuration = configuration;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
var gracePeriodDays = _configuration.GetValue<int>("HistoryCleanup:GracePeriodDays", 7);
var cleanupIntervalHours = _configuration.GetValue<int>("HistoryCleanup:CleanupIntervalHours", 6);
while (!stoppingToken.IsCancellationRequested)
{
try
{
using var scope = _scopeFactory.CreateScope();
var context = scope.ServiceProvider.GetRequiredService<MongoDbContext>();
if (context.IsConnected && context.Users != null && context.QRCodeHistory != null)
{
// Buscar usuários que cancelaram há mais de X dias
var cutoffDate = DateTime.UtcNow.AddDays(-gracePeriodDays);
var usersToCleanup = await context.Users
.Find(u => u.PremiumCancelledAt != null &&
u.PremiumCancelledAt < cutoffDate &&
u.QRHistoryIds.Count > 0)
.ToListAsync(stoppingToken);
foreach (var user in usersToCleanup)
{
// Remover histórico de QR codes
if (user.QRHistoryIds.Any())
{
await context.QRCodeHistory.DeleteManyAsync(
qr => user.QRHistoryIds.Contains(qr.Id), stoppingToken);
// Limpar lista de histórico do usuário
var update = Builders<User>.Update.Set(u => u.QRHistoryIds, new List<string>());
await context.Users.UpdateOneAsync(u => u.Id == user.Id, update, cancellationToken: stoppingToken);
_logger.LogInformation($"Histórico removido para usuário {user.Id} - inadimplente há {gracePeriodDays}+ dias");
}
}
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Erro no cleanup do histórico");
}
// Executar a cada X horas
await Task.Delay(TimeSpan.FromHours(cleanupIntervalHours), stoppingToken);
}
}
}
}