56 lines
2.3 KiB
C#
56 lines
2.3 KiB
C#
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
using Application.Services.Database.MongoDB;
|
|
|
|
namespace Infrastructure.BackgroundServices;
|
|
|
|
public class AppointmentCleanupService(
|
|
IAppointmentsMongoDbService appointmentsMongoDbService,
|
|
ILogger<AppointmentCleanupService> logger)
|
|
: BackgroundService
|
|
{
|
|
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
|
{
|
|
logger.LogInformation("Appointment Cleanup Service started.");
|
|
|
|
while (!stoppingToken.IsCancellationRequested)
|
|
{
|
|
await CheckAndDeletePastAppointments();
|
|
await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
|
|
}
|
|
}
|
|
|
|
private async Task CheckAndDeletePastAppointments()
|
|
{
|
|
// Get the current UTC time and adjust it to the local timezone (GMT +3)
|
|
var currentUtcDate = DateTime.UtcNow;
|
|
var currentDate = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(currentUtcDate, "E. Europe Standard Time"); // Adjust to GMT +3
|
|
logger.LogInformation("Checking for past appointments as of local time {CurrentDate}.", currentDate);
|
|
|
|
var appointments = await appointmentsMongoDbService.GetAllAppointments(CancellationToken.None);
|
|
int updatedCount = 0, deletedCount = 0;
|
|
|
|
foreach (var appointment in appointments)
|
|
{
|
|
// Filter out past appointments based on the adjusted current date
|
|
appointment.AppointmentsList.RemoveAll(date => date < currentDate);
|
|
|
|
if (appointment.AppointmentsList.Count > 0)
|
|
{
|
|
await appointmentsMongoDbService.UpdateAppointment(appointment, CancellationToken.None);
|
|
updatedCount++;
|
|
logger.LogInformation("Updated appointment {AppointmentId} by removing past dates.", appointment.Id);
|
|
}
|
|
else
|
|
{
|
|
await appointmentsMongoDbService.DeleteAppointment(appointment.Id, CancellationToken.None);
|
|
deletedCount++;
|
|
logger.LogInformation("Deleted appointment {AppointmentId} because all dates were in the past.", appointment.Id);
|
|
}
|
|
}
|
|
|
|
logger.LogInformation("Finished checking appointments. Updated: {UpdatedCount}, Deleted: {DeletedCount}.", updatedCount, deletedCount);
|
|
}
|
|
|
|
}
|