Spaces:
Runtime error
Runtime error
Download src/SCM.Application/Qualidade/ColetaService.cs from rafaeldavila/scm-api: direct link, hf CLI and curl.
- Browser
- Download file 20.3 kB
-
https://huggingface.co/spaces/rafaeldavila/scm-api/resolve/main/src/SCM.Application/Qualidade/ColetaService.cs
- Command line
-
hf download hf://spaces/rafaeldavila/scm-api/src/SCM.Application/Qualidade/ColetaService.cs
-
curl -L -o ColetaService.cs https://huggingface.co/spaces/rafaeldavila/scm-api/resolve/main/src/SCM.Application/Qualidade/ColetaService.cs
20.3 kB
| using SCM.Application.Common; | |
| using SCM.Application.Controle; | |
| using SCM.Domain.Controle; | |
| using SCM.Domain.Qualidade; | |
| using SCM.Shared.Exceptions; | |
| namespace SCM.Application.Qualidade; | |
| public sealed record ProgramarRequest(IReadOnlyList<Guid> ItemProgramadoIds, bool Match = true); | |
| public sealed record ProgramarResponse(int Efetivadas, int Ignoradas); | |
| public sealed record ProgramacaoResponse(Guid Id, Guid ItemProgramadoId, string DescricaoItem, DateTime DataCriacao); | |
| public sealed record CampoPacoteResponse(Guid Id, string Nome, string Tipo, string TipoDado, string Etapa, bool Obrigatorio, int Ordem); | |
| public sealed record EventoPacoteResponse( | |
| Guid ItemProgramadoId, string Descricao, decimal QtPrevista, | |
| decimal? QtExecutadaAtual, decimal? AvancoAtual, string? LaudoAtual, | |
| IReadOnlyList<CampoPacoteResponse> Campos); | |
| public sealed record PacoteProgramacaoResponse( | |
| Guid AgenteId, string AgenteNome, string Fase, IReadOnlyList<EventoPacoteResponse> Eventos); | |
| public sealed record ValorColetaRequest(Guid CampoInspecaoId, string? Valor); | |
| public sealed record EquipeColetaRequest(Guid EquipeId, decimal QuantidadeExecutada); | |
| public sealed record EventoColetaRequest( | |
| Guid ItemProgramadoId, | |
| DateOnly? Data = null, | |
| decimal QtPrevista = 0, | |
| decimal QtExecutada = 0, | |
| int Classificacao = 0, | |
| string? MotivoReapresentacao = null, | |
| Guid? ExecutorId = null, | |
| string? Laudo = null, | |
| DateOnly? DataLibCq = null, | |
| IReadOnlyList<EquipeColetaRequest>? Equipes = null, | |
| IReadOnlyList<ValorColetaRequest>? Valores = null); | |
| public sealed record SincronizarColetaRequest(Guid AgenteId, bool Previa, IReadOnlyList<EventoColetaRequest> Eventos); | |
| public sealed record ResultadoEventoResponse(Guid ItemProgramadoId, string Status, string Mensagem, Guid? ProducaoId); | |
| public sealed record SincronizacaoResponse(Guid? ColetaId, bool Previa, int Processados, int Erros, IReadOnlyList<ResultadoEventoResponse> Resultados); | |
| public sealed record LogSincronizacaoResponse(Guid Id, DateTime Data, string? IdEvento, string? Mensagem); | |
| public sealed record AtualizarValorRequest(Guid CampoInspecaoId, string? Valor, int Etapa = 0); | |
| public sealed record AtualizarValoresColetaRequest(IReadOnlyList<AtualizarValorRequest> Valores); | |
| public interface IColetaService | |
| { | |
| Task<ProgramarResponse> ProgramarAsync(Guid agenteId, ProgramarRequest request, CancellationToken ct = default); | |
| Task<IReadOnlyList<ProgramacaoResponse>> GetProgramacoesAsync(Guid agenteId, CancellationToken ct = default); | |
| Task<PacoteProgramacaoResponse> GetPacoteAsync(Guid agenteId, CancellationToken ct = default); | |
| Task<SincronizacaoResponse> SincronizarAsync(SincronizarColetaRequest request, CancellationToken ct = default); | |
| Task<IReadOnlyList<LogSincronizacaoResponse>> GetLogsAsync(Guid agenteId, CancellationToken ct = default); | |
| Task AtualizarValoresAsync(Guid eventoColetadoId, AtualizarValoresColetaRequest request, CancellationToken ct = default); | |
| } | |
| /// <summary> | |
| /// Coleta de inspeções MCQ (fatia 21): programação match/unmatch idempotente, pacote de | |
| /// programação JSON (substitui .prg/.PDB/SOAP do legado) e sincronização — agente PRD lança | |
| /// produção (reusa fatia 18, com todas as travas), agente CQ libera/inspeciona (reusa fatia 19; | |
| /// fiscal = o próprio agente; laudo Verificado→I, Amostragem→A, Reprovado→R, NaoAplicavel→NA). | |
| /// Prévia valida sem persistir. Cada evento é processado individualmente com log (legado | |
| /// cl_logPDA) — erro em um evento não interrompe os demais. | |
| /// ADIADOS: relatório técnico/croqui (PDF), importação por planilha, liberação parcial na | |
| /// coleta, GTSubAtivGC/caracProd (campos vêm da sub-atividade padrão do item programado). | |
| /// </summary> | |
| public sealed class ColetaService : IColetaService | |
| { | |
| private readonly IColetaRepository _repository; | |
| private readonly IProducaoControleService _producaoService; | |
| private readonly IProducaoCqService _cqService; | |
| private readonly IProducaoControleRepository _producaoRepository; | |
| private readonly IUnitOfWork _unitOfWork; | |
| private readonly IRelatorioTecnicoGancho _relatorioGancho; | |
| public ColetaService( | |
| IColetaRepository repository, | |
| IProducaoControleService producaoService, | |
| IProducaoCqService cqService, | |
| IProducaoControleRepository producaoRepository, | |
| IUnitOfWork unitOfWork, | |
| IRelatorioTecnicoGancho relatorioGancho) | |
| { | |
| _repository = repository; | |
| _producaoService = producaoService; | |
| _cqService = cqService; | |
| _producaoRepository = producaoRepository; | |
| _unitOfWork = unitOfWork; | |
| _relatorioGancho = relatorioGancho; | |
| } | |
| public async Task<ProgramarResponse> ProgramarAsync(Guid agenteId, ProgramarRequest r, CancellationToken ct = default) | |
| { | |
| if (!await _repository.AgenteExistsAsync(agenteId, ct)) | |
| throw new NotFoundException($"Agente {agenteId} não encontrado."); | |
| if (r.ItemProgramadoIds.Count == 0) | |
| throw new DomainException("Informe ao menos um item programado."); | |
| int efetivadas = 0, ignoradas = 0; | |
| var agora = DateTime.UtcNow; | |
| _unitOfWork.BeginTransaction(); | |
| try | |
| { | |
| foreach (var itemId in r.ItemProgramadoIds.Distinct()) | |
| { | |
| if (r.Match) | |
| { | |
| // Regra do legado: match só adiciona se o agente ainda NÃO possui o evento. | |
| if (await _repository.GetItemProgramadoAsync(itemId, ct) is null) | |
| throw new NotFoundException($"Item programado {itemId} não encontrado."); | |
| if (await _repository.ProgramacaoExistsAsync(agenteId, itemId, ct)) { ignoradas++; continue; } | |
| await _repository.AddProgramacaoAsync(Programacao.Create(agenteId, itemId, agora), ct); | |
| efetivadas++; | |
| } | |
| else | |
| { | |
| // Unmatch só remove vínculos existentes. | |
| if (await _repository.RemoveProgramacaoAsync(agenteId, itemId, ct)) efetivadas++; | |
| else ignoradas++; | |
| } | |
| } | |
| _unitOfWork.Commit(); | |
| } | |
| catch { _unitOfWork.Rollback(); throw; } | |
| return new ProgramarResponse(efetivadas, ignoradas); | |
| } | |
| public async Task<IReadOnlyList<ProgramacaoResponse>> GetProgramacoesAsync(Guid agenteId, CancellationToken ct = default) | |
| { | |
| if (!await _repository.AgenteExistsAsync(agenteId, ct)) | |
| throw new NotFoundException($"Agente {agenteId} não encontrado."); | |
| var programacoes = await _repository.GetProgramacoesAsync(agenteId, ct); | |
| var result = new List<ProgramacaoResponse>(programacoes.Count); | |
| foreach (var p in programacoes) | |
| { | |
| var item = await _repository.GetItemProgramadoAsync(p.ItemProgramadoId, ct); | |
| result.Add(new ProgramacaoResponse(p.Id, p.ItemProgramadoId, item?.Descricao ?? string.Empty, p.DataCriacao)); | |
| } | |
| return result; | |
| } | |
| public async Task<PacoteProgramacaoResponse> GetPacoteAsync(Guid agenteId, CancellationToken ct = default) | |
| { | |
| var agente = await _repository.GetAgenteAsync(agenteId, ct) | |
| ?? throw new NotFoundException($"Agente {agenteId} não encontrado."); | |
| // A 'fase' do agente dirige a coleta: Producao=etapa PRD; CQ=etapa CQ ('Ambas' entra sempre). | |
| var etapa = agente.Tipo == AgenteTipo.CQ ? CampoEtapa.Cq : CampoEtapa.Prd; | |
| var programacoes = await _repository.GetProgramacoesAsync(agenteId, ct); | |
| var eventos = new List<EventoPacoteResponse>(programacoes.Count); | |
| foreach (var prog in programacoes) | |
| { | |
| var item = await _repository.GetItemProgramadoAsync(prog.ItemProgramadoId, ct); | |
| if (item is null) continue; // evento excluído do SCM — fora do pacote | |
| // Para agente CQ envia a produção mais recente (a liberar); para PRD os campos vão vazios. | |
| ProducaoControle? ultima = null; | |
| if (agente.Tipo == AgenteTipo.CQ) | |
| ultima = await _producaoRepository.GetMaisRecenteNormalAsync(item.Id, ct); | |
| var campos = item.SubAtividadePadraoId.HasValue | |
| ? await _repository.GetCamposEmUsoAsync(item.SubAtividadePadraoId.Value, etapa, ct) | |
| : Array.Empty<CampoInspecao>(); | |
| eventos.Add(new EventoPacoteResponse( | |
| item.Id, item.Descricao, item.Quantidade, | |
| ultima?.QtExecutada, ultima?.Avanco, LaudoParaCampo(ultima?.TipoLibCq), | |
| campos.Select(c => new CampoPacoteResponse( | |
| c.Id, c.Nome, c.Tipo.ToString(), c.TipoDado.ToString(), c.Etapa.ToString(), | |
| etapa == CampoEtapa.Cq ? c.ObrigatorioCq : c.ObrigatorioPrd, c.Ordem)).ToList())); | |
| } | |
| return new PacoteProgramacaoResponse(agente.Id, agente.Nome, agente.Tipo.ToString(), eventos); | |
| } | |
| public async Task<SincronizacaoResponse> SincronizarAsync(SincronizarColetaRequest r, CancellationToken ct = default) | |
| { | |
| var agente = await _repository.GetAgenteAsync(r.AgenteId, ct) | |
| ?? throw new NotFoundException($"Agente {r.AgenteId} não encontrado."); | |
| if (r.Eventos.Count == 0) | |
| throw new DomainException("Informe ao menos um evento coletado."); | |
| var etapa = agente.Tipo == AgenteTipo.CQ ? CampoEtapa.Cq : CampoEtapa.Prd; | |
| var resultados = new List<ResultadoEventoResponse>(r.Eventos.Count); | |
| var processaveis = new List<(EventoColetaRequest Req, ItemProgramadoColeta Item)>(); | |
| // 1ª fase — validações de coleta (valem para prévia e efetivação). | |
| foreach (var ev in r.Eventos) | |
| { | |
| var item = await _repository.GetItemProgramadoAsync(ev.ItemProgramadoId, ct); | |
| if (item is null) | |
| { | |
| // Regra do legado: evento excluído do SCM gera log e pula (não interrompe). | |
| resultados.Add(new ResultadoEventoResponse(ev.ItemProgramadoId, "Erro", "EVENTO_EXCLUIDO_SCM: item programado não existe mais.", null)); | |
| continue; | |
| } | |
| // Trava do legado (ERRO_CARACPRODUCAO): coletadas < campos em uso da etapa. | |
| if (item.SubAtividadePadraoId.HasValue) | |
| { | |
| var campos = await _repository.GetCamposEmUsoAsync(item.SubAtividadePadraoId.Value, etapa, ct); | |
| var coletados = (ev.Valores ?? Array.Empty<ValorColetaRequest>()).Select(v => v.CampoInspecaoId).Distinct().Count(); | |
| if (coletados < campos.Count) | |
| { | |
| resultados.Add(new ResultadoEventoResponse(ev.ItemProgramadoId, "Erro", | |
| $"ERRO_CARACPRODUCAO: {coletados} característica(s) coletada(s), {campos.Count} em uso na etapa {etapa}.", null)); | |
| continue; | |
| } | |
| } | |
| if (agente.Tipo == AgenteTipo.CQ) | |
| { | |
| // Travas do legado: laudo e data de liberação obrigatórios na coleta CQ. | |
| if (string.IsNullOrWhiteSpace(ev.Laudo)) | |
| { | |
| resultados.Add(new ResultadoEventoResponse(ev.ItemProgramadoId, "Erro", "TIPO_LIBCQ_NAO_PREENCHIDO: laudo obrigatório.", null)); | |
| continue; | |
| } | |
| if (!ev.DataLibCq.HasValue) | |
| { | |
| resultados.Add(new ResultadoEventoResponse(ev.ItemProgramadoId, "Erro", "DATALIB_NAO_PREENCHIDA: data de liberação obrigatória.", null)); | |
| continue; | |
| } | |
| } | |
| processaveis.Add((ev, item)); | |
| } | |
| // Prévia: valida e retorna sem persistir nada (legado: rollback). | |
| if (r.Previa) | |
| { | |
| foreach (var (ev, _) in processaveis) | |
| resultados.Add(new ResultadoEventoResponse(ev.ItemProgramadoId, "Pendente", "Prévia válida — nada persistido.", null)); | |
| return Montar(null, true, resultados); | |
| } | |
| // 2ª fase — efetivação evento a evento (erro em um não interrompe os demais). | |
| var coleta = Coleta.Create(agente.Id, agente.Tipo, OrigemColeta.Rest, DateTime.UtcNow); | |
| var eventosPersistir = new List<(EventoColetado Evento, IReadOnlyList<ValorColetado> Valores, IReadOnlyList<EquipeEventoColetado> Equipes)>(); | |
| foreach (var (ev, item) in processaveis) | |
| { | |
| Guid? producaoId = null; | |
| string status, mensagem; | |
| try | |
| { | |
| if (agente.Tipo == AgenteTipo.CQ) | |
| { | |
| var alvo = await _producaoRepository.GetMaisRecenteNormalAsync(item.Id, ct) | |
| ?? throw new NotFoundException("PROD_INEXISTENTE: não há produção a liberar para o evento."); | |
| var lib = await _cqService.LiberarAsync(alvo.Id, new LiberarProducaoCqRequest( | |
| LaudoParaTipo(ev.Laudo!), ev.DataLibCq!.Value, agente.Id), ct); | |
| producaoId = lib.Id; | |
| status = "Processado"; mensagem = $"Produção liberada ({lib.TipoLibCq})."; | |
| } | |
| else | |
| { | |
| var lanc = await _producaoService.LancarAsync(new LancarProducaoRequest( | |
| item.Id, ev.Data ?? DateOnly.FromDateTime(DateTime.UtcNow.Date), | |
| Math.Round(ev.QtPrevista, 4), Math.Round(ev.QtExecutada, 4), 0, | |
| (ClassificacaoProducao)ev.Classificacao, ev.ExecutorId, ev.MotivoReapresentacao, | |
| ev.Equipes?.Select(e => new ProducaoEquipeRequest(e.EquipeId, e.QuantidadeExecutada)).ToList()), ct); | |
| producaoId = lanc.Id; | |
| status = "Processado"; mensagem = "Produção lançada."; | |
| } | |
| } | |
| catch (Exception ex) when (ex is DomainException or NotFoundException or ConflictException) | |
| { | |
| status = "Erro"; mensagem = ex.Message; | |
| } | |
| resultados.Add(new ResultadoEventoResponse(ev.ItemProgramadoId, status, mensagem, producaoId)); | |
| // Regra do legado: gera relatório técnico para as produções sem erro (best-effort). | |
| if (status == "Processado" && producaoId.HasValue) | |
| { | |
| var obraId = await _repository.GetObraIdDoIcAsync(item.ItemControleId, ct); | |
| if (obraId.HasValue) | |
| await _relatorioGancho.GerarAsync(obraId.Value, agente.Id, producaoId.Value, | |
| agente.Tipo == AgenteTipo.CQ ? "Q" : "P", ct); | |
| } | |
| var evento = new EventoColetado | |
| { | |
| Id = Guid.NewGuid(), | |
| ColetaId = coleta.Id, | |
| ItemProgramadoId = ev.ItemProgramadoId, | |
| ProducaoId = producaoId, | |
| DataColeta = ev.Data, | |
| QtPrevista = ev.QtPrevista, | |
| QtExecutada = ev.QtExecutada, | |
| Classificacao = ev.Classificacao, | |
| MotivoReapresentacao = ev.MotivoReapresentacao, | |
| ExecutorId = ev.ExecutorId, | |
| DataLibCq = ev.DataLibCq, | |
| TipoLibCq = string.IsNullOrWhiteSpace(ev.Laudo) ? null : LaudoParaTipo(ev.Laudo), | |
| Status = status == "Processado" ? StatusEventoColetado.Processado : StatusEventoColetado.Erro, | |
| MensagemLog = mensagem | |
| }; | |
| var valores = (ev.Valores ?? Array.Empty<ValorColetaRequest>()).Select(v => new ValorColetado | |
| { | |
| Id = Guid.NewGuid(), EventoColetadoId = evento.Id, CampoInspecaoId = v.CampoInspecaoId, Etapa = etapa, Valor = v.Valor | |
| }).ToList(); | |
| // Frente B (regra do legado): em REAPRESENTAÇÃO, os valores de características da | |
| // produção anterior (mais recente) sobrescrevem os preenchidos no aparelho. | |
| if (ev.Classificacao == (int)ClassificacaoProducao.Reapresentacao) | |
| { | |
| var anteriores = await _repository.GetUltimosValoresDoItemAsync(ev.ItemProgramadoId, ct); | |
| if (anteriores.Count > 0) | |
| valores = anteriores.Select(a => new ValorColetado | |
| { | |
| Id = Guid.NewGuid(), EventoColetadoId = evento.Id, | |
| CampoInspecaoId = a.CampoInspecaoId, Etapa = etapa, Valor = a.Valor | |
| }).ToList(); | |
| } | |
| var equipes = (ev.Equipes ?? Array.Empty<EquipeColetaRequest>()).Select(e => new EquipeEventoColetado | |
| { | |
| Id = Guid.NewGuid(), EventoColetadoId = evento.Id, EquipeId = e.EquipeId, QuantidadeExecutada = e.QuantidadeExecutada | |
| }).ToList(); | |
| eventosPersistir.Add((evento, valores, equipes)); | |
| } | |
| // Persiste cabeçalho + eventos + valores + equipes + logs em uma transação própria. | |
| _unitOfWork.BeginTransaction(); | |
| try | |
| { | |
| await _repository.AddColetaAsync(coleta, ct); | |
| foreach (var (evento, valores, equipes) in eventosPersistir) | |
| await _repository.AddEventoAsync(evento, valores, equipes, ct); | |
| foreach (var res in resultados) | |
| await _repository.AddLogAsync(new LogSincronizacaoColeta | |
| { | |
| Id = Guid.NewGuid(), AgenteId = agente.Id, Data = coleta.DataSincronizacao, | |
| IdEvento = res.ItemProgramadoId.ToString(), Mensagem = $"{res.Status}: {res.Mensagem}" | |
| }, ct); | |
| _unitOfWork.Commit(); | |
| } | |
| catch { _unitOfWork.Rollback(); throw; } | |
| return Montar(coleta.Id, false, resultados); | |
| } | |
| public async Task<IReadOnlyList<LogSincronizacaoResponse>> GetLogsAsync(Guid agenteId, CancellationToken ct = default) | |
| { | |
| if (!await _repository.AgenteExistsAsync(agenteId, ct)) | |
| throw new NotFoundException($"Agente {agenteId} não encontrado."); | |
| var logs = await _repository.GetLogsAsync(agenteId, ct); | |
| return logs.Select(l => new LogSincronizacaoResponse(l.Id, l.Data, l.IdEvento, l.Mensagem)).ToList(); | |
| } | |
| public async Task AtualizarValoresAsync(Guid eventoColetadoId, AtualizarValoresColetaRequest r, CancellationToken ct = default) | |
| { | |
| // Frente B: a regra de validação da importação por planilha vira um update de valores | |
| // coletados de um evento existente (sem o parser XLS do legado). | |
| if (!await _repository.EventoExistsAsync(eventoColetadoId, ct)) | |
| throw new NotFoundException($"Evento coletado {eventoColetadoId} não encontrado."); | |
| var valores = (r.Valores ?? Array.Empty<AtualizarValorRequest>()).Select(v => new ValorColetado | |
| { | |
| Id = Guid.NewGuid(), | |
| EventoColetadoId = eventoColetadoId, | |
| CampoInspecaoId = v.CampoInspecaoId, | |
| Etapa = (CampoEtapa)v.Etapa, | |
| Valor = v.Valor | |
| }).ToList(); | |
| _unitOfWork.BeginTransaction(); | |
| try | |
| { | |
| await _repository.ReplaceValoresAsync(eventoColetadoId, valores, ct); | |
| _unitOfWork.Commit(); | |
| } | |
| catch { _unitOfWork.Rollback(); throw; } | |
| } | |
| private static SincronizacaoResponse Montar(Guid? coletaId, bool previa, List<ResultadoEventoResponse> resultados) => | |
| new(coletaId, previa, | |
| resultados.Count(x => x.Status == "Processado"), | |
| resultados.Count(x => x.Status == "Erro"), | |
| resultados); | |
| /// <summary>Mapeamento do legado: laudo do aparelho → tipo de liberação.</summary> | |
| public static string LaudoParaTipo(string laudo) => laudo.Trim().ToUpperInvariant() switch | |
| { | |
| "VERIFICADO" or "I" => "I", | |
| "REPROVADO" or "R" => "R", | |
| "NAOAPLICAVEL" or "NÃO APLICÁVEL" or "NA" => "NA", | |
| _ => "A" // demais = amostragem | |
| }; | |
| /// <summary>Mapeamento do legado (ida ao aparelho): tipo → laudo.</summary> | |
| public static string? LaudoParaCampo(string? tipo) => tipo switch | |
| { | |
| null => null, | |
| "I" => "Verificado", | |
| "A" => "Amostragem", | |
| "R" => "Reprovado", | |
| "NA" => "NaoAplicavel", | |
| _ => tipo // CP/RCP ficam literais | |
| }; | |
| } | |