scm-api / src /SCM.Application /Controle /AcompanhamentoService.cs
rafaeldavila's picture
Deploy SCM API (.NET 8) - Docker Space
de8b914 verified
Raw History Blame Contribute Delete
6.62 kB
using SCM.Application.Common;
using SCM.Domain.Controle;
using SCM.Shared.Exceptions;
namespace SCM.Application.Controle;
public sealed record FotoAcompanhamentoResponse(
Guid ObraId, DateOnly Data,
decimal QtLiberada, decimal QtNaoLiberada, decimal QtTotal,
decimal QtAvancada, decimal QtCadastrada,
int ItensLiberados, int ItensNaoLiberados);
public sealed record HistAcompanhamentoResponse(
Guid Id, DateOnly Data,
decimal QtLiberada, decimal QtNaoLiberada, decimal QtAvancada, decimal QtCadastrada,
int ItensLiberados, int ItensNaoLiberados, DateTime DataGeracao);
public sealed record GerarHistoricoRequest(DateOnly Data);
public sealed record GerarLoteRequest(DateOnly DataInicial, DateOnly DataFinal);
public sealed record LoteHistoricoResponse(int Gerados, IReadOnlyList<DateOnly> Datas);
public interface IAcompanhamentoService
{
Task<FotoAcompanhamentoResponse> GetFotoAsync(Guid obraId, DateOnly data, CancellationToken ct = default);
Task<HistAcompanhamentoResponse> GerarHistoricoAsync(Guid obraId, GerarHistoricoRequest request, CancellationToken ct = default);
Task<LoteHistoricoResponse> GerarLoteAsync(Guid obraId, GerarLoteRequest request, CancellationToken ct = default);
Task<IReadOnlyList<HistAcompanhamentoResponse>> GetHistoricoAsync(Guid obraId, CancellationToken ct = default);
Task<FotoAcompanhamentoResponse> GetResumoParcialAsync(Guid obraId, DateOnly dataAntiga, DateOnly dataRecente, CancellationToken ct = default);
}
/// <summary>
/// Acompanhamento (fatia 24, legado Resumo de Acompanhamento): foto atual calculada como
/// read-model sobre as produções consolidadas, histórico persistido por obra×data (upsert),
/// geração em lote de 7 em 7 dias e resumo parcial = recente − antigo campo a campo.
/// ADIADOS: agrupamento por área/grupo/característica de filtro e a trava DIFF_FILTER_CARACS
/// (características de filtro não modeladas — totalização aqui é por obra/quantidade).
/// </summary>
public sealed class AcompanhamentoService : IAcompanhamentoService
{
private readonly IAcompanhamentoRepository _repository;
private readonly IUnitOfWork _unitOfWork;
public AcompanhamentoService(IAcompanhamentoRepository repository, IUnitOfWork unitOfWork)
{
_repository = repository;
_unitOfWork = unitOfWork;
}
public async Task<FotoAcompanhamentoResponse> GetFotoAsync(Guid obraId, DateOnly data, CancellationToken ct = default)
{
await GarantirObraAsync(obraId, ct);
var foto = await _repository.CalcularFotoAsync(obraId, data, ct);
return ToResponse(obraId, data, foto);
}
public async Task<HistAcompanhamentoResponse> GerarHistoricoAsync(Guid obraId, GerarHistoricoRequest r, CancellationToken ct = default)
{
await GarantirObraAsync(obraId, ct);
var hist = await GerarAsync(obraId, r.Data, ct);
return ToResponse(hist);
}
public async Task<LoteHistoricoResponse> GerarLoteAsync(Guid obraId, GerarLoteRequest r, CancellationToken ct = default)
{
await GarantirObraAsync(obraId, ct);
if (r.DataFinal < r.DataInicial)
throw new DomainException("A data final deve ser maior ou igual à inicial.");
// Regra do legado: geração em lote avança de 7 em 7 dias.
var datas = new List<DateOnly>();
for (var d = r.DataInicial; d <= r.DataFinal; d = d.AddDays(7))
datas.Add(d);
foreach (var data in datas)
await GerarAsync(obraId, data, ct);
return new LoteHistoricoResponse(datas.Count, datas);
}
public async Task<IReadOnlyList<HistAcompanhamentoResponse>> GetHistoricoAsync(Guid obraId, CancellationToken ct = default)
{
await GarantirObraAsync(obraId, ct);
var historico = await _repository.GetHistoricoAsync(obraId, ct);
return historico.Select(ToResponse).ToList();
}
public async Task<FotoAcompanhamentoResponse> GetResumoParcialAsync(
Guid obraId, DateOnly dataAntiga, DateOnly dataRecente, CancellationToken ct = default)
{
await GarantirObraAsync(obraId, ct);
if (dataRecente <= dataAntiga)
throw new DomainException("A data recente deve ser posterior à antiga.");
// Resumo parcial do legado: recente − antigo, campo a campo (sobre fotos calculadas).
var antiga = await _repository.CalcularFotoAsync(obraId, dataAntiga, ct);
var recente = await _repository.CalcularFotoAsync(obraId, dataRecente, ct);
var diff = new FotoAcompanhamento(
Math.Round(recente.QtLiberada - antiga.QtLiberada, 4),
Math.Round(recente.QtNaoLiberada - antiga.QtNaoLiberada, 4),
Math.Round(recente.QtAvancada - antiga.QtAvancada, 4),
Math.Round(recente.QtCadastrada - antiga.QtCadastrada, 4),
recente.ItensLiberados - antiga.ItensLiberados,
recente.ItensNaoLiberados - antiga.ItensNaoLiberados);
return ToResponse(obraId, dataRecente, diff);
}
private async Task<HistAcompanhamento> GerarAsync(Guid obraId, DateOnly data, CancellationToken ct)
{
var foto = await _repository.CalcularFotoAsync(obraId, data, ct);
var agora = DateTime.UtcNow;
var existente = await _repository.GetPorDataAsync(obraId, data, ct);
_unitOfWork.BeginTransaction();
try
{
if (existente is null)
{
existente = HistAcompanhamento.Create(obraId, data, foto, agora);
await _repository.AddAsync(existente, ct);
}
else
{
existente.Atualizar(foto, agora);
await _repository.UpdateAsync(existente, ct);
}
_unitOfWork.Commit();
}
catch { _unitOfWork.Rollback(); throw; }
return existente;
}
private async Task GarantirObraAsync(Guid obraId, CancellationToken ct)
{
if (!await _repository.ObraExistsAsync(obraId, ct))
throw new NotFoundException($"Obra {obraId} não encontrada.");
}
private static FotoAcompanhamentoResponse ToResponse(Guid obraId, DateOnly data, FotoAcompanhamento f) => new(
obraId, data, f.QtLiberada, f.QtNaoLiberada, f.QtTotal, f.QtAvancada, f.QtCadastrada,
f.ItensLiberados, f.ItensNaoLiberados);
private static HistAcompanhamentoResponse ToResponse(HistAcompanhamento h) => new(
h.Id, h.Data, h.QtLiberada, h.QtNaoLiberada, h.QtAvancada, h.QtCadastrada,
h.ItensLiberados, h.ItensNaoLiberados, h.DataGeracao);
}