Spaces:
Runtime error
Runtime error
Download src/SCM.Application/Controle/FatorProdutividadeService.cs from rafaeldavila/scm-api: direct link, hf CLI and curl.
- Browser
- Download file 16.5 kB
-
https://huggingface.co/spaces/rafaeldavila/scm-api/resolve/main/src/SCM.Application/Controle/FatorProdutividadeService.cs
- Command line
-
hf download hf://spaces/rafaeldavila/scm-api/src/SCM.Application/Controle/FatorProdutividadeService.cs
-
curl -L -o FatorProdutividadeService.cs https://huggingface.co/spaces/rafaeldavila/scm-api/resolve/main/src/SCM.Application/Controle/FatorProdutividadeService.cs
16.5 kB
| using SCM.Application.Common; | |
| using SCM.Domain.Controle; | |
| using SCM.Shared.Exceptions; | |
| namespace SCM.Application.Controle; | |
| public sealed record CreateFatorRequest( | |
| Guid ObraId, Guid SubAtividadePadraoId, string Codigo, string? Descricao, | |
| decimal Meta, decimal Planejado, Guid? UnidadeMedidaId = null); | |
| public sealed record UpdateFatorRequest(string Codigo, string? Descricao, decimal Meta, decimal Planejado); | |
| public sealed record FatorResponse( | |
| Guid Id, Guid ObraId, Guid SubAtividadePadraoId, string Codigo, string? Descricao, | |
| decimal Meta, decimal Planejado, decimal ProdAferido, Guid? UnidadeMedidaId); | |
| public sealed record AssociarFatorRequest(BaseCalculoFator BaseCalculo = BaseCalculoFator.Meta, Guid? UnidadeItemId = null); | |
| public sealed record AssociacaoFatorResponse(Guid ItemProgramadoId, Guid? FatorProdutividadeId, decimal HhPrev); | |
| public sealed record DiaEquipeFpResponse( | |
| Guid Id, Guid EquipeId, Guid ItemProgramadoId, DateOnly Data, | |
| decimal HhProdutivo, decimal HhImprodutivo, decimal QtExecutada, decimal ValorIndice); | |
| public sealed record ApuracaoFtResponse(Guid FolhaTarefaId, int LinhasGravadas, IReadOnlyList<DiaEquipeFpResponse> Historico); | |
| /// <summary> | |
| /// Gancho de apuração chamado por Finalizar/Reabrir da FT (fatia 12). Tolerante: FT de | |
| /// supervisor (sem equipe) ou sem itens/horas é no-op — não quebra o ciclo da FT. | |
| /// </summary> | |
| public interface IApuracaoFatorProdutividade | |
| { | |
| Task ApurarAsync(Guid folhaTarefaId, CancellationToken ct = default); | |
| Task EstornarAsync(Guid folhaTarefaId, CancellationToken ct = default); | |
| } | |
| public sealed record FatorDetalheRequest(Guid CaracteristicaId, string Operador, string Valor); | |
| public sealed record DefinirDetalhesRequest(IReadOnlyList<FatorDetalheRequest> Detalhes); | |
| public sealed record FatorDetalheResponse(Guid Id, Guid CaracteristicaId, string Operador, string Valor); | |
| public interface IFatorProdutividadeService | |
| { | |
| Task<IReadOnlyList<FatorDetalheResponse>> GetDetalhesAsync(Guid fatorId, CancellationToken ct = default); | |
| Task<IReadOnlyList<FatorDetalheResponse>> DefinirDetalhesAsync(Guid fatorId, DefinirDetalhesRequest request, CancellationToken ct = default); | |
| Task<IReadOnlyList<FatorResponse>> GetByObraAsync(Guid obraId, CancellationToken ct = default); | |
| Task<FatorResponse> CreateAsync(CreateFatorRequest request, CancellationToken ct = default); | |
| Task<FatorResponse> UpdateAsync(Guid id, UpdateFatorRequest request, CancellationToken ct = default); | |
| Task DeleteAsync(Guid id, CancellationToken ct = default); | |
| Task<AssociacaoFatorResponse> AssociarAsync(Guid itemProgramadoId, AssociarFatorRequest request, CancellationToken ct = default); | |
| Task<ApuracaoFtResponse> GetApuracaoAsync(Guid folhaTarefaId, CancellationToken ct = default); | |
| } | |
| /// <summary> | |
| /// Fator de produtividade (fatia 22). Associação (calculaFatorProdutividadePorIC): escolhe o | |
| /// fator pela sub-atividade padrão do item programado; hhPrev = round(base × quantidade × | |
| /// fatorConversão, 4); sem conversão cadastrada → ERRO_CONVERSAO_UNID_MEDIDA. Apuração | |
| /// (calculaIndiceAferido, gancho do Finalizar da FT — fatia 12): distribui o HH da FAH | |
| /// (produtivo = normais+extras; improdutivo = paradas) dia a dia, proporcional ao | |
| /// hhPrevReal = round(hhPrev × qtParcial/qtPrev, 4) de cada produção; índice = | |
| /// round((hhProd+hhImprod)/qtExec, 4) (qt 0 → 1); linhas zeradas excluídas; prod_aferido | |
| /// recalculado de FTs finalizadas. Reabrir estorna o histórico da FT (recalculável). | |
| /// SIMPLIFICAÇÕES documentadas: detalhes/operadores por característica do IC (não modelada) | |
| /// adiados — escolha só por sub-atividade; HH do dia agregado (FT é de uma equipe); | |
| /// ajuste cross-FT de reparo/reprovada adiado. | |
| /// </summary> | |
| public sealed class FatorProdutividadeService : IFatorProdutividadeService, IApuracaoFatorProdutividade | |
| { | |
| private readonly IFatorProdutividadeRepository _repository; | |
| private readonly IUnitOfWork _unitOfWork; | |
| public FatorProdutividadeService(IFatorProdutividadeRepository repository, IUnitOfWork unitOfWork) | |
| { | |
| _repository = repository; | |
| _unitOfWork = unitOfWork; | |
| } | |
| public async Task<IReadOnlyList<FatorResponse>> GetByObraAsync(Guid obraId, CancellationToken ct = default) | |
| { | |
| if (!await _repository.ObraExistsAsync(obraId, ct)) | |
| throw new NotFoundException($"Obra {obraId} não encontrada."); | |
| var fatores = await _repository.GetByObraAsync(obraId, ct); | |
| return fatores.Select(ToResponse).ToList(); | |
| } | |
| public async Task<FatorResponse> CreateAsync(CreateFatorRequest r, CancellationToken ct = default) | |
| { | |
| if (!await _repository.ObraExistsAsync(r.ObraId, ct)) | |
| throw new NotFoundException($"Obra {r.ObraId} não encontrada."); | |
| if (!await _repository.SubAtividadeExistsAsync(r.SubAtividadePadraoId, ct)) | |
| throw new NotFoundException($"Sub-atividade padrão {r.SubAtividadePadraoId} não encontrada."); | |
| if (await _repository.CodigoExistsAsync(r.Codigo.Trim(), r.ObraId, null, ct)) | |
| throw new ConflictException($"Já existe fator com o código '{r.Codigo}' na obra."); | |
| var fator = FatorProdutividade.Create( | |
| r.ObraId, r.SubAtividadePadraoId, r.Codigo, r.Descricao, r.Meta, r.Planejado, r.UnidadeMedidaId); | |
| await ExecuteInTransactionAsync(() => _repository.AddAsync(fator, ct)); | |
| return ToResponse(fator); | |
| } | |
| public async Task<FatorResponse> UpdateAsync(Guid id, UpdateFatorRequest r, CancellationToken ct = default) | |
| { | |
| var fator = await _repository.GetByIdAsync(id, ct) | |
| ?? throw new NotFoundException($"Fator {id} não encontrado."); | |
| if (await _repository.CodigoExistsAsync(r.Codigo.Trim(), fator.ObraId, id, ct)) | |
| throw new ConflictException($"Já existe fator com o código '{r.Codigo}' na obra."); | |
| fator.Codigo = r.Codigo.Trim(); | |
| fator.Descricao = string.IsNullOrWhiteSpace(r.Descricao) ? null : r.Descricao.Trim(); | |
| fator.AtualizarMetas(r.Meta, r.Planejado); | |
| await ExecuteInTransactionAsync(() => _repository.UpdateAsync(fator, ct)); | |
| return ToResponse(fator); | |
| } | |
| public async Task DeleteAsync(Guid id, CancellationToken ct = default) | |
| { | |
| _ = await _repository.GetByIdAsync(id, ct) | |
| ?? throw new NotFoundException($"Fator {id} não encontrado."); | |
| if (await _repository.ContarItensAssociadosAsync(id, ct) > 0) | |
| throw new ConflictException("O fator possui itens programados associados."); | |
| await ExecuteInTransactionAsync(() => _repository.DeleteAsync(id, ct)); | |
| } | |
| public async Task<AssociacaoFatorResponse> AssociarAsync(Guid itemProgramadoId, AssociarFatorRequest r, CancellationToken ct = default) | |
| { | |
| var item = await _repository.GetItemAssociacaoAsync(itemProgramadoId, ct) | |
| ?? throw new NotFoundException($"Item programado {itemProgramadoId} não encontrado."); | |
| // Regra do legado: sem sub-atividade ou sem fator casado → fator null e hhPrev 0. | |
| FatorProdutividade? fator = null; | |
| if (item.SubAtividadePadraoId.HasValue) | |
| fator = await EscolherFatorAsync(item.SubAtividadePadraoId.Value, itemProgramadoId, ct); | |
| decimal hhPrev = 0m; | |
| if (fator is not null) | |
| { | |
| var fatorConversao = 1m; | |
| if (r.UnidadeItemId.HasValue && fator.UnidadeMedidaId.HasValue && r.UnidadeItemId != fator.UnidadeMedidaId) | |
| { | |
| // Trava do legado (ERRO_CONVERSAO_UNID_MEDIDA). | |
| fatorConversao = await _repository.GetFatorConversaoAsync(r.UnidadeItemId.Value, fator.UnidadeMedidaId.Value, ct) | |
| ?? throw new DomainException("Não há conversão de unidade cadastrada entre a unidade do item e a do fator."); | |
| } | |
| // Fórmula do legado: hhPrev = round(base × valorUnidadeIC × fatorConversão, 4). | |
| hhPrev = Math.Round(fator.ValorBase(r.BaseCalculo) * item.Quantidade * fatorConversao, 4); | |
| } | |
| await ExecuteInTransactionAsync(() => _repository.AssociarItemAsync(itemProgramadoId, fator?.Id, hhPrev, ct)); | |
| return new AssociacaoFatorResponse(itemProgramadoId, fator?.Id, hhPrev); | |
| } | |
| public async Task<ApuracaoFtResponse> GetApuracaoAsync(Guid folhaTarefaId, CancellationToken ct = default) | |
| { | |
| _ = await _repository.GetFtApuracaoAsync(folhaTarefaId, ct) | |
| ?? throw new NotFoundException($"Folha de tarefa {folhaTarefaId} não encontrada."); | |
| var historico = await _repository.GetDiaEquipeFpAsync(folhaTarefaId, ct); | |
| return new ApuracaoFtResponse(folhaTarefaId, historico.Count, historico.Select(d => | |
| new DiaEquipeFpResponse(d.Id, d.EquipeId, d.ItemProgramadoId, d.Data, | |
| d.HhProdutivo, d.HhImprodutivo, d.QtExecutada, d.ValorIndice)).ToList()); | |
| } | |
| // ---- Apuração (calculaIndiceAferido) — gancho do Finalizar da FT ---- | |
| public async Task ApurarAsync(Guid folhaTarefaId, CancellationToken ct = default) | |
| { | |
| var ft = await _repository.GetFtApuracaoAsync(folhaTarefaId, ct); | |
| // Regra do legado: FT de supervisor (sem equipe) não apura. | |
| if (ft is null || !ft.EquipeId.HasValue) | |
| return; | |
| var itens = await _repository.GetItensFtAsync(folhaTarefaId, ct); | |
| if (itens.Count == 0) return; | |
| var inicio = ft.DataInicial; | |
| var fim = ft.DataInicial.AddDays(ft.Periodo - 1); | |
| var producoes = await _repository.GetProducoesPeriodoAsync(folhaTarefaId, inicio, fim, ct); | |
| var hhPrevPorItem = itens.ToDictionary(i => i.ItemProgramadoId, i => i.HhPrev); | |
| var linhas = new List<DiaEquipeFp>(); | |
| for (var dia = inicio; dia <= fim; dia = dia.AddDays(1)) | |
| { | |
| var producoesDia = producoes.Where(p => p.Data == dia).ToList(); | |
| if (producoesDia.Count == 0) continue; | |
| var horas = await _repository.GetHorasDiaAsync(folhaTarefaId, dia, ct); | |
| // hhPrevReal = round(hhPrev × (qtParcial/qtPrev), 4) — qtParcial>0 prevalece (coletor). | |
| var hhPrevReal = producoesDia.ToDictionary( | |
| p => p.ItemProgramadoId, | |
| p => | |
| { | |
| var qt = p.QtExecutadaParcial > 0 ? p.QtExecutadaParcial : p.QtExecutada; | |
| return p.QtPrevista <= 0 ? 0m : Math.Round(hhPrevPorItem.GetValueOrDefault(p.ItemProgramadoId) * (qt / p.QtPrevista), 4); | |
| }); | |
| var hhPrevTotal = hhPrevReal.Values.Sum(); | |
| foreach (var p in producoesDia) | |
| { | |
| // Distribuição proporcional do legado; sem hhPrev cadastrado distribui por igual. | |
| var proporcao = hhPrevTotal > 0 | |
| ? hhPrevReal[p.ItemProgramadoId] / hhPrevTotal | |
| : 1m / producoesDia.Count; | |
| var qt = p.QtExecutadaParcial > 0 ? p.QtExecutadaParcial : p.QtExecutada; | |
| var linha = DiaEquipeFp.Create( | |
| folhaTarefaId, ft.EquipeId.Value, p.ItemProgramadoId, dia, | |
| Math.Round(proporcao * horas.HhProdutivo, 4), | |
| Math.Round(proporcao * horas.HhImprodutivo, 4), | |
| qt); | |
| // Regra do legado: linha toda zerada é excluída (não grava). | |
| if (!linha.EstaZerado) | |
| linhas.Add(linha); | |
| } | |
| } | |
| _unitOfWork.BeginTransaction(); | |
| try | |
| { | |
| // Apuração recalculável: substitui o histórico da FT. | |
| await _repository.DeleteDiaEquipeFpByFtAsync(folhaTarefaId, ct); | |
| foreach (var linha in linhas) | |
| await _repository.AddDiaEquipeFpAsync(linha, ct); | |
| // prod_aferido dos fatores envolvidos (Σ hhProdutivo / Σ qtExec de FTs finalizadas). | |
| foreach (var fatorId in itens.Where(i => i.FatorProdutividadeId.HasValue) | |
| .Select(i => i.FatorProdutividadeId!.Value).Distinct()) | |
| await _repository.RecalcularProdAferidoAsync(fatorId, ct); | |
| _unitOfWork.Commit(); | |
| } | |
| catch { _unitOfWork.Rollback(); throw; } | |
| } | |
| public async Task EstornarAsync(Guid folhaTarefaId, CancellationToken ct = default) | |
| { | |
| var ft = await _repository.GetFtApuracaoAsync(folhaTarefaId, ct); | |
| if (ft is null) return; | |
| var itens = await _repository.GetItensFtAsync(folhaTarefaId, ct); | |
| _unitOfWork.BeginTransaction(); | |
| try | |
| { | |
| await _repository.DeleteDiaEquipeFpByFtAsync(folhaTarefaId, ct); | |
| foreach (var fatorId in itens.Where(i => i.FatorProdutividadeId.HasValue) | |
| .Select(i => i.FatorProdutividadeId!.Value).Distinct()) | |
| await _repository.RecalcularProdAferidoAsync(fatorId, ct); | |
| _unitOfWork.Commit(); | |
| } | |
| catch { _unitOfWork.Rollback(); throw; } | |
| } | |
| /// <summary> | |
| /// Escolha do legado (calculaFatorProdutividadePorIC, 5ª passada): entre os fatores da | |
| /// sub-atividade, descarta os com QUALQUER detalhe não casado com as características do IC | |
| /// e vence o de MAIS detalhes casados (empate: ordem por código — determinístico). | |
| /// Fator sem detalhes é o genérico (0 casados). | |
| /// </summary> | |
| private async Task<FatorProdutividade?> EscolherFatorAsync(Guid subAtividadePadraoId, Guid itemProgramadoId, CancellationToken ct) | |
| { | |
| var candidatos = await _repository.GetTodosBySubAtividadeAsync(subAtividadePadraoId, ct); | |
| if (candidatos.Count == 0) return null; | |
| var valores = await _repository.GetValoresCaracteristicasDoItemAsync(itemProgramadoId, ct); | |
| FatorProdutividade? melhor = null; | |
| var melhorCasados = -1; | |
| foreach (var candidato in candidatos) | |
| { | |
| var detalhes = await _repository.GetDetalhesAsync(candidato.Id, ct); | |
| var casados = 0; | |
| var desclassificado = false; | |
| foreach (var d in detalhes) | |
| { | |
| valores.TryGetValue(d.CaracteristicaId, out var valorIc); | |
| if (d.Casa(valorIc)) casados++; | |
| else { desclassificado = true; break; } | |
| } | |
| if (desclassificado) continue; | |
| if (casados > melhorCasados) | |
| { | |
| melhorCasados = casados; | |
| melhor = candidato; | |
| } | |
| } | |
| return melhor; | |
| } | |
| public async Task<IReadOnlyList<FatorDetalheResponse>> GetDetalhesAsync(Guid fatorId, CancellationToken ct = default) | |
| { | |
| _ = await _repository.GetByIdAsync(fatorId, ct) | |
| ?? throw new NotFoundException($"Fator {fatorId} não encontrado."); | |
| var detalhes = await _repository.GetDetalhesAsync(fatorId, ct); | |
| return detalhes.Select(d => new FatorDetalheResponse(d.Id, d.CaracteristicaId, d.Operador, d.Valor)).ToList(); | |
| } | |
| public async Task<IReadOnlyList<FatorDetalheResponse>> DefinirDetalhesAsync(Guid fatorId, DefinirDetalhesRequest r, CancellationToken ct = default) | |
| { | |
| _ = await _repository.GetByIdAsync(fatorId, ct) | |
| ?? throw new NotFoundException($"Fator {fatorId} não encontrado."); | |
| var detalhes = r.Detalhes | |
| .Select(d => FatorDetalhe.Create(fatorId, d.CaracteristicaId, d.Operador, d.Valor)) | |
| .ToList(); | |
| if (detalhes.Select(d => d.CaracteristicaId).Distinct().Count() != detalhes.Count) | |
| throw new DomainException("Não é permitido repetir a mesma característica nos detalhes."); | |
| _unitOfWork.BeginTransaction(); | |
| try | |
| { | |
| await _repository.ReplaceDetalhesAsync(fatorId, detalhes, ct); | |
| _unitOfWork.Commit(); | |
| } | |
| catch { _unitOfWork.Rollback(); throw; } | |
| return detalhes.Select(d => new FatorDetalheResponse(d.Id, d.CaracteristicaId, d.Operador, d.Valor)).ToList(); | |
| } | |
| private static FatorResponse ToResponse(FatorProdutividade f) => new( | |
| f.Id, f.ObraId, f.SubAtividadePadraoId, f.Codigo, f.Descricao, | |
| f.Meta, f.Planejado, f.ProdAferido, f.UnidadeMedidaId); | |
| private async Task ExecuteInTransactionAsync(Func<Task> action) | |
| { | |
| _unitOfWork.BeginTransaction(); | |
| try { await action(); _unitOfWork.Commit(); } | |
| catch { _unitOfWork.Rollback(); throw; } | |
| } | |
| } | |