using Indotalent.Infrastructure.Database; using MediatR; using Microsoft.EntityFrameworkCore; namespace Indotalent.Features.Leave.LeaveBalance.Cqrs; public record SyncLeaveBalanceCommand() : IRequest; public class SyncLeaveBalanceHandler : IRequestHandler { private readonly AppDbContext _context; public SyncLeaveBalanceHandler(AppDbContext context) => _context = context; public async Task Handle(SyncLeaveBalanceCommand request, CancellationToken cancellationToken) { var balances = await _context.LeaveBalance.ToListAsync(cancellationToken); if (!balances.Any()) return true; var allRequests = await _context.LeaveRequest .AsNoTracking() .ToListAsync(cancellationToken); foreach (var balance in balances) { var empRequests = allRequests .Where(x => x.EmployeeId == balance.EmployeeId && x.LeaveCategoryId == balance.LeaveCategoryId && x.StartDate.Year == balance.Year) .ToList(); balance.Used = (int)empRequests.Where(x => x.Status == "Approved").Sum(x => x.Days); balance.Pending = (int)empRequests.Where(x => x.Status == "Pending").Sum(x => x.Days); balance.Remaining = (balance.Entitlement + balance.CarryForward) - balance.Used; } return await _context.SaveChangesAsync(cancellationToken) > 0; } }