using FluentValidation; using NTP.Application.Abstractions; using NTP.Application.Common; namespace NTP.Application.Grains.Orders; public interface IQuotaService { Task> GetListAsync(DateTime date, PageRequest page, CancellationToken ct); Task SetQuotaAsync(SetQuotaRequest request, CancellationToken ct); } /// Port of grains.cfc getQuotaList / editQuota (quotaGrid.cfm). public sealed class QuotaService( IQuotaRepository repository, IUnitOfWork unitOfWork, ICurrentUser user, IValidator validator) : IQuotaService { public async Task> GetListAsync(DateTime date, PageRequest page, CancellationToken ct) { var day = date.Date; var result = await repository.GetListAsync(day, page, ct); var items = result.Items.Select(r => new QuotaDto( r.DestinationId, r.Name, day.ToString("yyyy-MM-dd"), r.Quota, r.DoneQuota ?? 0, r.CreatedBy, r.CreationDate)).ToList(); return new PagedResult(items, result.Page, result.PageSize, result.TotalCount); } /// /// Deactivates the active quota row of the destination/date and inserts a new active one (history is kept). /// DONEQUOTA is carried over from the row being replaced (legacy trusted the client's grid row; the server value is used here). /// public async Task SetQuotaAsync(SetQuotaRequest request, CancellationToken ct) { await validator.ValidateAndThrowAsync(request, ct); var day = request.QuotaDate.Date; return await unitOfWork.ExecuteInTransactionAsync(async token => { if (!await repository.DestinationExistsAsync(request.DestinationId, token)) throw new NotFoundException("Destination", request.DestinationId); var active = await repository.GetActiveAsync(request.DestinationId, day, token); var done = active?.DoneQuota ?? 0; // Legacy returned silently when the new quota was lower than the used quota; now the user is told. if (!QuotaRules.CanSetQuota(request.Quota, done)) throw OrdersErrors.QuotaBelowUsed(done); await repository.DeactivateAsync(request.DestinationId, day, user.UserId, token); await repository.InsertAsync(request.DestinationId, day, request.Quota, user.UserId, done, token); return new OrdersResult(OrdersErrors.Success, request.DestinationId); }, ct); } }