Files
FACULTATE-HEALTHCARE_MANAGER/backend/Infrastructure/BackgroundServices/AppointmentCleanupService.cs
T
2024-05-30 15:40:13 +03:00

57 lines
2.3 KiB
C#

using Application.Services.Database.MongoDB;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
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);
}
}