55 lines
2.5 KiB
C#
55 lines
2.5 KiB
C#
using FluentValidation;
|
|
using NTP.Application.Abstractions;
|
|
using NTP.Application.Common;
|
|
|
|
namespace NTP.Application.Grains.Orders;
|
|
|
|
public interface IQuotaService
|
|
{
|
|
Task<PagedResult<QuotaDto>> GetListAsync(DateTime date, PageRequest page, CancellationToken ct);
|
|
Task<OrdersResult> SetQuotaAsync(SetQuotaRequest request, CancellationToken ct);
|
|
}
|
|
|
|
/// <summary>Port of grains.cfc getQuotaList / editQuota (quotaGrid.cfm).</summary>
|
|
public sealed class QuotaService(
|
|
IQuotaRepository repository,
|
|
IUnitOfWork unitOfWork,
|
|
ICurrentUser user,
|
|
IValidator<SetQuotaRequest> validator) : IQuotaService
|
|
{
|
|
public async Task<PagedResult<QuotaDto>> 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<QuotaDto>(items, result.Page, result.PageSize, result.TotalCount);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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).
|
|
/// </summary>
|
|
public async Task<OrdersResult> 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);
|
|
}
|
|
}
|