12707 lines
570 KiB
PHP
12707 lines
570 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Ambulatorio;
|
|
|
|
use App\Enums\Ambulatorio\AcompanhamentoOciStatus;
|
|
use App\Enums\Ambulatorio\AgendamentoStatus;
|
|
use App\Enums\Ambulatorio\AgendamentoTipo;
|
|
use App\Enums\Ambulatorio\ArcadaDentaria;
|
|
use App\Enums\Ambulatorio\AtendimentoSoapSolicitacaoExameItemStatus;
|
|
use App\Enums\Ambulatorio\AtestadoModelo as AtestadoModeloEnum;
|
|
use App\Enums\Ambulatorio\ClassificacaoRisco as ClassificacaoRiscoEnum;
|
|
use App\Enums\Ambulatorio\DemandaTipo;
|
|
use App\Enums\Ambulatorio\PrescricaoFrequenciaDose;
|
|
use App\Enums\Ambulatorio\ProblemaCondicaoSituacao as ProblemaCondicaoSituacaoEnum;
|
|
use App\Enums\Ambulatorio\SaudeBucalDenteProblemaCondicao as SaudeBucalDenteProblemaCondicaoEnum;
|
|
use App\Enums\Ambulatorio\TesteRapido as TesteRapidoEnum;
|
|
use App\Enums\Apac\MotivoSaidaPermanencia as EnumsApacMotivoSaidaPermanencia;
|
|
use App\Enums\AtencaoBasica\AtendimentoDomiciliar\Modalidade;
|
|
use App\Enums\AtencaoBasica\AtendimentoDomiciliar\Procedimento as EnumAtendimentoDomiciliarProcedimento;
|
|
use App\Enums\AtencaoBasica\AtendimentoIndividual\CondicaoAvaliada as AtendimentoIndividualCondicaoAvaliada;
|
|
use App\Enums\AtencaoBasica\AtendimentoIndividual\Conduta as AtendimentoIndividualConduta;
|
|
use App\Enums\AtencaoBasica\AtendimentoIndividual\Encaminhamento as EncaminhamentoEnum;
|
|
use App\Enums\AtencaoBasica\AtendimentoIndividual\ExameSolicitadoAvaliado as EnumExameSolicitadoAvaliado;
|
|
use App\Enums\AtencaoBasica\AtendimentoIndividual\LocalAtendimento as LocalAtendimentoEnum;
|
|
use App\Enums\AtencaoBasica\AtendimentoIndividual\TipoAtendimento as TipoAtendimentoEnum;
|
|
use App\Enums\AtencaoBasica\Avaliacao\Cuidador as EnumCuidador;
|
|
use App\Enums\AtencaoBasica\Parametrizacao\Permissao as AtencaoBasicaPermissao;
|
|
use App\Enums\AtencaoBasica\Parametrizacao\Permissao;
|
|
use App\Enums\AtencaoBasica\TipoAtendimento as AtencaoBasicaTipoAtendimento;
|
|
use App\Enums\Cadastro\Estabelecimento\SetorTipo;
|
|
use App\Enums\Cadastro\EtapaClinica as EtapaClinicaEnum;
|
|
use App\Enums\Cadastro\Medicamento\TipoReceita;
|
|
use App\Enums\Cadastro\SujeitoAtencao\Classificacao;
|
|
use App\Enums\Cadastro\SujeitoAtencao\FatorRisco as FatorRiscoEnum;
|
|
use App\Enums\Cadastro\SujeitoAtencao\Sexo;
|
|
use App\Enums\Cadastro\UnidadeMedida as UnidadeMedidaEnum;
|
|
use App\Enums\ExameImagem\Fechamento\Status as FechamentoStatus;
|
|
use App\Enums\ExameLaboratorial\StatusAgendamento;
|
|
use App\Enums\Geral\Ciap as CiapEnum;
|
|
use App\Enums\Geral\DocumentoTipo as DocumentoTipoEnum;
|
|
use App\Enums\Geral\LmsParametroTipo;
|
|
use App\Enums\Geral\MedidaTempo as MedidaTempoEnum;
|
|
use App\Enums\Geral\Turno as TurnoEnum;
|
|
use App\Enums\PainelSenha\Status as PainelSenhaStatus;
|
|
use App\Enums\Parametrizacao\Exame\Tipo as ExameTipo;
|
|
use App\Enums\Parametrizacao\KitExame\Tipo;
|
|
use App\Enums\Regulacao\SolicitacaoPrioridade as SolicitacaoPrioridadeEnum;
|
|
use App\Enums\Regulacao\StatusTipo as RegulacaoStatusTipo;
|
|
use App\Enums\Sigtap\Cid as CidEnum;
|
|
use App\Enums\Sigtap\ClassificacaoServicoAtencaoPsicossocial;
|
|
use App\Enums\Sigtap\Procedimento as ProcedimentoEnum;
|
|
use App\Enums\Sigtap\Registro;
|
|
use App\Enums\Sigtap\Servico as SigtapServicoEnum;
|
|
use App\Exceptions\Ambulatorio\NaoPodeCriarFichaAtencaoBasicaException;
|
|
use App\Exceptions\Ambulatorio\ProtocoloFechamentoException;
|
|
use App\Models\Administracao\Funcionalidade;
|
|
use App\Models\Ambulatorio\AcompanhamentoOci;
|
|
use App\Models\Ambulatorio\Agendamento;
|
|
use App\Models\Ambulatorio\AmbulatorioEncaminhamentoCaraterInternacao;
|
|
use App\Models\Ambulatorio\AmbulatorioEncaminhamentoClinica;
|
|
use App\Models\Ambulatorio\AtendimentoAntropometria;
|
|
use App\Models\Ambulatorio\AtendimentoDeclaracaoComparecimento;
|
|
use App\Models\Ambulatorio\AtendimentoGlicemiaCapilar;
|
|
use App\Models\Ambulatorio\AtendimentoImpressaoLog;
|
|
use App\Models\Ambulatorio\AtendimentoPreAtendimento;
|
|
use App\Models\Ambulatorio\AtendimentoRaas;
|
|
use App\Models\Ambulatorio\AtendimentoSinalVital;
|
|
use App\Models\Ambulatorio\AtendimentoSoap;
|
|
use App\Models\Ambulatorio\AtendimentoSoapAntecedente;
|
|
use App\Models\Ambulatorio\AtendimentoSoapAtestado;
|
|
use App\Models\Ambulatorio\AtendimentoSoapCartaMedica;
|
|
use App\Models\Ambulatorio\AtendimentoSoapCompartilhamentoCuidado;
|
|
use App\Models\Ambulatorio\AtendimentoSoapEncaminhamento;
|
|
use App\Models\Ambulatorio\AtendimentoSoapExameSolicitado;
|
|
use App\Models\Ambulatorio\AtendimentoSoapFerida;
|
|
use App\Models\Ambulatorio\AtendimentoSoapMotivo;
|
|
use App\Models\Ambulatorio\AtendimentoSoapOdontograma;
|
|
use App\Models\Ambulatorio\AtendimentoSoapOrientacao;
|
|
use App\Models\Ambulatorio\AtendimentoSoapPrescricaoMedicamento;
|
|
use App\Models\Ambulatorio\AtendimentoSoapPrescricaoMedicamentoItem;
|
|
use App\Models\Ambulatorio\AtendimentoSoapProblemaCondicao;
|
|
use App\Models\Ambulatorio\AtendimentoSoapResultadoExame;
|
|
use App\Models\Ambulatorio\AtendimentoSoapSolicitacaoExame;
|
|
use App\Models\Ambulatorio\AtendimentoSoapSolicitacaoProcedimentoCirurgico;
|
|
use App\Models\Ambulatorio\AtendimentoSoapTriaHistorio;
|
|
use App\Models\Ambulatorio\AtendimentoSoapTriagemNeonatalSolicitado;
|
|
use App\Models\Ambulatorio\AtestadoModelo;
|
|
use App\Models\Ambulatorio\CasoSuspeito;
|
|
use App\Models\Ambulatorio\ClassificacaoRisco;
|
|
use App\Models\Ambulatorio\DemandaEspontanea;
|
|
use App\Models\Ambulatorio\Dente;
|
|
use App\Models\Ambulatorio\ExameResultadoTipo;
|
|
use App\Models\Ambulatorio\GlicemiaCapilarMomentoColeta;
|
|
use App\Models\Ambulatorio\GravidezEdema;
|
|
use App\Models\Ambulatorio\GravidezTipo;
|
|
use App\Models\Ambulatorio\ParametrizacaoAtendimento;
|
|
use App\Models\Ambulatorio\ParametrizacaoIntegracaoAplicativo;
|
|
use App\Models\Ambulatorio\ParametrizacaoInfraestrutura;
|
|
use App\Models\Ambulatorio\ParametrizacaoInfraestruturaEspecialidadeProcedimento;
|
|
use App\Models\Ambulatorio\ParametrizacaoInfraestruturaOcupacao;
|
|
use App\Models\Ambulatorio\PartoTipo;
|
|
use App\Models\Ambulatorio\ProblemaCondicaoSituacao;
|
|
use App\Models\Ambulatorio\Jornada;
|
|
use App\Models\Ambulatorio\PuericulturaAlteracaoFenotipica;
|
|
use App\Models\Ambulatorio\PuericulturaFatorRisco;
|
|
use App\Models\Ambulatorio\PuericulturaMarcoDesenvolvimento;
|
|
use App\Models\Ambulatorio\SaudeBucalDenteProblemaCondicao;
|
|
use App\Models\Ambulatorio\SaudeBucalFornecimento;
|
|
use App\Models\Ambulatorio\SaudeBucalVigilancia;
|
|
use App\Models\Ambulatorio\Servico;
|
|
use App\Models\Ambulatorio\TesteRapido;
|
|
use App\Models\Apac\MotivoSaidaPermanencia as ApacMotivoSaidaPermanencia;
|
|
use App\Models\AtencaoBasica\AtendimentoDomiciliar\AtendimentoDomiciliarCondicaoAvaliada;
|
|
use App\Models\AtencaoBasica\AtendimentoDomiciliar\CondutaDesfecho;
|
|
use App\Models\AtencaoBasica\AtendimentoIndividual\AleitamentoMaterno;
|
|
use App\Models\AtencaoBasica\AtendimentoIndividual\CondicaoAvaliada;
|
|
use App\Models\AtencaoBasica\AtendimentoIndividual\Conduta;
|
|
use App\Models\AtencaoBasica\AtendimentoIndividual\DoencaTransmissivel;
|
|
use App\Models\AtencaoBasica\AtendimentoIndividual\Encaminhamento;
|
|
use App\Models\AtencaoBasica\AtendimentoIndividual\ExameSolicitadoAvaliado;
|
|
use App\Models\AtencaoBasica\AtendimentoIndividual\ModalidadeAtencaoDomiciliar;
|
|
use App\Models\AtencaoBasica\AtendimentoIndividual\RacionalidadeSaude;
|
|
use App\Models\AtencaoBasica\AtendimentoIndividual\Rastreamento;
|
|
use App\Models\AtencaoBasica\AtendimentoIndividual\TipoAtendimento;
|
|
use App\Models\AtencaoBasica\AtendimentoIndividual\TriagemNeonatal;
|
|
use App\Models\AtencaoBasica\AtendimentoOdontologico\TipoConsulta;
|
|
use App\Models\AtencaoBasica\Avaliacao\Avaliacao;
|
|
use App\Models\AtencaoBasica\Avaliacao\Conclusao;
|
|
use App\Models\AtencaoBasica\Avaliacao\Cuidador;
|
|
use App\Models\AtencaoBasica\Avaliacao\JustificativaConclusao;
|
|
use App\Models\AtencaoBasica\Avaliacao\Procedencia;
|
|
use App\Models\AtencaoBasica\CadastroIndividual\Peso;
|
|
use App\Models\AtencaoBasica\MarcadorConsumoAlimentar\LocalAtendimento;
|
|
use App\Models\AtencaoBasica\MarcadorConsumoAlimentar\MarcadorConsumoAlimentarPergunta;
|
|
use App\Models\AtencaoBasica\MarcadorConsumoAlimentar\MarcadorConsumoAlimentarResposta;
|
|
use App\Models\AtencaoBasica\Parametrizacao\Equipe;
|
|
use App\Models\AtencaoBasica\Parametrizacao\OutrosPermissaoOcupacao;
|
|
use App\Models\Cadastro\Especialidade;
|
|
use App\Models\Cadastro\Estabelecimento\CentroCusto;
|
|
use App\Models\Cadastro\Estabelecimento\Infraestrutura;
|
|
use App\Models\Cadastro\Estabelecimento\Unidade;
|
|
use App\Models\Cadastro\Ferida;
|
|
use App\Models\Cadastro\FeridaExsudato;
|
|
use App\Models\Cadastro\FeridaNecrose;
|
|
use App\Models\Cadastro\LocalAnatomico;
|
|
use App\Models\Cadastro\LocalAnatomicoRegiao;
|
|
use App\Models\Cadastro\EtapaClinica;
|
|
use App\Models\Cadastro\Material\Material;
|
|
use App\Models\Cadastro\Medicamento\ReceitaTipo;
|
|
use App\Models\Cadastro\Oci;
|
|
use App\Models\Cadastro\SujeitoAtencao\Alergia;
|
|
use App\Models\Cadastro\SujeitoAtencao\AlergiaCriticidade;
|
|
use App\Models\Cadastro\SujeitoAtencao\AlergiaTipo;
|
|
use App\Models\Cadastro\SujeitoAtencao\CidadaoTelefone;
|
|
use App\Models\Cadastro\SujeitoAtencao\Paciente;
|
|
use App\Models\Cadastro\SujeitoAtencao\PacienteGestacao;
|
|
use App\Models\Cadastro\SujeitoAtencao\PacienteInformacaoSocial;
|
|
use App\Models\Cadastro\SujeitoAtencao\Usuario;
|
|
use App\Models\Cadastro\UnidadeMedida;
|
|
use App\Models\Geral\Ciap;
|
|
use App\Models\Geral\DocumentoTipo;
|
|
use App\Models\Geral\LmsParametro;
|
|
use App\Models\Geral\MedidaTempo;
|
|
use App\Models\Geral\Turno;
|
|
use App\Models\PainelSenha\Encaminhamento as ModelPainelSenhaEncaminhamento;
|
|
use App\Models\PainelSenha\Fila;
|
|
use App\Models\PainelSenha\OpcaoEntrada;
|
|
use App\Models\PainelSenha\Prioridade;
|
|
use App\Models\Parametrizacao\Exame\Exame;
|
|
use App\Models\Parametrizacao\KitExame\KitExame;
|
|
use App\Models\Parametrizacao\ProcedimentoCirurgico;
|
|
use App\Models\Raas\CaraterAtendimento;
|
|
use App\Models\Raas\DestinoPaciente;
|
|
use App\Models\Raas\LocalRealizacaoExame;
|
|
use App\Models\Raas\MotivoSaidaPermanencia;
|
|
use App\Models\Raas\OrigemPaciente;
|
|
use App\Models\Regulacao\Parametrizacao as RegulacaoParametrizacao;
|
|
use App\Models\Regulacao\Solicitacao as RegulacaoSolicitacao;
|
|
use App\Models\Regulacao\Status;
|
|
use App\Models\Sigtap\Cid;
|
|
use App\Models\Sigtap\Classificacao as SigtapClassificacao;
|
|
use App\Models\Sigtap\Competencia;
|
|
use App\Models\Sigtap\Ocupacao;
|
|
use App\Models\Sigtap\Procedimento;
|
|
use App\Models\ExameLaboratorial\AgendamentoExame\AgendamentoExame;
|
|
use App\Models\Ambulatorio\AtendimentoSoapSolicitacaoExameItem;
|
|
use App\Models\ExameImagem\Agendamento\AgendamentoExame as AgendamentoExameImagem;
|
|
use App\Rules\Cns;
|
|
use App\Rules\Cpf;
|
|
use App\Rules\Sigtap\QuantidadeIsValidForProcedimento;
|
|
use App\Services\AtencaoBasica\MarcadorConsumoAlimentar\MarcadorConsumoAlimentarService;
|
|
use App\Services\AtencaoBasica\VisitaDomiciliar\HistoricoService as VisitaDomiciliarHistoricoService;
|
|
use App\Services\Geral\AgeService;
|
|
use App\Services\Geral\ImcService;
|
|
use App\Services\Almoxarifado\AlmoxarifadoService;
|
|
use App\Services\ProntoAtendimento\HistoricoService as ProntoAtendimentoHistoricoService;
|
|
use App\Services\Regulacao\SolicitacaoService as RegulacaoSolicitacaoService;
|
|
use App\Services\Service;
|
|
use App\Utils\MaskUtil;
|
|
use Carbon\Carbon;
|
|
use Exception;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\Rule;
|
|
use App\Models\Ambulatorio\AtendimentoSoapFeridaImagem;
|
|
use App\Models\Ambulatorio\Atendimento;
|
|
use App\Models\Ambulatorio\AtendimentoSoapFeridaProcedimento;
|
|
use App\Models\Ambulatorio\AtendimentoSoapProcedimentoClinico;
|
|
use App\Models\Ambulatorio\AtendimentoSoapFeridaMaterial;
|
|
use App\Models\Ambulatorio\AtendimentoProcedimento;
|
|
use App\Models\Ambulatorio\ParametrizacaoInfraestruturaEspecialidade;
|
|
use App\Models\Ambulatorio\PuericulturaQuestionarioMChatR;
|
|
use App\Models\AtencaoBasica\CadastroIndividual\CadastroIndividual;
|
|
use App\Models\AtencaoBasica\CadastroPerfilEpidemiologico;
|
|
use Illuminate\Support\Facades\Storage;
|
|
use Illuminate\Support\Facades\File;
|
|
use App\Rules\Sigtap\ProcedimentoIsValidForOcupacao;
|
|
use Illuminate\Validation\ValidationException;
|
|
|
|
class AtendimentoService extends Service
|
|
{
|
|
public const IDADE_ANOS_INICIAL_IDOSO = 60;
|
|
public const IDADE_ANOS_FINAL_CRIANCA = 9;
|
|
public const IDADE_ANOS_FINAL_CRIANCA_ALEITAMENTO = 1;
|
|
public const IDADE_ANOS_FINAL_ADOLESCENTE = 18;
|
|
|
|
public const CIAPS_GRAVIDEZ_NORMAL = [
|
|
CiapEnum::GRAVIDEZ,
|
|
];
|
|
|
|
public const CIAPS_GRAVIDEZ_ALTO_RISCO = [
|
|
CiapEnum::INFECCOES_QUE_COMPLICAM_A_GRAVIDEZ,
|
|
CiapEnum::GRAVIDEZ_NAO_DESEJADA,
|
|
CiapEnum::GRAVIDEZ_ECTOPICA,
|
|
CiapEnum::TOXEMIA_GRAVIDICA_DHEG,
|
|
CiapEnum::GRAVIDEZ_DE_ALTO_RISCO,
|
|
CiapEnum::DIABETES_GESTACIONAL,
|
|
];
|
|
|
|
public const CIAPS_DESFECHO_GRAVIDEZ = [
|
|
CiapEnum::ABORTO_ESPONTANEO,
|
|
CiapEnum::ABORTO_PROVOCADO,
|
|
CiapEnum::PARTO_SEM_COMPLICACOES_DE_NASCIDO_VIVO,
|
|
CiapEnum::PARTO_SEM_COMPLICACOES_DE_NATIMORTO,
|
|
CiapEnum::PARTO_COM_COMPLICACOES_DE_NASCIDO_VIVO,
|
|
CiapEnum::PARTO_COM_COMPLICACOES_DE_NATIMORTO,
|
|
];
|
|
|
|
public const CIDS_GRAVIDEZ_NORMAL = [
|
|
CidEnum::SUPERVISAO_DE_GRAVIDEZ_NORMAL,
|
|
CidEnum::SUPERVISAO_DE_PRIMEIRA_GRAVIDEZ_NORMAL,
|
|
CidEnum::SUPERVISAO_DE_OUTRA_GRAVIDEZ_NORMAL,
|
|
CidEnum::SUPERVISAO_DE_GRAVIDEZ_NORMAL_NAO_ESPECIFICADA,
|
|
];
|
|
|
|
public const CIDS_GRAVIDEZ_ALTO_RISCO = [
|
|
CidEnum::SUPERVISAO_DE_GRAVIDEZ_DE_ALTO_RISCO,
|
|
CidEnum::SUPERVISAO_DE_GRAVIDEZ_COM_HISTORIA_DE_ESTERILIDADE,
|
|
CidEnum::SUPERVISAO_DE_GRAVIDEZ_COM_HISTORIA_DE_ABORTO,
|
|
CidEnum::SUPERVISAO_DE_GRAVIDEZ_COM_OUTROS_ANTECEDENTES_DE_PROCRIACAO_PROBLEMATICA,
|
|
CidEnum::SUPERVISAO_DE_GRAVIDEZ_COM_HISTORIA_DE_ASSISTENCIA_PRE_NATAL_INSUFICIENTE,
|
|
CidEnum::SUPERVISAO_DE_GRAVIDEZ_COM_GRANDE_MULTIPARIDADE,
|
|
CidEnum::SUPERVISAO_DE_PRIMIGESTA_IDOSA,
|
|
CidEnum::SUPERVISAO_DE_PRIMIGESTA_MUITO_JOVEM,
|
|
CidEnum::SUPERVISAO_DE_GRAVIDEZ_DE_ALTO_RISCO_DEVIDO_A_PROBLEMAS_SOCIAIS,
|
|
CidEnum::SUPERVISAO_DE_OUTRAS_GRAVIDEZES_DE_ALTO_RISCO,
|
|
CidEnum::SUPERVISAO_NAO_ESPECIFICADA_DE_GRAVIDEZ_DE_ALTO_RISCO,
|
|
];
|
|
|
|
public const CIDS_DESFECHO_GRAVIDEZ = [
|
|
CidEnum::OUTROS_PRODUTOS_ANORMAIS_DA_CONCEPCAO,
|
|
CidEnum::ABORTO_ESPONTANEO,
|
|
CidEnum::ABORTO_POR_RAZOES_MEDICAS_E_LEGAIS,
|
|
CidEnum::OUTROS_TIPOS_DE_ABORTO,
|
|
CidEnum::ABORTO_NAO_ESPECIFICADO,
|
|
CidEnum::RUPTURA_PREMATURA_DE_MEMBRANAS,
|
|
CidEnum::DESCOLAMENTO_PREMATURO_DA_PLACENTA_ABRUPTIO_PLACENTAE,
|
|
CidEnum::FALHA_NA_INDUCAO_DO_TRABALHO_DE_PARTO,
|
|
CidEnum::ANORMALIDADES_DA_CONTRACAO_UTERINA,
|
|
CidEnum::TRABALHO_DE_PARTO_PROLONGADO,
|
|
CidEnum::OBSTRUCAO_DO_TRABALHO_DE_PARTO_DEVIDA_A_MA_POSICAO_OU_MA_APRESENTACAO_DO_FETO,
|
|
CidEnum::OBSTRUCAO_DO_TRABALHO_DE_PARTO_DEVIDA_A_ANORMALIDADE_PELVICA_DA_MAE,
|
|
CidEnum::OUTRAS_FORMAS_DE_OBSTRUCAO_DO_TRABALHO_DE_PARTO,
|
|
CidEnum::TRABALHO_DE_PARTO_E_PARTO_COMPLICADOS_POR_HEMORRAGIA_INTRAPARTO_NAO_CLASSIFICADOS_EM_OUTRA_PARTE,
|
|
CidEnum::TRABALHO_DE_PARTO_E_PARTO_COMPLICADOS_POR_SOFRIMENTO_FETAL,
|
|
CidEnum::TRABALHO_DE_PARTO_E_PARTO_COMPLICADOS_POR_ANORMALIDADE_DO_CORDAO_UMBILICAL,
|
|
CidEnum::LACERACAO_DO_PERINEO_DURANTE_O_PARTO,
|
|
CidEnum::OUTROS_TRAUMATISMOS_OBSTETRICOS,
|
|
CidEnum::RETENCAO_DA_PLACENTA_E_DAS_MEMBRANAS_SEM_HEMORRAGIAS,
|
|
CidEnum::SOFRIMENTO_MATERNO_DURANTE_O_TRABALHO_DE_PARTO_E_O_PARTO,
|
|
CidEnum::CHOQUE_DURANTE_OU_SUBSEQUENTE_AO_TRABALHO_DE_PARTO_E_O_PARTO,
|
|
CidEnum::OUTRAS_COMPLICACOES_DE_PROCEDIMENTOS_OU_DE_CIRURGIA_OBSTETRICA,
|
|
CidEnum::DEMORA_DO_PARTO_APOS_RUPTURA_ARTIFICIAL_DAS_MEMBRANAS,
|
|
CidEnum::DEMORA_DO_PARTO_APOS_RUPTURA_ESPONTANEA_OU_NAO_ESPECIFICADA_DAS_MEMBRANAS,
|
|
CidEnum::PARTO_VAGINAL_SUBSEQUENTE_A_CESARIANA_ANTERIOR,
|
|
CidEnum::OUTRAS_COMPLICACOES_ESPECIFICADAS_DO_TRABALHO_DE_PARTO_E_DO_PARTO,
|
|
CidEnum::COMPLICACOES_DO_TRABALHO_DE_PARTO_E_DO_PARTO_NAO_ESPECIFICADAS,
|
|
CidEnum::PARTO_UNICO_ESPONTANEO,
|
|
CidEnum::PARTO_UNICO_POR_FORCEPS_OU_VACUO_EXTRATOR,
|
|
CidEnum::PARTO_UNICO_POR_CESARIANA,
|
|
CidEnum::OUTROS_TIPOS_DE_PARTO_UNICO_ASSISTIDO,
|
|
CidEnum::PARTO_MULTIPLO,
|
|
CidEnum::EXTRACAO_MENSTRUAL,
|
|
CidEnum::NASCIMENTO_UNICO_NATIVIVO_NADO_VIVO,
|
|
CidEnum::NASCIMENTO_UNICO_NATIMORTO_FETO_MORTO,
|
|
CidEnum::NASCIMENTO_GEMELAR_GEMEOS_AMBOS_NATIVIVOS_NADO_VIVOS,
|
|
CidEnum::NASCIMENTO_GEMELAR_UM_DOS_GEMEOS_NATIVIVO_NADO_VIVO_O_OUTRO_NATIMORTO_FETO_MORTO,
|
|
CidEnum::NASCIMENTO_GEMELAR_GEMEOS_NATIMORTOS_FETO_MORTOS,
|
|
CidEnum::OUTROS_NASCIMENTOS_MULTIPLOS_TODOS_NATIVIVOS_NADO_VIVOS,
|
|
CidEnum::OUTROS_NASCIMENTOS_MULTIPLOS_ALGUNS_NATIVIVOS_NADO_VIVOS,
|
|
CidEnum::OUTROS_NASCIMENTOS_MULTIPLOS_TODOS_NATIMORTOS_FETO_MORTOS,
|
|
CidEnum::NASCIMENTO_NAO_ESPECIFICADO,
|
|
CidEnum::NASCIDOS_VIVOS_SEGUNDO_O_LOCAL_DE_NASCIMENTO,
|
|
CidEnum::ASSISTENCIA_E_EXAME_POS_NATAL,
|
|
CidEnum::TRABALHO_DE_PARTO_PRE_TERMO,
|
|
];
|
|
|
|
public static function exameDentroPrazoValidade()
|
|
{
|
|
if (request()->exame_id) {
|
|
|
|
$exame = Exame::findOrFail(request()->exame_id);
|
|
|
|
if (is_null($exame->validade)) {
|
|
return false;
|
|
}
|
|
} else if (request()->codigo_procedimento) {
|
|
|
|
$exame = Exame::where('codigo', request()->codigo_procedimento)->first();
|
|
|
|
if (!$exame || is_null($exame->validade)) {
|
|
return false;
|
|
}
|
|
|
|
} else {
|
|
return false;
|
|
}
|
|
|
|
$pacienteId = request()->paciente_id;
|
|
|
|
$ultimaSolicitacaoAmbulatorial = DB::table('ambulatorio_atendimento_soap_solicitacao_exame_item as item')
|
|
->join('ambulatorio_atendimento_soap_solicitacao_exame as solicitacao', 'solicitacao.id', 'item.solicitacao_exame_id')
|
|
->join('ambulatorio_atendimento_soap as soap', 'soap.id', 'solicitacao.soap_id')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
|
|
->join('parametrizacao_exame as exame', 'exame.id', 'item.exame_id')
|
|
->leftJoin('regulacao_solicitacao', 'regulacao_solicitacao.soap_id', 'soap.id')
|
|
->leftJoin('regulacao_status as regulacaoStatus', 'regulacaoStatus.id', 'regulacao_solicitacao.status_id')
|
|
->where('soap.is_rascunho', false)
|
|
->where(function ($q) {
|
|
$q->whereNull('regulacaoStatus.tipo_id')
|
|
->orWhere('regulacaoStatus.tipo_id', '!=', RegulacaoStatusTipo::CANCELADO);
|
|
})
|
|
->where('atendimento.paciente_id', $pacienteId)
|
|
->when(request()->exame_id, fn ($q, $id) => $q->where('item.exame_id', $id))
|
|
->when(request()->codigo_procedimento, fn ($q, $codigo) => $q->where('exame.codigo', $codigo))
|
|
->select('item.created_at')
|
|
->orderByDesc('item.created_at')
|
|
->first();
|
|
|
|
$ultimaSolicitacaoLaboratorio = DB::table('exame_laboratorial_agendamento as a')
|
|
->join('exame_laboratorial_agendamento_exame as ae', 'ae.agendamento_id', 'a.id')
|
|
->join('parametrizacao_exame as exame', 'exame.id', 'ae.exame_id')
|
|
->where('a.paciente_id', $pacienteId)
|
|
->when(request()->exame_id, fn ($q, $id) => $q->where('ae.exame_id', $id))
|
|
->when(request()->codigo_procedimento, fn ($q, $codigo) => $q->where('exame.codigo', $codigo))
|
|
->select('a.data as created_at')
|
|
->orderByDesc('a.data')
|
|
->first();
|
|
|
|
$datas = collect([
|
|
optional($ultimaSolicitacaoAmbulatorial)->created_at,
|
|
optional($ultimaSolicitacaoLaboratorio)->created_at,
|
|
])->filter()->map(fn ($d) => new Carbon($d));
|
|
|
|
if ($datas->isEmpty()) {
|
|
return false;
|
|
}
|
|
|
|
$dataMaisRecente = $datas->sortDesc()->first()->startOfDay();
|
|
|
|
return Carbon::today()->diff($dataMaisRecente)->days <= $exame->validade;
|
|
}
|
|
|
|
public static function encaminhamentoPendente()
|
|
{
|
|
|
|
$ultimaSolicitacao = DB::table('regulacao_solicitacao as solicitacao')
|
|
->join('regulacao_solicitacao_item as item', 'item.solicitacao_id', 'solicitacao.id')
|
|
->join('regulacao_status as status', 'status.id', 'solicitacao.status_id')
|
|
->where('item.especialidade_id', request()->especialidade_id)
|
|
->where('solicitacao.paciente_id', request()->paciente_id)
|
|
->whereNotIn('status.tipo_id', [RegulacaoStatusTipo::CANCELADO, RegulacaoStatusTipo::FALTA, RegulacaoStatusTipo::REALIZADO])
|
|
->select('solicitacao.created_at')
|
|
->first();
|
|
|
|
if (is_null($ultimaSolicitacao)) {
|
|
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
public static function uploadImagem()
|
|
{
|
|
$images = request()->file('images');
|
|
$ids = request()->input('ids');
|
|
|
|
if (!$images || !$ids) {
|
|
return response()->json(['error' => 'Nenhuma imagem ou ID recebido.'], 400);
|
|
}
|
|
|
|
if (count($images) !== count($ids)) {
|
|
return response()->json(['error' => 'Número de imagens e IDs não corresponde.'], 400);
|
|
}
|
|
|
|
foreach ($images as $index => $image) {
|
|
$feridaId = $ids[$index];
|
|
|
|
if (!$image->isValid()) {
|
|
continue;
|
|
}
|
|
|
|
$arquivo = Str::uuid() . '.' . $image->getClientOriginalExtension();
|
|
|
|
$soapFeridaId = AtendimentoSoapFerida::where('id_old', $feridaId)
|
|
->value('id');
|
|
|
|
$imagem = new AtendimentoSoapFeridaImagem();
|
|
$imagem->soap_ferida_id = $soapFeridaId;
|
|
$imagem->arquivo = $arquivo;
|
|
|
|
$imagem->save();
|
|
|
|
$path = Storage::path('ambulatorio' . DIRECTORY_SEPARATOR . 'feridas' . DIRECTORY_SEPARATOR . app('config')->get('database.default'));
|
|
|
|
if (file_exists($path) === false) {
|
|
File::makeDirectory($path, 0777, true, true);
|
|
}
|
|
|
|
$image->move($path, $arquivo);
|
|
|
|
}
|
|
}
|
|
|
|
public static function destroy($id)
|
|
{
|
|
|
|
$imagem = AtendimentoSoapFeridaImagem::findOrFail($id);
|
|
|
|
if(Storage::exists('ambulatorio' . DIRECTORY_SEPARATOR . 'feridas' . DIRECTORY_SEPARATOR . app('config')->get('database.default') . DIRECTORY_SEPARATOR . $imagem->arquivo)){
|
|
|
|
Storage::delete('ambulatorio' . DIRECTORY_SEPARATOR . 'feridas' . DIRECTORY_SEPARATOR . app('config')->get('database.default') . DIRECTORY_SEPARATOR . $imagem->arquivo);
|
|
}
|
|
|
|
AtendimentoSoapFeridaImagem::findOrFail($id)->delete();
|
|
}
|
|
|
|
public static function prescricaoMedicamento()
|
|
{
|
|
|
|
$ultimaSolicitacao = DB::table('ambulatorio_atendimento_soap_prescricao_medicamento as solicitacao')
|
|
->join('ambulatorio_atendimento_soap_prescricao_medicamento_item as item', 'item.prescricao_medicamento_id', 'solicitacao.id')
|
|
->join('ambulatorio_atendimento_soap as soap', 'soap.id', 'solicitacao.soap_id')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
|
|
->join('painel_senha_fila as fila', 'fila.id', 'atendimento.fila_id')
|
|
->join('cadastro_material as material', 'material.id', 'item.material_id')
|
|
->join('cadastro_via_administracao', 'cadastro_via_administracao.id', 'material.via_administracao_id')
|
|
->leftJoin('cadastro_unidade_medida as um', 'um.id', '=', 'item.unidade_medida_id')
|
|
->leftJoin('geral_medida_tempo as imt', 'imt.id', '=', 'item.intervalo_medida_tempo_id')
|
|
->leftJoin('geral_medida_tempo as gmt', 'gmt.id', '=', 'item.duracao_medida_tempo_id')
|
|
->leftJoin('geral_turno as t', 't.id', '=', 'item.turno_id')
|
|
->where('fila.paciente_id', request()->paciente_id)
|
|
->where('item.material_id', request()->medicamento_id)
|
|
->where(function ($q) {
|
|
$q->where(function ($q2) {
|
|
|
|
$q2->where('item.is_dose_unica', true)
|
|
->whereDate('item.inicio', '<=', now());
|
|
})
|
|
->orWhere(function ($q2) {
|
|
|
|
$q2->where('item.is_dose_unica', false)
|
|
->whereRaw("
|
|
CASE
|
|
WHEN item.duracao_medida_tempo_id = ?
|
|
THEN DATE_ADD(item.inicio, INTERVAL item.duracao DAY)
|
|
WHEN item.duracao_medida_tempo_id = ?
|
|
THEN DATE_ADD(item.inicio, INTERVAL item.duracao WEEK)
|
|
WHEN item.duracao_medida_tempo_id = ?
|
|
THEN DATE_ADD(item.inicio, INTERVAL item.duracao MONTH)
|
|
ELSE item.inicio
|
|
END >= NOW()
|
|
", [
|
|
MedidaTempoEnum::DIAS,
|
|
MedidaTempoEnum::SEMANAS,
|
|
MedidaTempoEnum::MESES,
|
|
]);
|
|
});
|
|
})
|
|
->select(
|
|
'item.id',
|
|
'item.created_at',
|
|
DB::raw("
|
|
CASE
|
|
WHEN item.is_dose_unica = 1 THEN 'Sim'
|
|
ELSE 'Não'
|
|
END as is_dose_unica
|
|
"),
|
|
DB::raw("
|
|
CASE
|
|
WHEN item.is_uso_continuo = 1 THEN 'Sim'
|
|
ELSE 'Não'
|
|
END as is_uso_continuo
|
|
"),
|
|
DB::raw("DATE_FORMAT(item.inicio, '%d/%m/%Y') as inicio"),
|
|
'material.receita_tipo_id',
|
|
'item.duracao_medida_tempo_id',
|
|
'gmt.nome as duracao_medida_tempo',
|
|
'item.duracao',
|
|
'item.recomendacoes',
|
|
'material.descricao as material',
|
|
'cadastro_via_administracao.nome as materialViaAdministracao',
|
|
DB::raw("
|
|
DATE_FORMAT(
|
|
CASE
|
|
WHEN item.is_dose_unica = 1
|
|
THEN item.inicio
|
|
WHEN item.duracao_medida_tempo_id = " . MedidaTempoEnum::DIAS . "
|
|
THEN DATE_ADD(item.inicio, INTERVAL item.duracao DAY)
|
|
WHEN item.duracao_medida_tempo_id = " . MedidaTempoEnum::SEMANAS . "
|
|
THEN DATE_ADD(item.inicio, INTERVAL item.duracao WEEK)
|
|
WHEN item.duracao_medida_tempo_id = " . MedidaTempoEnum::MESES . "
|
|
THEN DATE_ADD(item.inicio, INTERVAL item.duracao MONTH)
|
|
ELSE item.inicio
|
|
END, '%d/%m/%Y'
|
|
) as data_conclusao
|
|
"),
|
|
DB::raw("
|
|
CASE
|
|
WHEN item.is_dose_unica = 1
|
|
THEN CONCAT(item.dose, ' dose única')
|
|
WHEN item.frequencia_vezes IS NOT NULL
|
|
THEN CONCAT(
|
|
item.dose,
|
|
COALESCE(CONCAT(' ', um.nome), ' (dose)'),
|
|
', ', item.frequencia_vezes, ' vez(es)',
|
|
CASE
|
|
WHEN item.intervalo = 1 AND item.intervalo_medida_tempo_id = " . MedidaTempoEnum::DIAS . "
|
|
THEN ' ao dia'
|
|
ELSE CONCAT(' a cada ', item.intervalo, ' ', imt.nome)
|
|
END
|
|
)
|
|
WHEN item.turno_id IS NOT NULL
|
|
THEN CONCAT(
|
|
item.dose,
|
|
COALESCE(CONCAT(' ', um.nome), ' (dose)'),
|
|
', pela ', t.nome,
|
|
CASE
|
|
WHEN NOT (item.intervalo = 1 AND item.intervalo_medida_tempo_id = " . MedidaTempoEnum::DIAS . ")
|
|
THEN CONCAT(' a cada ', item.intervalo, ' ', imt.nome)
|
|
ELSE ''
|
|
END
|
|
)
|
|
ELSE CONCAT(
|
|
item.dose,
|
|
COALESCE(CONCAT(' ', um.nome), ' (dose)'),
|
|
', a cada ',
|
|
CASE
|
|
WHEN item.intervalo_medida_tempo_id = " . MedidaTempoEnum::HORAS . "
|
|
THEN IF(item.intervalo > 1, CONCAT(item.intervalo, ' ', imt.nome), ' hora')
|
|
ELSE CONCAT(item.intervalo, ' ', imt.nome)
|
|
END
|
|
)
|
|
END as posologia
|
|
")
|
|
)
|
|
->orderByDesc('item.created_at')
|
|
->first();
|
|
|
|
|
|
if (is_null($ultimaSolicitacao)) {
|
|
|
|
return false;
|
|
}
|
|
|
|
return $ultimaSolicitacao;
|
|
}
|
|
|
|
public static function getHistoricoPreAtendimento($id)
|
|
{
|
|
return AtendimentoHistoricoService::getPreAtendimento($id);
|
|
}
|
|
|
|
public static function getHistoricoAtendimentoSoap($id)
|
|
{
|
|
return AtendimentoHistoricoService::getAtendimentoSoap($id);
|
|
}
|
|
|
|
public static function getHistoricoAtendimentoHospital($id)
|
|
{
|
|
return AtendimentoHistoricoService::getAtendimentoHospital($id);
|
|
}
|
|
|
|
public static function getHistoricoPosConsulta($id)
|
|
{
|
|
return AtendimentoHistoricoService::getPosConsulta($id);
|
|
}
|
|
|
|
public static function getHistoricoProntoAtendimentoAtendimento($id)
|
|
{
|
|
$historico = ProntoAtendimentoHistoricoService::getAtendimento($id);
|
|
|
|
$historico->atendimentos = collect($historico->atendimentos)
|
|
->map(function ($atendimento) {
|
|
|
|
$atendimento['visible'] = false;
|
|
|
|
return $atendimento;
|
|
});
|
|
|
|
return $historico;
|
|
}
|
|
|
|
public static function list()
|
|
{
|
|
switch (request()->origem) {
|
|
|
|
case 'avaliacao': {
|
|
|
|
return self::getAvaliacaoList();
|
|
}
|
|
case 'plano': {
|
|
|
|
return self::getPlanoList();
|
|
}
|
|
case 'desfecho': {
|
|
|
|
return self::getDesfechoList();
|
|
}
|
|
case 'protocolos': {
|
|
|
|
return self::getProtocolosList();
|
|
}
|
|
}
|
|
}
|
|
|
|
private static function getAvaliacaoList()
|
|
{
|
|
$params = (object) request()->all();
|
|
|
|
switch (request()->listar) {
|
|
|
|
case 'ocis': {
|
|
|
|
return self::getOcisVinculadasComCid($params);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static function getOcisVinculadasComCid($params)
|
|
{
|
|
$ocis = DB::table('cadastro_oci AS oci')
|
|
->join('sigtap.procedimento AS procedimento', fn ($j) => $j
|
|
->on('procedimento.codigo', 'oci.procedimento_codigo')
|
|
->where('procedimento.competencia_id', DB::table('sigtap.competencia')->max('id'))
|
|
)
|
|
->where('oci.ativo', true)
|
|
->whereExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('sigtap.procedimento_cid AS procedimento_cid')
|
|
->whereColumn('procedimento_cid.procedimento_id', 'procedimento.id')
|
|
->where('procedimento_cid.cid_id', $params->cid_id)
|
|
)
|
|
->whereExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('sigtap.procedimento_ocupacao AS procedimento_ocupacao')
|
|
->whereColumn('procedimento_ocupacao.procedimento_id', 'procedimento.id')
|
|
->where('procedimento_ocupacao.ocupacao_id', self::getCurrentLotacao()->ocupacao_id)
|
|
)
|
|
->select(
|
|
'oci.id',
|
|
'oci.nome',
|
|
'oci.linha_cuidado'
|
|
)
|
|
->orderBy('oci.nome')
|
|
->get();
|
|
|
|
return $ocis;
|
|
}
|
|
|
|
private static function getPlanoList()
|
|
{
|
|
$params = (object) request()->all();
|
|
|
|
switch (request()->listar) {
|
|
|
|
case 'encaminhamento-intersetorial-infraestruturas': {
|
|
|
|
return [
|
|
'infraestruturas' => self::getEncaminhamentoIntersetorialInfraestruturas($params),
|
|
];
|
|
}
|
|
}
|
|
}
|
|
|
|
private static function getEncaminhamentoIntersetorialInfraestruturas($params)
|
|
{
|
|
return Infraestrutura::setEagerLoads([])
|
|
->where('unidade_id', $params->unidade_id)
|
|
->whereHas('ambulatorioParametrizacaoJornadaInfraestrutura')
|
|
->get(['id', 'nome', 'principal', 'unidade_id'])
|
|
->map(fn ($infraestrutura) => [
|
|
'id' => $infraestrutura->id,
|
|
'nome' => $infraestrutura->nome,
|
|
])
|
|
->sortBy('nome')
|
|
->values();
|
|
}
|
|
|
|
private static function getDesfechoList()
|
|
{
|
|
$params = (object) request()->all();
|
|
$atendimento = Fila::findOrFail($params->fila_id)->ambulatorioAtendimento;
|
|
|
|
$params->paciente_id = $atendimento->paciente->id;
|
|
$params->paciente_nao_municipe = $atendimento->paciente->classificacao_id !== Classificacao::MUNICIPE;
|
|
$params->infraestrutura_id = self::getCurrentCentroCusto()->infraestrutura_id;
|
|
$params->data = Carbon::today();
|
|
|
|
switch (request()->listar) {
|
|
|
|
case 'ocupacoes': {
|
|
|
|
return [
|
|
'ocupacoes' => self::getOcupacoesWithJornada($params),
|
|
'especialidades' => [],
|
|
];
|
|
}
|
|
case 'especialidades': {
|
|
|
|
return [
|
|
'especialidades' => self::getEspecialidadesWithJornada($params),
|
|
];
|
|
}
|
|
}
|
|
}
|
|
|
|
private static function getProtocolosList()
|
|
{
|
|
$params = (object) request()->all();
|
|
|
|
switch (request()->listar) {
|
|
|
|
case 'ocis': {
|
|
|
|
return self::getProtocolosOcis($params);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static function getProtocolosOcis($params)
|
|
{
|
|
return DB::table('cadastro_oci AS oci')
|
|
->join('sigtap.procedimento AS procedimento', fn ($j) => $j
|
|
->on('procedimento.codigo', 'oci.procedimento_codigo')
|
|
->where('procedimento.competencia_id', DB::table('sigtap.competencia')->max('id'))
|
|
)
|
|
->where('oci.ativo', true)
|
|
->when($params->nome, fn ($q) => $q->where('oci.nome', 'like', "{$params->nome}%"))
|
|
->when($params->linha_cuidado, fn ($q) => $q->where('oci.linha_cuidado', 'like', "{$params->linha_cuidado}%"))
|
|
->whereExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('sigtap.procedimento_ocupacao AS procedimento_ocupacao')
|
|
->whereColumn('procedimento_ocupacao.procedimento_id', 'procedimento.id')
|
|
->where('procedimento_ocupacao.ocupacao_id', self::getCurrentLotacao()->ocupacao_id)
|
|
)
|
|
->select(
|
|
'oci.id',
|
|
'oci.nome',
|
|
'oci.linha_cuidado',
|
|
)
|
|
->get();
|
|
}
|
|
|
|
public static function create($filaId, $agendamentoId = null)
|
|
{
|
|
$fila = null;
|
|
$agendamento = null;
|
|
|
|
if (!is_null($agendamentoId)) {
|
|
|
|
$agendamento = Agendamento::findOrFail($agendamentoId);
|
|
|
|
if (is_null($agendamento->atendimento)) {
|
|
|
|
$dataHoraRetroativa = Carbon::create($agendamento->jornada->data->format('Y-m-d')
|
|
. ' ' . $agendamento->horario->format('H:i:s'));
|
|
|
|
$agendamentoAtendimento = $agendamento->atendimento()->create([
|
|
'paciente_id' => $agendamento->paciente_id
|
|
]);
|
|
|
|
$agendamentoAtendimento->created_at = $dataHoraRetroativa;
|
|
$agendamentoAtendimento->updated_at = $dataHoraRetroativa;
|
|
$agendamentoAtendimento->save();
|
|
|
|
$agendamento->refresh();
|
|
}
|
|
}
|
|
else {
|
|
|
|
$fila = Fila::findOrFail($filaId);
|
|
|
|
if (!$fila->ambulatorioAtendimento->soaps()->where('is_atendimento_enfermagem', false)->where('is_rascunho', true)->exists()) {
|
|
|
|
FilaService::answer($fila->id);
|
|
}
|
|
}
|
|
|
|
$atendimento = $fila->ambulatorioAtendimento ?? $agendamento->atendimento;
|
|
$soapRascunho = $atendimento->soaps()->where('is_atendimento_enfermagem', false)->where('is_rascunho', true)->first();
|
|
|
|
return [
|
|
'additionals' => self::getAdditionalsData($atendimento, $soapRascunho),
|
|
'form' => self::getFormData($atendimento, $soapRascunho, $fila),
|
|
'model' => self::getModelData($atendimento, $soapRascunho, $fila),
|
|
];
|
|
}
|
|
|
|
public static function getHistoricoErpsaude($paciente)
|
|
{
|
|
|
|
return AtendimentoHistoricoService::getHistoricoErpsaudeResumido($paciente);
|
|
}
|
|
|
|
private static function getAdditionalsData($atendimento, $soapRascunho)
|
|
{
|
|
$now = Carbon::now();
|
|
$unidadeLogada = self::getCurrentCentroCusto()->infraestrutura->unidade;
|
|
|
|
$hasCadastroIndividual = CadastroIndividual::where('paciente_id', $atendimento->paciente_id)->exists();
|
|
|
|
$parametrizacaoAtendimento = ParametrizacaoAtendimento::first();
|
|
|
|
$isOocupacaoParametrizadaMarcadorConsumoAlimentar = OutrosPermissaoOcupacao::where(
|
|
'ocupacao',
|
|
self::getCurrentLotacao()->ocupacao->codigo
|
|
)
|
|
->where('permissao_id', AtencaoBasicaPermissao::MARCADORES_DE_CONSUMO_ALIMENTAR)
|
|
->exists();
|
|
$currentLotacao = self::getCurrentLotacao();
|
|
return [
|
|
'unidade' => [
|
|
'nome' => $currentLotacao->infraestrutura->unidade->nome_fantasia,
|
|
'cnes' => $currentLotacao->infraestrutura->unidade->cnes,
|
|
],
|
|
'data_atendimento' => Carbon::parse($atendimento->created_at)->format('d/m/Y'),
|
|
'atendimento_id' => $atendimento->id,
|
|
'tipo_agendamento_safecare' => optional(ParametrizacaoIntegracaoAplicativo::first())->habilita_integracao_aplicativo_feridas ?? false,
|
|
'data_atual' => $now->format('d/m/Y'),
|
|
'hora_inicio_atendimento' => $now->format('H:i'),
|
|
'agendamento_competencia_id' => $atendimento->agendamento
|
|
? Competencia::where('valor', '<=', $atendimento->agendamento->jornada->data->format('Ym'))
|
|
->orderByDesc('valor')
|
|
->first()->id ?? null
|
|
: null,
|
|
'is_demanda_espontanea' => $atendimento->is_demanda_espontanea,
|
|
'show_marcador_consumo_alimentar' => self::criaFicha('marcador-consumo-alimentar') && $isOocupacaoParametrizadaMarcadorConsumoAlimentar,
|
|
'is_primeiro_atendimento_puericultura' => is_null(
|
|
self::getUltimoSoapPuericultura($atendimento->paciente)
|
|
),
|
|
'is_atendimento_saude_bucal' => self::isProfissionalSaudeBucal(),
|
|
'cria_ficha_atencao_basica' => self::criaFichaAtencaoBasica(),
|
|
'cria_ficha_atencao_basica_atendimento_individual' => self::criaFicha('atendimento-individual'),
|
|
'cria_ficha_atencao_basica_atendimento_domiciliar' => self::criaFicha('atendimento-domiciliar'),
|
|
'cria_ficha_atencao_basica_atendimento_odontologico' => self::criaFicha('atendimento-odontologico'),
|
|
'cria_ficha_atencao_basica_avaliacao' => self::criaFicha('avaliacao'),
|
|
'has_permissao_equipe_avaliacao' => self::getPermissaoEquipe(Permissao::AVALIACAO_ELEGIBILIDADE_ADMISSAO),
|
|
'has_permissao_equipe_atendimento_domiciliar' => self::getPermissaoEquipe(Permissao::ATENDIMENTO_DOMICILIAR),
|
|
'fatura_procedimento_raas' => self::faturaProcedimentoRaas(),
|
|
'exibe_box_exame_laboratorial_solicitado' => $parametrizacaoAtendimento->exibe_box_exame_laboratorial_solicitado ?? false,
|
|
'receita_nao_padronizada_justificativa_obrigatoria' => $parametrizacaoAtendimento->receita_nao_padronizada_justificativa_obrigatoria ?? false,
|
|
'visualizar_remume' => $parametrizacaoAtendimento->visualizar_remume ?? false,
|
|
'permite_exame_laboratorial_repetido' => $parametrizacaoAtendimento->permite_exame_laboratorial_repetido ?? false,
|
|
'permite_exame_imagem_repetido' => $parametrizacaoAtendimento->permite_exame_imagem_repetido ?? false,
|
|
'permite_encaminhar_repetido' => $parametrizacaoAtendimento->permite_encaminhar_repetido ?? false,
|
|
'permite_prescricao_repetida' => $parametrizacaoAtendimento->permite_prescricao_repetida ?? false,
|
|
'protocolo_fechamento' => self::getProtocoloFechamento($atendimento->agendamento_id),
|
|
'precisa_informar_conclusao_tratamento' => self::precisaInformarConclusaoTratamento($atendimento),
|
|
'is_rascunho' => isset($soapRascunho),
|
|
'has_avaliacao_elegibilidade' => Avaliacao::where('paciente_id', $atendimento->paciente->id)->first() ? true : false,
|
|
'permissao_assinatura' => self::getPermissaoAssinatura(),
|
|
'infraestrutura_id' => self::getCurrentLotacao()->infraestrutura_id,
|
|
'unidade_logada' => [
|
|
'id' => $unidadeLogada->id,
|
|
'nome_fantasia' => $unidadeLogada->nome_fantasia,
|
|
'cnes' => $unidadeLogada->cnes,
|
|
],
|
|
'oci' => self::getOciAdditionalsData($atendimento),
|
|
'em_atendimento' => true,
|
|
'has_cadastro_individual' => $hasCadastroIndividual,
|
|
];
|
|
}
|
|
|
|
private static function getOciAdditionalsData($atendimento)
|
|
{
|
|
$acompanhamentoOci = $atendimento->is_demanda_espontanea
|
|
? null
|
|
: AcompanhamentoOci::where('paciente_id', $atendimento->paciente->id)
|
|
->where('ocupacao_id', $atendimento->ocupacao->id)
|
|
->whereNull('finalizado_em')
|
|
->first();
|
|
|
|
$hasOciAtivada = !is_null($acompanhamentoOci);
|
|
$ultimaEtapaRealizadaMesmoAtendimento = false;
|
|
$problemasCondicoesLancadosEtapaEntrada = collect();
|
|
|
|
if ($hasOciAtivada) {
|
|
|
|
$ultimaEtapaConcluida = $acompanhamentoOci->etapasClinicasConcluidas()->orderByDesc('id')->first();
|
|
$ultimaEtapaRealizadaMesmoAtendimento = ($ultimaEtapaConcluida->soap->atendimento_id ?? null) === $atendimento->id;
|
|
$problemasCondicoesLancadosEtapaEntrada = self::getCidCiapLancadoNaEtapaEntradaOci($acompanhamentoOci);
|
|
}
|
|
|
|
return [
|
|
'has_oci_ativada' => $hasOciAtivada,
|
|
'acompanhamento_oci_id' => $acompanhamentoOci->id ?? null,
|
|
'ultima_etapa_realizada_mesmo_atendimento' => $ultimaEtapaRealizadaMesmoAtendimento,
|
|
'recusou_continuidade_oci' => false,
|
|
'problemas_condicoes_lancados_etapa_entrada' => $problemasCondicoesLancadosEtapaEntrada,
|
|
];
|
|
}
|
|
|
|
private static function getCidCiapLancadoNaEtapaEntradaOci($acompanhamentoOci)
|
|
{
|
|
$problemasCondicoesLancadosEtapaEntrada = collect();
|
|
|
|
$etapaEntrada = $acompanhamentoOci->etapasClinicasConcluidas()
|
|
->where('etapa_clinica_id', EtapaClinicaEnum::ENTRADA)
|
|
->first();
|
|
|
|
$cidsOci = self::getCidsOci($acompanhamentoOci->oci);
|
|
|
|
if ($etapaEntrada->soap) {
|
|
|
|
$etapaEntrada->soap->problemasCondicoes()
|
|
->whereIn('cid_id', $cidsOci)
|
|
->get()
|
|
->each(function ($problemaCondicao) use ($problemasCondicoesLancadosEtapaEntrada) {
|
|
|
|
$problemasCondicoesLancadosEtapaEntrada->push([
|
|
'automatico' => false,
|
|
'id' => null,
|
|
'ciap' => $problemaCondicao->ciap ? [
|
|
'id' => $problemaCondicao->ciap->id,
|
|
'codigo' => $problemaCondicao->ciap->codigo,
|
|
'descricao' => $problemaCondicao->ciap->descricao,
|
|
] : null,
|
|
'cid' => [
|
|
'id' => $problemaCondicao->cid->id,
|
|
'codigo' => $problemaCondicao->cid->codigo,
|
|
'nome' => $problemaCondicao->cid->nome,
|
|
],
|
|
'incluir_lista_paciente' => false,
|
|
'situacao_id' => null,
|
|
'situacao_nome' => null,
|
|
'inicio' => null,
|
|
'fim' => null,
|
|
'observacao' => null,
|
|
]);
|
|
});
|
|
}
|
|
else if ($etapaEntrada->regulacaoSolicitacao
|
|
&& !is_null($etapaEntrada->regulacaoSolicitacao->cid_id)
|
|
&& $cidsOci->contains($etapaEntrada->regulacaoSolicitacao->cid_id)
|
|
) {
|
|
|
|
$problemasCondicoesLancadosEtapaEntrada->push([
|
|
'automatico' => false,
|
|
'id' => null,
|
|
'ciap' => null,
|
|
'cid' => [
|
|
'id' => $etapaEntrada->regulacaoSolicitacao->cid->id,
|
|
'codigo' => $etapaEntrada->regulacaoSolicitacao->cid->codigo,
|
|
'nome' => $etapaEntrada->regulacaoSolicitacao->cid->nome,
|
|
],
|
|
'incluir_lista_paciente' => false,
|
|
'situacao_id' => null,
|
|
'situacao_nome' => null,
|
|
'inicio' => null,
|
|
'fim' => null,
|
|
'observacao' => null,
|
|
]);
|
|
}
|
|
|
|
return $problemasCondicoesLancadosEtapaEntrada;
|
|
}
|
|
|
|
public static function getPermissaoAssinatura()
|
|
{
|
|
$lotacaoLogada = self::getCurrentLotacao();
|
|
|
|
return DB::table('ambulatorio_parametrizacao_infraestrutura_assinatura_eletronica AS infraestrutura_assinatura_eletronica')
|
|
->join('ambulatorio_parametrizacao_infraestrutura AS parametrizacao_infraestrutura', 'parametrizacao_infraestrutura.id', 'infraestrutura_assinatura_eletronica.parametrizacao_infraestrutura_id')
|
|
->join('ambulatorio_parametrizacao_assinatura_eletronica as assinatura_eletronica', 'assinatura_eletronica.id', 'infraestrutura_assinatura_eletronica.parametrizacao_assinatura_eletronica_id')
|
|
->when($lotacaoLogada->infraestrutura_id, fn ($q, $id) => $q->where('parametrizacao_infraestrutura.infraestrutura_id', $id))
|
|
->select(
|
|
'assinatura_eletronica.id as id'
|
|
)
|
|
->get();
|
|
}
|
|
|
|
public static function getPermissaoEquipe($funcionalidadeIdentificador)
|
|
{
|
|
$lotacaoLogada = self::getCurrentLotacao();
|
|
|
|
return DB::table('atencao_basica_parametrizacao_equipe_usuario AS usuario')
|
|
->join('atencao_basica_parametrizacao_equipe AS equipe', 'equipe.id', 'usuario.equipe_id')
|
|
->join('cadastro_lotacao AS lotacao', 'lotacao.usuario_id', 'usuario.usuario_id')
|
|
->where('usuario.ativo', true)
|
|
->when($lotacaoLogada->usuario_id, fn ($q, $id) => $q->where('usuario.usuario_id', $id))
|
|
->when($lotacaoLogada->infraestrutura_id, fn ($q, $id) => $q->where('equipe.infraestrutura_id', $id))
|
|
->whereExists(function ($query) use ($lotacaoLogada, $funcionalidadeIdentificador) {
|
|
$query->select(DB::raw(1))
|
|
->from('atencao_basica_parametrizacao_outros_permissao_ocupacao')
|
|
->join('sigtap.ocupacao', 'sigtap.ocupacao.codigo', 'atencao_basica_parametrizacao_outros_permissao_ocupacao.ocupacao')
|
|
->where('atencao_basica_parametrizacao_outros_permissao_ocupacao.permissao_id', $funcionalidadeIdentificador)
|
|
->where('sigtap.ocupacao.id', $lotacaoLogada->ocupacao->id)
|
|
->whereColumn('lotacao.usuario_id', 'usuario.usuario_id');
|
|
})
|
|
->exists();
|
|
}
|
|
|
|
public static function criaFicha($funcionalidadeIdentificador)
|
|
{
|
|
$lotacaoLogada = self::getCurrentLotacao();
|
|
|
|
return ParametrizacaoInfraestruturaOcupacao::whereHas('parametrizacaoInfraestrutura', fn ($q) => $q
|
|
->where('infraestrutura_id', $lotacaoLogada->infraestrutura_id)
|
|
)
|
|
->where('ocupacao_id', $lotacaoLogada->ocupacao_id)
|
|
->whereHas('fichasAtb', fn ($q) => $q
|
|
->where('funcionalidade_id', Funcionalidade::whereHas('modulo', fn ($q) => $q
|
|
->where('identificador', 'atencao-basica')
|
|
)
|
|
->where('identificador', $funcionalidadeIdentificador)
|
|
->first('id')->id
|
|
)
|
|
)
|
|
->exists();
|
|
}
|
|
|
|
private static function getFormData($atendimento, $soapRascunho, $fila = null)
|
|
{
|
|
$unidade = $atendimento->infraestrutura->unidade;
|
|
$medicoesFormData = self::getMedicoesFormData($atendimento);
|
|
$exibeHistoricoErpsaude = app('config')->get('database.default') == 'santarita' ? true : false;
|
|
|
|
return [
|
|
'acompanhamentos_saude' => self::getAcompanhamentosSaude($atendimento),
|
|
'unidade' => [
|
|
'cnes' => $unidade->cnes,
|
|
],
|
|
'paciente' => self::getPacienteData($atendimento->paciente),
|
|
'usuario' => [
|
|
'nome' => $atendimento->usuario->nome ?? null,
|
|
'ocupacao_codigo' => $atendimento->ocupacao->codigo ?? null,
|
|
'especialidade_nome' => $atendimento->especialidade->nome ?? null,
|
|
],
|
|
'soap' => [
|
|
'acompanhamento_idoso' => self::getAcompanhamentoIdosoFormData($atendimento->paciente),
|
|
'medicoes' => $medicoesFormData,
|
|
'feridas' => self::getFeridaFormData(),
|
|
'problemas_condicoes_autorreferidas' => self::getProblemasCondicoesAutorreferidas($atendimento->paciente),
|
|
'raas' => self::getRaasFormData($atendimento),
|
|
'antecedentes' => self::getAntecedentesFormData($atendimento),
|
|
'subjetivo' => self::getSubjetivoFormData($atendimento),
|
|
'objetivo' => self::getObjetivoFormData($atendimento, $medicoesFormData),
|
|
'avaliacao' => self::getAvaliacaoFormData($atendimento),
|
|
'plano' => self::getPlanoFormData($atendimento, $soapRascunho),
|
|
'finalizacao' => self::getFinalizacaoFormData($atendimento, $fila),
|
|
'perfis_epidemiologicos' => CadastroPerfilEpidemiologico::orderBy('id')
|
|
->get(['id', 'descricao']),
|
|
],
|
|
'historico_soap' => [
|
|
'subjetivo' => self::getHistoricoSubjetivoFormData($atendimento),
|
|
'avaliacao' => self::getHistoricoAvaliacaoFormData($atendimento),
|
|
'plano' => self::getHistoricoPlanoFormData($atendimento),
|
|
'finalizacao' => self::getHistoricoFinalizacaoFormData($atendimento),
|
|
'risco_cardiovascular_framingham' => self::getHistoricoRiscoCardiovascularFraminghamFormData($atendimento),
|
|
],
|
|
'historico' => self::getHistorico($atendimento->paciente->id),
|
|
'historico_erpsaude' => $exibeHistoricoErpsaude ? self::getHistoricoErpsaude($atendimento->paciente) : null,
|
|
'exibe_historico_erpsaude' => $exibeHistoricoErpsaude,
|
|
'finalizado_em' => $atendimento->finalizado_em,
|
|
];
|
|
}
|
|
|
|
private static function getAcompanhamentosSaude($atendimento)
|
|
{
|
|
$acompanhamentos = collect();
|
|
|
|
$idade = $atendimento->paciente->cidadao->idade;
|
|
|
|
if ($idade) {
|
|
|
|
if ($idade['anos'] < 12) {
|
|
|
|
$acompanhamentos->push([
|
|
'sequencia' => 6,
|
|
'value' => 'crescimento-desenvolvimento-infantil',
|
|
'text' => 'CRESCIMENTO E DESENVOLVIMENTO INFANTIL'
|
|
]);
|
|
}
|
|
|
|
if ($idade['anos'] >= 10
|
|
&& $idade['anos'] <= 64
|
|
&& $atendimento->paciente->cidadao->sexo_id === Sexo::FEMININO
|
|
&& self::hasProblemaCondicaoGravidezAtivoOuLatente($atendimento->paciente)
|
|
) {
|
|
|
|
$acompanhamentos->push(['sequencia' => 2, 'value' => 'gestante', 'text' => 'GESTANTE']);
|
|
}
|
|
|
|
if ($idade['anos'] >= 20) {
|
|
|
|
if (self::hasProblemaCondicaoHipertensaoAtivoOuLatente($atendimento->paciente)) {
|
|
|
|
$acompanhamentos->push(['sequencia' => 3, 'value' => 'hipertenso', 'text' => 'HIPERTENSO']);
|
|
}
|
|
|
|
if (self::hasProblemaCondicaoDiabeteAtivoOuLatente($atendimento->paciente)) {
|
|
|
|
$acompanhamentos->push(['sequencia' => 4, 'value' => 'diabetico', 'text' => 'DIABÉTICO']);
|
|
}
|
|
}
|
|
|
|
if ($idade['anos'] >= 60) {
|
|
|
|
$acompanhamentos->push(['sequencia' => 1, 'value' => 'idoso', 'text' => 'IDOSO']);
|
|
}
|
|
|
|
if ($atendimento->paciente->cidadao->sexo_id === Sexo::FEMININO
|
|
&& (
|
|
($idade['anos'] >= 25 && $idade['anos'] <= 64)
|
|
|| ($idade['anos'] >= 50 && $idade['anos'] <= 69)
|
|
|| ($idade['anos'] >= 9 && $idade['anos'] <= 64)
|
|
)
|
|
) {
|
|
|
|
$acompanhamentos->push(['sequencia' => 5, 'value' => 'saude-mulher', 'text' => 'SAÚDE DA MULHER']);
|
|
}
|
|
}
|
|
|
|
return $acompanhamentos
|
|
->sortBy('sequencia')
|
|
->map(fn ($a) => ['value' => $a['value'], 'text' => $a['text']])
|
|
->values();
|
|
}
|
|
|
|
private static function hasProblemaCondicaoGravidezAtivoOuLatente($paciente)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_soap_problema_condicao as problema_condicao')
|
|
->join('geral_ciap as ciap', 'ciap.id', 'problema_condicao.ciap_id')
|
|
->join('ambulatorio_atendimento_soap as soap', 'soap.id', 'problema_condicao.soap_id')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
|
|
->leftJoin('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
|
|
->leftJoin('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
|
|
->whereIn('problema_condicao.situacao_id', [
|
|
ProblemaCondicaoSituacaoEnum::ATIVO,
|
|
ProblemaCondicaoSituacaoEnum::LATENTE,
|
|
])
|
|
->where('ciap.codigo', CiapEnum::GRAVIDEZ)
|
|
->where('soap.is_rascunho', false)
|
|
->where(fn ($q) => $q
|
|
->where('agendamento.paciente_id', $paciente->id)
|
|
->orWhere('demanda_espontanea.paciente_id', $paciente->id)
|
|
)
|
|
->whereNotExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('ambulatorio_atendimento_soap_problema_condicao as problema_condicao_posterior')
|
|
->join('ambulatorio_atendimento_soap as soap_posterior', 'soap_posterior.id', 'problema_condicao_posterior.soap_id')
|
|
->whereColumn('problema_condicao_posterior.problema_condicao_anterior_id', 'problema_condicao.id')
|
|
->where('soap_posterior.is_rascunho', false)
|
|
)
|
|
->exists();
|
|
}
|
|
|
|
private static function hasProblemaCondicaoHipertensaoAtivoOuLatente($paciente)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_soap_problema_condicao as problema_condicao')
|
|
->join('sigtap.cid as cid', 'cid.id', 'problema_condicao.cid_id')
|
|
->join('ambulatorio_atendimento_soap as soap', 'soap.id', 'problema_condicao.soap_id')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
|
|
->leftJoin('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
|
|
->leftJoin('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
|
|
->whereIn('problema_condicao.situacao_id', [
|
|
ProblemaCondicaoSituacaoEnum::ATIVO,
|
|
ProblemaCondicaoSituacaoEnum::LATENTE,
|
|
])
|
|
->whereIn('cid.codigo', [
|
|
CidEnum::HIPERTENSAO_ESSENCIAL_PRIMARIA,
|
|
CidEnum::DOENCA_CARDIACA_HIPERTENSIVA,
|
|
CidEnum::DOENCA_RENAL_HIPERTENSIVA,
|
|
CidEnum::DOENCA_CARDIACA_E_RENAL_HIPERTENSIVA,
|
|
CidEnum::HIPERTENSAO_SECUNDARIA,
|
|
])
|
|
->where('soap.is_rascunho', false)
|
|
->where(fn ($q) => $q
|
|
->where('agendamento.paciente_id', $paciente->id)
|
|
->orWhere('demanda_espontanea.paciente_id', $paciente->id)
|
|
)
|
|
->whereNotExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('ambulatorio_atendimento_soap_problema_condicao as problema_condicao_posterior')
|
|
->join('ambulatorio_atendimento_soap as soap_posterior', 'soap_posterior.id', 'problema_condicao_posterior.soap_id')
|
|
->whereColumn('problema_condicao_posterior.problema_condicao_anterior_id', 'problema_condicao.id')
|
|
->where('soap_posterior.is_rascunho', false)
|
|
)
|
|
->exists();
|
|
}
|
|
|
|
private static function hasProblemaCondicaoDiabeteAtivoOuLatente($paciente)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_soap_problema_condicao as problema_condicao')
|
|
->join('sigtap.cid as cid', 'cid.id', 'problema_condicao.cid_id')
|
|
->join('ambulatorio_atendimento_soap as soap', 'soap.id', 'problema_condicao.soap_id')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
|
|
->leftJoin('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
|
|
->leftJoin('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
|
|
->whereIn('problema_condicao.situacao_id', [
|
|
ProblemaCondicaoSituacaoEnum::ATIVO,
|
|
ProblemaCondicaoSituacaoEnum::LATENTE,
|
|
])
|
|
->whereIn('cid.codigo', [
|
|
CidEnum::DIABETES_MELLITUS_INSULINO_DEPENDENTE,
|
|
CidEnum::DIABETES_MELLITUS_NAO_INSULINO_DEPENDENTE,
|
|
CidEnum::DIABETES_MELLITUS_RELACIONADO_COM_A_DESNUTRICAO,
|
|
CidEnum::OUTROS_TIPOS_ESPECIFICADOS_DE_DIABETES_MELLITUS,
|
|
CidEnum::DIABETES_MELLITUS_NAO_ESPECIFICADO,
|
|
])
|
|
->where('soap.is_rascunho', false)
|
|
->where(fn ($q) => $q
|
|
->where('agendamento.paciente_id', $paciente->id)
|
|
->orWhere('demanda_espontanea.paciente_id', $paciente->id)
|
|
)
|
|
->whereNotExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('ambulatorio_atendimento_soap_problema_condicao as problema_condicao_posterior')
|
|
->join('ambulatorio_atendimento_soap as soap_posterior', 'soap_posterior.id', 'problema_condicao_posterior.soap_id')
|
|
->whereColumn('problema_condicao_posterior.problema_condicao_anterior_id', 'problema_condicao.id')
|
|
->where('soap_posterior.is_rascunho', false)
|
|
)
|
|
->exists();
|
|
}
|
|
|
|
private static function getPacienteData($paciente)
|
|
{
|
|
$municipioResidencia = $paciente->cidadao->domicilio->endereco->logradouro->municipio ?? null;
|
|
|
|
return [
|
|
'id' => $paciente->id,
|
|
'nome' => $paciente->cidadao->nome,
|
|
'nome_social' => $paciente->cidadao->nome_social,
|
|
'preferencia_nome_id' => $paciente->cidadao->preferencia_nome_id,
|
|
'sexo_id' => $paciente->cidadao->sexo_id,
|
|
'sexo_descricao' => $paciente->cidadao->sexo->descricao,
|
|
'sexo_identificador' => $paciente->cidadao->sexo->identificador,
|
|
'data_nascimento' => is_null($paciente->cidadao->data_nascimento)
|
|
? null
|
|
: (new Carbon($paciente->cidadao->data_nascimento))->format('d/m/Y'),
|
|
'idade_em_dias' => is_null($paciente->cidadao->data_nascimento)
|
|
? null
|
|
: Carbon::now()->diffInDays($paciente->cidadao->data_nascimento),
|
|
'idade_em_meses' => is_null($paciente->cidadao->data_nascimento)
|
|
? null
|
|
: ceil(Carbon::now()->diffInDays($paciente->cidadao->data_nascimento) / 31),
|
|
'idade_anos' => is_null($paciente->cidadao->data_nascimento)
|
|
? null
|
|
: $paciente->cidadao->idade['anos'],
|
|
'idade_formatada' => $paciente->cidadao->idade_formatada,
|
|
'idade_meses' => is_null($paciente->cidadao->data_nascimento)
|
|
? null
|
|
: $paciente->cidadao->idade['meses'],
|
|
'is_idoso' => is_null($paciente->cidadao->data_nascimento)
|
|
? false
|
|
: $paciente->cidadao->idade['anos'] >= self::IDADE_ANOS_INICIAL_IDOSO,
|
|
'is_crianca' => is_null($paciente->cidadao->data_nascimento)
|
|
? false
|
|
: $paciente->cidadao->idade['anos'] <= self::IDADE_ANOS_FINAL_CRIANCA,
|
|
'is_crianca_aleitamento' => is_null($paciente->cidadao->data_nascimento)
|
|
? false
|
|
: $paciente->cidadao->idade['anos'] <= self::IDADE_ANOS_FINAL_CRIANCA_ALEITAMENTO,
|
|
'is_adolescente' => is_null($paciente->cidadao->data_nascimento)
|
|
? false
|
|
: $paciente->cidadao->idade['anos'] > self::IDADE_ANOS_FINAL_CRIANCA
|
|
&& $paciente->cidadao->idade['anos'] <= self::IDADE_ANOS_FINAL_ADOLESCENTE,
|
|
'nome_mae' => $paciente->cidadao->nome_mae,
|
|
'prontuario' => $paciente->prontuario,
|
|
'cpf' => MaskUtil::getCpfMasked($paciente->cidadao->cpf),
|
|
'cns' => MaskUtil::getCnsMasked($paciente->cidadao->cns),
|
|
'municipio_uf' => is_null($municipioResidencia)
|
|
? null
|
|
: "{$municipioResidencia->nome} / {$municipioResidencia->estado->uf}",
|
|
'telefone_id' => $paciente->cidadao->telefone_principal->id ?? null,
|
|
'telefone_numero' => MaskUtil::getPhoneMasked($paciente->cidadao->telefone_principal->numero ?? null),
|
|
'telefone_autoriza_sms' => $paciente->cidadao->telefone_principal->autoriza_sms ?? false,
|
|
'telefone_atualizado' => false,
|
|
'unidade_referencia' => $paciente->unidade->nome_fantasia ?? null,
|
|
'cep' => $paciente->cidadao->domicilio->endereco->logradouro->cep ?? null,
|
|
'ibge' => $paciente->cidadao->domicilio->endereco->logradouro->municipio->ibge ?? null,
|
|
'raca_cor_descricao' => $paciente->cidadao->racaCor->descricao,
|
|
'raca_cor_id' => $paciente->cidadao->raca_cor_id,
|
|
'etnia_indigena' => Str::substr($paciente->cidadao->etniaIndigena->descricao ?? '', 0, 20),
|
|
'email' => $paciente->email ?? null,
|
|
'nacionalidade_id' => $paciente->cidadao->nacionalidade_id ?? null,
|
|
'has_campos_obrigatorios_mama' => !is_null($paciente->cidadao->nome)
|
|
&& !is_null($paciente->cidadao->data_nascimento)
|
|
&& (!is_null($paciente->cidadao->cpf) || !is_null($paciente->cidadao->cns))
|
|
];
|
|
}
|
|
|
|
private static function getAcompanhamentoIdosoFormData($paciente)
|
|
{
|
|
return [
|
|
'data_ultima_avaliacao_multidimensional' => self::getDataUltimaAvaliacaoMultidimensional($paciente),
|
|
];
|
|
}
|
|
|
|
private static function getDataUltimaAvaliacaoMultidimensional($paciente)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_procedimento as atendimento_procedimento')
|
|
->join('sigtap.procedimento as procedimento', 'procedimento.id', 'atendimento_procedimento.procedimento_id')
|
|
->join('ambulatorio_atendimento_soap as soap', 'soap.id', 'atendimento_procedimento.soap_id')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
|
|
->where('soap.is_rascunho', false)
|
|
->where('atendimento.paciente_id', $paciente->id)
|
|
->where('procedimento.codigo', ProcedimentoEnum::AVALIACAO_MULTIDIMENSIONAL_DA_PESSOA_IDOSA)
|
|
->select(
|
|
DB::raw("DATE_FORMAT(atendimento_procedimento.created_at, '%d/%m/%Y') as data")
|
|
)
|
|
->orderByDesc('atendimento_procedimento.created_at')
|
|
->first()->data ?? null;
|
|
}
|
|
|
|
public static function getMedicoesFormData($atendimento)
|
|
{
|
|
return [
|
|
'gestacao' => [
|
|
'grafico' => self::getGraficoGestacaoData(),
|
|
],
|
|
'antropometria' => [
|
|
'faixas_etarias' => self::getFaixasEtarias($atendimento->paciente),
|
|
'grafico' => self::getGraficoAntropometriaData($atendimento),
|
|
],
|
|
'medicoes_gestacao' => self::getMedicoesGestacao($atendimento->paciente),
|
|
'periodos_gestacao' => self::getPeriodosGestacao($atendimento->paciente),
|
|
'antropometrias' => self::getMedicoesAntropometriasFormData($atendimento->paciente),
|
|
'sinais_vitais' => self::getMedicoesSinaisVitaisFormData($atendimento->paciente),
|
|
'glicemias_capilares' => self::getMedicoesGlicemiasCapilaresFormData($atendimento->paciente),
|
|
];
|
|
}
|
|
|
|
private static function getGraficoGestacaoData()
|
|
{
|
|
$semanaInicial = 13;
|
|
$semanaFinal = 41;
|
|
$maxYScale = 39;
|
|
|
|
$datasets = collect([
|
|
(object) ['measure' => 'p10', 'axis' => collect()],
|
|
(object) ['measure' => 'p90', 'axis' => collect()],
|
|
(object) ['measure' => 'max', 'axis' => collect()],
|
|
]);
|
|
|
|
$getPercentil = function ($percentil, $semana) {
|
|
|
|
return $percentil === 10
|
|
? -0.0068839207 * ($semana * $semana) + 1.23239022 * $semana - 6.9606459
|
|
: -0.0139899373 * ($semana * $semana) + 1.55868069 * $semana - 4.6141899;
|
|
};
|
|
|
|
for ($semana = $semanaInicial; $semana <= $semanaFinal; $semana++) {
|
|
|
|
$datasets->where('measure', 'p10')->first()->axis
|
|
->push(['x' => $semana, 'y' => $getPercentil(10, $semana)]);
|
|
|
|
$datasets->where('measure', 'p90')->first()->axis
|
|
->push(['x' => $semana, 'y' => $getPercentil(90, $semana)]);
|
|
|
|
$datasets->where('measure', 'max')->first()->axis
|
|
->push(['x' => $semana, 'y' => $maxYScale]);
|
|
}
|
|
|
|
return [
|
|
'scales' => [
|
|
'x' => [
|
|
'title' => 'Idade gestacional (semanas)',
|
|
'min' => $semanaInicial,
|
|
'max' => $semanaFinal,
|
|
'step_size' => 2,
|
|
],
|
|
'y' => [
|
|
'title' => 'Altura uterina (cm)',
|
|
'min' => 7,
|
|
'max' => $maxYScale,
|
|
'step_size' => 2,
|
|
],
|
|
],
|
|
'measures' => $datasets,
|
|
];
|
|
}
|
|
|
|
private static function getFaixasEtarias($paciente)
|
|
{
|
|
$faixasEtarias = collect();
|
|
|
|
if (!is_null($paciente->cidadao->idade)) {
|
|
|
|
$idadePaciente = $paciente->cidadao->idade['anos'];
|
|
|
|
$getFaixaEtaria = fn ($min, $max) => [
|
|
'value' => "{$min}-{$max}",
|
|
'text' => "{$min} a {$max} anos",
|
|
'min' => $min,
|
|
'max' => $max,
|
|
];
|
|
|
|
$faixasEtarias->push($getFaixaEtaria(0, 2));
|
|
|
|
if ($idadePaciente > 2) {
|
|
|
|
$faixasEtarias->push($getFaixaEtaria(2, 5));
|
|
}
|
|
|
|
if ($idadePaciente > 5) {
|
|
|
|
$faixasEtarias->push($getFaixaEtaria(5, 10));
|
|
}
|
|
|
|
if ($idadePaciente > 10) {
|
|
|
|
$faixasEtarias->push($getFaixaEtaria(10, 15));
|
|
}
|
|
|
|
if ($idadePaciente > 15) {
|
|
|
|
$faixasEtarias->push($getFaixaEtaria(15, 19));
|
|
}
|
|
|
|
if ($idadePaciente > 19) {
|
|
|
|
$faixasEtarias->push($getFaixaEtaria(19, 30));
|
|
}
|
|
|
|
if ($idadePaciente > 30) {
|
|
|
|
for ($idadeInicial = 30; $idadeInicial <= $idadePaciente; $idadeInicial += 10) {
|
|
|
|
$idadeFinal = $idadeInicial + 10;
|
|
|
|
$faixasEtarias->push($getFaixaEtaria($idadeInicial, $idadeFinal));
|
|
}
|
|
}
|
|
}
|
|
|
|
return $faixasEtarias;
|
|
}
|
|
|
|
private static function getGraficoAntropometriaData($atendimento)
|
|
{
|
|
$sexoId = $atendimento->paciente->cidadao->sexo_id;
|
|
|
|
$getMonths = fn ($years) => $years * 12;
|
|
|
|
$getData = fn ($tipoId, $xMin, $xMax, $xStepSize, $yTitle, $yMin, $yMax, $yStepSize, $getZScores = true) => [
|
|
'scales' => [
|
|
'x' => [
|
|
'title' => 'Idade (meses completos e anos)',
|
|
'min' => $getMonths($xMin),
|
|
'max' => $getMonths($xMax),
|
|
'step_size' => $xStepSize,
|
|
],
|
|
'y' => [
|
|
'title' => $yTitle,
|
|
'min' => $yMin,
|
|
'max' => $yMax,
|
|
'step_size' => $yStepSize,
|
|
],
|
|
],
|
|
'z_scores' => $getZScores
|
|
? self::getZScores($tipoId, $sexoId, $getMonths($xMin), $getMonths($xMax), $yMax)
|
|
: [],
|
|
];
|
|
|
|
$pesoTitle = 'Peso (kg)';
|
|
$alturaTitle = 'Altura (cm)';
|
|
$imcTitle = 'IMC (kg/m²)';
|
|
$perimetroCefalicoTitle = 'Perímetro cefálico (cm)';
|
|
|
|
$peso = collect();
|
|
$altura = collect();
|
|
$imc = collect();
|
|
$perimetroCefalico = collect();
|
|
|
|
if (!is_null($atendimento->paciente->cidadao->idade)) {
|
|
|
|
$idadePaciente = $atendimento->paciente->cidadao->idade['anos'];
|
|
|
|
$peso->push([
|
|
'faixa_etaria' => '0-2',
|
|
'data' => $getData(LmsParametroTipo::PESO, 0, 2, 2, $pesoTitle, 0, 20, 1),
|
|
]);
|
|
|
|
$altura->push([
|
|
'faixa_etaria' => '0-2',
|
|
'data' => $getData(LmsParametroTipo::ALTURA, 0, 2, 2, $alturaTitle, 40, 105, 5),
|
|
]);
|
|
|
|
$imc->push([
|
|
'faixa_etaria' => '0-2',
|
|
'data' => $getData(LmsParametroTipo::IMC, 0, 2, 2, $imcTitle, 5, 25, 1),
|
|
]);
|
|
|
|
$perimetroCefalico->push([
|
|
'faixa_etaria' => '0-2',
|
|
'data' => $getData(LmsParametroTipo::PERIMETRO_CEFALICO, 0, 2, 2, $perimetroCefalicoTitle, 30, 53, 1),
|
|
]);
|
|
|
|
if ($idadePaciente > 2) {
|
|
|
|
$peso->push([
|
|
'faixa_etaria' => '2-5',
|
|
'data' => $getData(LmsParametroTipo::PESO, 2, 5, 2, $pesoTitle, 7, 32, 1),
|
|
]);
|
|
|
|
$altura->push([
|
|
'faixa_etaria' => '2-5',
|
|
'data' => $getData(LmsParametroTipo::ALTURA, 2, 5, 2, $alturaTitle, 75, 130, 5),
|
|
]);
|
|
|
|
$imc->push([
|
|
'faixa_etaria' => '2-5',
|
|
'data' => $getData(LmsParametroTipo::IMC, 2, 5, 2, $imcTitle, 10, 25, 1),
|
|
]);
|
|
|
|
$perimetroCefalico->push([
|
|
'faixa_etaria' => '2-5',
|
|
'data' => $getData(LmsParametroTipo::PERIMETRO_CEFALICO, 2, 5, 2, $perimetroCefalicoTitle, 30, 53, 1),
|
|
]);
|
|
}
|
|
|
|
if ($idadePaciente > 5) {
|
|
|
|
$peso->push([
|
|
'faixa_etaria' => '5-10',
|
|
'data' => $getData(LmsParametroTipo::PESO, 5, 10, 4, $pesoTitle, 10, 65, 5),
|
|
]);
|
|
|
|
$altura->push([
|
|
'faixa_etaria' => '5-10',
|
|
'data' => $getData(LmsParametroTipo::ALTURA, 5, 10, 4, $alturaTitle, 90, 165, 5),
|
|
]);
|
|
|
|
$imc->push([
|
|
'faixa_etaria' => '5-10',
|
|
'data' => $getData(LmsParametroTipo::IMC, 5, 10, 4, $imcTitle, 10, 30, 1),
|
|
]);
|
|
|
|
$perimetroCefalico->push([
|
|
'faixa_etaria' => '5-10',
|
|
'data' => $getData(LmsParametroTipo::PERIMETRO_CEFALICO, 5, 10, 4, $perimetroCefalicoTitle, 30, 53, 1, false),
|
|
]);
|
|
}
|
|
|
|
if ($idadePaciente > 10) {
|
|
|
|
$peso->push([
|
|
'faixa_etaria' => '10-15',
|
|
'data' => $getData(LmsParametroTipo::PESO, 10, 15, 4, $pesoTitle, 25, 150, 5, false),
|
|
]);
|
|
|
|
$altura->push([
|
|
'faixa_etaria' => '10-15',
|
|
'data' => $getData(LmsParametroTipo::ALTURA, 10, 15, 4, $alturaTitle, 100, 205, 5),
|
|
]);
|
|
|
|
$imc->push([
|
|
'faixa_etaria' => '10-15',
|
|
'data' => $getData(LmsParametroTipo::IMC, 10, 15, 4, $imcTitle, 10, 40, 2),
|
|
]);
|
|
|
|
$perimetroCefalico->push([
|
|
'faixa_etaria' => '10-15',
|
|
'data' => $getData(LmsParametroTipo::PERIMETRO_CEFALICO, 10, 15, 4, $perimetroCefalicoTitle, 30, 53, 1, false),
|
|
]);
|
|
}
|
|
|
|
if ($idadePaciente > 15) {
|
|
|
|
$peso->push([
|
|
'faixa_etaria' => '15-19',
|
|
'data' => $getData(LmsParametroTipo::PESO, 15, 19, 4, $pesoTitle, 25, 150, 5, false),
|
|
]);
|
|
|
|
$altura->push([
|
|
'faixa_etaria' => '15-19',
|
|
'data' => $getData(LmsParametroTipo::ALTURA, 15, 19, 4, $alturaTitle, 110, 210, 10),
|
|
]);
|
|
|
|
$imc->push([
|
|
'faixa_etaria' => '15-19',
|
|
'data' => $getData(LmsParametroTipo::IMC, 15, 19, 4, $imcTitle, 10, 40, 2),
|
|
]);
|
|
|
|
$perimetroCefalico->push([
|
|
'faixa_etaria' => '15-19',
|
|
'data' => $getData(LmsParametroTipo::PERIMETRO_CEFALICO, 15, 19, 4, $perimetroCefalicoTitle, 30, 53, 1, false),
|
|
]);
|
|
}
|
|
|
|
if ($idadePaciente > 19) {
|
|
|
|
$peso->push([
|
|
'faixa_etaria' => '19-30',
|
|
'data' => $getData(LmsParametroTipo::PESO, 19, 30, 6, $pesoTitle, 25, 150, 5, false),
|
|
]);
|
|
|
|
$altura->push([
|
|
'faixa_etaria' => '19-30',
|
|
'data' => $getData(LmsParametroTipo::ALTURA, 19, 30, 6, $alturaTitle, 110, 200, 5, false),
|
|
]);
|
|
|
|
$imc->push([
|
|
'faixa_etaria' => '19-30',
|
|
'data' => $getData(LmsParametroTipo::IMC, 19, 30, 6, $imcTitle, 10, 40, 2, false),
|
|
]);
|
|
|
|
$perimetroCefalico->push([
|
|
'faixa_etaria' => '19-30',
|
|
'data' => $getData(LmsParametroTipo::PERIMETRO_CEFALICO, 19, 30, 6, $perimetroCefalicoTitle, 30, 53, 1, false),
|
|
]);
|
|
}
|
|
|
|
if ($idadePaciente > 30) {
|
|
|
|
for ($idadeInicial = 30; $idadeInicial <= $idadePaciente; $idadeInicial += 10) {
|
|
|
|
$idadeFinal = $idadeInicial + 10;
|
|
$faixaEtaria = "{$idadeInicial}-{$idadeFinal}";
|
|
|
|
$peso->push([
|
|
'faixa_etaria' => $faixaEtaria,
|
|
'data' => $getData(LmsParametroTipo::PESO, $idadeInicial, $idadeFinal, 6, $pesoTitle, 25, 150, 5, false),
|
|
]);
|
|
|
|
$altura->push([
|
|
'faixa_etaria' => $faixaEtaria,
|
|
'data' => $getData(LmsParametroTipo::ALTURA, $idadeInicial, $idadeFinal, 6, $alturaTitle, 110, 200, 5, false),
|
|
]);
|
|
|
|
$imc->push([
|
|
'faixa_etaria' => $faixaEtaria,
|
|
'data' => $getData(LmsParametroTipo::IMC, $idadeInicial, $idadeFinal, 6, $imcTitle, 10, 40, 2, false),
|
|
]);
|
|
|
|
$perimetroCefalico->push([
|
|
'faixa_etaria' => $faixaEtaria,
|
|
'data' => $getData(LmsParametroTipo::PERIMETRO_CEFALICO, $idadeInicial, $idadeFinal, 6, $perimetroCefalicoTitle, 30, 53, 1, false),
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
|
|
return [
|
|
'peso' => $peso,
|
|
'altura' => $altura,
|
|
'imc' => $imc,
|
|
'perimetro_cefalico' => $perimetroCefalico,
|
|
];
|
|
}
|
|
|
|
private static function getZScores($parametroTipoId, $sexoId, $idadeMesesMin, $idadeMesesMax, $maxYScale = null)
|
|
{
|
|
$parametros = LmsParametro::where('tipo_id', $parametroTipoId)
|
|
->where('sexo_id', $sexoId)
|
|
->whereIn('mes', [
|
|
$idadeMesesMin,
|
|
$idadeMesesMax,
|
|
])
|
|
->get();
|
|
|
|
if ($parametros->isNotEmpty()) {
|
|
|
|
$datasets = collect([
|
|
(object) ['z-score' => -3, 'axis' => collect()],
|
|
(object) ['z-score' => -2, 'axis' => collect()],
|
|
(object) ['z-score' => -1, 'axis' => collect()],
|
|
(object) ['z-score' => 0, 'axis' => collect()],
|
|
(object) ['z-score' => 1, 'axis' => collect()],
|
|
(object) ['z-score' => 2, 'axis' => collect()],
|
|
(object) ['z-score' => 3, 'axis' => collect()],
|
|
]);
|
|
|
|
$parametros->each(function ($parametro) use ($datasets, $maxYScale) {
|
|
|
|
$datasets->where('z-score', -3)->first()->axis
|
|
->push(['x' => $parametro->mes, 'y' => $parametro->sd_3_negativo]);
|
|
|
|
$datasets->where('z-score', -2)->first()->axis
|
|
->push(['x' => $parametro->mes, 'y' => $parametro->sd_2_negativo]);
|
|
|
|
$datasets->where('z-score', -1)->first()->axis
|
|
->push(['x' => $parametro->mes, 'y' => $parametro->sd_1_negativo]);
|
|
|
|
$datasets->where('z-score', 0)->first()->axis
|
|
->push(['x' => $parametro->mes, 'y' => $parametro->sd_0]);
|
|
|
|
$datasets->where('z-score', 1)->first()->axis
|
|
->push(['x' => $parametro->mes, 'y' => $parametro->sd_1]);
|
|
|
|
$datasets->where('z-score', 2)->first()->axis
|
|
->push(['x' => $parametro->mes, 'y' => $parametro->sd_2]);
|
|
|
|
$datasets->where('z-score', 3)->first()->axis
|
|
->push(['x' => $parametro->mes, 'y' => $maxYScale ?? $parametro->sd_3]);
|
|
|
|
});
|
|
|
|
return $datasets;
|
|
}
|
|
|
|
return [];
|
|
}
|
|
|
|
private static function getMedicoesGestacao($paciente)
|
|
{
|
|
$ultimaDataPreNatal = null;
|
|
|
|
return DB::table('ambulatorio_atendimento_soap as soap')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
|
|
->where('soap.is_rascunho', false)
|
|
->where('atendimento.paciente_id', $paciente->id)
|
|
->whereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('ambulatorio_atendimento_soap_problema_condicao as problema_condicao')
|
|
->join('cadastro_paciente_gestacao as gestacao', 'gestacao.id', 'problema_condicao.paciente_gestacao_id')
|
|
->whereColumn('problema_condicao.soap_id', 'soap.id')
|
|
->where('problema_condicao.situacao_id', '<>', ProblemaCondicaoSituacaoEnum::RESOLVIDO)
|
|
->whereNull('gestacao.fim')
|
|
->where(fn ($q) => $q
|
|
->whereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('geral_ciap as ciap')
|
|
->whereColumn('ciap.id', 'problema_condicao.ciap_id')
|
|
->where('ciap.codigo', self::CIAPS_GRAVIDEZ_NORMAL)
|
|
)
|
|
->orWhereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('sigtap.cid as cid')
|
|
->whereColumn('cid.id', 'problema_condicao.cid_id')
|
|
->whereIn('cid.codigo', self::CIDS_GRAVIDEZ_NORMAL)
|
|
)
|
|
)
|
|
)
|
|
->orderBy('soap.created_at')
|
|
->select('soap.id')
|
|
->get()
|
|
->map(function ($soap, $i) use (&$ultimaDataPreNatal) {
|
|
|
|
$ordem = $i + 1;
|
|
$soap = AtendimentoSoap::find($soap->id);
|
|
|
|
$medidoEm = $soap->created_at->startOfDay();
|
|
$idadeGestacional = ['semanas' => 0, 'dias' => 0];
|
|
|
|
if (is_null($ultimaDataPreNatal)) {
|
|
|
|
$ultimaDataPreNatal = $medidoEm;
|
|
}
|
|
else {
|
|
|
|
$interval = $medidoEm->diff($ultimaDataPreNatal);
|
|
|
|
$idadeGestacional['semanas'] = floor($interval->days / 7);
|
|
$idadeGestacional['dias'] = $interval->days % 7;
|
|
}
|
|
|
|
return array_merge(self::getLogData($soap), [
|
|
'ordem_atendimento' => "{$ordem}º",
|
|
'idade_gestacional' => [
|
|
'semanas' => $idadeGestacional['semanas'],
|
|
'dias' => $idadeGestacional['dias'],
|
|
],
|
|
'edema_nome' => $soap->preNatalEdema->nome ?? null,
|
|
'altura_uterina' => $soap->pre_natal_altura_uterina,
|
|
'batimento_cardiaco_fetal' => $soap->pre_natal_batimento_cardiaco_fetal,
|
|
'movimentacao_fetal' => $soap->pre_natal_movimentacao_fetal,
|
|
]);
|
|
});
|
|
}
|
|
|
|
private static function getPeriodosGestacao($paciente)
|
|
{
|
|
return $paciente->gestacoes()->orderBy('inicio')->get()->map(function ($gestacao) use ($paciente) {
|
|
|
|
$inicio = $gestacao->inicio;
|
|
$inicioIdadeMeses = null;
|
|
$fim = $gestacao->fim ?? Carbon::today();
|
|
$fimIdadeMeses = null;
|
|
|
|
if (!is_null($paciente->cidadao->data_nascimento)) {
|
|
|
|
$idadeInicio = AgeService::getAge($paciente->cidadao->data_nascimento, $inicio);
|
|
$idadeFim = AgeService::getAge($paciente->cidadao->data_nascimento, $fim);
|
|
|
|
$inicioIdadeMeses = $idadeInicio->years * 12 + $idadeInicio->months;
|
|
$fimIdadeMeses = $idadeFim->years * 12 + $idadeFim->months;
|
|
}
|
|
|
|
return [
|
|
'inicio' => $inicio->format('d/m/Y'),
|
|
'inicio_idade_meses' => $inicioIdadeMeses,
|
|
'fim' => $fim->format('d/m/Y'),
|
|
'fim_idade_meses' => $fimIdadeMeses,
|
|
];
|
|
});
|
|
}
|
|
|
|
private static function getMedicoesAntropometriasFormData($paciente)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_antropometria')
|
|
->select([
|
|
'ambulatorio_atendimento_antropometria.id',
|
|
'ambulatorio_atendimento_antropometria.created_at',
|
|
'ambulatorio_atendimento_antropometria.medido_em',
|
|
'ambulatorio_atendimento_antropometria.peso',
|
|
'ambulatorio_atendimento_antropometria.altura',
|
|
'ambulatorio_atendimento_antropometria.perimetro_cefalico',
|
|
'ambulatorio_atendimento_antropometria.circunferencia_abdominal',
|
|
'ambulatorio_atendimento_antropometria.perimetro_panturrilha',
|
|
'ocupacao.id AS ocupacao_id',
|
|
'ocupacao.codigo AS ocupacao_codigo',
|
|
'ocupacao.nome AS ocupacao_nome',
|
|
'cadastro_cidadao.nome AS cidadao_nome',
|
|
'cadastro_setor.nome AS setor_nome',
|
|
])
|
|
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_antropometria.atendimento_id')
|
|
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
|
|
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_atendimento_antropometria.created_lotacao_id')
|
|
->join('cadastro_usuario', 'cadastro_usuario.id', 'cadastro_lotacao.usuario_id')
|
|
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
|
|
->join('sigtap.ocupacao', 'ocupacao.id', 'cadastro_lotacao.ocupacao_id')
|
|
->join('cadastro_centro_custo', 'cadastro_centro_custo.id', 'ambulatorio_atendimento_antropometria.created_centro_custo_id')
|
|
->join('cadastro_setor', 'cadastro_setor.id', 'cadastro_centro_custo.setor_id')
|
|
->where('ambulatorio_agendamento.paciente_id', $paciente->id)
|
|
->where(function ($query) {
|
|
$query
|
|
->whereExists(function ($query) {
|
|
$query->select(DB::raw(1))
|
|
->from('ambulatorio_atendimento_soap')
|
|
->whereColumn('ambulatorio_atendimento_soap.atendimento_id', 'ambulatorio_atendimento.id')
|
|
->where('ambulatorio_atendimento_soap.is_rascunho', false);
|
|
})
|
|
->orWhereNotExists(function ($query) {
|
|
$query->select(DB::raw(1))
|
|
->from('ambulatorio_atendimento_soap')
|
|
->whereColumn('ambulatorio_atendimento_soap.atendimento_id', 'ambulatorio_atendimento.id');
|
|
});
|
|
})
|
|
->unionAll(
|
|
DB::table('ambulatorio_atendimento_antropometria')
|
|
->select([
|
|
'ambulatorio_atendimento_antropometria.id',
|
|
'ambulatorio_atendimento_antropometria.created_at',
|
|
'ambulatorio_atendimento_antropometria.medido_em',
|
|
'ambulatorio_atendimento_antropometria.peso',
|
|
'ambulatorio_atendimento_antropometria.altura',
|
|
'ambulatorio_atendimento_antropometria.perimetro_cefalico',
|
|
'ambulatorio_atendimento_antropometria.circunferencia_abdominal',
|
|
'ambulatorio_atendimento_antropometria.perimetro_panturrilha',
|
|
'ocupacao.id AS ocupacao_id',
|
|
'ocupacao.codigo AS ocupacao_codigo',
|
|
'ocupacao.nome AS ocupacao_nome',
|
|
'cadastro_cidadao.nome AS cidadao_nome',
|
|
'cadastro_setor.nome AS setor_nome',
|
|
])
|
|
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_antropometria.atendimento_id')
|
|
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
|
|
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_atendimento_antropometria.created_lotacao_id')
|
|
->join('cadastro_usuario', 'cadastro_usuario.id', 'cadastro_lotacao.usuario_id')
|
|
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
|
|
->join('sigtap.ocupacao', 'ocupacao.id', 'cadastro_lotacao.ocupacao_id')
|
|
->join('cadastro_centro_custo', 'cadastro_centro_custo.id', 'ambulatorio_atendimento_antropometria.created_centro_custo_id')
|
|
->join('cadastro_setor', 'cadastro_setor.id', 'cadastro_centro_custo.setor_id')
|
|
->where('ambulatorio_demanda_espontanea.paciente_id', $paciente->id)
|
|
)
|
|
->get()
|
|
->map(function ($antropometria) {
|
|
$antropometria->created_at = Carbon::create($antropometria->created_at);
|
|
$antropometria->medido_em = Carbon::create($antropometria->medido_em);
|
|
|
|
$antropometria->createdLotacao = (object) [
|
|
'ocupacao' => (object) [
|
|
'id' => $antropometria->ocupacao_id,
|
|
'codigo' => $antropometria->ocupacao_codigo,
|
|
'nome' => $antropometria->ocupacao_nome,
|
|
],
|
|
'profissional' => (object) [
|
|
'nome' => $antropometria->cidadao_nome,
|
|
],
|
|
];
|
|
|
|
$antropometria->createdCentroCusto = (object) [
|
|
'setor' => (object) [
|
|
'nome' => $antropometria->setor_nome
|
|
],
|
|
];
|
|
|
|
return array_merge(self::getLogData($antropometria), [
|
|
'id' => $antropometria->id,
|
|
'medido_em' => $antropometria->medido_em->format('d/m/Y'),
|
|
'peso' => $antropometria->peso,
|
|
'altura' => (int) $antropometria->altura,
|
|
'imc' => isset($antropometria->peso) && isset($antropometria->altura)
|
|
? ImcService::calculate(
|
|
UnidadeMedidaEnum::QUILOGRAMAS,
|
|
$antropometria->peso,
|
|
UnidadeMedidaEnum::CENTIMETROS,
|
|
$antropometria->altura
|
|
)['imc']
|
|
: null,
|
|
'perimetro_cefalico' => $antropometria->perimetro_cefalico,
|
|
'circunferencia_abdominal' => (int) $antropometria->circunferencia_abdominal,
|
|
'perimetro_panturrilha' => (int) $antropometria->perimetro_panturrilha,
|
|
]);
|
|
});
|
|
}
|
|
|
|
private static function getMedicoesSinaisVitaisFormData($paciente)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_sinal_vital')
|
|
->select([
|
|
'ambulatorio_atendimento_sinal_vital.id',
|
|
'ambulatorio_atendimento_sinal_vital.created_at',
|
|
'ambulatorio_atendimento_sinal_vital.pressao_arterial',
|
|
'ambulatorio_atendimento_sinal_vital.frequencia_respiratoria',
|
|
'ambulatorio_atendimento_sinal_vital.frequencia_cardiaca',
|
|
'ambulatorio_atendimento_sinal_vital.temperatura',
|
|
'ambulatorio_atendimento_sinal_vital.saturacao_o2',
|
|
'ocupacao.id AS ocupacao_id',
|
|
'ocupacao.codigo AS ocupacao_codigo',
|
|
'ocupacao.nome AS ocupacao_nome',
|
|
'cadastro_cidadao.nome AS cidadao_nome',
|
|
'cadastro_setor.nome AS setor_nome',
|
|
])
|
|
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_sinal_vital.atendimento_id')
|
|
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
|
|
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_atendimento_sinal_vital.created_lotacao_id')
|
|
->join('cadastro_usuario', 'cadastro_usuario.id', 'cadastro_lotacao.usuario_id')
|
|
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
|
|
->join('sigtap.ocupacao', 'ocupacao.id', 'cadastro_lotacao.ocupacao_id')
|
|
->join('cadastro_centro_custo', 'cadastro_centro_custo.id', 'ambulatorio_atendimento_sinal_vital.created_centro_custo_id')
|
|
->join('cadastro_setor', 'cadastro_setor.id', 'cadastro_centro_custo.setor_id')
|
|
->where('ambulatorio_agendamento.paciente_id', $paciente->id)
|
|
->where(function ($query) {
|
|
$query
|
|
->whereExists(function ($query) {
|
|
$query->select(DB::raw(1))
|
|
->from('ambulatorio_atendimento_soap')
|
|
->whereColumn('ambulatorio_atendimento_soap.atendimento_id', 'ambulatorio_atendimento.id')
|
|
->where('ambulatorio_atendimento_soap.is_rascunho', false);
|
|
})
|
|
->orWhereNotExists(function ($query) {
|
|
$query->select(DB::raw(1))
|
|
->from('ambulatorio_atendimento_soap')
|
|
->whereColumn('ambulatorio_atendimento_soap.atendimento_id', 'ambulatorio_atendimento.id');
|
|
});
|
|
})
|
|
->unionAll(
|
|
DB::table('ambulatorio_atendimento_sinal_vital')
|
|
->select([
|
|
'ambulatorio_atendimento_sinal_vital.id',
|
|
'ambulatorio_atendimento_sinal_vital.created_at',
|
|
'ambulatorio_atendimento_sinal_vital.pressao_arterial',
|
|
'ambulatorio_atendimento_sinal_vital.frequencia_respiratoria',
|
|
'ambulatorio_atendimento_sinal_vital.frequencia_cardiaca',
|
|
'ambulatorio_atendimento_sinal_vital.temperatura',
|
|
'ambulatorio_atendimento_sinal_vital.saturacao_o2',
|
|
'ocupacao.id AS ocupacao_id',
|
|
'ocupacao.codigo AS ocupacao_codigo',
|
|
'ocupacao.nome AS ocupacao_nome',
|
|
'cadastro_cidadao.nome AS cidadao_nome',
|
|
'cadastro_setor.nome AS setor_nome',
|
|
])
|
|
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_sinal_vital.atendimento_id')
|
|
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
|
|
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_atendimento_sinal_vital.created_lotacao_id')
|
|
->join('cadastro_usuario', 'cadastro_usuario.id', 'cadastro_lotacao.usuario_id')
|
|
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
|
|
->join('sigtap.ocupacao', 'ocupacao.id', 'cadastro_lotacao.ocupacao_id')
|
|
->join('cadastro_centro_custo', 'cadastro_centro_custo.id', 'ambulatorio_atendimento_sinal_vital.created_centro_custo_id')
|
|
->join('cadastro_setor', 'cadastro_setor.id', 'cadastro_centro_custo.setor_id')
|
|
->where('ambulatorio_demanda_espontanea.paciente_id', $paciente->id)
|
|
)
|
|
->get()
|
|
->map(function ($sinalVital) {
|
|
$sinalVital->created_at = Carbon::create($sinalVital->created_at);
|
|
|
|
$sinalVital->createdLotacao = (object) [
|
|
'ocupacao' => (object) [
|
|
'id' => $sinalVital->ocupacao_id,
|
|
'codigo' => $sinalVital->ocupacao_codigo,
|
|
'nome' => $sinalVital->ocupacao_nome,
|
|
],
|
|
'profissional' => (object) [
|
|
'nome' => $sinalVital->cidadao_nome,
|
|
],
|
|
];
|
|
|
|
$sinalVital->createdCentroCusto = (object) [
|
|
'setor' => (object) [
|
|
'nome' => $sinalVital->setor_nome
|
|
],
|
|
];
|
|
|
|
return array_merge(self::getLogData($sinalVital), [
|
|
'id' => $sinalVital->id,
|
|
'medido_em' => $sinalVital->created_at->format('d/m/Y'),
|
|
'pressao_arterial' => $sinalVital->pressao_arterial,
|
|
'frequencia_respiratoria' => $sinalVital->frequencia_respiratoria,
|
|
'frequencia_cardiaca' => $sinalVital->frequencia_cardiaca,
|
|
'temperatura' => $sinalVital->temperatura,
|
|
'saturacao_o2' => $sinalVital->saturacao_o2,
|
|
]);
|
|
});
|
|
}
|
|
|
|
private static function getMedicoesGlicemiasCapilaresFormData($paciente)
|
|
{
|
|
return AtendimentoGlicemiaCapilar::whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
->where(fn ($q) => $q
|
|
->whereDoesntHave('soap')
|
|
->orWhereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
)
|
|
)
|
|
->get()
|
|
->map(fn ($glicemiaCapilar) => array_merge(self::getLogData($glicemiaCapilar), [
|
|
'id' => $glicemiaCapilar->id,
|
|
'medido_em' => $glicemiaCapilar->created_at->format('d/m/Y'),
|
|
'valor' => $glicemiaCapilar->valor,
|
|
'momento_coleta_nome' => $glicemiaCapilar->momentoColeta->nome,
|
|
]));
|
|
}
|
|
|
|
private static function getProblemasCondicoesAutorreferidas($paciente)
|
|
{
|
|
if (is_null($paciente->cadastroIndividual)) {
|
|
|
|
return [];
|
|
}
|
|
|
|
$cadastroIndividual = $paciente->cadastroIndividual;
|
|
|
|
$problemas = collect();
|
|
|
|
$booleanItens = [
|
|
[
|
|
'field' => 'gestante',
|
|
'label' => 'Gestante' . (is_null($cadastroIndividual->maternidade_referencia)
|
|
? '' : " ({$cadastroIndividual->maternidade_referencia})")
|
|
],
|
|
[
|
|
'field' => 'fumante',
|
|
'label' => 'Fumante'
|
|
],
|
|
[
|
|
'field' => 'usa_alcool',
|
|
'label' => 'Usa álcool'
|
|
],
|
|
[
|
|
'field' => 'outras_drogas',
|
|
'label' => 'Outras drogas'
|
|
],
|
|
[
|
|
'field' => 'hipertensao',
|
|
'label' => 'Hipertensão'
|
|
],
|
|
[
|
|
'field' => 'diabetes',
|
|
'label' => 'Diabetes'
|
|
],
|
|
[
|
|
'field' => 'avc_derrame',
|
|
'label' => 'Teve AVC/Derrame'
|
|
],
|
|
[
|
|
'field' => 'infarto',
|
|
'label' => 'Teve infarto'
|
|
],
|
|
[
|
|
'field' => 'hanseniase',
|
|
'label' => 'Está com hanseníase'
|
|
],
|
|
[
|
|
'field' => 'tuberculose',
|
|
'label' => 'Está com tuberculose'
|
|
],
|
|
[
|
|
'field' => 'cancer',
|
|
'label' => 'Tem ou teve câncer'
|
|
],
|
|
[
|
|
'field' => 'fibromialgia',
|
|
'label' => 'Fibromialgia'
|
|
],
|
|
[
|
|
'field' => 'transtorno_espectro_autista',
|
|
'label' => 'Transtorno do espectro autista'
|
|
],
|
|
[
|
|
'field' => 'internacao',
|
|
'label' => 'Internação nos últimos 12 meses' . (is_null($cadastroIndividual->internacao_motivo)
|
|
? '' : " ({$cadastroIndividual->internacao_motivo})")
|
|
],
|
|
[
|
|
'field' => 'doenca_cardiaca',
|
|
'label' => 'Doença cardíaca/do coração' . ($cadastroIndividual->doencaCardiaca->isEmpty()
|
|
? '' : " ({$cadastroIndividual->doencaCardiaca->pluck('descricao')->join(', ')})")
|
|
],
|
|
[
|
|
'field' => 'problemas_rins',
|
|
'label' => 'Problemas nos rins' . ($cadastroIndividual->problemasRins->isEmpty()
|
|
? '' : " ({$cadastroIndividual->problemasRins->pluck('descricao')->join(', ')})")
|
|
],
|
|
[
|
|
'field' => 'doenca_respiratoria',
|
|
'label' => 'Doença respiratória/no pulmão' . ($cadastroIndividual->doencaRespiratoria->isEmpty()
|
|
? '' : " ({$cadastroIndividual->doencaRespiratoria->pluck('descricao')->join(', ')})")
|
|
],
|
|
[
|
|
'field' => 'tratamento_saude_mental',
|
|
'label' => 'Tratamento psiquiátrico ou teve internação por problema de saúde mental'
|
|
],
|
|
[
|
|
'field' => 'acamado',
|
|
'label' => 'Acamado'
|
|
],
|
|
[
|
|
'field' => 'domiciliado',
|
|
'label' => 'Domiciliado'
|
|
],
|
|
[
|
|
'field' => 'plantas_medicinais',
|
|
'label' => 'Plantas medicinais' . (is_null($cadastroIndividual->plantas_medicinais_quais)
|
|
? '' : " ({$cadastroIndividual->plantas_medicinais_quais})")
|
|
],
|
|
[
|
|
'field' => 'praticas_integrativas',
|
|
'label' => 'Práticas integrativas e complementares'
|
|
],
|
|
];
|
|
|
|
foreach ($booleanItens as $item) {
|
|
|
|
if ($cadastroIndividual->{$item['field']}) {
|
|
|
|
$problemas->push($item['label']);
|
|
}
|
|
}
|
|
|
|
if (!is_null($cadastroIndividual->peso_id)) {
|
|
|
|
$problemas->push(Str::ucfirst(Str::lower(Peso::findOrFail($cadastroIndividual->peso_id)->descricao)));
|
|
}
|
|
|
|
if (!is_null($cadastroIndividual->outras_condicoes_primaria)) {
|
|
|
|
$problemas->push($cadastroIndividual->outras_condicoes_primaria);
|
|
}
|
|
|
|
if (!is_null($cadastroIndividual->outras_condicoes_secundaria)) {
|
|
|
|
$problemas->push($cadastroIndividual->outras_condicoes_secundaria);
|
|
}
|
|
|
|
if (!is_null($cadastroIndividual->outras_condicoes_terciaria)) {
|
|
|
|
$problemas->push($cadastroIndividual->outras_condicoes_terciaria);
|
|
}
|
|
|
|
return $problemas;
|
|
}
|
|
|
|
private static function getRaasFormData($atendimento)
|
|
{
|
|
return [
|
|
'origens_paciente' => OrigemPaciente::orderBy('nome')->get(['id', 'nome']),
|
|
'destinos_paciente' => DestinoPaciente::orderBy('nome')->get(['id', 'nome']),
|
|
'motivos_saida_permanencia' => MotivoSaidaPermanencia::orderBy('nome')->get(['id', 'nome']),
|
|
'carateres_atendimento' => CaraterAtendimento::orderBy('nome')->get(['id', 'nome']),
|
|
'classificacoes' => SigtapClassificacao::where('competencia_id', Competencia::max('id'))
|
|
->whereHas('servico', fn ($q) => $q
|
|
->where('codigo', SigtapServicoEnum::SERVICO_DE_ATENCAO_PSICOSSOCIAL)
|
|
)
|
|
->whereIn('codigo', [
|
|
ClassificacaoServicoAtencaoPsicossocial::RESIDENCIA_TERAPEUTICA_EM_SAUDE_MENTAL,
|
|
ClassificacaoServicoAtencaoPsicossocial::SERVICO_RESIDENCIAL_TERAPEUTICO_TIPO_I_SRT_TIPO_I,
|
|
ClassificacaoServicoAtencaoPsicossocial::SERVICO_RESIDENCIAL_TERAPEUTICO_TIPO_II_SRT_TIPO_II,
|
|
])
|
|
->orderBy('nome')
|
|
->get(['id', 'nome']),
|
|
'locais_realizacao_exame' => LocalRealizacaoExame::orderBy('nome')->get(['id', 'nome']),
|
|
'motivo_saida_permanencia_id' => $atendimento->especialidade->atencao_basica_motivo_saida_permanencia_id ?? null,
|
|
'numero_autorizacao' => $atendimento->especialidade->atencao_basica_numero_autorizacao ?? null,
|
|
'classificacao_id' => is_null($atendimento->especialidade)
|
|
? null
|
|
: SigtapClassificacao::where('competencia_id', Competencia::max('id'))
|
|
->whereHas('servico', fn ($q) => $q
|
|
->where('codigo', SigtapServicoEnum::SERVICO_DE_ATENCAO_PSICOSSOCIAL)
|
|
)
|
|
->where('codigo', $atendimento->especialidade->atencao_basica_classificacao_codigo)
|
|
->first()->id ?? null,
|
|
'has_procedimento_raas' => self::hasProcedimentoRaas($atendimento),
|
|
'has_procedimento_raas_que_precisa_de_classificacao' => self::hasProcedimentoRaasQuePrecisaDeClassificacao($atendimento),
|
|
'has_procedimento_raas_que_precisa_de_autorizacao' => self::hasProcedimentoRaasQuePrecisaDeAutorizacao($atendimento),
|
|
];
|
|
}
|
|
|
|
private static function getFeridaFormData()
|
|
{
|
|
return [
|
|
'tipos' => Ferida::where('ativo', true)->orderBy('nome')->get(['id', 'nome']),
|
|
'locais_anatomico' => LocalAnatomico::orderBy('descricao')->get(['id', 'descricao']),
|
|
'locais_anatomico_regiao' => LocalAnatomicoRegiao::orderBy('descricao')->get(['id', 'descricao', 'local_anatomico_id']),
|
|
'exsudatos' => FeridaExsudato::orderBy('descricao')->get(['id', 'descricao']),
|
|
'necroses' => FeridaNecrose::orderBy('id')->get(['id', 'descricao']),
|
|
];
|
|
}
|
|
|
|
private static function hasProcedimentoRaas($atendimento, $withRascunho = false)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_procedimento as atendimento_procedimento')
|
|
->join('sigtap.procedimento as procedimento', 'procedimento.id', 'atendimento_procedimento.procedimento_id')
|
|
->join('sigtap.procedimento_registro as procedimento_registro', 'procedimento_registro.procedimento_id', 'procedimento.id')
|
|
->join('sigtap.registro as registro', 'registro.id', 'procedimento_registro.registro_id')
|
|
->where('atendimento_procedimento.atendimento_id', $atendimento->id)
|
|
->when(!$withRascunho, fn ($q) => $q->where(fn ($q) => $q
|
|
->whereExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('ambulatorio_atendimento_soap as soap')
|
|
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
|
|
->where('soap.is_rascunho', false)
|
|
)
|
|
->orWhereNotExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('ambulatorio_atendimento_soap as soap')
|
|
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
|
|
)
|
|
))
|
|
->where('registro.codigo', Registro::RAAS_ATENCAO_PSICOSSOCIAL)
|
|
->exists();
|
|
}
|
|
|
|
private static function hasProcedimentoRaasQuePrecisaDeClassificacao($atendimento, $withRascunho = false)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_procedimento as atendimento_procedimento')
|
|
->join('sigtap.procedimento as procedimento', 'procedimento.id', 'atendimento_procedimento.procedimento_id')
|
|
->where('atendimento_procedimento.atendimento_id', $atendimento->id)
|
|
->when(!$withRascunho, fn ($q) => $q->where(fn ($q) => $q
|
|
->whereExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('ambulatorio_atendimento_soap as soap')
|
|
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
|
|
->where('soap.is_rascunho', false)
|
|
)
|
|
->orWhereNotExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('ambulatorio_atendimento_soap as soap')
|
|
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
|
|
)
|
|
))
|
|
->where('procedimento.codigo', ProcedimentoEnum::ACOMPANHAMENTO_DE_PACIENTE_EM_SAUDE_MENTAL)
|
|
->exists();
|
|
}
|
|
|
|
private static function hasProcedimentoRaasQuePrecisaDeAutorizacao($atendimento, $withRascunho = false)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_procedimento as atendimento_procedimento')
|
|
->join('sigtap.procedimento as procedimento', 'procedimento.id', 'atendimento_procedimento.procedimento_id')
|
|
->where('atendimento_procedimento.atendimento_id', $atendimento->id)
|
|
->when(!$withRascunho, fn ($q) => $q->where(fn ($q) => $q
|
|
->whereExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('ambulatorio_atendimento_soap as soap')
|
|
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
|
|
->where('soap.is_rascunho', false)
|
|
)
|
|
->orWhereNotExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('ambulatorio_atendimento_soap as soap')
|
|
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
|
|
)
|
|
))
|
|
->whereIn('procedimento.codigo', [
|
|
ProcedimentoEnum::ACOMPANHAMENTO_DE_PACIENTE_EM_SAUDE_MENTAL,
|
|
ProcedimentoEnum::ACOMPANHAMENTO_DE_PESSOAS_COM_NECESSIDADES_DECORRENTES_DO_USO_DE_ALCOOL_CRACK_E_OUTRAS_DROGAS,
|
|
ProcedimentoEnum::ACOMPANHAMENTO_DE_PESSOAS_ADULTAS_COM_SOFRIMENTO_OU_TRANSTORNOS_MENTAIS_DECORRENTES_DO_USO_DE_CRACK_ALCOOL_E_OUTRAS_DROGAS,
|
|
ProcedimentoEnum::ACOMPANHAMENTO_DA_POPULACAO_INFANTO_JUVENIL_COM_SOFRIMENTO_OU_TRANSTORNOS_MENTAIS_DECORRENTES_DO_USO_DE_CRACK_ALCOOL_E_OUTRAS_DROGAS,
|
|
])
|
|
->exists();
|
|
}
|
|
|
|
private static function getAntecedentesFormData($atendimento)
|
|
{
|
|
return [
|
|
'puericultura' => [
|
|
'gravidez_tipos' => GravidezTipo::get(['id', 'nome']),
|
|
'parto_tipos' => PartoTipo::get(['id', 'nome']),
|
|
],
|
|
'problema_condicao' => [
|
|
'situacoes' => ProblemaCondicaoSituacao::orderBy('nome')->get(['id', 'nome']),
|
|
],
|
|
'problemas_condicoes' => self::getProblemasCondicoesResolvidos($atendimento->paciente),
|
|
];
|
|
}
|
|
|
|
private static function getProblemasCondicoesResolvidos($paciente)
|
|
{
|
|
return AtendimentoSoapProblemaCondicao::where('situacao_id', ProblemaCondicaoSituacaoEnum::RESOLVIDO)
|
|
->whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
)
|
|
->get()
|
|
->map(fn ($problemaCondicao) => array_merge(self::getLogData($problemaCondicao), [
|
|
'id' => $problemaCondicao->id,
|
|
'ciap' => is_null($problemaCondicao->ciap_id) ? null : [
|
|
'codigo' => $problemaCondicao->ciap->codigo,
|
|
'descricao' => $problemaCondicao->ciap->descricao,
|
|
],
|
|
'cid' => is_null($problemaCondicao->cid_id) ? null : [
|
|
'codigo' => $problemaCondicao->cid->codigo,
|
|
'nome' => $problemaCondicao->cid->nome,
|
|
],
|
|
'situacao' => [
|
|
'nome' => $problemaCondicao->situacao->nome,
|
|
],
|
|
'inicio' => [
|
|
'data' => is_null($problemaCondicao->inicio) ? null : $problemaCondicao->inicio->format('d/m/Y'),
|
|
],
|
|
'fim' => [
|
|
'data' => is_null($problemaCondicao->fim) ? null : $problemaCondicao->fim->format('d/m/Y'),
|
|
],
|
|
'observacao' => $problemaCondicao->observacao,
|
|
]))
|
|
->all();
|
|
}
|
|
|
|
private static function getSubjetivoFormData($atendimento)
|
|
{
|
|
$preAtendimento = $atendimento->preAtendimento;
|
|
|
|
if (!$preAtendimento){
|
|
|
|
return [];
|
|
}
|
|
|
|
return [
|
|
'ciap_id' => $preAtendimento->ciap_id ?? null,
|
|
'ciap' => [
|
|
'codigo' => is_null($preAtendimento->ciap_id)
|
|
? null : $preAtendimento->ciap->codigo,
|
|
'descricao' => is_null($preAtendimento->ciap_id)
|
|
? null : $preAtendimento->ciap->descricao,
|
|
],
|
|
'observacao' => $preAtendimento->motivo_atendimento,
|
|
];
|
|
}
|
|
|
|
private static function getHistoricoSubjetivoFormData($atendimento)
|
|
{
|
|
$motivos = AtendimentoSoapMotivo::whereHas('soap', function ($q) use ($atendimento) {
|
|
$q->where('is_rascunho', false)->where('atendimento_id', $atendimento->id);
|
|
})
|
|
->get()
|
|
->map(function ($motivo) {
|
|
return [
|
|
'cid_id' => $motivo->cid_id ?? null,
|
|
'cid' => [
|
|
'id' => $motivo->cid->id ?? null,
|
|
'codigo' => $motivo->cid->codigo ?? null,
|
|
'nome' => $motivo->cid->nome ?? null,
|
|
],
|
|
];
|
|
});
|
|
|
|
return [
|
|
'motivos' => $motivos,
|
|
];
|
|
}
|
|
|
|
private static function getHistoricoAvaliacaoFormData($atendimento)
|
|
{
|
|
$problemasCondicoes = AtendimentoSoapProblemaCondicao::whereHas('soap', function ($q) use ($atendimento) {
|
|
$q->where('is_rascunho', false)->where('atendimento_id', $atendimento->id);
|
|
})
|
|
->get()
|
|
->map(function ($problemaCondicao) {
|
|
return [
|
|
'cid' => $problemaCondicao->cid ? [
|
|
'id' => $problemaCondicao->cid->id,
|
|
'codigo' => $problemaCondicao->cid->codigo,
|
|
'nome' => $problemaCondicao->cid->nome,
|
|
] : null,
|
|
];
|
|
});
|
|
|
|
return [
|
|
'problemas_condicoes' => $problemasCondicoes,
|
|
];
|
|
}
|
|
|
|
private static function getHistoricoPlanoFormData($atendimento)
|
|
{
|
|
$compartilhamentosCuidados = AtendimentoSoapCompartilhamentoCuidado::whereHas('soap', function ($q) use ($atendimento) {
|
|
$q->where('is_rascunho', false)->where('atendimento_id', $atendimento->id);
|
|
})
|
|
->get()
|
|
->map(function ($compartilhamentoCuidado) {
|
|
return [
|
|
'cid' => $compartilhamentoCuidado->cid ? [
|
|
'id' => $compartilhamentoCuidado->cid->id,
|
|
'codigo' => $compartilhamentoCuidado->cid->codigo,
|
|
'nome' => $compartilhamentoCuidado->cid->nome,
|
|
] : null,
|
|
];
|
|
});
|
|
|
|
$solicitacaoExamesComuns = self::getHistoricoSolicitacaoExamesComuns($atendimento->id);
|
|
$solicitacaoExamesAltoCusto = self::getHistoricoSolicitacaoExamesAltoCusto($atendimento->id);
|
|
$encaminhamentos = self::getHistoricoEncaminhamentos($atendimento->id);
|
|
$atestados = self::getHistoricoAtestados($atendimento->id);
|
|
|
|
return [
|
|
'compartilhamentos_cuidados' => $compartilhamentosCuidados,
|
|
'solicitacoes_exames_comuns' => $solicitacaoExamesComuns,
|
|
'solicitacoes_exames_alto_custo' => $solicitacaoExamesAltoCusto,
|
|
'encaminhamentos' => $encaminhamentos,
|
|
'atestados' => $atestados,
|
|
];
|
|
}
|
|
|
|
private static function getHistoricoFinalizacaoFormData($atendimento)
|
|
{
|
|
$cidEmad = AtendimentoSoap::where('is_rascunho', false)
|
|
->where('atendimento_id', $atendimento->id)
|
|
->whereNotNull('emad_cid_primario_id')
|
|
->get()
|
|
->map(function ($soap) {
|
|
return [
|
|
'cid' => $soap->emad_cid_primario_id ? [
|
|
'id' => $soap->emad_cid_primario_id,
|
|
'nome' => Cid::where('id', $soap->emad_cid_primario_id)->first()->nome,
|
|
'codigo' => Cid::where('id', $soap->emad_cid_primario_id)->first()->codigo,
|
|
] : null,
|
|
];
|
|
});
|
|
|
|
return [
|
|
'cid_emad' => $cidEmad,
|
|
];
|
|
}
|
|
|
|
private static function getObjetivoFormData($atendimento)
|
|
{
|
|
$preAtendimento = $atendimento->preAtendimento;
|
|
$unideMedidaQuilogramasSigla = UnidadeMedida::findOrFail(UnidadeMedidaEnum::QUILOGRAMAS)->sigla;
|
|
$unideMedidaCentimetrosSigla = UnidadeMedida::findOrFail(UnidadeMedidaEnum::CENTIMETROS)->sigla;
|
|
|
|
$examesAvaliados = self::getExamesAvaliados($atendimento);
|
|
$triagensNeonatal = self::getTriagensNeoNatal($atendimento);
|
|
|
|
$ultimoPreAtendimento = AtendimentoPreAtendimento::whereHas('atendimento', fn ($q) =>
|
|
$q->where('paciente_id', $atendimento->paciente->id)
|
|
->whereDate('created_at', $atendimento->created_at)
|
|
)
|
|
->whereHas('antropometria')
|
|
->orderByDesc('created_at')
|
|
->first();
|
|
|
|
$pacienteSoaps = self::getSoapsByPaciente($atendimento->paciente->id);
|
|
|
|
$questionarioMChatR = collect();
|
|
|
|
$pacienteSoaps->filter(fn ($q) => $q->puericulturaQuestionarioMChatR->isNotEmpty())->each(function($soap) use (&$questionarioMChatR) {
|
|
$score = PuericulturaQuestionarioMChatR::orderBy('id')
|
|
->get()
|
|
->reduce(function ($total, $query) use ($soap) {
|
|
$questionario = $soap->puericulturaQuestionarioMChatR()
|
|
->where('questionario_m_chat_r_id', $query->id)
|
|
->first();
|
|
|
|
$valor = $questionario->resposta
|
|
? $query->valor_resposta_sim
|
|
: $query->valor_resposta_nao;
|
|
|
|
return $total + $valor;
|
|
}, 0);
|
|
|
|
$classificacao = null;
|
|
|
|
if ($score <= 2) {
|
|
$classificacao = 'Baixo risco';
|
|
} elseif ($score >= 3 && $score <= 7) {
|
|
$classificacao = 'Risco moderado';
|
|
} elseif ($score >= 8) {
|
|
$classificacao = 'Alto risco';
|
|
}
|
|
|
|
$questionarioMChatR->push([
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
'soap_id' => $soap->id,
|
|
'data_hora_atendimento' => $soap->created_at->format('d/m/Y \à\s H:i'),
|
|
'usuario_nome' => $soap->createdLotacao->usuario->cidadao->nome ?? null,
|
|
'score' => $score,
|
|
'classificacao' => $classificacao,
|
|
]);
|
|
});
|
|
|
|
return [
|
|
'idade_gestacional' => self::getIdadeGestacional($atendimento->paciente),
|
|
'ultimo_atendimento_pre_natal' => self::getUltimoAtendimentoPreNatal($atendimento->paciente),
|
|
'ultima_dum' => self::getUltimaDum($atendimento->paciente),
|
|
'glicemia_capilar' => [
|
|
'momentos_coleta' => GlicemiaCapilarMomentoColeta::orderBy('id')->get(['id', 'nome']),
|
|
'valor' => $ultimoPreAtendimento->glicemiaCapilar->valor ?? null,
|
|
'momento_coleta' => [
|
|
'nome' => $ultimoPreAtendimento->glicemiaCapilar->momentoColeta->nome ?? null,
|
|
]
|
|
],
|
|
'antropometria' => $ultimoPreAtendimento ? (object) [
|
|
'peso' => $ultimoPreAtendimento->antropometria->peso ?? null,
|
|
'peso_unidade_medida_sigla' => $unideMedidaQuilogramasSigla,
|
|
'altura' => $ultimoPreAtendimento->antropometria->altura ?? null,
|
|
'altura_unidade_medida_sigla' => $unideMedidaCentimetrosSigla,
|
|
'imc' => isset($ultimoPreAtendimento->antropometria->peso) && isset($ultimoPreAtendimento->antropometria->altura)
|
|
? (object) ImcService::calculate(
|
|
UnidadeMedidaEnum::QUILOGRAMAS,
|
|
$ultimoPreAtendimento->antropometria->peso,
|
|
UnidadeMedidaEnum::CENTIMETROS,
|
|
$ultimoPreAtendimento->antropometria->altura
|
|
)
|
|
: (object) [
|
|
'imc' => null,
|
|
'classificacao' => null,
|
|
'grau_obesidade' => null,
|
|
],
|
|
'perimetro_cefalico' => $ultimoPreAtendimento->antropometria->perimetro_cefalico ?? null,
|
|
'perimetro_cefalico_unidade_medida_sigla' => $unideMedidaCentimetrosSigla,
|
|
'circunferencia_abdominal' => $ultimoPreAtendimento->antropometria->circunferencia_abdominal ?? null,
|
|
'circunferencia_abdominal_unidade_medida_sigla' => $unideMedidaCentimetrosSigla,
|
|
'perimetro_panturrilha' => $ultimoPreAtendimento->antropometria->perimetro_panturrilha ?? null,
|
|
'perimetro_panturrilha_unidade_medida_sigla' => $unideMedidaCentimetrosSigla,
|
|
] : null,
|
|
'sinal_vital' => $ultimoPreAtendimento ? (object) [
|
|
'pressao_arterial' => $ultimoPreAtendimento->sinalVital->pressao_arterial ?? null,
|
|
'frequencia_respiratoria' => $ultimoPreAtendimento->sinalVital->frequencia_respiratoria ?? null,
|
|
'frequencia_cardiaca' => $ultimoPreAtendimento->sinalVital->frequencia_cardiaca ?? null,
|
|
'temperatura' => $ultimoPreAtendimento->sinalVital->temperatura ?? null,
|
|
'saturacao_o2' => $ultimoPreAtendimento->sinalVital->saturacao_o2 ?? null,
|
|
] : null,
|
|
'marcador_consumo_alimentar' => [
|
|
'perguntas' => MarcadorConsumoAlimentarService::getGrupoPerguntas($atendimento->paciente->id),
|
|
'titulo' => MarcadorConsumoAlimentarService::getTitulo($atendimento->paciente->id),
|
|
'titulo_area' => MarcadorConsumoAlimentarService::getTituloArea($atendimento->paciente->id),
|
|
],
|
|
'tria' => [
|
|
'alimentos_acabaram' => optional($atendimento->paciente->informacaoSocial)->alimentos_acabaram,
|
|
'comeu_alguns_alimentos' => optional($atendimento->paciente->informacaoSocial)->comeu_alguns_alimentos,
|
|
'data_atualizacao_tria' => optional($atendimento->paciente->informacaoSocial)->data_atualizacao_tria
|
|
? (new Carbon(optional($atendimento->paciente->informacaoSocial)->data_atualizacao_tria))->format('d/m/Y')
|
|
: null,
|
|
'is_desatualizado' => self::isTriaDesatualizado(
|
|
optional($atendimento->paciente->informacaoSocial)->data_atualizacao_tria
|
|
?? optional($atendimento->paciente->cadastroIndividual)->data_atualizacao_tria
|
|
?? optional($atendimento->paciente->cadastroIndividual)->updated_at
|
|
),
|
|
],
|
|
'resultado_exame' => [
|
|
'resultado_tipos' => ExameResultadoTipo::get(['id', 'nome']),
|
|
],
|
|
'coletas_materiais' => is_null($preAtendimento)
|
|
? [] : $preAtendimento->coletasMateriais()->orderBy('nome')->pluck('nome'),
|
|
'outros_procedimentos' => is_null($preAtendimento)
|
|
? [] : $preAtendimento->outrosProcedimentos()->orderBy('nome')->pluck('nome'),
|
|
'administracoes_medicamentos' => is_null($preAtendimento)
|
|
? [] : $preAtendimento->administracoesMedicamentos()->orderBy('descricao')->pluck('descricao'),
|
|
'resultados_exames_laboratoriais' => self::getResultadosExamesLaboratoriais($atendimento->paciente),
|
|
'resultados_exames_imagens' => self::getResultadosExamesImagens($atendimento->paciente),
|
|
'exame_solicitado_avaliado' => ExameSolicitadoAvaliado::whereNotIn('id', $examesAvaliados->pluck('id'))
|
|
->orderBy('descricao')
|
|
->get(),
|
|
'exames_avaliados' => $examesAvaliados,
|
|
'triagens_neonatal' => $triagensNeonatal,
|
|
'triagem_neonatal' => TriagemNeonatal::whereNotIn('id', $triagensNeonatal->pluck('id'))
|
|
->orderBy('descricao')
|
|
->get(),
|
|
'pre_natal' => self::getPreNatalFormData(),
|
|
'puericultura' => [
|
|
'gravidez_tipos' => GravidezTipo::get(['id', 'nome']),
|
|
'parto_tipos' => PartoTipo::get(['id', 'nome']),
|
|
'aleitamento_tipos' => AleitamentoMaterno::get(['id', 'descricao']),
|
|
'questionario_m_chat_r' => $questionarioMChatR,
|
|
],
|
|
];
|
|
}
|
|
|
|
public static function getIdadeGestacional($paciente)
|
|
{
|
|
$atendimento = AtendimentoSoap::where('is_rascunho', false)
|
|
->whereNotNull('dum')
|
|
->where(fn($q) => $q->whereHas('atendimento.agendamento', fn($q) => $q->where('paciente_id', $paciente->id))
|
|
->orWhereHas('atendimento.demandaEspontanea', fn($q) => $q->where('paciente_id', $paciente->id))
|
|
)
|
|
->whereHas('problemasCondicoes', fn($q) => $q->where('situacao_id', '<>', ProblemaCondicaoSituacaoEnum::RESOLVIDO)
|
|
->whereHas('pacienteGestacao', fn($q) => $q->whereNull('fim'))
|
|
->where(fn($q) => $q->whereHas('ciap', fn($q) => $q->where('codigo', self::CIAPS_GRAVIDEZ_NORMAL))
|
|
->orWhereHas('cid', fn($q) => $q->whereIn('codigo', self::CIDS_GRAVIDEZ_NORMAL))
|
|
)
|
|
)
|
|
->orderByDesc('ambulatorio_atendimento_soap.created_at')
|
|
->first();
|
|
|
|
if($atendimento) {
|
|
$interval = $atendimento->dum->diff(Carbon::today());
|
|
return [
|
|
'semanas' => floor($interval->days / 7),
|
|
'dias' => $interval->days % 7,
|
|
];
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private static function getUltimoAtendimentoPreNatal($paciente)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_soap as soap')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
|
|
->leftjoin('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
|
|
->leftJoin('ambulatorio_demanda_espontanea as demanda', 'demanda.id', 'atendimento.demanda_espontanea_id')
|
|
->leftjoin('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
|
|
->leftjoin('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
|
|
->join('cadastro_usuario as usuario', function($join) {
|
|
$join->on('usuario.id', 'lotacao.usuario_id')
|
|
->orOn('usuario.id', 'demanda.usuario_id');
|
|
})
|
|
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
|
|
->where('soap.is_rascunho', false)
|
|
->where('is_atendimento_pre_natal', true)
|
|
->where('atendimento.paciente_id', $paciente->id)
|
|
->select(DB::raw("
|
|
DATE_FORMAT(soap.created_at, '%d/%m/%Y') as data,
|
|
cidadao.nome as usuario_nome
|
|
"))
|
|
->orderByDesc('soap.created_at')
|
|
->first();
|
|
}
|
|
|
|
public static function getUltimaDum($paciente)
|
|
{
|
|
if ($paciente->cidadao->sexo_id === Sexo::FEMININO) {
|
|
|
|
$soap = DB::table('ambulatorio_atendimento_soap as soap')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
|
|
->where('soap.is_rascunho', false)
|
|
->whereNotNull('dum')
|
|
->where('atendimento.paciente_id', $paciente->id)
|
|
->select(DB::raw("
|
|
soap.created_at,
|
|
DATE_FORMAT(soap.dum, '%d/%m/%Y') as dum
|
|
"))
|
|
->union(DB::table('ambulatorio_atendimento_pre_atendimento as pre_atendimento')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'pre_atendimento.atendimento_id')
|
|
->whereNotNull('dum')
|
|
->where('atendimento.paciente_id', $paciente->id)
|
|
->select(DB::raw("
|
|
pre_atendimento.created_at,
|
|
DATE_FORMAT(pre_atendimento.dum, '%d/%m/%Y') as dum
|
|
"))
|
|
)
|
|
->orderByDesc('created_at')
|
|
->first('dum');
|
|
|
|
if (!is_null($soap)) {
|
|
|
|
return $soap->dum;
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private static function getResultadosExamesLaboratoriais($paciente)
|
|
{
|
|
return self::getResultadosExamesLaboratoriaisAmbulatorio($paciente)
|
|
->concat(self::getResultadosExamesLaboratoriaisExameLaboratorial($paciente));
|
|
}
|
|
|
|
private static function getResultadosExamesLaboratoriaisAmbulatorio($paciente)
|
|
{
|
|
return AtendimentoSoapResultadoExame::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
)
|
|
->whereHas('exame', fn ($q) => $q->where('tipo_id', ExameTipo::LABORATORIAL))
|
|
->get()
|
|
->map(fn ($resultado) => array_merge(self::getLogData($resultado), [
|
|
'origem' => 'ambulatorio',
|
|
'percentual' => $resultado->percentual,
|
|
'idade_gestacional_semanas_eco' => $resultado->idade_gestacional_semanas_eco,
|
|
'idade_gestacional_dias_eco' => $resultado->idade_gestacional_dias_eco,
|
|
'dpp_eco' => is_null($resultado->dpp_eco) ? null : $resultado->dpp_eco->format('d/m/Y'),
|
|
'exame' => [
|
|
'codigo' => $resultado->exame->codigo,
|
|
'nome' => $resultado->exame->nome,
|
|
],
|
|
'solicitado_em' => is_null($resultado->solicitado_em)
|
|
? null : $resultado->solicitado_em->format('d/m/Y'),
|
|
'realizado_em' => $resultado->realizado_em->format('d/m/Y'),
|
|
'resultado_em' => is_null($resultado->resultado_em)
|
|
? null : $resultado->resultado_em->format('d/m/Y'),
|
|
'resultado' => $resultado->resultado,
|
|
'resultado_tipo_nome' => $resultado->resultadoTipo->nome ?? null,
|
|
]));
|
|
}
|
|
|
|
private static function getResultadosExamesLaboratoriaisExameLaboratorial($paciente)
|
|
{
|
|
$agendamentos = collect();
|
|
|
|
$setWhereStatus = function ($query) {
|
|
|
|
$query->where(fn ($q) => $q
|
|
->whereIn('agendamento_exame.status_id', [
|
|
StatusAgendamento::ASSINADO,
|
|
StatusAgendamento::PENDENTE_ENTREGA,
|
|
StatusAgendamento::ENTREGUE,
|
|
])
|
|
->whereExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('exame_laboratorial_agendamento_exame_resultado AS resultado')
|
|
->whereColumn('resultado.agendamento_exame_id', 'agendamento_exame.id')
|
|
)
|
|
)
|
|
->orWhere(fn ($q) => $q
|
|
->whereIn('agendamento_exame.status_id', [
|
|
StatusAgendamento::REALIZADO,
|
|
StatusAgendamento::PENDENTE_ASSINATURA,
|
|
StatusAgendamento::ASSINADO,
|
|
StatusAgendamento::PENDENTE_ENTREGA,
|
|
StatusAgendamento::ENTREGUE,
|
|
])
|
|
->whereExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('exame_laboratorial_agendamento_laudo AS laudo')
|
|
->whereColumn('laudo.agendamento_id', 'agendamento.id')
|
|
)
|
|
);
|
|
};
|
|
|
|
DB::table('exame_laboratorial_agendamento_exame AS agendamento_exame')
|
|
->join('parametrizacao_exame AS exame', 'exame.id', 'agendamento_exame.exame_id')
|
|
->join('cadastro_grupo AS grupo', 'grupo.id', 'exame.grupo_tipo_id')
|
|
->join('exame_laboratorial_agendamento AS agendamento', 'agendamento.id', 'agendamento_exame.agendamento_id')
|
|
->leftJoin('cadastro_usuario AS coleta_usuario', 'coleta_usuario.id', 'agendamento.usuario_id')
|
|
->leftJoin('cadastro_cidadao AS coleta_cidadao', 'coleta_cidadao.id', 'coleta_usuario.cidadao_id')
|
|
->leftJoin('sigtap.ocupacao AS coleta_ocupacao', 'coleta_ocupacao.id', 'agendamento.ocupacao_id')
|
|
->whereNotNull('exame.grupo_tipo_id')
|
|
->where($setWhereStatus)
|
|
->where('exame.mapa_agrupado', true)
|
|
->where('agendamento.paciente_id', $paciente->id)
|
|
->select(
|
|
'agendamento.id AS agendamento_id',
|
|
DB::raw("CONCAT(agendamento.data, ' ', agendamento.horario) AS data_hora_agendada"),
|
|
'coleta_cidadao.nome AS coleta_usuario_nome',
|
|
'coleta_ocupacao.nome AS coleta_ocupacao_nome',
|
|
DB::raw("CAST(agendamento_exame.data_coleta AS DATE) AS data_coleta"),
|
|
DB::raw("IF (agendamento_exame.status_id IN (
|
|
" . StatusAgendamento::REALIZADO . ",
|
|
" . StatusAgendamento::PENDENTE_ASSINATURA . "
|
|
),
|
|
NULL,
|
|
CAST(agendamento_exame.data_laudo AS DATE)
|
|
) AS data_resultado"),
|
|
'agendamento_exame.assinatura_profissional_id',
|
|
'grupo.id AS exame_grupo_id',
|
|
'grupo.nome AS exame_grupo_nome',
|
|
DB::raw('TRUE AS pertence_grupo'),
|
|
DB::raw('TRUE AS mapa_agrupado')
|
|
)
|
|
->groupBy(
|
|
'agendamento.id',
|
|
'grupo.id',
|
|
'agendamento_exame.assinatura_profissional_id',
|
|
)
|
|
->unionAll(DB::table('exame_laboratorial_agendamento_exame AS agendamento_exame')
|
|
->join('parametrizacao_exame AS exame', 'exame.id', 'agendamento_exame.exame_id')
|
|
->join('exame_laboratorial_agendamento AS agendamento', 'agendamento.id', 'agendamento_exame.agendamento_id')
|
|
->leftJoin('cadastro_usuario AS coleta_usuario', 'coleta_usuario.id', 'agendamento.usuario_id')
|
|
->leftJoin('cadastro_cidadao AS coleta_cidadao', 'coleta_cidadao.id', 'coleta_usuario.cidadao_id')
|
|
->leftJoin('sigtap.ocupacao AS coleta_ocupacao', 'coleta_ocupacao.id', 'agendamento.ocupacao_id')
|
|
->whereNotNull('exame.grupo_tipo_id')
|
|
->where($setWhereStatus)
|
|
->where(fn ($q) => $q
|
|
->where('exame.mapa_agrupado', false)
|
|
->orWhereNull('exame.mapa_agrupado')
|
|
)
|
|
->where('agendamento.paciente_id', $paciente->id)
|
|
->select(
|
|
'agendamento.id AS agendamento_id',
|
|
DB::raw("CONCAT(agendamento.data, ' ', agendamento.horario) AS data_hora_agendada"),
|
|
'coleta_cidadao.nome AS coleta_usuario_nome',
|
|
'coleta_ocupacao.nome AS coleta_ocupacao_nome',
|
|
DB::raw("CAST(agendamento_exame.data_coleta AS DATE) AS data_coleta"),
|
|
DB::raw("IF (agendamento_exame.status_id IN (
|
|
" . StatusAgendamento::REALIZADO . ",
|
|
" . StatusAgendamento::PENDENTE_ASSINATURA . "
|
|
),
|
|
NULL,
|
|
CAST(agendamento_exame.data_laudo AS DATE)
|
|
) AS data_resultado"),
|
|
'agendamento_exame.assinatura_profissional_id',
|
|
'exame.id AS exame_grupo_id',
|
|
'exame.nome AS exame_grupo_nome',
|
|
DB::raw('TRUE AS pertence_grupo'),
|
|
DB::raw('FALSE AS mapa_agrupado')
|
|
)
|
|
->groupBy(
|
|
'agendamento.id',
|
|
'exame.id'
|
|
)
|
|
)
|
|
->unionAll(DB::table('exame_laboratorial_agendamento_exame AS agendamento_exame')
|
|
->join('parametrizacao_exame AS exame', 'exame.id', 'agendamento_exame.exame_id')
|
|
->join('exame_laboratorial_agendamento AS agendamento', 'agendamento.id', 'agendamento_exame.agendamento_id')
|
|
->leftJoin('cadastro_usuario AS coleta_usuario', 'coleta_usuario.id', 'agendamento.usuario_id')
|
|
->leftJoin('cadastro_cidadao AS coleta_cidadao', 'coleta_cidadao.id', 'coleta_usuario.cidadao_id')
|
|
->leftJoin('sigtap.ocupacao AS coleta_ocupacao', 'coleta_ocupacao.id', 'agendamento.ocupacao_id')
|
|
->whereNull('exame.grupo_tipo_id')
|
|
->where($setWhereStatus)
|
|
->where('agendamento.paciente_id', $paciente->id)
|
|
->select(
|
|
'agendamento.id AS agendamento_id',
|
|
DB::raw("CONCAT(agendamento.data, ' ', agendamento.horario) AS data_hora_agendada"),
|
|
'coleta_cidadao.nome AS coleta_usuario_nome',
|
|
'coleta_ocupacao.nome AS coleta_ocupacao_nome',
|
|
DB::raw("CAST(agendamento_exame.data_coleta AS DATE) AS data_coleta"),
|
|
DB::raw("IF (agendamento_exame.status_id IN (
|
|
" . StatusAgendamento::REALIZADO . ",
|
|
" . StatusAgendamento::PENDENTE_ASSINATURA . "
|
|
),
|
|
NULL,
|
|
CAST(agendamento_exame.data_laudo AS DATE)
|
|
) AS data_resultado"),
|
|
'agendamento_exame.assinatura_profissional_id',
|
|
'exame.id AS exame_grupo_id',
|
|
'exame.nome AS exame_grupo_nome',
|
|
DB::raw('FALSE AS pertence_grupo'),
|
|
DB::raw('NULL AS mapa_agrupado')
|
|
)
|
|
)
|
|
->get()
|
|
->each(function ($agendamentoExame) use ($agendamentos) {
|
|
|
|
$agendamento = $agendamentos->where('agendamento_id', $agendamentoExame->agendamento_id)->first();
|
|
|
|
if (is_null($agendamento)) {
|
|
|
|
$agendamento = (object) [
|
|
'origem' => 'exame-laboratorial',
|
|
'agendamento_id' => $agendamentoExame->agendamento_id,
|
|
'data_hora_agendada' => Carbon::create($agendamentoExame->data_hora_agendada)->format('d/m/Y \à\s H:i'),
|
|
'coleta_usuario_nome' => $agendamentoExame->coleta_usuario_nome,
|
|
'coleta_ocupacao_nome' => $agendamentoExame->coleta_ocupacao_nome,
|
|
'laudos' => self::getExameLaboratorialLaudos($agendamentoExame->agendamento_id),
|
|
'exames' => collect(),
|
|
];
|
|
|
|
$agendamentos->push($agendamento);
|
|
}
|
|
|
|
$agendamento->exames->push((object) [
|
|
'agendamento_id' => $agendamentoExame->agendamento_id,
|
|
'exame_grupo_id' => $agendamentoExame->exame_grupo_id,
|
|
'exame_grupo_nome' => $agendamentoExame->exame_grupo_nome,
|
|
'pertence_grupo' => $agendamentoExame->pertence_grupo,
|
|
'mapa_agrupado' => $agendamentoExame->mapa_agrupado,
|
|
'data_coleta' => $agendamentoExame->data_coleta,
|
|
'data_resultado' => $agendamentoExame->data_resultado,
|
|
'assinatura_profissional_id' => $agendamentoExame->assinatura_profissional_id,
|
|
]);
|
|
});
|
|
|
|
$agendamentos->each(function ($agendamento) {
|
|
|
|
unset($agendamento->agendamento_id);
|
|
});
|
|
|
|
return $agendamentos;
|
|
}
|
|
|
|
private static function getExameLaboratorialLaudos($agendamentoId)
|
|
{
|
|
return DB::table('exame_laboratorial_agendamento_laudo AS laudo')
|
|
->leftJoin('cadastro_lotacao AS lotacao', 'lotacao.id', 'laudo.created_lotacao_id')
|
|
->leftJoin('cadastro_usuario AS usuario', 'usuario.id', 'lotacao.usuario_id')
|
|
->leftJoin('cadastro_cidadao AS cidadao', 'cidadao.id', 'usuario.cidadao_id')
|
|
->leftJoin('web_service_usuario AS ws_usuario', 'ws_usuario.id', 'laudo.externo_created_usuario_id')
|
|
->where('laudo.agendamento_id', $agendamentoId)
|
|
->select(
|
|
'laudo.id',
|
|
'laudo.arquivo',
|
|
'laudo.url',
|
|
DB::raw("CAST(laudo.created_at AS DATE) AS data"),
|
|
DB::raw("COALESCE(cidadao.nome, CONCAT(ws_usuario.nome, ' (Web service)')) AS responsavel")
|
|
)
|
|
->get();
|
|
}
|
|
|
|
private static function getResultadosExamesImagens($paciente)
|
|
{
|
|
return self::getResultadosExamesImagensAmbulatorio($paciente)
|
|
->concat(self::getResultadosExamesLaboratoriaisExameImagem($paciente));
|
|
}
|
|
|
|
private static function getResultadosExamesImagensAmbulatorio($paciente)
|
|
{
|
|
return AtendimentoSoapResultadoExame::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
)
|
|
->whereHas('exame', fn ($q) => $q->where('tipo_id', ExameTipo::IMAGEM))
|
|
->get()
|
|
->map(fn ($resultado) => array_merge(self::getLogData($resultado), [
|
|
'origem' => 'ambulatorio',
|
|
'percentual' => $resultado->percentual,
|
|
'idade_gestacional_semanas_eco' => $resultado->idade_gestacional_semanas_eco,
|
|
'idade_gestacional_dias_eco' => $resultado->idade_gestacional_dias_eco,
|
|
'dpp_eco' => is_null($resultado->dpp_eco) ? null : $resultado->dpp_eco->format('d/m/Y'),
|
|
'exame' => [
|
|
'codigo' => $resultado->exame->codigo,
|
|
'nome' => $resultado->exame->nome,
|
|
],
|
|
'solicitado_em' => is_null($resultado->solicitado_em)
|
|
? null : $resultado->solicitado_em->format('d/m/Y'),
|
|
'realizado_em' => $resultado->realizado_em->format('d/m/Y'),
|
|
'resultado_em' => is_null($resultado->resultado_em)
|
|
? null : $resultado->resultado_em->format('d/m/Y'),
|
|
'resultado' => $resultado->resultado,
|
|
'resultado_tipo_nome' => $resultado->resultadoTipo->nome ?? null,
|
|
]));
|
|
}
|
|
|
|
private static function getResultadosExamesLaboratoriaisExameImagem($paciente)
|
|
{
|
|
$agendamentos = collect();
|
|
|
|
DB::table('exame_imagem_agendamento_exame AS agendamento_exame')
|
|
->join('parametrizacao_exame AS exame', 'exame.id', 'agendamento_exame.exame_id')
|
|
->join('exame_imagem_historico_alteracao AS historico', fn ($j) => $j
|
|
->on('historico.agendamento_exame_id', 'agendamento_exame.id')
|
|
->where('historico.id', fn ($q) => $q
|
|
->select('historico2.id')
|
|
->from('exame_imagem_historico_alteracao AS historico2')
|
|
->whereColumn('historico2.agendamento_exame_id', 'agendamento_exame.id')
|
|
->orderByDesc('historico2.created_at')
|
|
->limit(1)
|
|
)
|
|
)
|
|
->join('exame_imagem_agendamento AS agendamento', 'agendamento.id', 'agendamento_exame.agendamento_id')
|
|
->join('exame_imagem_jornada AS jornada', 'jornada.id', 'agendamento.jornada_id')
|
|
->join('cadastro_usuario AS jornada_usuario', 'jornada_usuario.id', 'jornada.usuario_id')
|
|
->join('cadastro_cidadao AS jornada_cidadao', 'jornada_cidadao.id', 'jornada_usuario.cidadao_id')
|
|
->whereIn('agendamento_exame.status_id', [FechamentoStatus::REALIZADO, FechamentoStatus::RESULTADO])
|
|
->where('agendamento.paciente_id', $paciente->id)
|
|
->where(fn ($q) => $q
|
|
->whereNotNull('agendamento_exame.resultado')
|
|
->orWhereNotNull('historico.arquivo')
|
|
)
|
|
->select(
|
|
'agendamento.id AS agendamento_id',
|
|
'agendamento_exame.id AS agendamento_exame_id',
|
|
DB::raw("CONCAT(agendamento.data, ' ', agendamento.hora_exame) AS data_hora_agendada"),
|
|
'jornada_cidadao.nome AS usuario_nome',
|
|
'exame.nome AS exame_nome',
|
|
DB::raw("IF(agendamento_exame.resultado IS NOT NULL, TRUE, FALSE) AS has_resultado"),
|
|
DB::raw("IF(agendamento_exame.arquivo IS NOT NULL, TRUE, FALSE) AS has_laudo"),
|
|
DB::raw("historico.created_at AS data_hora_resultado_laudo")
|
|
)
|
|
->get()
|
|
->map(function ($agendamentoExame) use ($agendamentos) {
|
|
|
|
$agendamento = $agendamentos->where('agendamento_id', $agendamentoExame->agendamento_id)->first();
|
|
|
|
if (is_null($agendamento)) {
|
|
|
|
$agendamento = (object) [
|
|
'origem' => 'exame-imagem',
|
|
'agendamento_id' => $agendamentoExame->agendamento_id,
|
|
'data_hora_agendada' => Carbon::create($agendamentoExame->data_hora_agendada)->format('d/m/Y \à\s H:i'),
|
|
'usuario_nome' => $agendamentoExame->usuario_nome,
|
|
'exames' => collect(),
|
|
];
|
|
|
|
$agendamentos->push($agendamento);
|
|
}
|
|
|
|
$agendamento->exames->push((object) [
|
|
'agendamento_exame_id' => $agendamentoExame->agendamento_exame_id,
|
|
'exame_nome' => $agendamentoExame->exame_nome,
|
|
'has_resultado' => (bool) $agendamentoExame->has_resultado,
|
|
'has_laudo' => (bool) $agendamentoExame->has_laudo,
|
|
'data_hora_resultado_laudo' => $agendamentoExame->data_hora_resultado_laudo,
|
|
]);
|
|
});
|
|
|
|
$agendamentos->each(function ($agendamento) {
|
|
|
|
unset($agendamento->agendamento_id);
|
|
});
|
|
|
|
return $agendamentos;
|
|
}
|
|
|
|
private static function getAvaliacaoFormData($atendimento)
|
|
{
|
|
return [
|
|
'problema_condicao' => [
|
|
'condicoes_avaliadas' => CondicaoAvaliada::whereNotIn('id', [
|
|
AtendimentoIndividualCondicaoAvaliada::PRE_NATAL,
|
|
AtendimentoIndividualCondicaoAvaliada::PUERICULTURA,
|
|
])
|
|
->orderBy('descricao')
|
|
->get(['id', 'descricao']),
|
|
'condicoes_emad' => AtendimentoDomiciliarCondicaoAvaliada::get()
|
|
->map(function($query) {
|
|
return [
|
|
'nome' => $query->nome,
|
|
'codigo' => $query->codigo
|
|
];
|
|
}),
|
|
'doencas_transmissiveis' => DoencaTransmissivel::orderBy('descricao')->get(['id', 'descricao']),
|
|
'rastreamentos' => Rastreamento::orderBy('descricao')->get(['id', 'descricao']),
|
|
'problemas_condicoes_paciente' => self::getProblemasCondicoesAtivosOuLatentes($atendimento->paciente),
|
|
'situacoes' => ProblemaCondicaoSituacao::orderBy('nome')->get(['id', 'nome']),
|
|
],
|
|
'alergia' => [
|
|
'tipos' => AlergiaTipo::orderBy('descricao')->get(['id', 'descricao']),
|
|
'criticidades' => AlergiaCriticidade::orderBy('nome')->get(['id', 'nome']),
|
|
],
|
|
'pre_natal' => self::getPreNatalFormData(),
|
|
'saude_bucal' => [
|
|
'vigilancias' => SaudeBucalVigilancia::orderBy('nome')->get(['id', 'nome']),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getProblemasCondicoesAtivosOuLatentes($paciente)
|
|
{
|
|
return AtendimentoSoapProblemaCondicao::whereIn('situacao_id', [
|
|
ProblemaCondicaoSituacaoEnum::ATIVO,
|
|
ProblemaCondicaoSituacaoEnum::LATENTE,
|
|
])
|
|
->whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
)
|
|
->whereDoesntHave('problemaCondicaoPosterior', fn ($q) => $q
|
|
->whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
)
|
|
)
|
|
->get()
|
|
->map(fn ($problemaCondicao) => array_merge(self::getLogData($problemaCondicao), [
|
|
'id' => $problemaCondicao->id,
|
|
'ciap' => [
|
|
'id' => $problemaCondicao->ciap_id,
|
|
'codigo' => $problemaCondicao->ciap->codigo ?? null,
|
|
'descricao' => $problemaCondicao->ciap->descricao ?? null,
|
|
],
|
|
'cid' => [
|
|
'id' => $problemaCondicao->cid_id,
|
|
'codigo' => $problemaCondicao->cid->codigo ?? null,
|
|
'nome' => $problemaCondicao->cid->nome ?? null,
|
|
],
|
|
'situacao_id' => $problemaCondicao->situacao_id,
|
|
'situacao_nome' => $problemaCondicao->situacao->nome,
|
|
'inicio' => is_null($problemaCondicao->inicio) ? null : $problemaCondicao->inicio->format('d/m/Y'),
|
|
'fim' => is_null($problemaCondicao->fim) ? null : $problemaCondicao->fim->format('d/m/Y'),
|
|
'observacao' => $problemaCondicao->observacao,
|
|
]));
|
|
}
|
|
|
|
private static function getPreNatalFormData()
|
|
{
|
|
return [
|
|
'gravidez_tipos' => GravidezTipo::orderBy('id')->get(['id', 'nome']),
|
|
'edemas' => GravidezEdema::orderBy('id')->get(['id', 'nome']),
|
|
];
|
|
}
|
|
|
|
private static function getPlanoFormData($atendimento, $soapRascunho)
|
|
{
|
|
$testesRapidosRealizados = self::getTestesRapidosRealizados($atendimento);
|
|
|
|
$ultimoPreAtendimento = AtendimentoPreAtendimento::whereHas('atendimento', fn ($q) =>
|
|
$q->where('paciente_id', $atendimento->paciente->id)
|
|
->whereDate('created_at', $atendimento->created_at->format('Y-m-d'))
|
|
)
|
|
->whereHas('testesRapidos')
|
|
->orderByDesc('created_at')
|
|
->first();
|
|
|
|
return [
|
|
'saude_bucal' => self::getPlanoSaudeBucalFormData($atendimento->paciente),
|
|
'encaminhamento_hospitalar' => [
|
|
'procedimento' => [
|
|
'clinicas' => AmbulatorioEncaminhamentoClinica::orderBy('nome')->get(['id', 'nome']),
|
|
'caraters_internacao' => AmbulatorioEncaminhamentoCaraterInternacao::orderBy('nome')->get(['id', 'nome']),
|
|
'documentos' => DocumentoTipo::orderBy('nome')->whereIn('id', [
|
|
DocumentoTipoEnum::CPF,
|
|
DocumentoTipoEnum::CNS,
|
|
])->get(['id', 'nome']),
|
|
],
|
|
'causa_externa' => [
|
|
'causas_externas' => \App\Models\ProntoAtendimento\Aih\CausaExterna::orderBy('nome')->get(['id', 'nome'])
|
|
->prepend(['id' => null, 'nome' => 'NÃO INFORMADO']),
|
|
'vinculos_previdencia' => \App\Models\ProntoAtendimento\Aih\VinculoPrevidencia::orderBy('nome')->get(['id', 'nome'])
|
|
->prepend(['id' => null, 'nome' => 'NÃO INFORMADO']),
|
|
],
|
|
'autorizacao' => [
|
|
'documentos' => DocumentoTipo::orderBy('nome')->whereIn('id', [
|
|
DocumentoTipoEnum::CPF,
|
|
DocumentoTipoEnum::CNS,
|
|
])->get(['id', 'nome']),
|
|
],
|
|
],
|
|
'prescricao_medicamentos' => [
|
|
'receita_tipos' => ReceitaTipo::whereIn('id', [TipoReceita::COMUM, TipoReceita::ESPECIAL])
|
|
->orderBy('nome')
|
|
->get(['id', 'nome']),
|
|
'frequencias_dose' => [
|
|
['value' => PrescricaoFrequenciaDose::INTERVALO, 'text' => 'Intervalo'],
|
|
['value' => PrescricaoFrequenciaDose::FREQUENCIA, 'text' => 'Frequência'],
|
|
['value' => PrescricaoFrequenciaDose::TURNO, 'text' => 'Turno'],
|
|
],
|
|
'intervalos' => [4, 6, 8, 12, 24],
|
|
'frequencias' => [1, 2, 3, 4],
|
|
'turnos' => Turno::orderBy('id')->get(['id', 'nome']),
|
|
'unidades_medida_tempo' => MedidaTempo::whereIn('id', [
|
|
MedidaTempoEnum::DIAS,
|
|
MedidaTempoEnum::SEMANAS,
|
|
MedidaTempoEnum::MESES,
|
|
])
|
|
->orderBy('id')
|
|
->get(['id', 'nome']),
|
|
],
|
|
'unidades_medida' => self::getUnidadesMedida(),
|
|
'solicitacao_exame_comum' => [
|
|
'kits_exames' => self::getKitsExames(),
|
|
'classificacoes_risco' => ClassificacaoRisco::orderBy('id')
|
|
->get(['id', 'nome', 'descricao_encaminhamento', 'cor']),
|
|
],
|
|
'solicitacao_exame_alto_custo' => [
|
|
'classificacoes_risco' => ClassificacaoRisco::orderBy('id')
|
|
->get(['id', 'nome', 'descricao_encaminhamento', 'cor']),
|
|
],
|
|
'solicitacao_procedimento_cirurgico' => [
|
|
'classificacoes_risco' => ClassificacaoRisco::orderBy('id')
|
|
->get(['id', 'nome', 'descricao_encaminhamento', 'cor']),
|
|
],
|
|
'atestado' => [
|
|
'modelos' => AtestadoModelo::orderBy('id')->get(['id', 'nome']),
|
|
'documento_tipos' => DocumentoTipo::whereIn('id', [
|
|
DocumentoTipoEnum::CNS,
|
|
DocumentoTipoEnum::CPF,
|
|
])
|
|
->orderBy('nome')
|
|
->get(['id', 'nome']),
|
|
],
|
|
'declaracao_comparecimento' => [
|
|
'turnos' => Turno::orderBy('id')->get(['id', 'nome']),
|
|
],
|
|
'encaminhamento' => [
|
|
'encaminhamentos' => Encaminhamento::orderBy('descricao')
|
|
->whereNotIn('id', [EncaminhamentoEnum::ENCAMINHAMENTO_INTERNO_NO_DIA])
|
|
->get(['id', 'descricao']),
|
|
'servico_especializado' => [
|
|
'especialidades' => Especialidade::where('ativo', true)
|
|
->where('encaminhamento', true)
|
|
->where(function ($q) {
|
|
$q->where('is_regulado', false)
|
|
->orWhere(function ($q2) {
|
|
$q2->where('is_regulado', true)
|
|
->whereExists(function ($sub) {
|
|
$sub->select(DB::raw(1))
|
|
->from('regulacao_parametrizacao_solicitante as solicitante')
|
|
->join('regulacao_parametrizacao_solicitante_regulador as regulador', 'regulador.solicitante_id', 'solicitante.id')
|
|
->join('regulacao_parametrizacao_solicitante_regulador_especialidade as regulador_especialidade', 'regulador_especialidade.solicitante_regulador_id', 'regulador.id')
|
|
->whereColumn('regulador_especialidade.especialidade_id', 'cadastro_especialidade.id')
|
|
->where('solicitante.infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id);
|
|
});
|
|
});
|
|
})
|
|
->orderBy('nome')
|
|
->get(['id', 'nome', 'ocupacao_id', 'exigir_peso_altura_circunferencia'])
|
|
->map(fn ($especialidade) => [
|
|
'id' => $especialidade->id,
|
|
'descricao' => "{$especialidade->ocupacao->codigo} - {$especialidade->nome}",
|
|
'exigir_peso_altura_circunferencia' => $especialidade->exigir_peso_altura_circunferencia,
|
|
]),
|
|
'classificacoes_risco' => ClassificacaoRisco::orderBy('id')
|
|
->get(['id', 'nome', 'descricao_encaminhamento', 'cor']),
|
|
],
|
|
'intersetorial' => [
|
|
'unidades' => self::getEncaminhamentoIntersetorialUnidades(),
|
|
'infraestruturas' => [],
|
|
],
|
|
],
|
|
'compartilhamento_cuidado' => [
|
|
'especialidades' => Especialidade::where('ativo', true)
|
|
->orderBy('nome')
|
|
->get(['id', 'nome', 'ocupacao_id'])
|
|
->map(fn ($especialidade) => [
|
|
'id' => $especialidade->id,
|
|
'descricao' => "{$especialidade->ocupacao->codigo} - {$especialidade->nome}",
|
|
]),
|
|
'classificacoes_risco' => ClassificacaoRisco::orderBy('id')->get(['id', 'nome', 'cor']),
|
|
],
|
|
'prescricoes_medicamentos' => self::getPrescricoesMedicamentos($atendimento->paciente, $soapRascunho),
|
|
'solicitacoes_exames_comuns' => self::getSolicitacaoExamesComuns($atendimento->paciente),
|
|
'solicitacoes_exames_alto_custo' => self::getSolicitacaoExamesAltoCusto($atendimento->paciente),
|
|
'solicitacoes_procedimentos_cirurgicos' => self::getSolicitacaoProcedimentosCirurgicos($atendimento->paciente),
|
|
'testes_rapidos' => TesteRapido::whereNotIn('id', $testesRapidosRealizados->pluck('id'))
|
|
->whereNotIn('id',
|
|
[
|
|
TesteRapidoEnum::DETECCAO_DE_HEPATITE_C,
|
|
TesteRapidoEnum::SIFILIS_NA_GESTANTE_OU_PAI_PARCEIRO,
|
|
TesteRapidoEnum::DETECCAO_DE_HIV_NA_GESTANTE_OU_PAI_PARCEIRO,
|
|
TesteRapidoEnum::DETECCAO_DE_INFECCAO_PELO_HBV
|
|
])
|
|
->orderBy('nome')
|
|
->get(['id', 'codigo', 'nome']),
|
|
'testes_rapidos_ultimo_atendimento' => $ultimoPreAtendimento->testesRapidos ?? null,
|
|
'testes_rapidos_realizados' => $testesRapidosRealizados,
|
|
'atestados' => self::getAtestados($atendimento->paciente),
|
|
'declaracoes_comparecimento' => self::getDeclaracoesComparecimento($atendimento->paciente),
|
|
'orientacoes' => self::getOrientacoes($atendimento->paciente),
|
|
'cartas_medicas' => self::getCartasMedicas($atendimento->paciente),
|
|
'encaminhamentos' => self::getEncaminhamentos($atendimento->paciente),
|
|
'exame_solicitado_avaliado' => ExameSolicitadoAvaliado::whereNotIn('id', self::getExameSolicitadosItens($atendimento))
|
|
->whereNotIn('id', [EnumExameSolicitadoAvaliado::ELETROCARDIOGRAMA, EnumExameSolicitadoAvaliado::ESPIROMETRIA, EnumExameSolicitadoAvaliado::ULTRASSONOGRAFIA_OBSTETRICA])
|
|
->orderBy('descricao')
|
|
->get(),
|
|
'exames_solicitados' => self::getExameSolicitados($atendimento),
|
|
'triagens_neonatal' => self::getTriagemNeonatalSolicitados($atendimento),
|
|
'triagem_neonatal' => TriagemNeonatal::whereNotIn('id', self::getTriagemNeonatalSolicitadosItens($atendimento))
|
|
->orderBy('descricao')
|
|
->get(),
|
|
'procedimentos_emad' => Procedimento::whereIn('codigo', [
|
|
EnumAtendimentoDomiciliarProcedimento::ACOMPANHAMENTO_PACIENTE_REABILITACAO_COMUNICACAO,
|
|
EnumAtendimentoDomiciliarProcedimento::ANTIBIOTICOTERAPIA_PARENTERAL,
|
|
EnumAtendimentoDomiciliarProcedimento::ATENDIMENTO_ACOMPANHAMENTO_PACIENTE_REABILITACAO_DESENVOLVIMENTO_MOTOR,
|
|
EnumAtendimentoDomiciliarProcedimento::ATENDIMENTO_FISIOTERAPEUTICO_PACIENTE_TRANSTORNO_RESPIRATORIO_SEM_COMPLICACOES_SISTEMICAS,
|
|
EnumAtendimentoDomiciliarProcedimento::ATEMDIMENTO_MEDICO_FINALIDADE_ATESTAR_OBITO,
|
|
EnumAtendimentoDomiciliarProcedimento::ATENDIMENTO_ACOMPANHAMENTO_REABILITACAO_MULTIPLAS_DEFICIENCIAS,
|
|
EnumAtendimentoDomiciliarProcedimento::CATETERISMO_VESICAL_ALIVIO,
|
|
EnumAtendimentoDomiciliarProcedimento::CATETERISMO_VESICAL_DEMORA,
|
|
EnumAtendimentoDomiciliarProcedimento::COLETA_MATERIAL_EXAME_LABORATORIAL,
|
|
EnumAtendimentoDomiciliarProcedimento::CUIDADOS_ESTOMAS,
|
|
EnumAtendimentoDomiciliarProcedimento::CUIDADOS_TRAQUEOSTOMIA,
|
|
EnumAtendimentoDomiciliarProcedimento::ENEMA,
|
|
EnumAtendimentoDomiciliarProcedimento::OXIGENOTERAPIA,
|
|
EnumAtendimentoDomiciliarProcedimento::RETIRADAS_PONTOS_CIRURGIAS_BASICAS,
|
|
EnumAtendimentoDomiciliarProcedimento::SONDAGEM_GASTRICA,
|
|
EnumAtendimentoDomiciliarProcedimento::TERAPIA_REIDRATACAO_ORAL,
|
|
EnumAtendimentoDomiciliarProcedimento::TERAPIA_REIDRATACAO_PARENTERAL,
|
|
EnumAtendimentoDomiciliarProcedimento::TERAPIA_FONOAUDIOLOGICA_INDIVIDUAL,
|
|
EnumAtendimentoDomiciliarProcedimento::TRATAMENTO_TRAUMATISMO,
|
|
EnumAtendimentoDomiciliarProcedimento::TRATAMENTO_REABILITACAO,
|
|
EnumAtendimentoDomiciliarProcedimento::TRAQUEOSTOMIA,
|
|
])
|
|
->groupBy('codigo')
|
|
->get()
|
|
->map(function($query){
|
|
return [
|
|
'id' => $query->id,
|
|
'nome' => $query->nome,
|
|
'codigo' => $query->codigo
|
|
];
|
|
}),
|
|
];
|
|
}
|
|
|
|
private static function getPlanoSaudeBucalFormData($paciente)
|
|
{
|
|
$odontogramasData = self::getOdontogramas($paciente);
|
|
|
|
return [
|
|
'odontograma' => self::getPlanoSaudeBucalOdontogramaFormData(),
|
|
'odontogramas' => $odontogramasData['odontogramas'],
|
|
'procedimentos' => $odontogramasData['procedimentos'],
|
|
];
|
|
}
|
|
|
|
private static function getPlanoSaudeBucalOdontogramaFormData()
|
|
{
|
|
return [
|
|
'proteses_totais' => [
|
|
['value' => 'superior', 'text' => 'Total superior'],
|
|
['value' => 'inferior', 'text' => 'Total inferior'],
|
|
],
|
|
'dentes' => [
|
|
'dente' => [
|
|
'problemas_condicoes' => self::getDentesProblemasCondicoes(),
|
|
],
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getDentesProblemasCondicoes()
|
|
{
|
|
return [
|
|
[
|
|
'dentes' => [18, 17, 16, 15, 14, 24, 25, 26, 27, 28, 48, 47, 46, 45, 44, 34, 35, 36, 37, 38],
|
|
'itens' => SaudeBucalDenteProblemaCondicao::orderBy('nome')
|
|
->whereIn('id', [
|
|
SaudeBucalDenteProblemaCondicaoEnum::AUSENTE_A,
|
|
SaudeBucalDenteProblemaCondicaoEnum::EXTRAIDO_E,
|
|
SaudeBucalDenteProblemaCondicaoEnum::HIGIDO_H,
|
|
SaudeBucalDenteProblemaCondicaoEnum::HIGIDO_SELADO_HS,
|
|
SaudeBucalDenteProblemaCondicaoEnum::PROTESE_PARCIAL_REMOVIVEL,
|
|
SaudeBucalDenteProblemaCondicaoEnum::PROTESE_TEMPORARIA,
|
|
SaudeBucalDenteProblemaCondicaoEnum::INCLUSO_I,
|
|
SaudeBucalDenteProblemaCondicaoEnum::PROTESE_CORONARIA_UNITARIA,
|
|
SaudeBucalDenteProblemaCondicaoEnum::COROA_CO,
|
|
SaudeBucalDenteProblemaCondicaoEnum::IMPLANTE,
|
|
SaudeBucalDenteProblemaCondicaoEnum::PILAR_P,
|
|
SaudeBucalDenteProblemaCondicaoEnum::NUCLEO_PINO,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RESTO_RADICULAR_RR,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RETRACAO_GENGIVAL_RG,
|
|
SaudeBucalDenteProblemaCondicaoEnum::CALCULO_DENTAL_CD,
|
|
SaudeBucalDenteProblemaCondicaoEnum::EXTRACAO_INDICADA_EI,
|
|
SaudeBucalDenteProblemaCondicaoEnum::SELANTE_INDICADO_SI,
|
|
SaudeBucalDenteProblemaCondicaoEnum::FRATURA_FR,
|
|
SaudeBucalDenteProblemaCondicaoEnum::MANCHA_BRANCA_ATIVA_M,
|
|
SaudeBucalDenteProblemaCondicaoEnum::CARIADO_C,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RESTAURADO_R,
|
|
SaudeBucalDenteProblemaCondicaoEnum::CARIE_DA_RAIZ,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RESTAURADO_COM_CARIE_RC,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RAIZ_RESTAURADA,
|
|
SaudeBucalDenteProblemaCondicaoEnum::NECESSITA_DE_TRATAMENTO_ENDODONTICO,
|
|
SaudeBucalDenteProblemaCondicaoEnum::POSSUI_LESAO_DE_FURCA,
|
|
SaudeBucalDenteProblemaCondicaoEnum::TRATAMENTO_ENDODONTICO_REALIZADO,
|
|
SaudeBucalDenteProblemaCondicaoEnum::LESAO_DE_FURCA_TRATADA,
|
|
])
|
|
->get(['id', 'nome']),
|
|
],
|
|
[
|
|
'dentes' => [13, 12, 11, 21, 22, 23, 43, 42, 41, 31, 32, 33],
|
|
'itens' => SaudeBucalDenteProblemaCondicao::orderBy('nome')
|
|
->whereIn('id', [
|
|
SaudeBucalDenteProblemaCondicaoEnum::AUSENTE_A,
|
|
SaudeBucalDenteProblemaCondicaoEnum::EXTRAIDO_E,
|
|
SaudeBucalDenteProblemaCondicaoEnum::HIGIDO_H,
|
|
SaudeBucalDenteProblemaCondicaoEnum::HIGIDO_SELADO_HS,
|
|
SaudeBucalDenteProblemaCondicaoEnum::PROTESE_PARCIAL_REMOVIVEL,
|
|
SaudeBucalDenteProblemaCondicaoEnum::PROTESE_TEMPORARIA,
|
|
SaudeBucalDenteProblemaCondicaoEnum::INCLUSO_I,
|
|
SaudeBucalDenteProblemaCondicaoEnum::PROTESE_CORONARIA_UNITARIA,
|
|
SaudeBucalDenteProblemaCondicaoEnum::COROA_CO,
|
|
SaudeBucalDenteProblemaCondicaoEnum::IMPLANTE,
|
|
SaudeBucalDenteProblemaCondicaoEnum::PILAR_P,
|
|
SaudeBucalDenteProblemaCondicaoEnum::NUCLEO_PINO,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RESTO_RADICULAR_RR,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RETRACAO_GENGIVAL_RG,
|
|
SaudeBucalDenteProblemaCondicaoEnum::CALCULO_DENTAL_CD,
|
|
SaudeBucalDenteProblemaCondicaoEnum::EXTRACAO_INDICADA_EI,
|
|
SaudeBucalDenteProblemaCondicaoEnum::SELANTE_INDICADO_SI,
|
|
SaudeBucalDenteProblemaCondicaoEnum::FRATURA_FR,
|
|
SaudeBucalDenteProblemaCondicaoEnum::MANCHA_BRANCA_ATIVA_M,
|
|
SaudeBucalDenteProblemaCondicaoEnum::CARIADO_C,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RESTAURADO_R,
|
|
SaudeBucalDenteProblemaCondicaoEnum::CARIE_DA_RAIZ,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RESTAURADO_COM_CARIE_RC,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RAIZ_RESTAURADA,
|
|
SaudeBucalDenteProblemaCondicaoEnum::NECESSITA_DE_TRATAMENTO_ENDODONTICO,
|
|
SaudeBucalDenteProblemaCondicaoEnum::TRATAMENTO_ENDODONTICO_REALIZADO,
|
|
])
|
|
->get(['id', 'nome']),
|
|
],
|
|
[
|
|
'dentes' => [55, 54, 53, 52, 51, 61, 62, 63, 64, 65, 85, 84, 83, 82, 81, 71, 72, 73, 74, 75],
|
|
'itens' => SaudeBucalDenteProblemaCondicao::orderBy('nome')
|
|
->whereIn('id', [
|
|
SaudeBucalDenteProblemaCondicaoEnum::AUSENTE_A,
|
|
SaudeBucalDenteProblemaCondicaoEnum::EXTRAIDO_E,
|
|
SaudeBucalDenteProblemaCondicaoEnum::HIGIDO_H,
|
|
SaudeBucalDenteProblemaCondicaoEnum::HIGIDO_SELADO_HS,
|
|
SaudeBucalDenteProblemaCondicaoEnum::INCLUSO_I,
|
|
SaudeBucalDenteProblemaCondicaoEnum::MANTENEDOR_DE_ESPACO_ME,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RESTO_RADICULAR_RR,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RETRACAO_GENGIVAL_RG,
|
|
SaudeBucalDenteProblemaCondicaoEnum::CALCULO_DENTAL_CD,
|
|
SaudeBucalDenteProblemaCondicaoEnum::EXTRACAO_INDICADA_EI,
|
|
SaudeBucalDenteProblemaCondicaoEnum::SELANTE_INDICADO_SI,
|
|
SaudeBucalDenteProblemaCondicaoEnum::FRATURA_FR,
|
|
SaudeBucalDenteProblemaCondicaoEnum::MANCHA_BRANCA_ATIVA_M,
|
|
SaudeBucalDenteProblemaCondicaoEnum::CARIADO_C,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RESTAURADO_R,
|
|
SaudeBucalDenteProblemaCondicaoEnum::CARIE_DA_RAIZ,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RESTAURADO_COM_CARIE_RC,
|
|
SaudeBucalDenteProblemaCondicaoEnum::RAIZ_RESTAURADA,
|
|
SaudeBucalDenteProblemaCondicaoEnum::NECESSITA_DE_TRATAMENTO_ENDODONTICO,
|
|
SaudeBucalDenteProblemaCondicaoEnum::TRATAMENTO_ENDODONTICO_REALIZADO,
|
|
])
|
|
->get(['id', 'nome']),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getOdontogramas($paciente)
|
|
{
|
|
$procedimentos = collect();
|
|
|
|
$odontogramas = AtendimentoSoapOdontograma::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
)
|
|
->orderByDesc('created_at')
|
|
->get()
|
|
->map(function ($odontograma) use ($procedimentos) {
|
|
|
|
$arcadaSuperior = $odontograma->odontogramaArcadas()
|
|
->where('arcada_id', ArcadaDentaria::SUPERIOR)
|
|
->first();
|
|
|
|
$arcadaInferior = $odontograma->odontogramaArcadas()
|
|
->where('arcada_id', ArcadaDentaria::INFERIOR)
|
|
->first();
|
|
|
|
$getDentesData = function ($arcadaId, $dente) use ($arcadaSuperior, $arcadaInferior) {
|
|
|
|
$arcada = $arcadaId === ArcadaDentaria::SUPERIOR ? $arcadaSuperior : $arcadaInferior;
|
|
|
|
$odontogramaArcadaDente = $arcada->odontogramaArcadaDentes()
|
|
->where('dente_id', $dente->id)
|
|
->first();
|
|
|
|
return [
|
|
'numero' => $dente->numero,
|
|
'fragmentos' => [
|
|
'esquerda' => ['is_tratado' => $odontogramaArcadaDente->is_fragmento_esquerda_tratado],
|
|
'cima' => ['is_tratado' => $odontogramaArcadaDente->is_fragmento_cima_tratado],
|
|
'direita' => ['is_tratado' => $odontogramaArcadaDente->is_fragmento_direita_tratado],
|
|
'baixo' => ['is_tratado' => $odontogramaArcadaDente->is_fragmento_baixo_tratado],
|
|
'centro' => ['is_tratado' => $odontogramaArcadaDente->is_fragmento_centro_tratado],
|
|
],
|
|
'problemas_condicoes' => $odontogramaArcadaDente->problemasCondicoes()
|
|
->orderBy('nome')
|
|
->pluck('nome'),
|
|
];
|
|
};
|
|
|
|
$protesesTotais = collect();
|
|
|
|
if ($arcadaSuperior->possui_protese_total) {
|
|
|
|
$protesesTotais->push('superior');
|
|
}
|
|
|
|
if ($arcadaInferior->possui_protese_total) {
|
|
|
|
$protesesTotais->push('inferior');
|
|
}
|
|
|
|
$setProcedimentoData = function ($model, $local) use ($procedimentos) {
|
|
|
|
$data = (object) array_merge(self::getLogData($model), [
|
|
'local' => $local,
|
|
'procedimentos' => collect(),
|
|
'observacao' => $model->observacao,
|
|
]);
|
|
|
|
$model->atendimentoProcedimentos
|
|
->each(function ($atendimentoProcedimento) use ($data) {
|
|
|
|
$procedimento = $atendimentoProcedimento->atendimentoProcedimento->procedimento;
|
|
$codigo = MaskUtil::getProcedimentoMasked($procedimento->codigo);
|
|
|
|
$data->procedimentos->push([
|
|
'descricao' => "{$codigo} - {$procedimento->nome}",
|
|
'quantidade' => $atendimentoProcedimento->atendimentoProcedimento->quantidade,
|
|
]);
|
|
});
|
|
|
|
$procedimentos->push($data);
|
|
};
|
|
|
|
$odontograma->odontogramaArcadas
|
|
->each(function ($odontogramaArcada) use ($setProcedimentoData) {
|
|
|
|
if ($odontogramaArcada->atendimentoProcedimentos->isNotEmpty()) {
|
|
|
|
$setProcedimentoData(
|
|
$odontogramaArcada,
|
|
$odontogramaArcada->arcada_id === ArcadaDentaria::SUPERIOR
|
|
? 'Arcada superior' : 'Arcada inferior'
|
|
);
|
|
}
|
|
|
|
$odontogramaArcada->odontogramaArcadaDentes()
|
|
->whereHas('atendimentoProcedimentos')
|
|
->get()
|
|
->each(fn ($odontogramaArcadaDente) => $setProcedimentoData(
|
|
$odontogramaArcadaDente,
|
|
"Dente {$odontogramaArcadaDente->dente->numero}"
|
|
));
|
|
});
|
|
|
|
$odontograma->dentesSupranumerarios->each(fn ($dente) => $setProcedimentoData($dente, $dente->local));
|
|
|
|
return [
|
|
'id' => $odontograma->id,
|
|
'data' => $odontograma->created_at->format('d/m/Y'),
|
|
'possui_aparelho' => $odontograma->possui_aparelho,
|
|
'possui_contencao' => $odontograma->possui_contencao,
|
|
'proteses_totais' => $protesesTotais,
|
|
'arcadas' => [
|
|
'superior' => [
|
|
'dentes' => [
|
|
'permanentes' => Dente::where('arcada_id', ArcadaDentaria::SUPERIOR)
|
|
->where('is_deciduo', false)
|
|
->orderBy('ordem')
|
|
->get()
|
|
->map(fn ($dente) => $getDentesData(ArcadaDentaria::SUPERIOR, $dente)),
|
|
'deciduos' => Dente::where('arcada_id', ArcadaDentaria::SUPERIOR)
|
|
->where('is_deciduo', true)
|
|
->orderBy('ordem')
|
|
->get()
|
|
->map(fn ($dente) => $getDentesData(ArcadaDentaria::SUPERIOR, $dente)),
|
|
],
|
|
],
|
|
'inferior' => [
|
|
'dentes' => [
|
|
'permanentes' => Dente::where('arcada_id', ArcadaDentaria::INFERIOR)
|
|
->where('is_deciduo', false)
|
|
->orderBy('ordem')
|
|
->get()
|
|
->map(fn ($dente) => $getDentesData(ArcadaDentaria::INFERIOR, $dente)),
|
|
'deciduos' => Dente::where('arcada_id', ArcadaDentaria::INFERIOR)
|
|
->where('is_deciduo', true)
|
|
->orderBy('ordem')
|
|
->get()
|
|
->map(fn ($dente) => $getDentesData(ArcadaDentaria::INFERIOR, $dente)),
|
|
],
|
|
],
|
|
],
|
|
];
|
|
});
|
|
|
|
$procedimentos = $procedimentos->sort()->values();
|
|
|
|
return compact('procedimentos', 'odontogramas');
|
|
}
|
|
|
|
private static function getUnidadesMedida()
|
|
{
|
|
return DB::table('cadastro_unidade_medida')
|
|
->whereIn('id', [
|
|
UnidadeMedidaEnum::MILIGRAMAS,
|
|
UnidadeMedidaEnum::GRAMAS,
|
|
UnidadeMedidaEnum::QUILOGRAMAS,
|
|
UnidadeMedidaEnum::CENTIMETROS,
|
|
UnidadeMedidaEnum::METROS,
|
|
UnidadeMedidaEnum::UNIDADES,
|
|
UnidadeMedidaEnum::NAO_DEFINIDO,
|
|
UnidadeMedidaEnum::LITROS,
|
|
UnidadeMedidaEnum::MILILITROS,
|
|
UnidadeMedidaEnum::UNIDADES_INTERNACIONAIS,
|
|
UnidadeMedidaEnum::MICROGRAMAS,
|
|
UnidadeMedidaEnum::DOSE,
|
|
UnidadeMedidaEnum::COMPRIMIDO,
|
|
UnidadeMedidaEnum::FRASCO,
|
|
UnidadeMedidaEnum::AMPOLA,
|
|
UnidadeMedidaEnum::ADESIVO,
|
|
UnidadeMedidaEnum::ANEL,
|
|
UnidadeMedidaEnum::APLICACAO,
|
|
UnidadeMedidaEnum::BARRA,
|
|
UnidadeMedidaEnum::BASTAO,
|
|
UnidadeMedidaEnum::BISNAGA,
|
|
UnidadeMedidaEnum::BLISTER,
|
|
UnidadeMedidaEnum::BOLSA,
|
|
UnidadeMedidaEnum::CAIXA,
|
|
UnidadeMedidaEnum::CAPSULA,
|
|
UnidadeMedidaEnum::CAPSULA_INALANTE,
|
|
UnidadeMedidaEnum::CARPULE,
|
|
UnidadeMedidaEnum::CARTAO,
|
|
UnidadeMedidaEnum::CARTELA,
|
|
UnidadeMedidaEnum::DRAGEA,
|
|
UnidadeMedidaEnum::EMPLASTRO,
|
|
UnidadeMedidaEnum::ENVELOPE,
|
|
UnidadeMedidaEnum::FLACONETE,
|
|
UnidadeMedidaEnum::FRASCO_AMPOLA,
|
|
UnidadeMedidaEnum::GLOBULO,
|
|
UnidadeMedidaEnum::LATA,
|
|
UnidadeMedidaEnum::OVULO,
|
|
UnidadeMedidaEnum::PASTILHA,
|
|
UnidadeMedidaEnum::PILULA,
|
|
UnidadeMedidaEnum::POTE,
|
|
UnidadeMedidaEnum::SACHE,
|
|
UnidadeMedidaEnum::SERINGA,
|
|
UnidadeMedidaEnum::SUPOSITORIO,
|
|
UnidadeMedidaEnum::TABLETE,
|
|
UnidadeMedidaEnum::TUBETE,
|
|
UnidadeMedidaEnum::TUBO,
|
|
UnidadeMedidaEnum::GOTAS,
|
|
UnidadeMedidaEnum::JATO,
|
|
])
|
|
->select(
|
|
'id',
|
|
'nome'
|
|
)
|
|
->orderBy('nome')
|
|
->get();
|
|
}
|
|
|
|
private static function getKitsExames()
|
|
{
|
|
return KitExame::where('tipo_id', Tipo::LABORATORIAL)
|
|
->orderBy('nome')
|
|
->get()
|
|
->map(fn ($kit) => [
|
|
'id' => $kit->id,
|
|
'nome' => $kit->nome,
|
|
'exames' => DB::table('parametrizacao_kit_exame_item')
|
|
->join(
|
|
'parametrizacao_exame',
|
|
'parametrizacao_exame.id',
|
|
'parametrizacao_kit_exame_item.exame_id'
|
|
)
|
|
->leftjoin('sigtap.procedimento', function ($join) {
|
|
|
|
$join->on('sigtap.procedimento.codigo', 'parametrizacao_exame.codigo')
|
|
->where('sigtap.procedimento.competencia_id', '=', function ($query) {
|
|
|
|
$query->select('sigtap.competencia.id')
|
|
->from('sigtap.competencia')
|
|
->orderByDesc('sigtap.competencia.valor')
|
|
->limit(1);
|
|
});
|
|
})
|
|
->whereNull('parametrizacao_kit_exame_item.deleted_at')
|
|
->where('parametrizacao_kit_exame_item.kit_exame_id', $kit->id)
|
|
->orderBy('parametrizacao_exame.nome')
|
|
->select(
|
|
'parametrizacao_exame.id',
|
|
'parametrizacao_exame.codigo',
|
|
'parametrizacao_exame.nome',
|
|
'parametrizacao_exame.tipo_id'
|
|
)
|
|
->get()
|
|
->map(fn ($exame) => [
|
|
'id' => $exame->id,
|
|
'codigo' => $exame->codigo,
|
|
'nome' => $exame->nome,
|
|
'tipo_id' => $exame->tipo_id,
|
|
])
|
|
->values()
|
|
])
|
|
->filter(fn ($kit) => count($kit['exames']) > 0)
|
|
->values();
|
|
}
|
|
|
|
private static function getEncaminhamentoIntersetorialUnidades()
|
|
{
|
|
return Unidade::whereHas('infraestruturas', fn ($q) => $q
|
|
->whereHas('ambulatorioParametrizacaoJornadaInfraestrutura')
|
|
)
|
|
->orderBy('nome_fantasia')
|
|
->get(['id', 'nome_fantasia']);
|
|
}
|
|
|
|
private static function getPrescricoesMedicamentos($paciente, $soapRascunho)
|
|
{
|
|
$prescricoesAnterioresIds = collect();
|
|
|
|
($soapRascunho->prescricoesMedicamentos ?? collect())
|
|
->each(function ($prescricao) use ($prescricoesAnterioresIds) {
|
|
|
|
$prescricao->itens->each(function ($item) use ($prescricoesAnterioresIds) {
|
|
|
|
if ($item->prescricaoMedicamentoItemAnterior
|
|
&& !$prescricoesAnterioresIds->contains($item->prescricaoMedicamentoItemAnterior->prescricao_medicamento_id)
|
|
) {
|
|
|
|
$prescricoesAnterioresIds->push($item->prescricaoMedicamentoItemAnterior->prescricao_medicamento_id);
|
|
}
|
|
});
|
|
});
|
|
|
|
return AtendimentoSoapPrescricaoMedicamento::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
)
|
|
->get()
|
|
->map(fn ($prescricao) => array_merge(self::getLogData($prescricao), [
|
|
'id' => $prescricao->id,
|
|
'revalidar' => $prescricoesAnterioresIds->contains($prescricao->id),
|
|
'medicamentos' => $prescricao->itens->map(function ($item) {
|
|
|
|
$data = null;
|
|
|
|
if ($item->is_manual) {
|
|
|
|
$data = [
|
|
'id' => $item->id,
|
|
'is_manual' => true,
|
|
'descricao' => $item->descricao,
|
|
'justificativa' => $item->justificativa,
|
|
'receita_tipo_id' => $item->receita_tipo_id
|
|
];
|
|
}
|
|
else {
|
|
|
|
if ($item->tratamento_interrompido_from_rascunho) {
|
|
|
|
$item->tratamento_interrompido_em = null;
|
|
$item->tratamento_interrompido_justificativa = null;
|
|
$item->tratamento_interrompido_soap_id = null;
|
|
}
|
|
|
|
$data = [
|
|
'id' => $item->id,
|
|
'is_manual' => false,
|
|
'dose' => $item->dose,
|
|
'frequencia_dose' => $item->frequencia_dose,
|
|
'frequencia_vezes' => $item->frequencia_vezes,
|
|
'turno_id' => $item->turno_id,
|
|
'unidade_medida_id' => $item->unidade_medida_id,
|
|
'unidade_medida' => $item->unidadeMedida->nome ?? null,
|
|
'intervalo' => $item->intervalo,
|
|
'intervalo_medida_tempo_id' => $item->intervalo_medida_tempo_id,
|
|
'duracao_medida_tempo_id' => $item->duracao_medida_tempo_id,
|
|
'material_id' => $item->material->id ?? null,
|
|
'material_descricao' => $item->material->descricao ?? null,
|
|
'material_via_administracao' => $item->material->viaAdministracao->nome ?? null,
|
|
'material_receita_tipo_id' => $item->material->receita_tipo_id ?? null,
|
|
'material_quantidade' => $item->material->quantidade ?? null,
|
|
'material_apresentacao_nome' => isset($item->material->apresentacao) ? $item->material->apresentacao->nome ?? null : null,
|
|
'material_receita_tipo' => isset($item->material->receitaTipo) ? $item->material->receitaTipo->nome ?? null : null,
|
|
'is_dose_unica' => $item->is_dose_unica,
|
|
'is_uso_continuo' => $item->is_uso_continuo,
|
|
'is_imprimir_separado' => $item->is_imprimir_separado,
|
|
'is_remover_impressao' => $item->is_remover_impressao,
|
|
'posologia' => $item->posologia,
|
|
'inicio' => $item->inicio->format('d/m/Y'),
|
|
'duracao' => $item->duracao,
|
|
'conclusao' => is_null($item->conclusao)
|
|
? null : $item->conclusao->format('d/m/Y'),
|
|
'tratamento_concluido' => !$item->is_tratamento_interrompido
|
|
&& !is_null($item->conclusao)
|
|
&& $item->conclusao->isBefore(Carbon::today()),
|
|
'is_tratamento_concluido' => $item->is_tratamento_concluido,
|
|
'is_tratamento_interrompido' => $item->is_tratamento_interrompido,
|
|
'tratamento_interrompido_em' => $item->is_tratamento_interrompido
|
|
? $item->tratamento_interrompido_em->format('d/m/Y') : null,
|
|
'tratamento_interrompido_justificativa' => $item->tratamento_interrompido_justificativa,
|
|
];
|
|
|
|
if (!$item->is_uso_continuo) {
|
|
|
|
$data['duracao_descricao'] = is_null($item->conclusao)
|
|
? 'INDETERMINADO'
|
|
: "{$item->duracao} {$item->duracaoMedidaTempo->nome}";
|
|
}
|
|
}
|
|
|
|
$data['recomendacoes'] = $item->recomendacoes;
|
|
|
|
return $data;
|
|
}),
|
|
]));
|
|
}
|
|
|
|
private static function getSolicitacaoExamesComuns($paciente)
|
|
{
|
|
return AtendimentoSoapSolicitacaoExame::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
)
|
|
->where('alto_custo', false)
|
|
->get()
|
|
->map(fn ($solicitacao) => array_merge(self::getLogData($solicitacao), [
|
|
'origem' => 'ambulatorio',
|
|
'cid_descricao' => is_null($solicitacao->cid_id)
|
|
? null : "{$solicitacao->cid->codigo} - {$solicitacao->cid->nome}",
|
|
'cid' => is_null($solicitacao->cid_id) ? null : [
|
|
'id' => $solicitacao->cid->id,
|
|
'codigo' => $solicitacao->cid->codigo,
|
|
'nome' => $solicitacao->cid->nome,
|
|
],
|
|
'ciap_descricao' => is_null($solicitacao->ciap_id)
|
|
? null : "{$solicitacao->ciap->codigo} - {$solicitacao->ciap->descricao}",
|
|
'classificacao_id' => $solicitacao->classificacao_id,
|
|
'classificacao_nome' => $solicitacao->classificacao->nome ?? null,
|
|
'justificativa' => $solicitacao->justificativa,
|
|
'observacao' => $solicitacao->observacao,
|
|
'exames' => $solicitacao->itens->map(fn ($item) => [
|
|
'descricao' => MaskUtil::getProcedimentoMasked($item->exame->codigo) . " - {$item->exame->nome}",
|
|
]),
|
|
]))
|
|
->concat(self::getResultadosExamesLaboratoriaisExameLaboratorial($paciente));
|
|
}
|
|
|
|
private static function getHistoricoSolicitacaoExamesComuns($id)
|
|
{
|
|
return AtendimentoSoapSolicitacaoExame::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('id', $id)
|
|
)
|
|
)
|
|
->where('alto_custo', false)
|
|
->get()
|
|
->map(fn ($solicitacao) => ([
|
|
'cid' => is_null($solicitacao->cid_id) ? null : [
|
|
'id' => $solicitacao->cid->id,
|
|
'codigo' => $solicitacao->cid->codigo,
|
|
'nome' => $solicitacao->cid->nome,
|
|
],
|
|
]));
|
|
}
|
|
|
|
private static function getSolicitacaoExamesAltoCusto($paciente)
|
|
{
|
|
return AtendimentoSoapSolicitacaoExame::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
)
|
|
->where('alto_custo', true)
|
|
->get()
|
|
->map(fn ($solicitacao) => array_merge(self::getLogData($solicitacao), [
|
|
'origem' => 'ambulatorio',
|
|
'cid_descricao' => is_null($solicitacao->cid_id)
|
|
? null : "{$solicitacao->cid->codigo} - {$solicitacao->cid->nome}",
|
|
'cid' => is_null($solicitacao->cid_id) ? null : [
|
|
'id' => $solicitacao->cid->id,
|
|
'codigo' => $solicitacao->cid->codigo,
|
|
'nome' => $solicitacao->cid->nome,
|
|
],
|
|
'ciap_descricao' => is_null($solicitacao->ciap_id)
|
|
? null : "{$solicitacao->ciap->codigo} - {$solicitacao->ciap->descricao}",
|
|
'justificativa' => $solicitacao->justificativa,
|
|
'observacao' => $solicitacao->observacao,
|
|
'exames' => $solicitacao->itens->map(fn ($item) => [
|
|
'descricao' => MaskUtil::getProcedimentoMasked($item->exame->codigo) . " - {$item->exame->nome}",
|
|
]),
|
|
]))
|
|
->concat(self::getResultadosExamesLaboratoriaisExameImagem($paciente));
|
|
}
|
|
|
|
private static function getSolicitacaoProcedimentosCirurgicos($paciente)
|
|
{
|
|
return AtendimentoSoapSolicitacaoProcedimentoCirurgico::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
)
|
|
->get()
|
|
->map(fn ($solicitacao) => array_merge(self::getLogData($solicitacao), [
|
|
'cid_descricao' => is_null($solicitacao->cid_id)
|
|
? null : "{$solicitacao->cid->codigo} - {$solicitacao->cid->nome}",
|
|
'ciap_descricao' => is_null($solicitacao->ciap_id)
|
|
? null : "{$solicitacao->ciap->codigo} - {$solicitacao->ciap->descricao}",
|
|
'justificativa' => $solicitacao->justificativa,
|
|
'observacao' => $solicitacao->observacao,
|
|
'procedimentos_cirurgicos' => $solicitacao->itens->map(fn ($item) => [
|
|
'descricao' => MaskUtil::getProcedimentoMasked($item->procedimentoCirurgico->procedimento_codigo)
|
|
. " - {$item->procedimentoCirurgico->nome}",
|
|
]),
|
|
]));
|
|
}
|
|
|
|
private static function getHistoricoSolicitacaoExamesAltoCusto($id)
|
|
{
|
|
return AtendimentoSoapSolicitacaoExame::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('id', $id)
|
|
)
|
|
)
|
|
->where('alto_custo', true)
|
|
->get()
|
|
->map(fn ($solicitacao) => ([
|
|
'cid' => is_null($solicitacao->cid_id) ? null : [
|
|
'id' => $solicitacao->cid->id,
|
|
'codigo' => $solicitacao->cid->codigo,
|
|
'nome' => $solicitacao->cid->nome,
|
|
],
|
|
]));
|
|
}
|
|
|
|
private static function getTestesRapidosRealizados($atendimento)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_pre_atendimento_teste_rapido as pivot')
|
|
->join('ambulatorio_atendimento_pre_atendimento as pre_atendimento', 'pre_atendimento.id', 'pivot.pre_atendimento_id')
|
|
->join('ambulatorio_teste_rapido as teste_rapido', 'teste_rapido.id', 'pivot.teste_rapido_id')
|
|
->where('pre_atendimento.atendimento_id', $atendimento->id)
|
|
->select(DB::raw("
|
|
teste_rapido.id,
|
|
teste_rapido.nome,
|
|
pivot.resultado
|
|
"))
|
|
->union(DB::table('ambulatorio_atendimento_soap_teste_rapido as pivot')
|
|
->join('ambulatorio_atendimento_soap as soap', 'soap.id', 'pivot.soap_id')
|
|
->join('ambulatorio_teste_rapido as teste_rapido', 'teste_rapido.id', 'pivot.teste_rapido_id')
|
|
->where('soap.is_rascunho', false)
|
|
->where('soap.atendimento_id', $atendimento->id)
|
|
->select(DB::raw("
|
|
teste_rapido.id,
|
|
teste_rapido.nome,
|
|
pivot.resultado
|
|
"))
|
|
)
|
|
->orderBy('nome')
|
|
->get();
|
|
}
|
|
|
|
private static function getExamesAvaliados($atendimento)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_soap_exame_avaliado as pivot')
|
|
->join('ambulatorio_atendimento_soap as soap', 'soap.id', 'pivot.soap_id')
|
|
->join('atencao_basica_cadastro_exame_solicitado_avaliado as exame_avaliado', 'exame_avaliado.id', 'pivot.exame_solicitado_avaliado_id')
|
|
->where('soap.is_rascunho', false)
|
|
->where('soap.atendimento_id', $atendimento->id)
|
|
->select(DB::raw("
|
|
exame_avaliado.id,
|
|
exame_avaliado.descricao,
|
|
pivot.solicitado_em,
|
|
pivot.realizado_em,
|
|
pivot.resultado_em,
|
|
pivot.resultado
|
|
"))
|
|
->orderBy('descricao')
|
|
->get();
|
|
}
|
|
|
|
private static function getExameSolicitados($atendimento)
|
|
{
|
|
return AtendimentoSoapExameSolicitado::whereHas('soap', function ($q) use ($atendimento) {
|
|
$q->where('is_rascunho', false)->where('atendimento_id', $atendimento->id);
|
|
})
|
|
->get()
|
|
->map(function ($solicitacao) {
|
|
|
|
return [
|
|
'cid_descricao' => is_null($solicitacao->cid_id)
|
|
? null : "{$solicitacao->cid->codigo} - {$solicitacao->cid->nome}",
|
|
'ciap_descricao' => is_null($solicitacao->ciap_id)
|
|
? null : "{$solicitacao->ciap->codigo} - {$solicitacao->ciap->descricao}",
|
|
'justificativa' => $solicitacao->justificativa,
|
|
'observacao' => $solicitacao->observacao,
|
|
'exames' => $solicitacao->examesSolicitados->map(function ($item) {
|
|
return [
|
|
'id' => $item->id,
|
|
'descricao' => $item->descricao,
|
|
];
|
|
}),
|
|
];
|
|
});
|
|
}
|
|
|
|
private static function getTriagemNeonatalSolicitados($atendimento)
|
|
{
|
|
return AtendimentoSoapTriagemNeonatalSolicitado::whereHas('soap', function ($q) use ($atendimento) {
|
|
$q->where('is_rascunho', false)->where('atendimento_id', $atendimento->id);
|
|
})
|
|
->get()
|
|
->map(function ($solicitacao) {
|
|
|
|
return [
|
|
'cid_descricao' => is_null($solicitacao->cid_id)
|
|
? null : "{$solicitacao->cid->codigo} - {$solicitacao->cid->nome}",
|
|
'ciap_descricao' => is_null($solicitacao->ciap_id)
|
|
? null : "{$solicitacao->ciap->codigo} - {$solicitacao->ciap->descricao}",
|
|
'justificativa' => $solicitacao->justificativa,
|
|
'observacao' => $solicitacao->observacao,
|
|
'exames' => $solicitacao->triagensNeonatalSolicitados->map(function ($item) {
|
|
return [
|
|
'id' => $item->id,
|
|
'descricao' => $item->descricao,
|
|
];
|
|
}),
|
|
];
|
|
});
|
|
}
|
|
|
|
private static function getExameSolicitadosItens($atendimento)
|
|
{
|
|
|
|
$ids = [];
|
|
|
|
AtendimentoSoapExameSolicitado::whereHas('soap', function ($q) use ($atendimento) {
|
|
$q->where('is_rascunho', false)->where('atendimento_id', $atendimento->id);
|
|
})
|
|
->get()
|
|
->map(function ($solicitacao) use (&$ids) {
|
|
|
|
$solicitacao->examesSolicitados->map(function ($item) use (&$ids) {
|
|
|
|
$ids[] = $item->id;
|
|
});
|
|
});
|
|
|
|
return $ids;
|
|
}
|
|
|
|
private static function getTriagemNeonatalSolicitadosItens($atendimento)
|
|
{
|
|
|
|
$ids = [];
|
|
|
|
AtendimentoSoapTriagemNeonatalSolicitado::whereHas('soap', function ($q) use ($atendimento) {
|
|
$q->where('is_rascunho', false)->where('atendimento_id', $atendimento->id);
|
|
})
|
|
->get()
|
|
->map(function ($solicitacao) use (&$ids) {
|
|
$solicitacao->triagensNeonatalSolicitados->map(function ($item) use (&$ids) {
|
|
|
|
$ids[] = $item->id;
|
|
});
|
|
});
|
|
|
|
return $ids;
|
|
}
|
|
|
|
private static function getTriagensNeoNatal($atendimento)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_soap_triagem_neonatal as pivot')
|
|
->join('ambulatorio_atendimento_soap as soap', 'soap.id', 'pivot.soap_id')
|
|
->join('atencao_basica_cadastro_triagem_neonatal as triagem_neonatal', 'triagem_neonatal.id', 'pivot.triagem_neonatal_id')
|
|
->where('soap.is_rascunho', false)
|
|
->where('soap.atendimento_id', $atendimento->id)
|
|
->select(DB::raw("
|
|
triagem_neonatal.id,
|
|
triagem_neonatal.descricao,
|
|
pivot.solicitado_em,
|
|
pivot.realizado_em,
|
|
pivot.resultado_em,
|
|
pivot.resultado
|
|
"))
|
|
->orderBy('descricao')
|
|
->get();
|
|
}
|
|
|
|
private static function getAtestados($paciente)
|
|
{
|
|
return AtendimentoSoapAtestado::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
)
|
|
->get()
|
|
->map(fn ($atestado) => array_merge(self::getLogData($atestado), [
|
|
'modelo_id' => $atestado->modelo_id,
|
|
'descricao' => $atestado->descricao,
|
|
'is_atestado_acompanhante' => $atestado->is_atestado_acompanhante,
|
|
'nome' => $atestado->is_atestado_acompanhante
|
|
? $atestado->nome_acompanhante
|
|
: $paciente->cidadao->nome,
|
|
'documento_tipo_id' => $atestado->documento_tipo_id,
|
|
'cpf' => MaskUtil::getCpfMasked($atestado->cpf),
|
|
'cns' => MaskUtil::getCnsMasked($atestado->cns),
|
|
'data' => is_null($atestado->data) ? null : $atestado->data->format('d/m/Y'),
|
|
'horario' => is_null($atestado->horario) ? null : $atestado->horario->format('H:i'),
|
|
'dias' => $atestado->dias,
|
|
'quantidade_horas' => $atestado->quantidade_horas,
|
|
'horario_inicial' => is_null($atestado->horario_inicial) ? null : $atestado->horario_inicial->format('H:i'),
|
|
'cid' => $atestado->cid ? [
|
|
'id' => $atestado->cid->id,
|
|
'codigo' => $atestado->cid->codigo,
|
|
'nome' => $atestado->cid->nome,
|
|
] : null,
|
|
]));
|
|
}
|
|
|
|
private static function getHistoricoAtestados($id)
|
|
{
|
|
return AtendimentoSoapAtestado::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('id', $id)
|
|
)
|
|
)
|
|
->get()
|
|
->map(fn ($atestado) => ([
|
|
'cid' => $atestado->cid ? [
|
|
'id' => $atestado->cid->id,
|
|
'codigo' => $atestado->cid->codigo,
|
|
'nome' => $atestado->cid->nome,
|
|
] : null,
|
|
]));
|
|
}
|
|
|
|
private static function getDeclaracoesComparecimento($paciente)
|
|
{
|
|
return AtendimentoDeclaracaoComparecimento::whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
->where(fn ($q) => $q
|
|
->whereDoesntHave('soap')
|
|
->orWhereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
)
|
|
)
|
|
->get()
|
|
->map(fn ($declaracao) => array_merge(self::getLogData($declaracao), [
|
|
'id' => $declaracao->id,
|
|
'nome_acompanhante' => $declaracao->nome_acompanhante ?? null,
|
|
'motivo_comparecimento' => $declaracao->motivo_comparecimento ?? null,
|
|
'turno_nome' => $declaracao->turno->nome ?? null,
|
|
'entrada' => is_null($declaracao->entrada) ? null : $declaracao->entrada->format('H:i'),
|
|
'saida' => is_null($declaracao->saida) ? null : $declaracao->saida->format('H:i'),
|
|
]));
|
|
}
|
|
|
|
private static function getOrientacoes($paciente)
|
|
{
|
|
return AtendimentoSoapOrientacao::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
)
|
|
->get()
|
|
->map(fn ($orientacao) => array_merge(self::getLogData($orientacao), [
|
|
'descricao' => $orientacao->descricao,
|
|
]));
|
|
}
|
|
|
|
private static function getCartasMedicas($paciente)
|
|
{
|
|
return AtendimentoSoapCartaMedica::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
)
|
|
->get()
|
|
->map(fn ($cartaMedica) => array_merge(self::getLogData($cartaMedica), [
|
|
'descricao' => $cartaMedica->descricao,
|
|
]));
|
|
}
|
|
|
|
private static function getEncaminhamentos($paciente)
|
|
{
|
|
return AtendimentoSoapEncaminhamento::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
)
|
|
->get()
|
|
->map(fn ($orientacao) => array_merge(self::getLogData($orientacao), [
|
|
'tipo_id' => $orientacao->tipo_id,
|
|
'tipo_descricao' => $orientacao->tipo->descricao,
|
|
'servico_especializado_especialidade_nome' => $orientacao->servicoEspecializadoEspecialidade
|
|
->nome ?? null,
|
|
'servico_especializado_complemento' => $orientacao->servico_especializado_complemento ?? ' - ',
|
|
'servico_especializado_cid_descricao' => is_null($orientacao->servico_especializado_cid_id)
|
|
? ' - '
|
|
: MaskUtil::getCidMasked($orientacao->servicoEspecializadoCid->codigo)
|
|
. ' - ' . $orientacao->servicoEspecializadoCid->nome,
|
|
'cid' => is_null($orientacao->servicoEspecializadoCid) ? null : [
|
|
'id' => $orientacao->servicoEspecializadoCid->id,
|
|
'codigo' => $orientacao->servicoEspecializadoCid->codigo,
|
|
'nome' => $orientacao->servicoEspecializadoCid->nome,
|
|
],
|
|
'servico_especializado_ciap_descricao' => is_null($orientacao->servico_especializado_ciap_id)
|
|
? ' - '
|
|
: $orientacao->servicoEspecializadoCiap->codigo . ' - ' . $orientacao->servicoEspecializadoCiap->descricao,
|
|
'servico_especializado_classificacao_risco_nome' => $orientacao->servicoEspecializadoClassificacaoRisco
|
|
->nome ?? null,
|
|
'servico_especializado_motivo' => $orientacao->servico_especializado_motivo,
|
|
'servico_especializado_observacao' => $orientacao->servico_especializado_observacao,
|
|
'intersetorial_unidade_nome_fantasia' => is_null($orientacao->intersetorial_infraestrutura_id)
|
|
? null
|
|
: $orientacao->intersetorialInfraestrutura->unidade->nome_fantasia,
|
|
'intersetorial_infraestrutura_nome' => is_null($orientacao->intersetorial_infraestrutura_id)
|
|
? null
|
|
: $orientacao->intersetorialInfraestrutura->nome,
|
|
]));
|
|
}
|
|
|
|
private static function getHistoricoEncaminhamentos($id)
|
|
{
|
|
return AtendimentoSoapEncaminhamento::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('id', $id)
|
|
)
|
|
)
|
|
->get()
|
|
->map(fn ($orientacao) => ([
|
|
'cid' => is_null($orientacao->servicoEspecializadoCid) ? null : [
|
|
'id' => $orientacao->servicoEspecializadoCid->id,
|
|
'codigo' => $orientacao->servicoEspecializadoCid->codigo,
|
|
'nome' => $orientacao->servicoEspecializadoCid->nome,
|
|
],
|
|
]));
|
|
}
|
|
|
|
private static function getFinalizacaoFormData($atendimento, $fila = null)
|
|
{
|
|
$especialidadeId = $atendimento->is_demanda_espontanea ? ($atendimento->especialidade->id ?? null) : null;
|
|
$demandaEspontaneaObservaVagaAtendimento = self::demandaEspontaneaObservaVagaAtendimento($especialidadeId);
|
|
|
|
$paciente = $atendimento->paciente;
|
|
|
|
$desfechoParams = [
|
|
'paciente_id' => $paciente->id,
|
|
'paciente_nao_municipe' => $paciente->classificacao_id !== Classificacao::MUNICIPE,
|
|
'infraestrutura_id' => self::getCurrentCentroCusto()->infraestrutura_id,
|
|
'data' => Carbon::today(),
|
|
];
|
|
|
|
$usuarios = self::getUsuariosWithJornada((object) $desfechoParams);
|
|
$ocupacoes = [];
|
|
|
|
if (!is_null($atendimento->usuario)) {
|
|
|
|
$ocupacoes = self::getOcupacoesWithJornada((object) array_merge($desfechoParams, [
|
|
'usuario_id' => $atendimento->usuario->id,
|
|
]));
|
|
}
|
|
|
|
$especialidades = [];
|
|
|
|
if (!is_null($atendimento->ocupacao)) {
|
|
|
|
$especialidades = self::getEspecialidadesWithJornada((object) array_merge($desfechoParams, [
|
|
'usuario_id' => $atendimento->usuario->id,
|
|
'ocupacao_id' => $atendimento->ocupacao->id,
|
|
]));
|
|
}
|
|
|
|
$atendimentoTipos = TipoAtendimento::whereIn('id', [
|
|
TipoAtendimentoEnum::CONSULTA_AGENDADA_PROGRAMADA,
|
|
TipoAtendimentoEnum::CONSULTA_AGENDADA,
|
|
TipoAtendimentoEnum::ESCUTA_INICIAL_ORIENTACAO,
|
|
TipoAtendimentoEnum::CONSULTA_NO_DIA,
|
|
TipoAtendimentoEnum::ATENDIMENTO_DE_URGENCIA,
|
|
])->orderBy('descricao')->get(['id', 'descricao'])->map(fn ($tipo) => [
|
|
'id' => $tipo->id,
|
|
'nome' => $tipo->descricao,
|
|
'is_demanda_espontanea' => collect([
|
|
TipoAtendimentoEnum::ESCUTA_INICIAL_ORIENTACAO,
|
|
TipoAtendimentoEnum::CONSULTA_NO_DIA,
|
|
TipoAtendimentoEnum::ATENDIMENTO_DE_URGENCIA,
|
|
])->contains($tipo->id)
|
|
]);
|
|
|
|
$jornadas = [];
|
|
|
|
if ($atendimento->is_demanda_espontanea) {
|
|
if ($demandaEspontaneaObservaVagaAtendimento) {
|
|
if (!is_null($atendimento->usuario) && !is_null($atendimento->ocupacao)) {
|
|
$jornadas = self::getJornadas((object) [
|
|
'data' => $atendimento->created_at->format('Y-m-d'),
|
|
'usuario_id' => $atendimento->usuario->id,
|
|
'ocupacao_id' => $atendimento->ocupacao->id,
|
|
'infraestrutura_id' => $desfechoParams['infraestrutura_id'],
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
|
|
return [
|
|
'demanda_tipos' => self::getDemandaTipos(),
|
|
'atendimento_tipos' => $atendimentoTipos,
|
|
'casos_suspeitos' => CasoSuspeito::orderBy('nome')->get()->map(fn ($casoSuspeito) => [
|
|
'id' => $casoSuspeito->id,
|
|
'nome' => $casoSuspeito->nome,
|
|
'cids' => $casoSuspeito->cids()->pluck('cid_id'),
|
|
'gera_impressao' => $casoSuspeito->gera_impressao,
|
|
]),
|
|
'racionalidades_saude' => RacionalidadeSaude::orderBy('descricao')->get(['id', 'descricao']),
|
|
'condutas' => Conduta::whereNotIn('id', [AtendimentoIndividualConduta::AGENDAMENTO_PARA_NASF])->orderBy('descricao')->get(['id', 'descricao', 'codigo_esus']),
|
|
'saude_bucal' => [
|
|
'consulta_tipos' => TipoConsulta::orderBy('id')->get(['id', 'descricao']),
|
|
'fornecimentos' => SaudeBucalFornecimento::orderBy('nome')->get(['id', 'nome']),
|
|
],
|
|
'equipes' => self::getEquipesUsuarioLogado(),
|
|
'locais_atendimento' => LocalAtendimento::orderBy('descricao')->get(['id', 'descricao']),
|
|
'turnos' => Turno::orderBy('id')->get(['id', 'nome']),
|
|
'cuidador' => Cuidador::orderBy('id')->get(),
|
|
'desfecho' => [
|
|
'usuarios' => $usuarios,
|
|
'ocupacoes' => $ocupacoes,
|
|
'especialidades' => $especialidades,
|
|
'jornadas' => $jornadas,
|
|
'opcoes_entrada' => $fila
|
|
? OpcaoEntrada::where('id', $fila->opcao_entrada_id)->get(['id', 'nome', 'prioridade_obrigatoria'])
|
|
: collect(),
|
|
'prioridades' => Prioridade::orderBy('nome')->get(['id', 'nome']),
|
|
'servicos' => Servico::orderBy('nome')
|
|
->whereHas('parametrizacoesInfraestrutura', fn ($q) => $q
|
|
->where('infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id)
|
|
)
|
|
->get(['id', 'tipo_id', 'nome']),
|
|
'centros_custo_encaminhamento' => self::getCentrosCustoEncaminhamento(),
|
|
],
|
|
'conduta_desfecho' => CondutaDesfecho::get(),
|
|
'modalidades' => ModalidadeAtencaoDomiciliar::whereIn('id', [
|
|
Modalidade::AD_1,
|
|
Modalidade::AD_2,
|
|
Modalidade::AD_3,
|
|
])->get(),
|
|
'tipos_atendimento' => TipoAtendimento::whereIn('id', [
|
|
AtencaoBasicaTipoAtendimento::ATENDIMENTO_PROGRAMADO,
|
|
AtencaoBasicaTipoAtendimento::ATENDIMENTO_NAO_PROGRAMADO,
|
|
])->get(),
|
|
'procedencias' => Procedencia::orderBy('descricao')->get(),
|
|
'conclusao' => Conclusao::orderBy('id')->get(),
|
|
'elegivel' => JustificativaConclusao::where('elegivel', true)->orderBy('id')->get(),
|
|
'inelegivel' => JustificativaConclusao::where('elegivel', false)->orderBy('id')->get(),
|
|
'ocis_etapas_clinicas' => [
|
|
['id' => EtapaClinicaEnum::RETORNO, 'nome' => 'Retorno'],
|
|
['id' => EtapaClinicaEnum::TRATAMENTO, 'nome' => 'Continuidade do tratamento'],
|
|
['id' => EtapaClinicaEnum::REABILITACAO, 'nome' => 'Paciente em reabilitação'],
|
|
['id' => EtapaClinicaEnum::ALTA, 'nome' => 'Alta'],
|
|
],
|
|
'apac_motivos_saida_permanencia' => ApacMotivoSaidaPermanencia::whereIn('id', [
|
|
EnumsApacMotivoSaidaPermanencia::ALTA_CURADO,
|
|
EnumsApacMotivoSaidaPermanencia::ALTA_MELHORADO,
|
|
EnumsApacMotivoSaidaPermanencia::ALTA_A_PEDIDO,
|
|
EnumsApacMotivoSaidaPermanencia::ALTA_COM_PREVISAO_DE_RETORNO_PARA_ACOMPANHAMENTO_DO_PACIENTE,
|
|
])->orderBy('nome')->get(['id', 'nome'])
|
|
];
|
|
}
|
|
|
|
private static function getCentrosCustoEncaminhamento($centroCustoId = null)
|
|
{
|
|
|
|
if (is_null($centroCustoId)) {
|
|
|
|
return ModelPainelSenhaEncaminhamento::where('centro_custo_id_de', self::getCurrentCentroCusto()->id)
|
|
->whereHas('centroCustoPara', fn ($q) => $q
|
|
->whereHas('setor', fn ($q) => $q
|
|
->whereIn('tipo_id', [
|
|
SetorTIpo::ENFERMAGEM,
|
|
SetorTipo::CONSULTORIO
|
|
])
|
|
)
|
|
)
|
|
->get()
|
|
->map(fn ($encaminhamento) => [
|
|
'id' => $encaminhamento->centroCustoPara->id,
|
|
'setor_tipo_id' => $encaminhamento->centroCustoPara->setor->tipo_id,
|
|
'setor_nome' => $encaminhamento->centroCustoPara->setor->nome,
|
|
]);
|
|
}
|
|
|
|
return CentroCusto::where('id', $centroCustoId)
|
|
->get()
|
|
->map(fn ($centroCusto) => [
|
|
'id' => $centroCusto->id,
|
|
'setor_tipo_id' => $centroCusto->setor->tipo_id,
|
|
'setor_nome' => $centroCusto->setor->nome,
|
|
]);
|
|
}
|
|
|
|
private static function getEquipesUsuarioLogado()
|
|
{
|
|
$lotacao = self::getCurrentLotacao();
|
|
|
|
return Equipe::where('infraestrutura_id', $lotacao->infraestrutura_id)
|
|
->whereHas('usuarios', function ($q) use ($lotacao) {
|
|
$q->where('cadastro_usuario.id', $lotacao->usuario_id)
|
|
->where('atencao_basica_parametrizacao_equipe_usuario.ativo', 1);
|
|
})
|
|
->get()
|
|
->map(fn($equipe) => [
|
|
'id' => $equipe->id,
|
|
'descricao' => "INE: {$equipe->area->numero_ine} - Área: {$equipe->area->descricao}"
|
|
. (is_null($equipe->microarea_id) ? '' : " - Microárea: {$equipe->microarea->descricao}"),
|
|
])
|
|
->sortBy('descricao')
|
|
->values();
|
|
}
|
|
|
|
public static function getHistorico($pacienteId)
|
|
{
|
|
$historicoAmbulatorio = AtendimentoHistoricoService::getHistoricoResumido(
|
|
['paciente_id' => $pacienteId],
|
|
['format_date_time' => false]
|
|
);
|
|
|
|
$historicoAmbulatorio->each(function ($atendimento) {
|
|
|
|
$atendimento->origem = 'ambulatorio';
|
|
$atendimento->timestamp = $atendimento->data_hora;
|
|
});
|
|
|
|
$historicoAtencaoBasicaVisitaDomiciliar = VisitaDomiciliarHistoricoService::getHistoricoResumido(
|
|
['paciente_id' => $pacienteId],
|
|
['format_date' => false]
|
|
);
|
|
|
|
$historicoAtencaoBasicaVisitaDomiciliar->each(function ($atendimento) {
|
|
|
|
$atendimento->origem = 'atencao-basica-visita-domiciliar';
|
|
$atendimento->timestamp = $atendimento->data;
|
|
});
|
|
|
|
$historicoProntoAtendimento = ProntoAtendimentoHistoricoService::getHistoricoResumido(
|
|
['paciente_id' => $pacienteId],
|
|
['format_date_time' => false]
|
|
);
|
|
|
|
$historicoProntoAtendimento->each(function ($atendimento) {
|
|
|
|
$atendimento->origem = 'pronto-atendimento';
|
|
$atendimento->timestamp = $atendimento->data_hora;
|
|
});
|
|
|
|
$historico = $historicoAmbulatorio
|
|
->concat($historicoAtencaoBasicaVisitaDomiciliar)
|
|
->concat($historicoProntoAtendimento)
|
|
->sortByDesc('timestamp')
|
|
->values();
|
|
|
|
$historico->each(function ($atendimento) {
|
|
|
|
if ($atendimento->origem === 'ambulatorio' || $atendimento->origem === 'pronto-atendimento') {
|
|
|
|
$atendimento->data_hora = $atendimento->data_hora->format('d/m/Y');
|
|
}
|
|
else if ($atendimento->origem === 'atencao-basica-visita-domiciliar') {
|
|
|
|
$atendimento->data = $atendimento->data->format('d/m/Y');
|
|
}
|
|
|
|
$atendimento->selecionado = false;
|
|
|
|
unset($atendimento->timestamp);
|
|
});
|
|
|
|
return $historico;
|
|
}
|
|
|
|
private static function getUsuariosWithJornada($params)
|
|
{
|
|
return Usuario::setEagerLoads([])
|
|
->whereHas('lotacoes', fn ($q) => $q
|
|
->where('infraestrutura_id', $params->infraestrutura_id)
|
|
->whereHas('ambulatorioJornadas', fn ($q) => $q
|
|
->whereNotNull('quantidade_consulta')
|
|
->whereNull('situacao_id')
|
|
->whereDate('data', $params->data)
|
|
->whereHas('especialidade', fn ($q) =>
|
|
$q->where('encaminhamento', true)
|
|
->where(function ($q) {
|
|
$q->where(function ($q) {
|
|
$q->where('is_regulado', true)
|
|
->whereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('regulacao_parametrizacao_data_desejada_especialidade')
|
|
->whereColumn('regulacao_parametrizacao_data_desejada_especialidade.especialidade_id', 'cadastro_especialidade.id')
|
|
);
|
|
})
|
|
->orWhere('is_regulado', false);
|
|
})
|
|
)
|
|
)
|
|
)
|
|
->get(['id', 'cidadao_id'])
|
|
->map(fn ($usuario) => [
|
|
'id' => $usuario->id,
|
|
'nome' => $usuario->cidadao()->setEagerLoads([])->first(['nome'])->nome,
|
|
])
|
|
->sortBy('nome')
|
|
->values();
|
|
}
|
|
|
|
private static function getOcupacoesWithJornada($params)
|
|
{
|
|
return DB::table('sigtap.ocupacao as ocupacao')
|
|
->whereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('cadastro_lotacao as lotacao')
|
|
->whereColumn('lotacao.ocupacao_id', 'ocupacao.id')
|
|
->where('lotacao.usuario_id', $params->usuario_id)
|
|
->where('lotacao.infraestrutura_id', $params->infraestrutura_id)
|
|
->whereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('ambulatorio_jornada as jornada')
|
|
->join(
|
|
'cadastro_especialidade as especialidade',
|
|
'especialidade.id',
|
|
'jornada.especialidade_id'
|
|
)
|
|
->whereColumn('jornada.lotacao_id', 'lotacao.id')
|
|
->whereNotNull('jornada.quantidade_consulta')
|
|
->whereNull('jornada.situacao_id')
|
|
->whereDate('jornada.data', $params->data)
|
|
->where(fn ($query) => self::setCadastroWhereEspecialidadePaciente(
|
|
$query,
|
|
$params->paciente_id,
|
|
'especialidade'
|
|
))
|
|
->when($params->paciente_nao_municipe, fn ($q) => $q
|
|
->where('especialidade.permite_agendamento_nao_municipe', true)
|
|
)
|
|
->where('especialidade.encaminhamento', true)
|
|
)
|
|
)
|
|
->orderByRaw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome)")
|
|
->select(DB::raw("
|
|
ocupacao.id,
|
|
CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) as descricao
|
|
"))
|
|
->get();
|
|
}
|
|
|
|
private static function getEspecialidadesWithJornada($params)
|
|
{
|
|
return Especialidade::where(fn ($q) => self::setCadastroWhereEspecialidadePaciente($q, $params->paciente_id))
|
|
->whereHas('ambulatorioJornadas', fn ($q) => $q
|
|
->whereNotNull('quantidade_consulta')
|
|
->whereNull('situacao_id')
|
|
->whereDate('data', $params->data)
|
|
->whereHas('lotacao', fn ($q) => $q
|
|
->where('infraestrutura_id', $params->infraestrutura_id)
|
|
->where('usuario_id', $params->usuario_id)
|
|
->where('ocupacao_id', $params->ocupacao_id)
|
|
)
|
|
)
|
|
->when($params->paciente_nao_municipe, fn ($q) => $q
|
|
->where('permite_agendamento_nao_municipe', true)
|
|
)
|
|
->where('encaminhamento', true)
|
|
->orderBy('nome')
|
|
->get()
|
|
->map(fn ($q) => [
|
|
'id' => $q->id,
|
|
'nome' => $q->nome,
|
|
'demanda_espontanea_observa_vaga_atendimento' => $q->ambulatorioParametrizacoesInfraestruturaEspecialidade()
|
|
->whereHas('parametrizacaoInfraestrutura', fn ($q) => $q->where('infraestrutura_id', $params->infraestrutura_id))
|
|
->first()->demanda_espontanea_observa_vaga_atendimento ?? false,
|
|
]);
|
|
}
|
|
|
|
private static function setCadastroWhereEspecialidadePaciente($query, $pacienteId, $tableAlias = '')
|
|
{
|
|
if (!empty($tableAlias)) {
|
|
|
|
$tableAlias .= '.';
|
|
}
|
|
|
|
$paciente = Paciente::find($pacienteId);
|
|
$idade = $paciente->cidadao->idade;
|
|
|
|
return $query->where(fn ($q) => $q
|
|
->when($idade, fn ($q) => $q
|
|
->where(fn ($q) => $q
|
|
->whereNull("{$tableAlias}idade_minima")
|
|
->orWhere("{$tableAlias}idade_minima", '<=', $idade['anos'])
|
|
)
|
|
->where(fn ($q) => $q
|
|
->whereNull("{$tableAlias}idade_maxima")
|
|
->orWhere("{$tableAlias}idade_maxima", '>=', $idade['anos'])
|
|
)
|
|
)
|
|
->where(fn ($q) => $q
|
|
->whereNull("{$tableAlias}sexo_id")
|
|
->orWhere("{$tableAlias}sexo_id", $paciente->cidadao->sexo_id)
|
|
)
|
|
);
|
|
}
|
|
|
|
private static function getModelData($atendimento, $soapRascunho, $fila = null)
|
|
{
|
|
return [
|
|
'soap' => [
|
|
'id' => $soapRascunho->id ?? null,
|
|
'medicoes' => self::getMedicoesModelData($soapRascunho),
|
|
'feridas' => self::getFeridasModelData($atendimento),
|
|
'medicamentos_em_uso' => self::getMedicamentosEmUsoModelData($soapRascunho),
|
|
'raas' => self::getRaasModelData($atendimento),
|
|
'antecedentes' => self::getAntecedentesModelData($atendimento->paciente, $soapRascunho),
|
|
'subjetivo' => self::getSubjetivoModelData($soapRascunho),
|
|
'objetivo' => self::getObjetivoModelData($atendimento, $soapRascunho),
|
|
'avaliacao' => self::getAvaliacaoModelData($atendimento->paciente, $soapRascunho),
|
|
'plano' => self::getPlanoModelData($atendimento, $soapRascunho),
|
|
'finalizacao' => self::getFinalizacaoModelData($atendimento, $soapRascunho, $fila),
|
|
'oci' => self::getOciModelData($atendimento, $soapRascunho),
|
|
'perfis_epidemiologicos' => $soapRascunho ? $soapRascunho->perfisEpidemiologicos->pluck('id') : collect(),
|
|
'observacao_perfil_epidemiologico' => $soapRascunho->observacao_perfil_epidemiologico ?? null,
|
|
'ivcf' => [
|
|
'deseja_preencher' => $soapRascunho && $soapRascunho->ivcf ? true : false,
|
|
'estado_saude_geral' => $soapRascunho->ivcf->estado_saude_geral ?? null,
|
|
'limitacao_compras' => $soapRascunho->ivcf->limitacao_compras ?? null,
|
|
'limitacao_gestao_financeira' => $soapRascunho->ivcf->limitacao_gestao_financeira ?? null,
|
|
'limitacao_tarefas_domesticas' => $soapRascunho->ivcf->limitacao_tarefas_domesticas ?? null,
|
|
'banho_independencia' => $soapRascunho->ivcf->banho_independencia ?? null,
|
|
'relato_esquecimento_por_terceiros' => $soapRascunho->ivcf->relato_esquecimento_por_terceiros ?? null,
|
|
'esquecimento_piorando' => $soapRascunho->ivcf->esquecimento_piorando ?? null,
|
|
'esquecimento_impacta_atividades' => $soapRascunho->ivcf->esquecimento_impacta_atividades ?? null,
|
|
'humor_tristeza_desanimo' => $soapRascunho->ivcf->humor_tristeza_desanimo ?? null,
|
|
'perda_interesse_atividades' => $soapRascunho->ivcf->perda_interesse_atividades ?? null,
|
|
'limitacao_elevar_bracos' => $soapRascunho->ivcf->limitacao_elevar_bracos ?? null,
|
|
'limitacao_motricidade_fina' => $soapRascunho->ivcf->limitacao_motricidade_fina ?? null,
|
|
'perda_peso_nao_intencional' => $soapRascunho->ivcf->perda_peso_nao_intencional ?? null,
|
|
'imc_abaixo_22' => $soapRascunho->ivcf->imc_abaixo_22 ?? null,
|
|
'panturrilha_abaixo_31' => $soapRascunho->ivcf->panturrilha_abaixo_31 ?? null,
|
|
'marcha_lenta_4m_maior_5s' => $soapRascunho->ivcf->marcha_lenta_4m_maior_5s ?? null,
|
|
'dificuldade_caminhar_impacto_atividades' => $soapRascunho->ivcf->dificuldade_caminhar_impacto_atividades ?? null,
|
|
'quedas_recorrentes' => $soapRascunho->ivcf->quedas_recorrentes ?? null,
|
|
'incontinencia' => $soapRascunho->ivcf->incontinencia ?? null,
|
|
'problema_visao_impacto_atividades' => $soapRascunho->ivcf->problema_visao_impacto_atividades ?? null,
|
|
'problema_audicao_impacto_atividades' => $soapRascunho->ivcf->problema_audicao_impacto_atividades ?? null,
|
|
'doencas_cronicas_multiplas' => $soapRascunho->ivcf->doencas_cronicas_multiplas ?? null,
|
|
'polifarmacia_5_ou_mais_medicamentos' => $soapRascunho->ivcf->polifarmacia_5_ou_mais_medicamentos ?? null,
|
|
'internacao_ultimos_6_meses' => $soapRascunho->ivcf->internacao_ultimos_6_meses ?? null,
|
|
],
|
|
'risco_cardiovascular_framingham' => [
|
|
'colesterol_total' => $soapRascunho->riscoCardiovascularFramingham->colesterol_total ?? null,
|
|
'colesterol_hdl' => $soapRascunho->riscoCardiovascularFramingham->colesterol_hdl ?? null,
|
|
'toma_remedio_hipertensao' => $soapRascunho->riscoCardiovascularFramingham->toma_remedio_hipertensao ?? false,
|
|
'tabagista' => $soapRascunho->riscoCardiovascularFramingham->tabagista ?? false,
|
|
'diabetico' => $soapRascunho->riscoCardiovascularFramingham->diabetico ?? false,
|
|
],
|
|
'tempo_atendimento' => $soapRascunho->tempo_atendimento ?? null
|
|
]
|
|
];
|
|
}
|
|
|
|
private static function getFeridasModelData($atendimento)
|
|
{
|
|
|
|
$pacienteId = null;
|
|
|
|
if ($atendimento->agendamento_id && $atendimento->agendamento) {
|
|
|
|
$pacienteId = $atendimento->agendamento->paciente_id;
|
|
|
|
} elseif ($atendimento->demanda_espontanea_id && $atendimento->demandaEspontanea) {
|
|
|
|
$pacienteId = $atendimento->demandaEspontanea->paciente_id;
|
|
}
|
|
|
|
$atendimentos = Atendimento::where(function ($q) use ($pacienteId) {
|
|
$q->where('paciente_id', $pacienteId);
|
|
})->pluck('id');
|
|
|
|
$soaps = AtendimentoSoap::whereIn('atendimento_id', $atendimentos)
|
|
->with([
|
|
'feridas',
|
|
'feridas.ferida',
|
|
'feridas.localAnatomico',
|
|
'feridas.localAnatomicoRegiao',
|
|
'feridas.exsudato',
|
|
'feridas.necrose',
|
|
'feridas.procedimentos',
|
|
'feridas.procedimentos.atendimentoProcedimento',
|
|
'feridas.procedimentos.atendimentoProcedimento.cid',
|
|
'feridas.procedimentos.atendimentoProcedimento.procedimento',
|
|
'feridas.procedimentos.atendimentoProcedimento.materiais',
|
|
])->get();
|
|
|
|
$feridas = $soaps->flatMap(function ($soap) {
|
|
return $soap->feridas->map(function ($ferida) {
|
|
|
|
$procedimentos = $ferida->procedimentos->map(function ($item) {
|
|
$atendimentoProcedimento = $item->atendimentoProcedimento;
|
|
|
|
return [
|
|
'id' => $item->id,
|
|
'procedimento_id' => $item->atendimentoProcedimento->procedimento_id,
|
|
'cid_id' => $item->atendimentoProcedimento->cid_id ?? null,
|
|
'cid' => $item->atendimentoProcedimento->cid ? [
|
|
'id' => $item->atendimentoProcedimento->cid->id,
|
|
'codigo' => $item->atendimentoProcedimento->cid->codigo,
|
|
'nome' => $item->atendimentoProcedimento->cid->nome,
|
|
] : null,
|
|
'quantidade' => $item->atendimentoProcedimento->quantidade ?? null,
|
|
'procedimento' => [
|
|
'id' => $item->atendimentoProcedimento->procedimento->id ?? null,
|
|
'codigo' => $item->atendimentoProcedimento->procedimento->codigo ?? null,
|
|
'nome' => $item->atendimentoProcedimento->procedimento->nome ?? null,
|
|
'materiais' => $atendimentoProcedimento
|
|
? $atendimentoProcedimento->materiais->map(function ($material) {
|
|
return [
|
|
'id' => $material->almoxarifadoSaidaItem->material->id ?? null,
|
|
'descricao_completa' =>$material->almoxarifadoSaidaItem->material->descricaoCompleta ?? null,
|
|
'quantidade' => $material->almoxarifadoSaidaItem->quantidade ?? null
|
|
];
|
|
}) : collect(),
|
|
],
|
|
];
|
|
});
|
|
|
|
|
|
$imagesBase64 = $ferida->images->map(function ($image) {
|
|
$arquivo = $image->arquivo;
|
|
|
|
$path = Storage::path('ambulatorio' . DIRECTORY_SEPARATOR . 'feridas' . DIRECTORY_SEPARATOR . app('config')->get('database.default') . DIRECTORY_SEPARATOR . $arquivo);
|
|
|
|
if (file_exists($path)) {
|
|
$type = pathinfo($path, PATHINFO_EXTENSION);
|
|
$data = file_get_contents($path);
|
|
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
|
|
|
|
return [
|
|
'id' => $image->id,
|
|
'arquivo' => $base64
|
|
];
|
|
}
|
|
|
|
return [
|
|
'id' => $image->id,
|
|
'arquivo' => null
|
|
];
|
|
});
|
|
|
|
return [
|
|
'id' => $ferida->id,
|
|
'id_old' => $ferida->id_old,
|
|
'soap_id' => $ferida->soap_id ?? null,
|
|
'data' => $ferida->data->format('d/m/Y'),
|
|
'tipo_descricao' => $ferida->ferida->nome ?? null,
|
|
'tipo_id' => $ferida->ferida_id,
|
|
'local_anatomico_descricao' => $ferida->localAnatomico->descricao ?? null,
|
|
'local_anatomico_id' => $ferida->local_anatomico_id,
|
|
'local_anatomico_regiao_descricao' => $ferida->localAnatomicoRegiao->descricao ?? null,
|
|
'local_anatomico_regiao_id' => $ferida->local_anatomico_regiao_id,
|
|
'exsudato_descricao' => $ferida->exsudato->descricao ?? null,
|
|
'exsudato_id' => $ferida->ferida_exsudato_id,
|
|
'necrose_descricao' => $ferida->necrose->descricao ?? null,
|
|
'necrose_id' => $ferida->ferida_necrose,
|
|
'cicatrizada' => $ferida->cicatrizada ? true : false,
|
|
'comprimento' => $ferida->comprimento,
|
|
'largura' => $ferida->largura,
|
|
'profundidade' => $ferida->profundidade,
|
|
'dor' => $ferida->dor,
|
|
'observacao' => $ferida->observacao,
|
|
'procedimentos' => $procedimentos,
|
|
'images' => $imagesBase64,
|
|
];
|
|
});
|
|
});
|
|
|
|
return [
|
|
'feridas' => $feridas
|
|
];
|
|
}
|
|
|
|
private static function getMedicoesModelData($soapRascunho)
|
|
{
|
|
$antropometrias = $soapRascunho
|
|
? $soapRascunho->antropometrias()->whereDoesntHave('soapObjetivoAntropometria')->get()
|
|
: collect();
|
|
|
|
return [
|
|
'antropometrias' => $antropometrias->map(fn ($antropometria) => [
|
|
'medido_em' => $antropometria->medido_em->format('d/m/Y'),
|
|
'peso' => $antropometria->peso,
|
|
'altura' => isset($antropometria->altura) ? (int) $antropometria->altura : null,
|
|
'imc' => isset($antropometria->peso) && isset($antropometria->altura)
|
|
? ImcService::calculate(
|
|
UnidadeMedidaEnum::QUILOGRAMAS,
|
|
$antropometria->peso,
|
|
UnidadeMedidaEnum::CENTIMETROS,
|
|
$antropometria->altura
|
|
)['imc']
|
|
: null,
|
|
'perimetro_cefalico' => isset($antropometria->perimetro_cefalico)
|
|
? $antropometria->perimetro_cefalico
|
|
: null,
|
|
'circunferencia_abdominal' => isset($antropometria->circunferencia_abdominal)
|
|
? (int) $antropometria->circunferencia_abdominal
|
|
: null,
|
|
'perimetro_panturrilha' => isset($antropometria->perimetro_panturrilha)
|
|
? (int) $antropometria->perimetro_panturrilha
|
|
: null,
|
|
]),
|
|
];
|
|
}
|
|
|
|
private static function getMedicamentosEmUsoModelData($soapRascunho)
|
|
{
|
|
return [
|
|
'medicamentos_com_tratamento_interrompido' => ($soapRascunho->prescricaoMedicamentoTratamentosInterrompidos ?? collect())
|
|
->map(fn ($prescricaoItem) => [
|
|
'prescricao_medicamento_item_id' => $prescricaoItem->id,
|
|
'justificativa' => $prescricaoItem->tratamento_interrompido_justificativa,
|
|
]),
|
|
];
|
|
}
|
|
|
|
private static function getRaasModelData($atendimento)
|
|
{
|
|
return [
|
|
'origem_paciente_id' => $atendimento->raas->origem_paciente_id ?? null,
|
|
'destino_paciente_id' => $atendimento->raas->destino_paciente_id ?? null,
|
|
'motivo_saida_permanencia_id' => $atendimento->raas->motivo_saida_permanencia_id ?? null,
|
|
'carater_atendimento_id' => $atendimento->raas->carater_atendimento_id ?? null,
|
|
'numero_autorizacao' => $atendimento->raas->numero_autorizacao ?? null,
|
|
'classificacao_id' => $atendimento->raas->classificacao_id ?? null,
|
|
'local_realizacao_exame_id' => $atendimento->raas->local_realizacao_exame_id ?? null,
|
|
];
|
|
}
|
|
|
|
private static function getAntecedentesModelData($paciente, $soapRascunho)
|
|
{
|
|
$antecedentes = $soapRascunho->antecedente ?? AtendimentoSoapAntecedente::whereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
)
|
|
->orderByDesc('created_at')
|
|
->first();
|
|
|
|
return [
|
|
'descricao' => $antecedentes->descricao ?? null,
|
|
'descricao_familiar' => $antecedentes->descricao_familiar ?? null,
|
|
'informacoes_obstetricas' => [
|
|
'gestas_previas' => $antecedentes->gestas_previas ?? null,
|
|
'abortos' => $antecedentes->abortos ?? null,
|
|
'desfecho_gestacao_aconteceu_menos_um_ano' => $antecedentes->desfecho_gestacao_aconteceu_menos_um_ano ?? false,
|
|
'partos_realizados' => $antecedentes->partos_realizados ?? null,
|
|
'partos_vaginais' => $antecedentes->partos_vaginais ?? null,
|
|
'partos_cesareas' => $antecedentes->partos_cesareas ?? null,
|
|
'partos_domiciliares' => $antecedentes->partos_domiciliares ?? null,
|
|
'nascidos_vivos' => $antecedentes->nascidos_vivos ?? null,
|
|
'nascidos_mortos' => $antecedentes->nascidos_mortos ?? null,
|
|
'recem_nascidos_com_menos2500_gramas' => $antecedentes->recem_nascidos_com_menos2500_gramas ?? null,
|
|
'recem_nascidos_com_mais4500_gramas' => $antecedentes->recem_nascidos_com_mais4500_gramas ?? null,
|
|
'nascidos_vivos_vivem' => $antecedentes->nascidos_vivos_vivem ?? null,
|
|
'nascidos_vivos_mortos_primeira_semana' => $antecedentes->nascidos_vivos_mortos_primeira_semana ?? null,
|
|
'nascidos_vivos_mortos_depois_primeira_semana' => $antecedentes->nascidos_vivos_mortos_depois_primeira_semana ?? null,
|
|
],
|
|
'puericultura' => self::getPuericulturaAntecedentes($paciente),
|
|
'problemas_condicoes' => is_null($antecedentes) ? [] : $antecedentes
|
|
->problemasCondicoes()
|
|
->get()
|
|
->map(fn ($problemaCondicao) => array_merge(self::getLogData($problemaCondicao), [
|
|
'id' => $problemaCondicao->id,
|
|
'ciap' => is_null($problemaCondicao->ciap_id) ? null : [
|
|
'id' => $problemaCondicao->ciap->id,
|
|
'codigo' => $problemaCondicao->ciap->codigo,
|
|
'descricao' => $problemaCondicao->ciap->descricao,
|
|
],
|
|
'cid' => is_null($problemaCondicao->cid_id) ? null : [
|
|
'id' => $problemaCondicao->cid->id,
|
|
'codigo' => $problemaCondicao->cid->codigo,
|
|
'nome' => $problemaCondicao->cid->nome,
|
|
],
|
|
'situacao_id' => $problemaCondicao->situacao_id,
|
|
'inicio' => [
|
|
'data' => is_null($problemaCondicao->inicio) ? null : $problemaCondicao->inicio->format('d/m/Y'),
|
|
],
|
|
'fim' => [
|
|
'data' => is_null($problemaCondicao->fim) ? null : $problemaCondicao->fim->format('d/m/Y'),
|
|
],
|
|
'observacao' => $problemaCondicao->observacao,
|
|
]))
|
|
->all(),
|
|
'cirurgias_internacoes' => is_null($antecedentes) ? [] : $antecedentes
|
|
->cirurgiasInternacoes()
|
|
->get()
|
|
->map(fn ($cirurgiaInternacao) => array_merge(self::getLogData($cirurgiaInternacao), [
|
|
'id' => $cirurgiaInternacao->id,
|
|
'descricao' => $cirurgiaInternacao->descricao,
|
|
'realizada_em' => [
|
|
'data' => is_null($cirurgiaInternacao->realizada_em)
|
|
? null : $cirurgiaInternacao->realizada_em->format('d/m/Y'),
|
|
],
|
|
'observacao' => $cirurgiaInternacao->observacao,
|
|
])),
|
|
'problemas_familiares' => is_null($antecedentes) ? [] : $antecedentes
|
|
->problemasFamiliares()
|
|
->get()
|
|
->map(fn ($problemaFamiliar) => array_merge(self::getLogData($problemaFamiliar), [
|
|
'id' => $problemaFamiliar->id,
|
|
'ciap' => [
|
|
'id' => $problemaFamiliar->ciap_id,
|
|
'codigo' => $problemaFamiliar->ciap->codigo,
|
|
'descricao' => $problemaFamiliar->ciap->descricao,
|
|
],
|
|
'observacao' => $problemaFamiliar->observacao,
|
|
])),
|
|
];
|
|
}
|
|
|
|
private static function getPuericulturaAntecedentes($paciente)
|
|
{
|
|
if (is_null($paciente->cidadao->data_nascimento)
|
|
|| $paciente->cidadao->idade['anos'] > self::IDADE_ANOS_FINAL_ADOLESCENTE
|
|
) {
|
|
|
|
return null;
|
|
}
|
|
|
|
$ultimoSoapPuericultura = self::getUltimoSoapPuericultura($paciente, true);
|
|
|
|
return [
|
|
'gravidez_tipo_id' => $ultimoSoapPuericultura->puericultura_gravidez_tipo_id ?? null,
|
|
'parto_tipo_id' => $ultimoSoapPuericultura->puericultura_parto_tipo_id ?? null,
|
|
'idade_gestacional_semanas' => $ultimoSoapPuericultura->puericultura_idade_gestacional_semanas ?? null,
|
|
'idade_gestacional_dias' => $ultimoSoapPuericultura->puericultura_idade_gestacional_dias ?? null,
|
|
'apgar_primeiro_minuto' => $ultimoSoapPuericultura->puericultura_apgar_primeiro_minuto ?? null,
|
|
'apgar_quinto_minuto' => $ultimoSoapPuericultura->puericultura_apgar_quinto_minuto ?? null,
|
|
'apgar_decimo_minuto' => $ultimoSoapPuericultura->puericultura_apgar_decimo_minuto ?? null,
|
|
'peso' => $ultimoSoapPuericultura->puericultura_peso ?? null,
|
|
'comprimento' => $ultimoSoapPuericultura->puericultura_comprimento ?? null,
|
|
'perimetro_cefalico' => $ultimoSoapPuericultura->puericultura_perimetro_cefalico ?? null,
|
|
];
|
|
}
|
|
|
|
private static function getSubjetivoModelData($soapRascunho)
|
|
{
|
|
return [
|
|
'descricao' => $soapRascunho->subjetivo_descricao ?? null,
|
|
'motivos' => ($soapRascunho->motivos ?? collect())->map(fn ($motivo) => [
|
|
'ciap' => $motivo->ciap ? [
|
|
'id' => $motivo->ciap->id,
|
|
'codigo' => $motivo->ciap->codigo,
|
|
'descricao' => $motivo->ciap->descricao,
|
|
] : null,
|
|
'cid' => $motivo->cid ? [
|
|
'id' => $motivo->cid->id,
|
|
'codigo' => $motivo->cid->codigo,
|
|
'nome' => $motivo->cid->nome,
|
|
] : null,
|
|
'observacao' => $motivo->observacao,
|
|
]),
|
|
];
|
|
}
|
|
|
|
private static function getObjetivoModelData($atendimento, $soapRascunho)
|
|
{
|
|
$atendimentosPuericultura = self::getAtendimentosPuericultura($atendimento->paciente);
|
|
|
|
$antropometria = self::getUltimaAntropometriaAtendimento($atendimento);
|
|
$sinalVital = self::getUltimoSinalVitalAtendimento($atendimento);
|
|
$glicemiaCapilar = self::getUltimaGlicemiaCapilarAtendimento($atendimento);
|
|
|
|
return [
|
|
|
|
'descricao' => $soapRascunho->objetivo_descricao ?? null,
|
|
'pre_natal' => self::getPreNatalModelData($atendimento->paciente, $soapRascunho),
|
|
'is_atendimento_puericultura' => $soapRascunho->is_atendimento_puericultura ?? false,
|
|
'dum' => $soapRascunho
|
|
? ($soapRascunho->dum ? $soapRascunho->dum->format('Y-m-d') : null)
|
|
: ($atendimento->paciente->dum && $atendimento->paciente->dum->data_ultima_menstruacao
|
|
? $atendimento->paciente->dum->data_ultima_menstruacao
|
|
: null
|
|
),
|
|
'puericultura' => [
|
|
'gravidez_tipo_id' => $soapRascunho->puericultura_gravidez_tipo_id ?? null,
|
|
'parto_tipo_id' => $soapRascunho->puericultura_parto_tipo_id ?? null,
|
|
'idade_gestacional_semanas' => $soapRascunho->puericultura_idade_gestacional_semanas ?? null,
|
|
'idade_gestacional_dias' => $soapRascunho->puericultura_idade_gestacional_dias ?? null,
|
|
'apgar_primeiro_minuto' => $soapRascunho->puericultura_apgar_primeiro_minuto ?? null,
|
|
'apgar_quinto_minuto' => $soapRascunho->puericultura_apgar_quinto_minuto ?? null,
|
|
'apgar_decimo_minuto' => $soapRascunho->puericultura_apgar_decimo_minuto ?? null,
|
|
'peso' => $soapRascunho->puericultura_peso ?? null,
|
|
'comprimento' => isset($soapRascunho->puericultura_comprimento)
|
|
? (int) $soapRascunho->puericultura_comprimento
|
|
: null,
|
|
'perimetro_cefalico' => isset($soapRascunho->puericultura_perimetro_cefalico)
|
|
? (int) $soapRascunho->puericultura_perimetro_cefalico
|
|
: null,
|
|
'aleitamento_tipo_id' => $soapRascunho->puericultura_aleitamento_tipo_id ?? null,
|
|
'alteracoes_fenotipicas' => self::getPuericulturaAlteracoesFenotipicas($atendimentosPuericultura, $soapRascunho),
|
|
'fatores_risco' => self::getPuericulturaFatoresRisco($atendimentosPuericultura, $soapRascunho),
|
|
'marcos_desenvolvimento' => self::getPuericulturaMarcosDesenvolvimento($atendimento->paciente, $atendimentosPuericultura, $soapRascunho),
|
|
'questionario_m_chat_r' => self::getPuericulturaQuestionarioMChatR($soapRascunho),
|
|
],
|
|
'antropometria' => [
|
|
'peso' => $soapRascunho
|
|
? ($soapRascunho->objetivoAntropometria->atendimentoAntropometria->peso ?? null)
|
|
: ($antropometria->peso ?? null),
|
|
'altura' => $soapRascunho
|
|
? (isset($soapRascunho->objetivoAntropometria->atendimentoAntropometria->altura)
|
|
? (float) $soapRascunho->objetivoAntropometria->atendimentoAntropometria->altura
|
|
: null
|
|
)
|
|
: ($antropometria->altura ?? null),
|
|
'imc' => $soapRascunho
|
|
? (isset($soapRascunho->objetivoAntropometria->atendimentoAntropometria->peso)
|
|
&& isset($soapRascunho->objetivoAntropometria->atendimentoAntropometria->altura)
|
|
? ImcService::calculate(
|
|
UnidadeMedidaEnum::QUILOGRAMAS,
|
|
$soapRascunho->objetivoAntropometria->atendimentoAntropometria->peso,
|
|
UnidadeMedidaEnum::CENTIMETROS,
|
|
$soapRascunho->objetivoAntropometria->atendimentoAntropometria->altura
|
|
)
|
|
: [
|
|
'imc' => null,
|
|
'classificacao' => null,
|
|
'grau_obesidade' => null,
|
|
]
|
|
)
|
|
: ($antropometria->imc ?? [
|
|
'imc' => null,
|
|
'classificacao' => null,
|
|
'grau_obesidade' => null,
|
|
]),
|
|
'perimetro_cefalico' => $soapRascunho
|
|
? (isset($soapRascunho->objetivoAntropometria->atendimentoAntropometria->perimetro_cefalico)
|
|
? $soapRascunho->objetivoAntropometria->atendimentoAntropometria->perimetro_cefalico
|
|
: null
|
|
)
|
|
: ($antropometria->perimetro_cefalico ?? null),
|
|
'circunferencia_abdominal' => $soapRascunho
|
|
? (isset($soapRascunho->objetivoAntropometria->atendimentoAntropometria->circunferencia_abdominal)
|
|
? (float) $soapRascunho->objetivoAntropometria->atendimentoAntropometria->circunferencia_abdominal
|
|
: null
|
|
)
|
|
: ($antropometria->circunferencia_abdominal ?? null),
|
|
'perimetro_panturrilha' => $soapRascunho
|
|
? (isset($soapRascunho->objetivoAntropometria->atendimentoAntropometria->perimetro_panturrilha)
|
|
? (float) $soapRascunho->objetivoAntropometria->atendimentoAntropometria->perimetro_panturrilha
|
|
: null
|
|
)
|
|
: ($antropometria->perimetro_panturrilha ?? null),
|
|
'comprimento_pe_direito' => $soapRascunho
|
|
? (isset($soapRascunho->objetivoAntropometria->atendimentoAntropometria->comprimento_pe_direito)
|
|
? (float) $soapRascunho->objetivoAntropometria->atendimentoAntropometria->comprimento_pe_direito
|
|
: null
|
|
)
|
|
: ($antropometria->comprimento_pe_direito ?? null),
|
|
'largura_pe_direito' => $soapRascunho
|
|
? (isset($soapRascunho->objetivoAntropometria->atendimentoAntropometria->largura_pe_direito)
|
|
? (float) $soapRascunho->objetivoAntropometria->atendimentoAntropometria->largura_pe_direito
|
|
: null
|
|
)
|
|
: ($antropometria->largura_pe_direito ?? null),
|
|
'circunferencia_pe_direito' => $soapRascunho
|
|
? (isset($soapRascunho->objetivoAntropometria->atendimentoAntropometria->circunferencia_pe_direito)
|
|
? (float) $soapRascunho->objetivoAntropometria->atendimentoAntropometria->circunferencia_pe_direito
|
|
: null
|
|
)
|
|
: ($antropometria->circunferencia_pe_direito ?? null),
|
|
'comprimento_pe_esquerdo' => $soapRascunho
|
|
? (isset($soapRascunho->objetivoAntropometria->atendimentoAntropometria->comprimento_pe_esquerdo)
|
|
? (float) $soapRascunho->objetivoAntropometria->atendimentoAntropometria->comprimento_pe_esquerdo
|
|
: null
|
|
)
|
|
: ($antropometria->comprimento_pe_esquerdo ?? null),
|
|
'largura_pe_esquerdo' => $soapRascunho
|
|
? (isset($soapRascunho->objetivoAntropometria->atendimentoAntropometria->largura_pe_esquerdo)
|
|
? (float) $soapRascunho->objetivoAntropometria->atendimentoAntropometria->largura_pe_esquerdo
|
|
: null
|
|
)
|
|
: ($antropometria->largura_pe_esquerdo ?? null),
|
|
'circunferencia_pe_esquerdo' => $soapRascunho
|
|
? (isset($soapRascunho->objetivoAntropometria->atendimentoAntropometria->circunferencia_pe_esquerdo)
|
|
? (float) $soapRascunho->objetivoAntropometria->atendimentoAntropometria->circunferencia_pe_esquerdo
|
|
: null
|
|
)
|
|
: ($antropometria->circunferencia_pe_esquerdo ?? null),
|
|
],
|
|
'sinal_vital' => [
|
|
'pressao_arterial' => $soapRascunho
|
|
? ($soapRascunho->objetivoSinalVital->atendimentoSinalVital->pressao_arterial ?? null)
|
|
: ($sinalVital->pressao_arterial ?? null),
|
|
'frequencia_respiratoria' => $soapRascunho
|
|
? ($soapRascunho->objetivoSinalVital->atendimentoSinalVital->frequencia_respiratoria ?? null)
|
|
: ($sinalVital->frequencia_respiratoria ?? null),
|
|
'frequencia_cardiaca' => $soapRascunho
|
|
? ($soapRascunho->objetivoSinalVital->atendimentoSinalVital->frequencia_cardiaca ?? null)
|
|
: ($sinalVital->frequencia_cardiaca ?? null),
|
|
'temperatura' => $soapRascunho
|
|
? ($soapRascunho->objetivoSinalVital->atendimentoSinalVital->temperatura ?? null)
|
|
: ($sinalVital->temperatura ?? null),
|
|
'saturacao_o2' => $soapRascunho
|
|
? ($soapRascunho->objetivoSinalVital->atendimentoSinalVital->saturacao_o2 ?? null)
|
|
: ($sinalVital->saturacao_o2 ?? null),
|
|
],
|
|
'glicemia_capilar' => [
|
|
'valor' => $soapRascunho
|
|
? ($soapRascunho->objetivoGlicemiaCapilar->atendimentoGlicemiaCapilar->valor ?? null)
|
|
: ($glicemiaCapilar->valor ?? null),
|
|
'momento_coleta_id' => $soapRascunho
|
|
? ($soapRascunho->objetivoGlicemiaCapilar->atendimentoGlicemiaCapilar->momento_coleta_id ?? null)
|
|
: ($glicemiaCapilar->momento_coleta_id ?? null),
|
|
],
|
|
'tria' => [
|
|
'alimentos_acabaram' => optional($atendimento->paciente->informacaoSocial)->alimentos_acabaram,
|
|
'comeu_alguns_alimentos' => optional($atendimento->paciente->informacaoSocial)->comeu_alguns_alimentos,
|
|
'data_atualizacao_tria' =>
|
|
optional($atendimento->paciente->informacaoSocial)->data_atualizacao_tria
|
|
? optional($atendimento->paciente->informacaoSocial)->data_atualizacao_tria->toDateString()
|
|
: optional(optional($atendimento->paciente->cadastroIndividual)->created_at)->toDateString(),
|
|
'is_desatualizado' => self::isTriaDesatualizado(
|
|
optional($atendimento->paciente->informacaoSocial)->data_atualizacao_tria
|
|
?? optional($atendimento->paciente->cadastroIndividual)->data_atualizacao_tria
|
|
?? optional($atendimento->paciente->cadastroIndividual)->updated_at
|
|
),
|
|
],
|
|
'vacinacao_em_dia' => $soapRascunho->vacinacao_em_dia ?? null,
|
|
'paciente_com_necessidade_especial' => $soapRascunho->paciente_com_necessidade_especial ?? false,
|
|
'marcador_consumo_alimentar' => [
|
|
'perguntas' => ($soapRascunho->marcadorConsumoAlimentarPerguntasRespostas ?? collect())
|
|
->map(fn ($marcador) => [
|
|
'pergunta_id' => $marcador->pergunta_id,
|
|
'respostas' => $soapRascunho->marcadorConsumoAlimentarPerguntasRespostas()
|
|
->where('pergunta_id', $marcador->pergunta_id)
|
|
->get()
|
|
->map(fn ($marcador2) => $marcador2->resposta->descricao)
|
|
])
|
|
->unique('pergunta_id')
|
|
->values(),
|
|
'pergunta_multipla' => [],
|
|
'pergunta_unica' => [],
|
|
],
|
|
'resultados_exames' => ($soapRascunho->resultadosExames ?? collect())->map(fn ($resultado) => [
|
|
'exame' => [
|
|
'id' => $resultado->exame->id,
|
|
'codigo' => $resultado->exame->codigo,
|
|
'nome' => $resultado->exame->nome,
|
|
],
|
|
'idade_gestacional_semanas_eco' => $resultado->idade_gestacional_semanas_eco,
|
|
'idade_gestacional_dias_eco' => $resultado->idade_gestacional_dias_eco,
|
|
'dpp_eco' => $resultado->dpp_eco,
|
|
'solicitado_em' => $resultado->solicitado_em ? $resultado->solicitado_em->format('d/m/Y') : null,
|
|
'realizado_em' => $resultado->realizado_em->format('d/m/Y'),
|
|
'resultado_em' => $resultado->resultado_em ? $resultado->resultado_em->format('d/m/Y') : null,
|
|
'percentual' => isset($resultado->percentual)
|
|
? (fmod($resultado->percentual, 1) == 0 ? (int) $resultado->percentual : $resultado->percentual)
|
|
: null,
|
|
'resultado_tipo_id' => $resultado->resultado_tipo_id,
|
|
'resultado' => $resultado->resultado,
|
|
]),
|
|
'triagem_neonatal' => ($soapRascunho->triagensNeonatal ?? collect())->map(fn ($triagemNeonatal) => [
|
|
'id' => $triagemNeonatal->id,
|
|
'solicitado_em' => $triagemNeonatal->soapTriagemNeonatal->solicitado_em,
|
|
'realizado_em' => $triagemNeonatal->soapTriagemNeonatal->realizado_em,
|
|
'resultado_em' => $triagemNeonatal->soapTriagemNeonatal->resultado_em,
|
|
'resultado' => $triagemNeonatal->soapTriagemNeonatal->resultado,
|
|
]),
|
|
'exame_avaliado' => ($soapRascunho->examesAvaliados ?? collect())->map(fn ($exameAvaliado) => [
|
|
'id' => $exameAvaliado->id,
|
|
'solicitado_em' => $exameAvaliado->soapExameAvaliado->solicitado_em,
|
|
'realizado_em' => $exameAvaliado->soapExameAvaliado->realizado_em,
|
|
'resultado_em' => $exameAvaliado->soapExameAvaliado->resultado_em,
|
|
'resultado' => $exameAvaliado->soapExameAvaliado->resultado,
|
|
]),
|
|
];
|
|
}
|
|
|
|
private static function getAtendimentosPuericultura($paciente)
|
|
{
|
|
return AtendimentoSoap::where('is_rascunho', false)
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
->where('is_atendimento_puericultura', true)
|
|
->orderBy('created_at')
|
|
->get();
|
|
}
|
|
|
|
private static function getUltimoSoapPuericultura($paciente, $withRascunho = false)
|
|
{
|
|
return AtendimentoSoap::when(!$withRascunho, fn ($q) => $q->where('is_rascunho', false))
|
|
->whereHas('atendimento', fn ($q) => $q
|
|
->where('paciente_id', $paciente->id)
|
|
)
|
|
->where('is_atendimento_puericultura', true)
|
|
->orderByDesc('created_at')
|
|
->first();
|
|
}
|
|
|
|
private static function getAvaliacaoModelData($paciente, $soapRascunho)
|
|
{
|
|
return [
|
|
'descricao' => $soapRascunho->avaliacao_descricao ?? null,
|
|
'condicoes_avaliadas' => $soapRascunho ? $soapRascunho->condicoesAvaliadas()->pluck('id') : [],
|
|
'condicoes_emad' => $soapRascunho ? $soapRascunho->condicoesEmad()->pluck('atencao_basica_atendimento_domiciliar_condicao_avaliada.id') : [],
|
|
'doencas_transmissiveis' => $soapRascunho ? $soapRascunho->doencasTransmissiveis()->pluck('id') : [],
|
|
'rastreamentos' => $soapRascunho ? $soapRascunho->rastreamentos()->pluck('id') : [],
|
|
'problemas_condicoes' => ($soapRascunho->problemasCondicoes ?? collect())->map(fn ($problemaCondicao) => [
|
|
'automatico' => $problemaCondicao->automatico,
|
|
'id' => $problemaCondicao->problema_condicao_anterior_id,
|
|
'ciap' => $problemaCondicao->ciap ? [
|
|
'id' => $problemaCondicao->ciap->id,
|
|
'codigo' => $problemaCondicao->ciap->codigo,
|
|
'descricao' => $problemaCondicao->ciap->descricao,
|
|
] : null,
|
|
'cid' => $problemaCondicao->cid ? [
|
|
'id' => $problemaCondicao->cid->id,
|
|
'codigo' => $problemaCondicao->cid->codigo,
|
|
'nome' => $problemaCondicao->cid->nome,
|
|
] : null,
|
|
'incluir_lista_paciente' => !is_null($problemaCondicao->situacao_id),
|
|
'situacao_id' => $problemaCondicao->situacao_id,
|
|
'situacao_nome' => $problemaCondicao->situacao->nome ?? null,
|
|
'inicio' => $problemaCondicao->inicio ? [
|
|
'data' => $problemaCondicao->inicio->format('d/m/Y'),
|
|
'ano' => null,
|
|
'mes' => null,
|
|
] : null,
|
|
'fim' => $problemaCondicao->fim ? [
|
|
'data' => $problemaCondicao->fim->format('d/m/Y'),
|
|
'ano' => null,
|
|
'mes' => null,
|
|
] : null,
|
|
'observacao' => $problemaCondicao->observacao,
|
|
]),
|
|
'pre_natal' => self::getPreNatalModelData($paciente, $soapRascunho),
|
|
'alergias_reacoes_adversas' => self::getAlergias($paciente),
|
|
'saude_bucal' => [
|
|
'vigilancias' => $soapRascunho ? $soapRascunho->saudeBucalVigilancias()->pluck('id') : [],
|
|
'necessidade_protese_inferior_superior' => $soapRascunho->saude_bucal_necessidade_protese_inferior_superior ?? null,
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getPreNatalModelData($paciente, $soapRascunho)
|
|
{
|
|
$data = [
|
|
'is_rascunho_atendimento_pre_natal' => $soapRascunho
|
|
? self::hasProblemaCondicaoGravidezNormal($soapRascunho)
|
|
: false,
|
|
'gravidez_tipo_id' => $soapRascunho->pre_natal_gravidez_tipo_id ?? null,
|
|
'altura_uterina' => $soapRascunho->pre_natal_altura_uterina ?? null,
|
|
'gravidez_alto_risco' => is_null($soapRascunho)
|
|
? false
|
|
: self::isGravidezAltoRisco($paciente, true),
|
|
'edema_id' => $soapRascunho->pre_natal_edema_id ?? null,
|
|
'movimentacao_fetal' => $soapRascunho->pre_natal_movimentacao_fetal ?? null,
|
|
'gravidez_planejada' => $soapRascunho->pre_natal_gravidez_planejada ?? null,
|
|
'batimento_cardiaco_fetal' => $soapRascunho->pre_natal_batimento_cardiaco_fetal ?? null,
|
|
'desfecho_em' => $soapRascunho && $soapRascunho->pre_natal_desfecho_em
|
|
? $soapRascunho->pre_natal_desfecho_em->format('Y-m-d')
|
|
: null,
|
|
];
|
|
|
|
if (is_null($soapRascunho)) {
|
|
|
|
$soap = self::getUltimoSoapPreNatalNaoResolvido($paciente);
|
|
|
|
if (!is_null($soap)) {
|
|
|
|
$data['gravidez_tipo_id'] = $soap->pre_natal_gravidez_tipo_id;
|
|
$data['gravidez_planejada'] = $soap->pre_natal_gravidez_planejada;
|
|
$data['gravidez_alto_risco'] = self::isGravidezAltoRisco($paciente);
|
|
}
|
|
}
|
|
|
|
return $data;
|
|
}
|
|
|
|
private static function hasProblemaCondicaoGravidezNormal($soap)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_soap_problema_condicao as problema_condicao')
|
|
->where('problema_condicao.soap_id', $soap->id)
|
|
->where(fn ($q) => $q
|
|
->whereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('geral_ciap as ciap')
|
|
->whereColumn('ciap.id', 'problema_condicao.ciap_id')
|
|
->whereIn('ciap.codigo', self::CIAPS_GRAVIDEZ_NORMAL)
|
|
)
|
|
->orWhereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('sigtap.cid as cid')
|
|
->whereColumn('cid.id', 'problema_condicao.cid_id')
|
|
->whereIn('cid.codigo', self::CIDS_GRAVIDEZ_NORMAL)
|
|
)
|
|
)
|
|
->exists();
|
|
}
|
|
|
|
public static function getDataInicioGravidezNaoResolvida($paciente)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_soap_problema_condicao as problema_condicao')
|
|
->join('ambulatorio_atendimento_soap as soap', 'soap.id', 'problema_condicao.soap_id')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
|
|
->where('soap.is_rascunho', false)
|
|
->where('atendimento.paciente_id', $paciente->id)
|
|
->where(fn ($q) => $q
|
|
->whereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('geral_ciap as ciap')
|
|
->whereColumn('ciap.id', 'problema_condicao.ciap_id')
|
|
->whereIn('ciap.codigo', self::CIAPS_GRAVIDEZ_NORMAL)
|
|
)
|
|
->orWhereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('sigtap.cid as cid')
|
|
->whereColumn('cid.id', 'problema_condicao.cid_id')
|
|
->whereIn('cid.codigo', self::CIDS_GRAVIDEZ_NORMAL)
|
|
)
|
|
)
|
|
->where('problema_condicao.situacao_id', '<>', ProblemaCondicaoSituacaoEnum::RESOLVIDO)
|
|
->whereNotExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('ambulatorio_atendimento_soap_problema_condicao as problema_condicao_posterior')
|
|
->whereColumn('problema_condicao_posterior.problema_condicao_anterior_id', 'problema_condicao.id')
|
|
)
|
|
->select(
|
|
DB::raw("DATE_FORMAT(problema_condicao.inicio, '%d/%m/%Y') as inicio"),
|
|
)
|
|
->first()->inicio ?? null;
|
|
}
|
|
|
|
private static function getUltimoSoapPreNatalNaoResolvido($paciente)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_soap as soap')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
|
|
->where('soap.is_rascunho', false)
|
|
->where('atendimento.paciente_id', $paciente->id)
|
|
->whereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('ambulatorio_atendimento_soap_problema_condicao as problema_condicao')
|
|
->whereColumn('problema_condicao.soap_id', 'soap.id')
|
|
->where('problema_condicao.situacao_id', '<>', ProblemaCondicaoSituacaoEnum::RESOLVIDO)
|
|
->where(fn ($q) => $q
|
|
->whereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('geral_ciap as ciap')
|
|
->whereColumn('ciap.id', 'problema_condicao.ciap_id')
|
|
->whereIn('ciap.codigo', array_merge(
|
|
self::CIAPS_GRAVIDEZ_NORMAL,
|
|
self::CIAPS_GRAVIDEZ_ALTO_RISCO,
|
|
))
|
|
)
|
|
->orWhereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('sigtap.cid as cid')
|
|
->whereColumn('cid.id', 'problema_condicao.cid_id')
|
|
->whereIn('cid.codigo', array_merge(
|
|
self::CIDS_GRAVIDEZ_NORMAL,
|
|
self::CIDS_GRAVIDEZ_ALTO_RISCO,
|
|
))
|
|
)
|
|
)
|
|
)
|
|
->orderByDesc('soap.created_at')
|
|
->select(
|
|
'soap.pre_natal_gravidez_tipo_id',
|
|
'soap.pre_natal_gravidez_planejada'
|
|
)
|
|
->first();
|
|
}
|
|
|
|
private static function isGravidezAltoRisco($paciente, $withRascunho = false)
|
|
{
|
|
$soap = self::getUltimoSoapComDesfechoGravidez($paciente);
|
|
|
|
return DB::table('ambulatorio_atendimento_soap as soap')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
|
|
->when(!$withRascunho, fn ($q) => $q->where('soap.is_rascunho', false))
|
|
->when(!is_null($soap), fn ($q) => $q->where('soap.id', '>', $soap->id))
|
|
->where('atendimento.paciente_id', $paciente->id)
|
|
->whereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('ambulatorio_atendimento_soap_problema_condicao as problema_condicao')
|
|
->whereColumn('problema_condicao.soap_id', 'soap.id')
|
|
->where(fn ($q) => $q
|
|
->whereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('geral_ciap as ciap')
|
|
->whereColumn('ciap.id', 'problema_condicao.ciap_id')
|
|
->whereIn('ciap.codigo', self::CIAPS_GRAVIDEZ_ALTO_RISCO)
|
|
)
|
|
->orWhereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('sigtap.cid as cid')
|
|
->whereColumn('cid.id', 'problema_condicao.cid_id')
|
|
->whereIn('cid.codigo', self::CIDS_GRAVIDEZ_ALTO_RISCO)
|
|
)
|
|
)
|
|
)
|
|
->exists();
|
|
}
|
|
|
|
private static function getUltimoSoapComDesfechoGravidez($paciente)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_soap as soap')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
|
|
->where('soap.is_rascunho', false)
|
|
->where('atendimento.paciente_id', $paciente->id)
|
|
->where(fn ($q) => $q
|
|
->whereNotNull('soap.pre_natal_desfecho_em')
|
|
->orWhereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('ambulatorio_atendimento_soap_problema_condicao as problema_condicao')
|
|
->whereColumn('problema_condicao.soap_id', 'soap.id')
|
|
->where('problema_condicao.situacao_id', ProblemaCondicaoSituacaoEnum::RESOLVIDO)
|
|
->where(fn ($q) => $q
|
|
->whereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('geral_ciap as ciap')
|
|
->whereColumn('ciap.id', 'problema_condicao.ciap_id')
|
|
->whereIn('ciap.codigo', self::CIAPS_GRAVIDEZ_NORMAL)
|
|
)
|
|
->orWhereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('sigtap.cid as cid')
|
|
->whereColumn('cid.id', 'problema_condicao.cid_id')
|
|
->whereIn('cid.codigo', self::CIDS_GRAVIDEZ_NORMAL)
|
|
)
|
|
)
|
|
)
|
|
)
|
|
->orderByDesc('soap.created_at')
|
|
->select('soap.id')
|
|
->first();
|
|
}
|
|
|
|
private static function getAlergias($paciente)
|
|
{
|
|
return $paciente->cidadao->alergias->map(fn ($alergia, $i) => array_merge(
|
|
self::getLogData($alergia->cidadaoAlergia),
|
|
[
|
|
'index' => $i,
|
|
'alergia' => [
|
|
'agente_substancia_especifica' => $alergia->agente_substancia_especifica,
|
|
'criticidade' => [
|
|
'id' => $alergia->cidadaoAlergia->criticidade->id,
|
|
'nome' => $alergia->cidadaoAlergia->criticidade->nome,
|
|
],
|
|
'id' => $alergia->cidadaoAlergia->alergia_id,
|
|
'reacoes_observacoes' => $alergia->cidadaoAlergia->reacoes_observacoes,
|
|
'tipo' => [
|
|
'id' => $alergia->tipo->id,
|
|
'descricao' => $alergia->tipo->descricao,
|
|
]
|
|
],
|
|
]
|
|
));
|
|
}
|
|
|
|
private static function getPuericulturaAlteracoesFenotipicas($atendimentosPuericultura, $soapRascunho)
|
|
{
|
|
$getResposta = function ($alteracaoId) use ($atendimentosPuericultura) {
|
|
|
|
$resposta = (object) ['is_presente' => null, 'status' => null];
|
|
|
|
$atendimentosPuericultura->each(function ($atendimento) use ($alteracaoId, $resposta) {
|
|
|
|
$alteracao = $atendimento->puericulturaAlteracoesFenotipicas()
|
|
->where('alteracao_fenotipica_id', $alteracaoId)
|
|
->first();
|
|
|
|
if (!is_null($alteracao) && $alteracao->is_presente !== $resposta->is_presente) {
|
|
|
|
$resposta->is_presente = $alteracao->is_presente;
|
|
|
|
$resposta->status = is_null($alteracao->is_presente)
|
|
? null
|
|
: (($alteracao->is_presente ? 'Presente em ' : 'Ausente em ')
|
|
. $alteracao->created_at->format('d/m/Y'));
|
|
}
|
|
});
|
|
|
|
return $resposta;
|
|
};
|
|
|
|
return PuericulturaAlteracaoFenotipica::orderBy('id')->get()->map(function ($alteracao) use ($getResposta, $soapRascunho) {
|
|
|
|
$resposta = $getResposta($alteracao->id);
|
|
|
|
if (is_null($resposta->is_presente) && !is_null($soapRascunho)) {
|
|
|
|
$alteracaoRascunho = $soapRascunho->puericulturaAlteracoesFenotipicas()
|
|
->where('alteracao_fenotipica_id', $alteracao->id)
|
|
->first();
|
|
|
|
return [
|
|
'id' => $alteracao->id,
|
|
'descricao' => $alteracao->descricao,
|
|
'is_presente' => $alteracaoRascunho->is_presente ?? null,
|
|
'status' => null,
|
|
'is_respondido' => false,
|
|
'permite_alteracao' => true
|
|
];
|
|
}
|
|
|
|
return [
|
|
'id' => $alteracao->id,
|
|
'descricao' => $alteracao->descricao,
|
|
'is_presente' => $resposta->is_presente,
|
|
'status' => $resposta->status,
|
|
'is_respondido' => !is_null($resposta->is_presente),
|
|
'permite_alteracao' => is_null($resposta->is_presente) || !$resposta->is_presente
|
|
];
|
|
});
|
|
}
|
|
|
|
private static function getPuericulturaFatoresRisco($atendimentosPuericultura, $soapRascunho)
|
|
{
|
|
$getResposta = function ($fatorId) use ($atendimentosPuericultura) {
|
|
|
|
$resposta = (object) ['is_presente' => null, 'status' => null];
|
|
|
|
$atendimentosPuericultura->each(function ($atendimento) use ($fatorId, $resposta) {
|
|
|
|
$fator = $atendimento->puericulturaFatoresRisco()
|
|
->where('fator_risco_id', $fatorId)
|
|
->first();
|
|
|
|
if (!is_null($fator) && $fator->is_presente !== $resposta->is_presente) {
|
|
|
|
$resposta->is_presente = $fator->is_presente;
|
|
|
|
$resposta->status = is_null($fator->is_presente)
|
|
? null
|
|
: (($fator->is_presente ? 'Presente em ' : 'Ausente em ')
|
|
. $fator->created_at->format('d/m/Y'));
|
|
}
|
|
});
|
|
|
|
return $resposta;
|
|
};
|
|
|
|
return PuericulturaFatorRisco::orderBy('id')->get()->map(function ($fator) use ($getResposta, $soapRascunho) {
|
|
|
|
$resposta = $getResposta($fator->id);
|
|
|
|
if (is_null($resposta->is_presente) && !is_null($soapRascunho)) {
|
|
|
|
$fatorRascunho = $soapRascunho->puericulturaFatoresRisco()
|
|
->where('fator_risco_id', $fator->id)
|
|
->first();
|
|
|
|
return [
|
|
'id' => $fator->id,
|
|
'descricao' => $fator->descricao,
|
|
'is_presente' => $fatorRascunho->is_presente ?? null,
|
|
'status' => null,
|
|
'is_respondido' => false,
|
|
];
|
|
}
|
|
|
|
return [
|
|
'id' => $fator->id,
|
|
'descricao' => $fator->descricao,
|
|
'is_presente' => $resposta->is_presente,
|
|
'status' => $resposta->status,
|
|
'is_respondido' => !is_null($resposta->is_presente),
|
|
];
|
|
});
|
|
}
|
|
|
|
private static function getPuericulturaMarcosDesenvolvimento($paciente, $atendimentosPuericultura, $soapRascunho)
|
|
{
|
|
$dataNascimento = $paciente->cidadao->data_nascimento;
|
|
|
|
if (is_null($dataNascimento)) {
|
|
|
|
return [];
|
|
}
|
|
|
|
$getResposta = function ($marcoId) use ($atendimentosPuericultura, $dataNascimento) {
|
|
|
|
$resposta = (object) [
|
|
'is_presente' => null,
|
|
'status' => null,
|
|
'alcancado_com_anos' => null,
|
|
'alcancado_com_meses' => null,
|
|
];
|
|
|
|
$atendimentosPuericultura->sortByDesc('id')->take(1)->each(function ($atendimento) use ($marcoId, $resposta, $dataNascimento) {
|
|
|
|
$marco = $atendimento->puericulturaMarcosDesenvolvimento()
|
|
->where('marco_desenvolvimento_id', $marcoId)
|
|
->first();
|
|
|
|
if (!is_null($marco)) {
|
|
|
|
if ($marco->is_presente !== $resposta->is_presente) {
|
|
|
|
$resposta->is_presente = $marco->is_presente;
|
|
|
|
if ($marco->is_presente
|
|
&& (!is_null($marco->alcancado_com_anos) || !is_null($marco->alcancado_com_meses))
|
|
) {
|
|
|
|
$resposta->alcancado_com_anos = $marco->alcancado_com_anos;
|
|
$resposta->alcancado_com_meses = $marco->alcancado_com_meses;
|
|
|
|
$resposta->status = $dataNascimento->copy()
|
|
->addYears($resposta->alcancado_com_anos)
|
|
->addMonths($resposta->alcancado_com_meses)
|
|
->format('d/m/Y');
|
|
}
|
|
else {
|
|
|
|
$resposta->alcancado_com_anos = null;
|
|
$resposta->alcancado_com_meses = null;
|
|
$resposta->status = $marco->created_at->format('d/m/Y');
|
|
}
|
|
}
|
|
else if ($marco->is_presente
|
|
&& $resposta->is_presente
|
|
&& ($marco->alcancado_com_anos !== $resposta->alcancado_com_anos
|
|
|| $marco->alcancado_com_meses !== $resposta->alcancado_com_meses
|
|
)
|
|
) {
|
|
|
|
$resposta->alcancado_com_anos = $marco->alcancado_com_anos;
|
|
$resposta->alcancado_com_meses = $marco->alcancado_com_meses;
|
|
|
|
$resposta->status = $dataNascimento->copy()
|
|
->addYears($resposta->alcancado_com_anos)
|
|
->addMonths($resposta->alcancado_com_meses)
|
|
->format('d/m/Y');
|
|
}
|
|
}
|
|
});
|
|
|
|
return $resposta;
|
|
};
|
|
|
|
$marcos = collect();
|
|
$idadeEmMeses = ceil(Carbon::now()->diffInDays($dataNascimento) / 31);
|
|
|
|
PuericulturaMarcoDesenvolvimento::orderBy('faixa_etaria_dias_fim')
|
|
->get()
|
|
->each(function ($marco) use ($marcos, $idadeEmMeses, $getResposta, $soapRascunho) {
|
|
|
|
$faixaEtariaEmMeses = floor($marco->faixa_etaria_dias_fim / 31);
|
|
|
|
if ($faixaEtariaEmMeses <= $idadeEmMeses) {
|
|
|
|
$marcoFaixaEtaria = $marcos->where('descricao', $marco->faixa_etaria_descricao)->first();
|
|
|
|
if (is_null($marcoFaixaEtaria)) {
|
|
|
|
$marcoFaixaEtaria = (object) [
|
|
'descricao' => $marco->faixa_etaria_descricao,
|
|
'perguntas' => collect(),
|
|
'show_alcancado_com' => $marco->faixa_etaria_dias_fim > 15,
|
|
'meses_final' => $faixaEtariaEmMeses,
|
|
];
|
|
|
|
$marcos->push($marcoFaixaEtaria);
|
|
}
|
|
|
|
$resposta = $getResposta($marco->id);
|
|
|
|
if (is_null($resposta->is_presente) && !is_null($soapRascunho)) {
|
|
|
|
$marcoRascunho = $soapRascunho->puericulturaMarcosDesenvolvimento()
|
|
->where('marco_desenvolvimento_id', $marco->id)
|
|
->first();
|
|
|
|
$marcoFaixaEtaria->perguntas->push((object) [
|
|
'id' => $marco->id,
|
|
'descricao' => $marco->descricao,
|
|
'dica' => $marco->dica,
|
|
'is_presente' => $marcoRascunho->is_presente ?? null,
|
|
'status' => null,
|
|
'is_respondido' => false,
|
|
'alcancado_com_anos' => $marcoRascunho->alcancado_com_anos ?? null,
|
|
'alcancado_com_meses' => $marcoRascunho->alcancado_com_meses ?? null,
|
|
]);
|
|
}
|
|
else {
|
|
|
|
$marcoFaixaEtaria->perguntas->push((object) [
|
|
'id' => $marco->id,
|
|
'descricao' => $marco->descricao,
|
|
'dica' => $marco->dica,
|
|
'is_presente' => $resposta->is_presente,
|
|
'status' => $resposta->status,
|
|
'is_respondido' => !is_null($resposta->is_presente),
|
|
'alcancado_com_anos' => $resposta->alcancado_com_anos,
|
|
'alcancado_com_meses' => $resposta->alcancado_com_meses,
|
|
]);
|
|
}
|
|
}
|
|
});
|
|
|
|
$marcos->each(function ($marco) {
|
|
|
|
$marco->perguntas->each(function ($pergunta) use ($marco) {
|
|
|
|
if ($pergunta->is_respondido) {
|
|
|
|
$meses = ($pergunta->alcancado_com_anos * 12) + $pergunta->alcancado_com_meses;
|
|
|
|
if ($pergunta->is_presente
|
|
&& $marco->meses_final > 0
|
|
&& $meses > $marco->meses_final
|
|
) {
|
|
|
|
$pergunta->status = "Presente com atraso em {$pergunta->status}";
|
|
}
|
|
else {
|
|
|
|
$pergunta->status = ($pergunta->is_presente ? 'Presente em ' : 'Ausente em ')
|
|
. $pergunta->status;
|
|
}
|
|
}
|
|
});
|
|
});
|
|
|
|
return $marcos;
|
|
}
|
|
|
|
private static function getUltimaAntropometriaAtendimento($atendimento)
|
|
{
|
|
$antropometria = AtendimentoAntropometria::where('atendimento_id', $atendimento->id)
|
|
->where(fn ($q) => $q
|
|
->whereDoesntHave('soap')
|
|
->orWhereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
)
|
|
)
|
|
->orderByDesc('medido_em')
|
|
->first();
|
|
|
|
if (is_null($antropometria)) {
|
|
|
|
return null;
|
|
}
|
|
|
|
return (object) [
|
|
'peso' => $antropometria->peso,
|
|
'altura' => is_null($antropometria->altura)
|
|
? null : (int) $antropometria->altura,
|
|
'imc' => isset($antropometria->peso) && isset($antropometria->altura)
|
|
? ImcService::calculate(
|
|
UnidadeMedidaEnum::QUILOGRAMAS,
|
|
$antropometria->peso,
|
|
UnidadeMedidaEnum::CENTIMETROS,
|
|
$antropometria->altura
|
|
)
|
|
: null,
|
|
'perimetro_cefalico' => is_null($antropometria->perimetro_cefalico)
|
|
? null : $antropometria->perimetro_cefalico,
|
|
'circunferencia_abdominal' => is_null($antropometria->circunferencia_abdominal)
|
|
? null : (int) $antropometria->circunferencia_abdominal,
|
|
'perimetro_panturrilha' => is_null($antropometria->perimetro_panturrilha)
|
|
? null : (int) $antropometria->perimetro_panturrilha,
|
|
'comprimento_pe_direito' => is_null($antropometria->comprimento_pe_direito)
|
|
? null : (int) $antropometria->comprimento_pe_direito,
|
|
'largura_pe_direito' => is_null($antropometria->largura_pe_direito)
|
|
? null : (int) $antropometria->largura_pe_direito,
|
|
'circunferencia_pe_direito' => is_null($antropometria->circunferencia_pe_direito)
|
|
? null : (int) $antropometria->circunferencia_pe_direito,
|
|
'comprimento_pe_esquerdo' => is_null($antropometria->comprimento_pe_esquerdo)
|
|
? null : (int) $antropometria->comprimento_pe_esquerdo,
|
|
'largura_pe_esquerdo' => is_null($antropometria->largura_pe_esquerdo)
|
|
? null : (int) $antropometria->largura_pe_esquerdo,
|
|
'circunferencia_pe_esquerdo' => is_null($antropometria->circunferencia_pe_esquerdo)
|
|
? null : (int) $antropometria->circunferencia_pe_esquerdo,
|
|
];
|
|
}
|
|
|
|
private static function getOrCreateSoapAtendimento(int $atendimentoId)
|
|
{
|
|
$soaps = AtendimentoSoap::where('atendimento_id', $atendimentoId)
|
|
->where('is_rascunho', false)
|
|
->lockForUpdate()
|
|
->orderByDesc('updated_at')
|
|
->get();
|
|
|
|
foreach ($soaps as $soap) {
|
|
|
|
if (self::dadosSoap($soap->id)) {
|
|
|
|
return $soap;
|
|
}
|
|
}
|
|
|
|
$novoSoap = new AtendimentoSoap();
|
|
$novoSoap->atendimento_id = $atendimentoId;
|
|
|
|
return $novoSoap;
|
|
}
|
|
|
|
private static function dadosSoap(int $soapId): bool
|
|
{
|
|
$dadosAntropometria = DB::table('ambulatorio_atendimento_antropometria')
|
|
->where('soap_id', $soapId)
|
|
->exists();
|
|
|
|
if ($dadosAntropometria) {
|
|
|
|
return true;
|
|
}
|
|
|
|
$dadosSinaisVitais = DB::table('ambulatorio_atendimento_sinal_vital')
|
|
->where('soap_id', $soapId)
|
|
->exists();
|
|
|
|
return $dadosSinaisVitais;
|
|
}
|
|
|
|
private static function getUltimoSinalVitalAtendimento($atendimento)
|
|
{
|
|
return AtendimentoSinalVital::where('atendimento_id', $atendimento->id)
|
|
->where(fn ($q) => $q
|
|
->whereDoesntHave('soap')
|
|
->orWhereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
)
|
|
)
|
|
->orderByDesc('created_at')
|
|
->first();
|
|
}
|
|
|
|
private static function getUltimaGlicemiaCapilarAtendimento($atendimento)
|
|
{
|
|
return AtendimentoGlicemiaCapilar::where('atendimento_id', $atendimento->id)
|
|
->where(fn ($q) => $q
|
|
->whereDoesntHave('soap')
|
|
->orWhereHas('soap', fn ($q) => $q
|
|
->where('is_rascunho', false)
|
|
)
|
|
)
|
|
->orderByDesc('created_at')
|
|
->first();
|
|
}
|
|
|
|
private static function getUltimasFeridasAtendimento($atendimento)
|
|
{
|
|
$soap = AtendimentoSoap::where('atendimento_id', $atendimento->id)
|
|
->where('is_rascunho', false)
|
|
->whereHas('feridas')
|
|
->orderByDesc('created_at')
|
|
->with([
|
|
'feridas.procedimentos.atendimentoProcedimento.procedimento',
|
|
'feridas.procedimentos.atendimentoProcedimento.cid'
|
|
])
|
|
->first();
|
|
|
|
return $soap ? $soap->feridas : collect();
|
|
}
|
|
|
|
private static function getPlanoModelData($atendimento, $soapRascunho)
|
|
{
|
|
$feridaProcedimentosIds = [];
|
|
|
|
$feridas = ($soapRascunho && $soapRascunho->feridas && $soapRascunho->feridas->isNotEmpty())
|
|
? $soapRascunho->feridas
|
|
: self::getUltimasFeridasAtendimento($atendimento);
|
|
|
|
|
|
|
|
$procedimentosFeridas = $feridas
|
|
->flatMap(function ($ferida) use (&$feridaProcedimentosIds) {
|
|
return $ferida->procedimentos->map(function ($feridaProcedimento) use (&$feridaProcedimentosIds) {
|
|
|
|
$atendimentoProcedimento = $feridaProcedimento->atendimentoProcedimento;
|
|
|
|
if (!$atendimentoProcedimento) {
|
|
return null;
|
|
}
|
|
|
|
$feridaProcedimentosIds[] = $atendimentoProcedimento->id;
|
|
|
|
return [
|
|
'id' => $feridaProcedimento->id,
|
|
'procedimento' => [
|
|
'id' => $atendimentoProcedimento->procedimento->id,
|
|
'codigo' => $atendimentoProcedimento->procedimento->codigo,
|
|
'nome' => $atendimentoProcedimento->procedimento->nome,
|
|
],
|
|
'cid' => $atendimentoProcedimento->cid ? [
|
|
'id' => $atendimentoProcedimento->cid->id,
|
|
'codigo' => $atendimentoProcedimento->cid->codigo,
|
|
'nome' => $atendimentoProcedimento->cid->nome,
|
|
] : null,
|
|
'quantidade' => $atendimentoProcedimento->quantidade,
|
|
'automatico' => $atendimentoProcedimento->automatico,
|
|
];
|
|
})->filter();
|
|
});
|
|
|
|
return [
|
|
'descricao' => $soapRascunho->plano_descricao ?? null,
|
|
'intervencoes' => ($soapRascunho->intervencoes ?? collect())->map(fn ($intervencao) => [
|
|
'ciap' => [
|
|
'id' => $intervencao->ciap->id,
|
|
'codigo' => $intervencao->ciap->codigo,
|
|
'descricao' => $intervencao->ciap->descricao,
|
|
],
|
|
'observacao' => $intervencao->observacao,
|
|
]),
|
|
'procedimentos_emad' => $soapRascunho && $soapRascunho->procedimentosEmad
|
|
? $soapRascunho->procedimentosEmad->map(function ($item) {
|
|
return [
|
|
'id' => $item->procedimento->id,
|
|
'codigo' => $item->procedimento->codigo,
|
|
'nome' => $item->procedimento->nome,
|
|
];
|
|
})
|
|
: collect(),
|
|
'procedimentos_clinicos' => ($soapRascunho->procedimentosClinicos ?? collect())
|
|
->filter(fn ($pc) => !in_array($pc->atendimento_procedimento_id, $feridaProcedimentosIds))
|
|
->map(fn ($procedmentoClinico) => [
|
|
'procedimento' => [
|
|
'id' => $procedmentoClinico->atendimentoProcedimento->procedimento->id,
|
|
'codigo' => $procedmentoClinico->atendimentoProcedimento->procedimento->codigo,
|
|
'nome' => $procedmentoClinico->atendimentoProcedimento->procedimento->nome,
|
|
'has_instrumento_registro_raas' => $procedmentoClinico->atendimentoProcedimento->procedimento
|
|
->registros()
|
|
->whereIn('codigo', [Registro::RAAS_ATENCAO_DOMICILIAR, Registro::RAAS_ATENCAO_PSICOSSOCIAL])
|
|
->exists(),
|
|
'has_cid_principal' => $procedmentoClinico->atendimentoProcedimento->procedimento->has_cid_principal,
|
|
],
|
|
'cid' => $procedmentoClinico->atendimentoProcedimento->cid ? [
|
|
'id' => $procedmentoClinico->atendimentoProcedimento->cid->id,
|
|
'codigo' => $procedmentoClinico->atendimentoProcedimento->cid->codigo,
|
|
'nome' => $procedmentoClinico->atendimentoProcedimento->cid->nome,
|
|
] : null,
|
|
'automatico' => $procedmentoClinico->atendimentoProcedimento->automatico,
|
|
'quantidade' => $procedmentoClinico->atendimentoProcedimento->quantidade,
|
|
'observacao' => $procedmentoClinico->observacao,
|
|
])->values(),
|
|
'procedimentos_feridas' => $procedimentosFeridas,
|
|
'prescricao_medicamentos' => $soapRascunho && $soapRascunho->prescricoesMedicamentos->isNotEmpty()
|
|
? $soapRascunho->prescricoesMedicamentos->first()->itens->map(fn ($item) => [
|
|
'old_id' => $item->prescricaoMedicamentoItemAnterior->prescricao_medicamento_id ?? null,
|
|
'prescricao_medicamento_item_anterior_id' => $item->prescricao_medicamento_item_anterior_id,
|
|
'is_manual' => $item->is_manual,
|
|
'manual_id' => $item->is_manual ? $item->id : null,
|
|
'receita_tipo_id' => $item->receita_tipo_id,
|
|
'descricao' => $item->descricao,
|
|
'justificativa' => $item->justificativa,
|
|
'material' => $item->material ? [
|
|
'id' => $item->material->id,
|
|
'descricao' => $item->material->descricao,
|
|
'via_administracao' => $item->material->viaAdministracao->nome ?? null,
|
|
'receita_tipo_id' => $item->material->receita_tipo_id,
|
|
'quantidade' => $item->material->quantidade,
|
|
'apresentacao' => $item->material->apresentacao->nome ?? null,
|
|
'receita_tipo' => $item->material->receitaTipo->nome ?? null,
|
|
'alto_custo' => $item->material->is_alto_custo ? 'ALTO CUSTO' : '',
|
|
'programa_remedio_em_casa' => $item->material->is_programa_remedio_em_casa ? 'PROGRAMA REMÉDIO EM CASA' : '',
|
|
'acao_judicial' => $item->material->is_acao_judicial ? 'AÇÃO JUDICIAL' : '',
|
|
'remume' => $item->material->is_remume ? 'REMUME' : '',
|
|
] : null,
|
|
'dose' => $item->dose,
|
|
'is_dose_unica' => $item->is_dose_unica,
|
|
'frequencia_dose' => $item->frequencia_dose,
|
|
'intervalo' => $item->intervalo,
|
|
'intervalo_medida_tempo_id' => $item->intervalo_medida_tempo_id,
|
|
'frequencia_vezes' => $item->frequencia_vezes,
|
|
'turno_id' => $item->turno_id,
|
|
'unidade_medida_id' => $item->unidade_medida_id,
|
|
'unidade_medida' => $item->unidadeMedida->nome ?? null,
|
|
'is_uso_continuo' => $item->is_uso_continuo,
|
|
'is_imprimir_separado' => $item->is_imprimir_separado,
|
|
'is_remover_impressao' => $item->is_remover_impressao,
|
|
'inicio' => $item->inicio ? $item->inicio->format('d/m/Y') : null,
|
|
'duracao' => $item->duracao,
|
|
'duracao_medida_tempo_id' => $item->duracao_medida_tempo_id ?? 'indeterminado',
|
|
'recomendacoes' => $item->recomendacoes,
|
|
'posologia' => $item->posologia,
|
|
'diagnostico' => 'diagnostico',
|
|
'tratamento_previo' => [
|
|
'status' => false,
|
|
'relatar' => 'relatar'
|
|
]
|
|
])
|
|
: [],
|
|
|
|
'prescricao_medicamento_anamnese' => $soapRascunho && $soapRascunho->prescricoesMedicamentos->isNotEmpty()
|
|
? $soapRascunho->prescricoesMedicamentos->first()->anamnese
|
|
: null,
|
|
'prescricao_medicamento_diagnostico' => $soapRascunho && $soapRascunho->prescricoesMedicamentos->isNotEmpty()
|
|
? $soapRascunho->prescricoesMedicamentos->first()->diagnostico
|
|
: null,
|
|
'prescricao_medicamento_tratamento_previo' => $soapRascunho && $soapRascunho->prescricoesMedicamentos->isNotEmpty()
|
|
? [
|
|
'status' => $soapRascunho->prescricoesMedicamentos->first()->tratamento_previo_status,
|
|
'relatar' => $soapRascunho->prescricoesMedicamentos->first()->tratamento_previo_relatar
|
|
]: [],
|
|
|
|
'prescricoes_medicamentos_clonados' => [],
|
|
'solicitacoes_exames_comuns' => ($soapRascunho
|
|
? $soapRascunho->solicitacoesExames()->where('alto_custo', false)->get()
|
|
: collect()
|
|
)->map(fn ($solicitacao) => [
|
|
'cid' => $solicitacao->cid ? [
|
|
'id' => $solicitacao->cid->id,
|
|
'codigo' => $solicitacao->cid->codigo,
|
|
'nome' => $solicitacao->cid->nome,
|
|
] : null,
|
|
'ciap' => $solicitacao->ciap ? [
|
|
'id' => $solicitacao->ciap->id,
|
|
'codigo' => $solicitacao->ciap->codigo,
|
|
'descricao' => $solicitacao->ciap->descricao,
|
|
] : null,
|
|
'classificacao_risco_id' => $solicitacao->classificacao_risco_id,
|
|
'classificacao_risco_descricao_encaminhamento' => $solicitacao->classificacaoRisco->descricao_encaminhamento ?? null,
|
|
'justificativa' => $solicitacao->justificativa,
|
|
'observacao' => $solicitacao->observacao,
|
|
'exames' => $solicitacao->itens->map(fn ($item) => [
|
|
'checked' => true,
|
|
'id' => $item->exame->id,
|
|
'codigo' => $item->exame->codigo,
|
|
'nome' => $item->exame->nome,
|
|
'tipoId' => $item->exame->tipo_id,
|
|
]),
|
|
]),
|
|
'solicitacoes_exames_alto_custo' => ($soapRascunho
|
|
? $soapRascunho->solicitacoesExames()->where('alto_custo', true)->get()
|
|
: collect()
|
|
)->map(fn ($solicitacao) => [
|
|
'cid' => $solicitacao->cid ? [
|
|
'id' => $solicitacao->cid->id,
|
|
'codigo' => $solicitacao->cid->codigo,
|
|
'nome' => $solicitacao->cid->nome,
|
|
] : null,
|
|
'ciap' => $solicitacao->ciap ? [
|
|
'id' => $solicitacao->ciap->id,
|
|
'codigo' => $solicitacao->ciap->codigo,
|
|
'descricao' => $solicitacao->ciap->descricao,
|
|
] : null,
|
|
'classificacao_risco_id' => $solicitacao->classificacao_risco_id,
|
|
'classificacao_risco_descricao_encaminhamento' => $solicitacao->classificacaoRisco->descricao_encaminhamento ?? null,
|
|
'justificativa' => $solicitacao->justificativa,
|
|
'observacao' => $solicitacao->observacao,
|
|
'exames' => $solicitacao->itens->map(fn ($item) => [
|
|
'id' => $item->exame->id,
|
|
'codigo' => $item->exame->codigo,
|
|
'nome' => $item->exame->nome,
|
|
'tipoId' => $item->exame->tipo_id,
|
|
]),
|
|
]),
|
|
'solicitacoes_procedimentos_cirurgicos' => ($soapRascunho
|
|
? $soapRascunho->solicitacoesProcedimentosCirurgicos()->get()
|
|
: collect()
|
|
)->map(fn ($solicitacao) => [
|
|
'cid' => $solicitacao->cid ? [
|
|
'id' => $solicitacao->cid->id,
|
|
'codigo' => $solicitacao->cid->codigo,
|
|
'nome' => $solicitacao->cid->nome,
|
|
] : null,
|
|
'ciap' => $solicitacao->ciap ? [
|
|
'id' => $solicitacao->ciap->id,
|
|
'codigo' => $solicitacao->ciap->codigo,
|
|
'descricao' => $solicitacao->ciap->descricao,
|
|
] : null,
|
|
'classificacao_risco_id' => $solicitacao->classificacao_risco_id,
|
|
'classificacao_risco_descricao_encaminhamento' => $solicitacao->classificacaoRisco->descricao_encaminhamento,
|
|
'justificativa' => $solicitacao->justificativa,
|
|
'observacao' => $solicitacao->observacao,
|
|
'procedimentos_cirurgicos' => $solicitacao->itens->map(fn ($item) => [
|
|
'id' => $item->procedimentoCirurgico->id,
|
|
'codigo' => $item->procedimentoCirurgico->procedimento_codigo,
|
|
'nome' => $item->procedimentoCirurgico->nome,
|
|
]),
|
|
]),
|
|
'atestados' => ($soapRascunho->atestados ?? collect())->map(fn ($atestado) => [
|
|
'modelo_id' => $atestado->modelo_id,
|
|
'nome' => $atestado->nome_acompanhante ?? $atestado->soap->atendimento->paciente->cidadao->nome,
|
|
'is_atestado_acompanhante' => $atestado->is_atestado_acompanhante,
|
|
'documento_tipo_id' => $atestado->documento_tipo_id,
|
|
'cpf' => MaskUtil::getCpfMasked($atestado->cpf),
|
|
'cns' => MaskUtil::getCnsMasked($atestado->cns),
|
|
'data' => $atestado->data ? $atestado->data->format('d/m/Y') : null,
|
|
'horario' => $atestado->horario ? $atestado->horario->format('H:i') : null,
|
|
'dias' => $atestado->dias,
|
|
'cid' => $atestado->cid ? [
|
|
'id' => $atestado->cid->id,
|
|
'codigo' => $atestado->cid->codigo,
|
|
'nome' => $atestado->cid->nome,
|
|
] : null,
|
|
'descricao' => $atestado->descricao,
|
|
'usuario' => [
|
|
'id' => $atestado->createdLotacao->usuario->id,
|
|
'nome' => $atestado->createdLotacao->usuario->nome,
|
|
],
|
|
]),
|
|
'declaracoes_comparecimento' => ($soapRascunho->declaracoesComparecimento ?? collect())
|
|
->map(fn ($declaracaoComparecimento) => [
|
|
'turno' => $declaracaoComparecimento->turno_id ? [
|
|
'id' => $declaracaoComparecimento->turno->id,
|
|
'nome' => $declaracaoComparecimento->turno->nome,
|
|
] : null,
|
|
'entrada' => $declaracaoComparecimento->entrada ? $declaracaoComparecimento->entrada->format('H:i') : null,
|
|
'saida' => $declaracaoComparecimento->saida ? $declaracaoComparecimento->saida->format('H:i') : null,
|
|
'nome_acompanhante' => $declaracaoComparecimento->nome_acompanhante,
|
|
'motivo_comparecimento' => $declaracaoComparecimento->motivo_comparecimento,
|
|
]),
|
|
'orientacoes' => ($soapRascunho->orientacoes ?? collect())->map(fn ($orientacao) => [
|
|
'descricao' => $orientacao->descricao
|
|
]),
|
|
'cartas_medicas' => ($soapRascunho->cartasMedicas ?? collect())->map(fn ($cartaMedica) => [
|
|
'descricao' => $cartaMedica->descricao
|
|
]),
|
|
'encaminhamentos' => ($soapRascunho->encaminhamentos ?? collect())->map(fn ($encaminhamento) => [
|
|
'tipo' => [
|
|
'id' => $encaminhamento->tipo->id,
|
|
'descricao' => $encaminhamento->tipo->descricao,
|
|
],
|
|
'unidade' => $encaminhamento->intersetorial_infraestrutura_id ? [
|
|
'id' => $encaminhamento->intersetorialInfraestrutura->unidade->id,
|
|
'nomeFantasia' => $encaminhamento->intersetorialInfraestrutura->unidade->nome_fantasia
|
|
] : null,
|
|
'infraestrutura' => $encaminhamento->intersetorial_infraestrutura_id ? [
|
|
'id' => $encaminhamento->intersetorialInfraestrutura->id,
|
|
'nome' => $encaminhamento->intersetorialInfraestrutura->nome,
|
|
] : null,
|
|
'especialidade' => $encaminhamento->servico_especializado_especialidade_id ? [
|
|
'id' => $encaminhamento->servicoEspecializadoEspecialidade->id,
|
|
'nome' => $encaminhamento->servicoEspecializadoEspecialidade->nome,
|
|
'ocupacao_codigo' => $encaminhamento->servicoEspecializadoEspecialidade->ocupacao->codigo
|
|
] : null,
|
|
'complemento' => $encaminhamento->servico_especializado_complemento,
|
|
'ciap' => $encaminhamento->servico_especializado_ciap_id ? [
|
|
'id' => $encaminhamento->servicoEspecializadoCiap->id,
|
|
'codigo' => $encaminhamento->servicoEspecializadoCiap->codigo,
|
|
'descricao' => $encaminhamento->servicoEspecializadoCiap->descricao,
|
|
] : null,
|
|
'cid' => $encaminhamento->servico_especializado_cid_id ? [
|
|
'id' => $encaminhamento->servicoEspecializadoCid->id,
|
|
'codigo' => $encaminhamento->servicoEspecializadoCid->codigo,
|
|
'nome' => $encaminhamento->servicoEspecializadoCid->nome,
|
|
] : null,
|
|
'classificacaoRisco' => $encaminhamento->servico_especializado_classificacao_risco_id ? [
|
|
'id' => $encaminhamento->servicoEspecializadoClassificacaoRisco->id,
|
|
'nome' => $encaminhamento->servicoEspecializadoClassificacaoRisco->nome,
|
|
] : null,
|
|
'motivo' => $encaminhamento->servico_especializado_motivo,
|
|
'observacao' => $encaminhamento->servico_especializado_observacao,
|
|
'internacao_hospitalar' => [
|
|
'cid_principal' => $encaminhamento->internacaoHospitalarCidPrincipal,
|
|
'cid_secundario' => $encaminhamento->internacaoHospitalarCidSecundario,
|
|
'cid_causas_associadas' => $encaminhamento->internacaoHospitalarCausasAssociadas,
|
|
'unidade_solicitante' => $encaminhamento->internacaoHospitalarUnidadeSolicitante,
|
|
'principais_sinais_sintomas_clinicos' => $encaminhamento->internacao_hosp_principais_sinais_sintomas_clinicos,
|
|
'condicoes_que_justificam_internacao' => $encaminhamento->internacao_hosp_condicoes_que_justificam_internacao,
|
|
'principais_resultados_de_provas_diagnosticas' => $encaminhamento->internacao_hosp_principais_resultados_de_provas_diagnosticas,
|
|
'procedimento' => [
|
|
'procedimento_solicitado' => $encaminhamento->internacaoHospitalarProcedimentoSolicitado,
|
|
'data_solicitacao' => $encaminhamento->internacao_hospitalar_data_solicitacao,
|
|
'clinica_id' => $encaminhamento->internacao_hospitalar_clinica_id,
|
|
'carater_internacao_id' => $encaminhamento->internacao_hospitalar_carater_internacao_id,
|
|
'profissional_solicitante_assistente' => $encaminhamento->internacaoHospitalarProfissionalSolicitanteAssistente ? [
|
|
'id' => $encaminhamento->internacaoHospitalarProfissionalSolicitanteAssistente->id,
|
|
'cidadaoNome' => $encaminhamento->internacaoHospitalarProfissionalSolicitanteAssistente->cidadao->nome,
|
|
'cidadaoCpf' => $encaminhamento->internacaoHospitalarProfissionalSolicitanteAssistente->cidadao->cpf,
|
|
'cidadaoCns' => $encaminhamento->internacaoHospitalarProfissionalSolicitanteAssistente->cidadao->cns,
|
|
] : null,
|
|
'profissional_solicitante_assistente_documento_tipo_id' => $encaminhamento->internacao_hospitalar_profissional_solicitante_documento_tipo_id,
|
|
'profissional_solicitante_assistente_documento_numero' => $encaminhamento->internacao_hospitalar_profissional_solicitante_documento_numero,
|
|
],
|
|
'causas_externas' => [
|
|
'causa_externa_id' => $encaminhamento->internacao_hospitalar_causa_externa_id,
|
|
'cnpj_seguradora' => $encaminhamento->internacao_hospitalar_cnpj_seguradora,
|
|
'numero_bilhete' => $encaminhamento->internacao_hospitalar_numero_bilhete,
|
|
'serie' => $encaminhamento->internacao_hospitalar_serie,
|
|
'cnpj_empresa' => $encaminhamento->internacao_hospitalar_cnpj_empresa,
|
|
'cnae_empresa' => $encaminhamento->internacao_hospitalar_cnae_empresa,
|
|
'cbor' => $encaminhamento->internacao_hospitalar_cbor,
|
|
'vinculo_previdencia_id' => $encaminhamento->internacao_hospitalar_vinculo_previdencia_id,
|
|
],
|
|
'autorizacao' => [
|
|
'profissional_autorizador' => $encaminhamento->internacaoHospitalarProfissionalAutorizador ? [
|
|
'id' => $encaminhamento->internacaoHospitalarProfissionalAutorizador->id,
|
|
'cidadaoNome' => $encaminhamento->internacaoHospitalarProfissionalAutorizador->cidadao->nome,
|
|
'cidadaoCpf' => $encaminhamento->internacaoHospitalarProfissionalAutorizador->cidadao->cpf,
|
|
'cidadaoCns' => $encaminhamento->internacaoHospitalarProfissionalAutorizador->cidadao->cns,
|
|
] : null,
|
|
'data_autorizacao' => $encaminhamento->internacao_hospitalar_data_autorizacao,
|
|
'codigo_orgao_emissor' => $encaminhamento->internacao_hospitalar_codigo_orgao_emissor,
|
|
'profissional_autorizador_documento_tipo_id' => $encaminhamento->internacao_hospitalar_profissional_autorizador_documento_tipo_id,
|
|
'profissional_autorizador_documento_numero' => $encaminhamento->internacao_hospitalar_profissional_autorizador_documento_numero,
|
|
],
|
|
],
|
|
]),
|
|
'compartilhamentos_cuidado' => ($soapRascunho->compartilhamentosCuidado ?? collect())
|
|
->map(fn ($compartilhamentoCuidado) => [
|
|
'especialidade_id' => $compartilhamentoCuidado->especialidade_id,
|
|
'usuario' => [
|
|
'id' => $compartilhamentoCuidado->usuario->id,
|
|
'cidadao_nome' => $compartilhamentoCuidado->usuario->cidadao->nome,
|
|
'cidadao_cns' => $compartilhamentoCuidado->usuario->cidadao->cns,
|
|
],
|
|
'ciap' => $compartilhamentoCuidado->ciap ? [
|
|
'id' => $compartilhamentoCuidado->ciap->id,
|
|
'codigo' => $compartilhamentoCuidado->ciap->codigo,
|
|
'descricao' => $compartilhamentoCuidado->ciap->descricao,
|
|
] : null,
|
|
'cid' => $compartilhamentoCuidado->cid ? [
|
|
'id' => $compartilhamentoCuidado->cid->id,
|
|
'codigo' => $compartilhamentoCuidado->cid->codigo,
|
|
'nome' => $compartilhamentoCuidado->cid->nome,
|
|
] : null,
|
|
'classificacao_risco' => $compartilhamentoCuidado->classificacao_risco_id ? [
|
|
'id' => $compartilhamentoCuidado->classificacaoRisco->id,
|
|
'nome' => $compartilhamentoCuidado->classificacaoRisco->nome,
|
|
] : null,
|
|
'discussao_caso_clinico' => $compartilhamentoCuidado->discussao_caso_clinico,
|
|
]),
|
|
'testes_rapidos' => ($soapRascunho->testesRapidos ?? collect())->map(fn ($testeRapido) => [
|
|
'id' => $testeRapido->id,
|
|
'resultado' => $testeRapido->soapTesteRapido->resultado,
|
|
]),
|
|
'saude_bucal' => self::getPlanoSaudeBucalModelData($soapRascunho),
|
|
'triagem_neonatal' => ($soapRascunho->atendimentoSoapTriagemNeonatalSolicitado->triagensNeonatalSolicitados ?? collect()),
|
|
'triagem_neonatal_cid' => $soapRascunho
|
|
&& $soapRascunho->atendimentoSoapTriagemNeonatalSolicitado
|
|
&& $soapRascunho->atendimentoSoapTriagemNeonatalSolicitado->cid
|
|
? [
|
|
'id' => $soapRascunho->atendimentoSoapTriagemNeonatalSolicitado->cid->id,
|
|
'codigo' => $soapRascunho->atendimentoSoapTriagemNeonatalSolicitado->cid->codigo,
|
|
'nome' => $soapRascunho->atendimentoSoapTriagemNeonatalSolicitado->cid->nome,
|
|
]
|
|
: null,
|
|
'triagem_neonatal_ciap' => $soapRascunho
|
|
&& $soapRascunho->atendimentoSoapTriagemNeonatalSolicitado
|
|
&& $soapRascunho->atendimentoSoapTriagemNeonatalSolicitado->ciap
|
|
? [
|
|
'id' => $soapRascunho->atendimentoSoapTriagemNeonatalSolicitado->ciap->id,
|
|
'codigo' => $soapRascunho->atendimentoSoapTriagemNeonatalSolicitado->ciap->codigo,
|
|
'descricao' => $soapRascunho->atendimentoSoapTriagemNeonatalSolicitado->ciap->descricao,
|
|
]
|
|
: null,
|
|
'triagem_neonatal_justificativa' => $soapRascunho->atendimentoSoapTriagemNeonatalSolicitado->justificativa ?? null,
|
|
'triagem_neonatal_observacao' => $soapRascunho->atendimentoSoapTriagemNeonatalSolicitado->observacao ?? null,
|
|
'exame_solicitado' => ($soapRascunho->atendimentoSoapExameSolicitado->examesSolicitados ?? collect()),
|
|
'exame_solicitado_cid' => $soapRascunho
|
|
&& $soapRascunho->atendimentoSoapExameSolicitado
|
|
&& $soapRascunho->atendimentoSoapExameSolicitado->cid
|
|
? [
|
|
'id' => $soapRascunho->atendimentoSoapExameSolicitado->cid->id,
|
|
'codigo' => $soapRascunho->atendimentoSoapExameSolicitado->cid->codigo,
|
|
'nome' => $soapRascunho->atendimentoSoapExameSolicitado->cid->nome,
|
|
]
|
|
: null,
|
|
'exame_solicitado_ciap' => $soapRascunho
|
|
&& $soapRascunho->atendimentoSoapExameSolicitado
|
|
&& $soapRascunho->atendimentoSoapExameSolicitado->ciap
|
|
? [
|
|
'id' => $soapRascunho->atendimentoSoapExameSolicitado->ciap->id,
|
|
'codigo' => $soapRascunho->atendimentoSoapExameSolicitado->ciap->codigo,
|
|
'descricao' => $soapRascunho->atendimentoSoapExameSolicitado->ciap->descricao,
|
|
]
|
|
: null,
|
|
'exame_solicitado_justificativa' => $soapRascunho->atendimentoSoapExameSolicitado->justificativa ?? null,
|
|
'exame_solicitado_observacao' => $soapRascunho->atendimentoSoapExameSolicitado->observacao ?? null,
|
|
'orientacao_individual_em_saude' => $soapRascunho->orientacao_individual_em_saude ?? false,
|
|
];
|
|
}
|
|
|
|
private static function getPlanoSaudeBucalModelData($soapRascunho)
|
|
{
|
|
return [
|
|
'odontograma' => self::getPlanoSaudeBucalOdontogramaModelData($soapRascunho),
|
|
];
|
|
}
|
|
|
|
private static function getPlanoSaudeBucalOdontogramaModelData($soapRascunho)
|
|
{
|
|
$odontograma = $soapRascunho->odontograma ?? null;
|
|
|
|
$getDentesData = function ($dente, $arcada) {
|
|
|
|
$denteData = $arcada ? $arcada->odontogramaArcadaDentes()->where('dente_id', $dente->id)->first() : null;
|
|
|
|
return [
|
|
'id' => $dente->id,
|
|
'numero' => $dente->numero,
|
|
'fragmentos' => [
|
|
'esquerda' => ['is_tratado' => $denteData->is_fragmento_esquerda_tratado ?? null],
|
|
'cima' => ['is_tratado' => $denteData->is_fragmento_cima_tratado ?? null],
|
|
'direita' => ['is_tratado' => $denteData->is_fragmento_direita_tratado ?? null],
|
|
'baixo' => ['is_tratado' => $denteData->is_fragmento_baixo_tratado ?? null],
|
|
'centro' => ['is_tratado' => $denteData->is_fragmento_centro_tratado ?? null],
|
|
],
|
|
'problemas_condicoes' => ($denteData->problemasCondicoes ?? collect())->pluck('id'),
|
|
'procedimentos' => ($denteData->atendimentoProcedimentos ?? collect())->map(fn ($atendimentoProcedimento) => [
|
|
'procedimento' => [
|
|
'id' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->id,
|
|
'codigo' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->codigo,
|
|
'nome' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->nome,
|
|
'has_cid_principal' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->has_cid_principal,
|
|
],
|
|
'cid' => $atendimentoProcedimento->atendimentoProcedimento->cid ? [
|
|
'id' => $atendimentoProcedimento->atendimentoProcedimento->cid->id,
|
|
'codigo' => $atendimentoProcedimento->atendimentoProcedimento->cid->codigo,
|
|
'nome' => $atendimentoProcedimento->atendimentoProcedimento->cid->nome,
|
|
] : null,
|
|
'quantidade' => $atendimentoProcedimento->atendimentoProcedimento->quantidade,
|
|
]),
|
|
'observacao' => $denteData->observacao ?? null,
|
|
];
|
|
};
|
|
|
|
$arcadaSuperior = $odontograma
|
|
? $odontograma->odontogramaArcadas()
|
|
->where('arcada_id', ArcadaDentaria::SUPERIOR)
|
|
->first()
|
|
: null;
|
|
|
|
$arcadaInferior = $odontograma
|
|
? $odontograma->odontogramaArcadas()
|
|
->where('arcada_id', ArcadaDentaria::INFERIOR)
|
|
->first()
|
|
: null;
|
|
|
|
$protesesTotais = collect();
|
|
|
|
if ($arcadaSuperior && $arcadaSuperior->possui_protese_total) {
|
|
|
|
$protesesTotais->push('superior');
|
|
}
|
|
|
|
if ($arcadaInferior && $arcadaInferior->possui_protese_total) {
|
|
|
|
$protesesTotais->push('inferior');
|
|
}
|
|
|
|
return [
|
|
'id' => null,
|
|
'possui_aparelho' => $odontograma->possui_aparelho ?? false,
|
|
'possui_contencao' => $odontograma->possui_contencao ?? false,
|
|
'proteses_totais' => $protesesTotais,
|
|
'mostrar_dentes_deciduos' => $odontograma
|
|
? $odontograma->whereHas('odontogramaArcadas', fn ($q) => $q
|
|
->whereHas('odontogramaArcadaDentes', fn ($q) => $q
|
|
->whereHas('dente', fn ($q) => $q->where('is_deciduo', true))
|
|
)
|
|
)
|
|
->exists()
|
|
: false,
|
|
'arcadas' => [
|
|
'superior' => [
|
|
'dentes' => [
|
|
'permanentes' => Dente::where('arcada_id', ArcadaDentaria::SUPERIOR)
|
|
->where('is_deciduo', false)
|
|
->orderBy('ordem')
|
|
->get()
|
|
->map(fn ($dente) => $getDentesData($dente, $arcadaSuperior)),
|
|
'deciduos' => Dente::where('arcada_id', ArcadaDentaria::SUPERIOR)
|
|
->where('is_deciduo', true)
|
|
->orderBy('ordem')
|
|
->get()
|
|
->map(fn ($dente) => $getDentesData($dente, $arcadaSuperior)),
|
|
],
|
|
'procedimentos' => ($arcadaSuperior->atendimentoProcedimentos ?? collect())
|
|
->map(fn ($atendimentoProcedimento) => [
|
|
'procedimento' => [
|
|
'id' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->id,
|
|
'codigo' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->codigo,
|
|
'nome' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->nome,
|
|
'has_cid_principal' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->has_cid_principal,
|
|
],
|
|
'cid' => $atendimentoProcedimento->atendimentoProcedimento->cid ? [
|
|
'id' => $atendimentoProcedimento->atendimentoProcedimento->cid->id,
|
|
'codigo' => $atendimentoProcedimento->atendimentoProcedimento->cid->codigo,
|
|
'nome' => $atendimentoProcedimento->atendimentoProcedimento->cid->nome,
|
|
] : null,
|
|
'quantidade' => $atendimentoProcedimento->atendimentoProcedimento->quantidade,
|
|
]),
|
|
'observacao' => $arcadaSuperior->observacao ?? null,
|
|
],
|
|
'inferior' => [
|
|
'dentes' => [
|
|
'permanentes' => Dente::where('arcada_id', ArcadaDentaria::INFERIOR)
|
|
->where('is_deciduo', false)
|
|
->orderBy('ordem')
|
|
->get()
|
|
->map(fn ($dente) => $getDentesData($dente, $arcadaInferior)),
|
|
'deciduos' => Dente::where('arcada_id', ArcadaDentaria::INFERIOR)
|
|
->where('is_deciduo', true)
|
|
->orderBy('ordem')
|
|
->get()
|
|
->map(fn ($dente) => $getDentesData($dente, $arcadaInferior)),
|
|
],
|
|
'procedimentos' => ($arcadaInferior->atendimentoProcedimentos ?? collect())
|
|
->map(fn ($atendimentoProcedimento) => [
|
|
'procedimento' => [
|
|
'id' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->id,
|
|
'codigo' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->codigo,
|
|
'nome' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->nome,
|
|
'has_cid_principal' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->has_cid_principal,
|
|
],
|
|
'cid' => $atendimentoProcedimento->atendimentoProcedimento->cid ? [
|
|
'id' => $atendimentoProcedimento->atendimentoProcedimento->cid->id,
|
|
'codigo' => $atendimentoProcedimento->atendimentoProcedimento->cid->codigo,
|
|
'nome' => $atendimentoProcedimento->atendimentoProcedimento->cid->nome,
|
|
] : null,
|
|
'quantidade' => $atendimentoProcedimento->atendimentoProcedimento->quantidade,
|
|
]),
|
|
'observacao' => $arcadaInferior->observacao ?? null,
|
|
],
|
|
],
|
|
'dentes_supranumerarios' => ($odontograma->dentesSupranumerarios ?? collect())
|
|
->map(fn ($denteSupranumerario) => [
|
|
'local' => $denteSupranumerario->local,
|
|
'procedimentos' => $denteSupranumerario->atendimentoProcedimentos->map(fn ($atendimentoProcedimento) => [
|
|
'procedimento' => [
|
|
'id' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->id,
|
|
'codigo' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->codigo,
|
|
'nome' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->nome,
|
|
'has_cid_principal' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->has_cid_principal,
|
|
],
|
|
'cid' => $atendimentoProcedimento->atendimentoProcedimento->cid ? [
|
|
'id' => $atendimentoProcedimento->atendimentoProcedimento->cid->id,
|
|
'codigo' => $atendimentoProcedimento->atendimentoProcedimento->cid->codigo,
|
|
'nome' => $atendimentoProcedimento->atendimentoProcedimento->cid->nome,
|
|
] : null,
|
|
'quantidade' => $atendimentoProcedimento->atendimentoProcedimento->quantidade,
|
|
]),
|
|
'observacao' => $denteSupranumerario->observacao,
|
|
]),
|
|
];
|
|
}
|
|
|
|
private static function getFinalizacaoModelData($atendimento, $soapRascunho, $fila = null)
|
|
{
|
|
$lotacaoLogada = self::getCurrentLotacao();
|
|
|
|
$parametrizacaoOcupacao = ParametrizacaoInfraestruturaOcupacao::whereHas('parametrizacaoInfraestrutura', fn ($q) => $q
|
|
->where('infraestrutura_id', $lotacaoLogada->infraestrutura_id)
|
|
)
|
|
->where('ocupacao_id', $lotacaoLogada->ocupacao_id)
|
|
->first();
|
|
|
|
return [
|
|
'atendimento_id' => $atendimento->id,
|
|
'demanda_tipo' => $atendimento->is_demanda_espontanea ? DemandaTipo::ESPONTANEA : DemandaTipo::AGENDADA,
|
|
'atendimento_tipo_id' => $soapRascunho->atendimento_tipo_id ?? $atendimento->atendimento_tipo_id,
|
|
'atendimento_compartilhado_usuario' => $soapRascunho
|
|
&& isset($soapRascunho->atendimentoCompartilhadoUsuario)
|
|
? [
|
|
'id' => $soapRascunho->atendimentoCompartilhadoUsuario->id,
|
|
'cidadao_cns' => $soapRascunho->atendimentoCompartilhadoUsuario->cidadao->cns,
|
|
'cidadao_nome' => $soapRascunho->atendimentoCompartilhadoUsuario->cidadao->nome,
|
|
]
|
|
: null,
|
|
'procedimentos_administrativos' => isset($soapRascunho)
|
|
? ($soapRascunho->procedimentosAdministrativos ?? collect())
|
|
->map(fn ($atendimentoProcedimento) => [
|
|
'procedimento' => [
|
|
'id' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->id,
|
|
'codigo' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->codigo,
|
|
'nome' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->nome,
|
|
'has_instrumento_registro_raas' => $atendimentoProcedimento->atendimentoProcedimento->procedimento
|
|
->registros()
|
|
->whereIn('codigo', [Registro::RAAS_ATENCAO_DOMICILIAR, Registro::RAAS_ATENCAO_PSICOSSOCIAL])
|
|
->exists(),
|
|
'has_cid_principal' => $atendimentoProcedimento->atendimentoProcedimento->procedimento->has_cid_principal,
|
|
],
|
|
'cid' => $atendimentoProcedimento->atendimentoProcedimento->cid ? [
|
|
'id' => $atendimentoProcedimento->atendimentoProcedimento->cid->id,
|
|
'codigo' => $atendimentoProcedimento->atendimentoProcedimento->cid->codigo,
|
|
'nome' => $atendimentoProcedimento->atendimentoProcedimento->cid->nome,
|
|
] : null,
|
|
'quantidade' => $atendimentoProcedimento->atendimentoProcedimento->quantidade,
|
|
'automatico' => $atendimentoProcedimento->atendimentoProcedimento->automatico,
|
|
])
|
|
: self::getProcedimentosPadroes($atendimento),
|
|
'caso_suspeito_id' => null,
|
|
'casos_suspeitos' => ($soapRascunho->casosSuspeitos ?? collect())->map(fn ($casoSuspeito) => [
|
|
'id' => $casoSuspeito->id,
|
|
'nome' => $casoSuspeito->nome,
|
|
'gera_impressao' => $casoSuspeito->gera_impressao,
|
|
]),
|
|
'racionalidade_saude_id' => $soapRascunho->racionalidade_saude_id ?? null,
|
|
'condutas' => ($soapRascunho->condutas ?? collect())->pluck('id'),
|
|
'saude_bucal' => [
|
|
'consulta_tipo_id' => $soapRascunho->saude_bucal_consulta_tipo_id ?? null,
|
|
'fornecimentos' => ($soapRascunho->saudeBucalFornecimentos ?? collect())->pluck('id'),
|
|
],
|
|
'equipe_id' => $soapRascunho->equipe_id ?? null,
|
|
'atencao_basica_local_atendimento_id' => $soapRascunho->atencao_basica_local_atendimento_id
|
|
?? (self::criaFichaAtencaoBasica() ? LocalAtendimentoEnum::UBS : null),
|
|
'turno_id' => $soapRascunho
|
|
? $soapRascunho->turno_id
|
|
: (self::criaFichaAtencaoBasica() ? self::getTurnoMomento() : null),
|
|
'desfecho' => [
|
|
'finalizado' => null,
|
|
'ocupacao_id' => $atendimento->ocupacao->id ?? null,
|
|
'especialidade_id' => $atendimento->especialidade->id ?? null,
|
|
'usuario_id' => $atendimento->usuario->id ?? null,
|
|
'jornada_id' => $atendimento->demandaEspontanea->jornada_id ?? null,
|
|
'opcao_entrada_id' => $fila->opcao_entrada_id ?? null,
|
|
'prioridade_id' => $fila->prioridade_id ?? null,
|
|
'centro_custo_encaminhamento_id' => null,
|
|
'pos_consulta' => $parametrizacaoOcupacao->pos_consulta ?? false,
|
|
'servicos' => $atendimento->servicos->pluck('id'),
|
|
'protocolo_fechamento' => null,
|
|
],
|
|
'is_tratamento_concluido' => $soapRascunho->is_tratamento_concluido ?? null,
|
|
'emad_conduta_desfecho_id' => $soapRascunho->emad_conduta_desfecho_id ?? null,
|
|
'emad_modalidade_id' => $soapRascunho->emad_modalidade_id ?? null,
|
|
'emad_procedencia_id' => $soapRascunho->emad_procedencia_id ?? null,
|
|
'emad_conclusao_id' => $soapRascunho->emad_conclusao_id ?? null,
|
|
'emad_cid_primario_id' => $soapRascunho && $soapRascunho->emad_cid_primario_id
|
|
? [
|
|
'id' => $soapRascunho->emad_cid_primario_id,
|
|
'nome' => Cid::where('id', $soapRascunho->emad_cid_primario_id)->first()->nome,
|
|
'codigo' => Cid::where('id', $soapRascunho->emad_cid_primario_id)->first()->codigo,
|
|
] : null,
|
|
'emad_select_cid_primario_id' => $soapRascunho && $soapRascunho->emad_cid_primario_id
|
|
? [
|
|
'id' => $soapRascunho->emad_cid_primario_id,
|
|
'nome' => Cid::where('id', $soapRascunho->emad_cid_primario_id)->first()->nome,
|
|
'codigo' => Cid::where('id', $soapRascunho->emad_cid_primario_id)->first()->codigo,
|
|
] : null,
|
|
'emad_cuidador_id' => $soapRascunho->emad_cuidador_id ?? EnumCuidador::NAO_POSSUI,
|
|
'emad_cns_cuidador' => $soapRascunho->emad_cns_cuidador ?? null,
|
|
'emad_cpf_cuidador' => $soapRascunho->emad_cpf_cuidador ?? null,
|
|
'emad_tipo_atendimento_id' => $soapRascunho && $soapRascunho->emad_tipo_atendimento_id
|
|
? $soapRascunho->emad_tipo_atendimento_id
|
|
: ($atendimento->is_demanda_espontanea ? TipoAtendimentoEnum::ATENDIMENTO_NAO_PROGRAMADO : TipoAtendimentoEnum::ATENDIMENTO_PROGRAMADO),
|
|
'emad_conclusao_justificativa' => $soapRascunho && $soapRascunho->justificativaEmad
|
|
? $soapRascunho->justificativaEmad->pluck('id')
|
|
: collect(),
|
|
'oci_desfecho_etapa_clinica_id' => $soapRascunho->oci_desfecho_etapa_clinica_id ?? null,
|
|
'apac_motivo_saida_permanencia_id' => $soapRascunho->apac_motivo_saida_permanencia_id ?? null,
|
|
];
|
|
}
|
|
|
|
private static function getProcedimentosPadroes($atendimento)
|
|
{
|
|
if ($atendimento->especialidade) {
|
|
|
|
$procedimentosParametrizados = self::getProcedimentosParametrizados($atendimento);
|
|
|
|
if ($procedimentosParametrizados->isNotEmpty()) {
|
|
|
|
return $procedimentosParametrizados;
|
|
}
|
|
else if ($atendimento->especialidade->atencao_basica_procedimento_padrao_codigo) {
|
|
|
|
return collect([
|
|
[
|
|
'procedimento' => [
|
|
'id' => $atendimento->especialidade->atencao_basica_procedimento_padrao->id,
|
|
'codigo' => $atendimento->especialidade->atencao_basica_procedimento_padrao->codigo,
|
|
'nome' => $atendimento->especialidade->atencao_basica_procedimento_padrao->nome,
|
|
'has_instrumento_registro_raas' => $atendimento->especialidade->atencao_basica_procedimento_padrao
|
|
->registros()
|
|
->whereIn('codigo', [Registro::RAAS_ATENCAO_DOMICILIAR, Registro::RAAS_ATENCAO_PSICOSSOCIAL])
|
|
->exists(),
|
|
'has_cid_principal' => $atendimento->especialidade->atencao_basica_procedimento_padrao->has_cid_principal,
|
|
],
|
|
'cid' => null,
|
|
'quantidade' => 1,
|
|
'automatico' => true,
|
|
]
|
|
]);
|
|
}
|
|
}
|
|
|
|
return collect();
|
|
}
|
|
|
|
private static function getProcedimentosParametrizados($atendimento)
|
|
{
|
|
return ParametrizacaoInfraestruturaEspecialidadeProcedimento::whereHas(
|
|
'parametrizacaoInfraestruturaEspecialidade',
|
|
fn ($q) => $q
|
|
->where('especialidade_id', $atendimento->especialidade->id)
|
|
->whereHas('parametrizacaoInfraestrutura', fn ($q) => $q
|
|
->where('infraestrutura_id', $atendimento->infraestrutura->id)
|
|
)
|
|
)
|
|
->get()
|
|
->map(fn ($parametrizacaoProcedimento) => [
|
|
'procedimento' => [
|
|
'id' => $parametrizacaoProcedimento->procedimento->id,
|
|
'codigo' => $parametrizacaoProcedimento->procedimento->codigo,
|
|
'nome' => $parametrizacaoProcedimento->procedimento->nome,
|
|
'has_instrumento_registro_raas' => $parametrizacaoProcedimento->procedimento
|
|
->registros()
|
|
->whereIn('codigo', [Registro::RAAS_ATENCAO_DOMICILIAR, Registro::RAAS_ATENCAO_PSICOSSOCIAL])
|
|
->exists(),
|
|
'has_cid_principal' => $parametrizacaoProcedimento->procedimento->has_cid_principal,
|
|
],
|
|
'cid' => null,
|
|
'quantidade' => 1,
|
|
'automatico' => true,
|
|
]);
|
|
}
|
|
|
|
private static function getTurnoMomento()
|
|
{
|
|
$now = Carbon::now();
|
|
|
|
$isManha = fn () => $now->hour >= 6 && $now->hour <= 11;
|
|
$isTarde = fn () => $now->hour >= 12 && $now->hour <= 17;
|
|
|
|
if ($isManha()) {
|
|
|
|
return TurnoEnum::MANHA;
|
|
}
|
|
else if ($isTarde()) {
|
|
|
|
return TurnoEnum::TARDE;
|
|
}
|
|
else {
|
|
|
|
return TurnoEnum::NOITE;
|
|
}
|
|
}
|
|
|
|
private static function getExamesRealizadosOci($acompanhamentoOci){
|
|
|
|
$procedimentosPrimariosOci = DB::table('cadastro_oci_procedimento_primario AS procedimento_primario')
|
|
->where('procedimento_primario.oci_id', $acompanhamentoOci->oci_id)
|
|
->select('procedimento_primario.procedimento_codigo')
|
|
->get()
|
|
->pluck('procedimento_codigo')
|
|
->all();
|
|
|
|
$competencias = Competencia::latest()->take(2)->get()->pluck('id');
|
|
|
|
$procedimentoOciRealizado = false;
|
|
|
|
DB::table('ambulatorio_atendimento_soap_solicitacao_exame_item as solicitacao_exame_item')
|
|
->join('parametrizacao_exame as exame', 'exame.id', 'solicitacao_exame_item.exame_id')
|
|
->join('sigtap.procedimento as procedimento', fn ($j) => $j
|
|
->on('procedimento.codigo', 'exame.codigo')
|
|
->whereIn('procedimento.competencia_id', $competencias)
|
|
)
|
|
->join(
|
|
'ambulatorio_atendimento_soap_solicitacao_exame as solicitacao_exame',
|
|
'solicitacao_exame.id',
|
|
'solicitacao_exame_item.solicitacao_exame_id'
|
|
)
|
|
->join('ambulatorio_atendimento_soap as soap', 'soap.id', 'solicitacao_exame.soap_id')
|
|
->where('soap.acompanhamento_oci_id', $acompanhamentoOci->id)
|
|
->whereIn('exame.codigo', $procedimentosPrimariosOci)
|
|
->select(
|
|
'solicitacao_exame_item.id',
|
|
'procedimento.id as procedimento_id',
|
|
'solicitacao_exame_item.ocupacao_executora_id',
|
|
'solicitacao_exame_item.status_id'
|
|
)
|
|
->get()
|
|
->each(function ($solicitacaoExameItem) use (&$procedimentoOciRealizado){
|
|
|
|
$exameLaboratorial = DB::table('exame_laboratorial_agendamento_exame as agendamento_exame')
|
|
->join('exame_laboratorial_agendamento as agendamento', 'agendamento.id', 'agendamento_exame.agendamento_id')
|
|
->where('agendamento_exame.soap_solicitacao_exame_item_id', $solicitacaoExameItem->id)
|
|
->whereIn('agendamento_exame.status_id', [
|
|
StatusAgendamento::REALIZADO,
|
|
StatusAgendamento::PENDENTE_ASSINATURA,
|
|
StatusAgendamento::ASSINADO,
|
|
StatusAgendamento::PENDENTE_ENTREGA,
|
|
StatusAgendamento::ENTREGUE,
|
|
])
|
|
->first();
|
|
|
|
if (!is_null($exameLaboratorial)) {
|
|
|
|
$procedimentoOciRealizado = true;
|
|
|
|
return;
|
|
}
|
|
|
|
$exameImagem = DB::table('exame_imagem_agendamento_exame as agendamento_exame')
|
|
->join('exame_imagem_fechamento_faturamento as fechamento', 'fechamento.agendamento_exame_id', 'agendamento_exame.id')
|
|
->where('agendamento_exame.soap_solicitacao_exame_item_id', $solicitacaoExameItem->id)
|
|
->first();
|
|
|
|
if (!is_null($exameImagem)) {
|
|
|
|
$procedimentoOciRealizado = true;
|
|
|
|
return;
|
|
}
|
|
|
|
$exameLaboratorialReguladoInterno = DB::table('regulacao_solicitacao_item as solicitacao_item')
|
|
->join('regulacao_solicitacao as solicitacao', 'solicitacao.id', 'solicitacao_item.solicitacao_id')
|
|
->join('regulacao_status as status', 'status.id', 'solicitacao.status_id')
|
|
->join('exame_laboratorial_agendamento as agendamento', 'agendamento.regulacao_solicitacao_id', 'solicitacao.id')
|
|
->join('exame_laboratorial_agendamento_exame as agendamento_exame', fn ($j) => $j
|
|
->on('agendamento_exame.agendamento_id', 'agendamento.id')
|
|
->whereColumn('agendamento_exame.exame_id', 'solicitacao_item.exame_id')
|
|
)
|
|
->where('solicitacao_item.soap_solicitacao_item_id', $solicitacaoExameItem->id)
|
|
->where('status.tipo_id', RegulacaoStatusTipo::REALIZADO)
|
|
->first();
|
|
|
|
if (!is_null($exameLaboratorialReguladoInterno)) {
|
|
|
|
$procedimentoOciRealizado = true;
|
|
|
|
return;
|
|
}
|
|
|
|
$exameImagemReguladoInterno = DB::table('regulacao_solicitacao_item as solicitacao_item')
|
|
->join('regulacao_solicitacao as solicitacao', 'solicitacao.id', 'solicitacao_item.solicitacao_id')
|
|
->join('regulacao_status as status', 'status.id', 'solicitacao.status_id')
|
|
->join('exame_imagem_agendamento as agendamento', 'agendamento.regulacao_solicitacao_id', 'solicitacao.id')
|
|
->join('exame_imagem_agendamento_exame as agendamento_exame', fn ($j) => $j
|
|
->on('agendamento_exame.agendamento_id', 'agendamento.id')
|
|
->whereColumn('agendamento_exame.exame_id', 'solicitacao_item.exame_id')
|
|
)
|
|
->join('exame_imagem_fechamento_faturamento as fechamento', 'fechamento.agendamento_exame_id', 'agendamento_exame.id')
|
|
->where('solicitacao_item.soap_solicitacao_item_id', $solicitacaoExameItem->id)
|
|
->where('status.tipo_id', RegulacaoStatusTipo::REALIZADO)
|
|
->first();
|
|
|
|
if (!is_null($exameImagemReguladoInterno)) {
|
|
|
|
$procedimentoOciRealizado = true;
|
|
|
|
return;
|
|
}
|
|
|
|
$exameReguladoExterno = DB::table('regulacao_solicitacao_item as solicitacao_item')
|
|
->join('regulacao_solicitacao as solicitacao', 'solicitacao.id', 'solicitacao_item.solicitacao_id')
|
|
->join('regulacao_status as status', 'status.id', 'solicitacao.status_id')
|
|
->where('solicitacao_item.soap_solicitacao_item_id', $solicitacaoExameItem->id)
|
|
->where('status.tipo_id', RegulacaoStatusTipo::REALIZADO)
|
|
->whereNotNull('solicitacao.prestador_externo_id')
|
|
->first();
|
|
|
|
if ($exameReguladoExterno) {
|
|
|
|
$procedimentoOciRealizado = true;
|
|
|
|
return;
|
|
}
|
|
|
|
$exameExternoNaoRegulado = DB::table('ambulatorio_atendimento_soap_solicitacao_exame_item')
|
|
->select('ambulatorio_atendimento_soap_solicitacao_exame_item.*')
|
|
->leftJoin('exame_laboratorial_agendamento_exame as agendamento_exame', 'agendamento_exame.soap_solicitacao_exame_item_id', 'ambulatorio_atendimento_soap_solicitacao_exame_item.id')
|
|
->leftJoin('exame_imagem_agendamento_exame as agendamento_exame_imagem', 'agendamento_exame_imagem.soap_solicitacao_exame_item_id', 'ambulatorio_atendimento_soap_solicitacao_exame_item.id')
|
|
->leftJoin('regulacao_solicitacao_item as solicitacao_item', 'solicitacao_item.soap_solicitacao_item_id', 'ambulatorio_atendimento_soap_solicitacao_exame_item.id')
|
|
->whereNull('agendamento_exame.soap_solicitacao_exame_item_id')
|
|
->whereNull('agendamento_exame_imagem.soap_solicitacao_exame_item_id')
|
|
->whereNull('solicitacao_item.soap_solicitacao_item_id')
|
|
->where('ambulatorio_atendimento_soap_solicitacao_exame_item.id', $solicitacaoExameItem->id)
|
|
->where('ambulatorio_atendimento_soap_solicitacao_exame_item.status_id', AtendimentoSoapSolicitacaoExameItemStatus::REALIZADO)
|
|
->first();
|
|
|
|
if (!is_null($exameExternoNaoRegulado)) {
|
|
|
|
$procedimentoOciRealizado = true;
|
|
|
|
return;
|
|
}
|
|
|
|
});
|
|
|
|
if (!$procedimentoOciRealizado) {
|
|
|
|
$realizado = true;
|
|
|
|
foreach ($procedimentosPrimariosOci as $procedimentoPrimarioCodigo) {
|
|
|
|
$hasProcedimentoRealizado = DB::table('ambulatorio_acompanhamento_oci_procedimento_realizado as procedimento_realizado')
|
|
->join('sigtap.procedimento as procedimento', 'procedimento.id', 'procedimento_realizado.procedimento_id')
|
|
->where('procedimento_realizado.acompanhamento_oci_id', $acompanhamentoOci->id)
|
|
->where('procedimento.codigo', $procedimentoPrimarioCodigo)
|
|
->exists();
|
|
|
|
if (!$hasProcedimentoRealizado) {
|
|
|
|
$realizado = false;
|
|
}
|
|
}
|
|
|
|
$procedimentoOciRealizado = $realizado;
|
|
}
|
|
|
|
return $procedimentoOciRealizado;
|
|
}
|
|
|
|
private static function getOciModelData($atendimento, $soapRascunho)
|
|
{
|
|
$oci = null;
|
|
|
|
if (!$atendimento->is_demanda_espontanea) {
|
|
|
|
$ociModel = null;
|
|
$etapaClinicaAtual = null;
|
|
$etapasConcluidas = null;
|
|
$prazoValidade = null;
|
|
$usuarioQueIniciou = null;
|
|
$procedimentosRealizadosSaved = [];
|
|
$procedimentoOciRealizado = null;
|
|
|
|
$acompanhamentoOci = AcompanhamentoOci::where('paciente_id', $atendimento->paciente->id)
|
|
->where('ocupacao_id', $atendimento->ocupacao->id)
|
|
->whereNull('finalizado_em')
|
|
->first();
|
|
|
|
if (!is_null($acompanhamentoOci)) {
|
|
|
|
$ultimaEtapaConcluida = $acompanhamentoOci->etapasClinicasConcluidas()->orderByDesc('id')->first();
|
|
$ociModel = $acompanhamentoOci->oci;
|
|
$prazoValidade = self::getPrazoValidadeOci($acompanhamentoOci)->format('d/m/Y');
|
|
$usuarioQueIniciou = $acompanhamentoOci->iniciadoLotacao->usuario->cidadao->nome;
|
|
$procedimentoOciRealizado = self::getExamesRealizadosOci($acompanhamentoOci);
|
|
|
|
if (($ultimaEtapaConcluida->soap->atendimento_id ?? null) !== $atendimento->id) {
|
|
|
|
$etapaClinicaAtual = $acompanhamentoOci->etapaClinicaAtual;
|
|
}
|
|
else {
|
|
|
|
$etapaClinicaAtual = $ultimaEtapaConcluida->etapaClinica;
|
|
}
|
|
|
|
$procedimentosRealizadosSaved = $acompanhamentoOci->procedimentosRealizados->map(fn ($procedimentoRealizado) => [
|
|
'id' => $procedimentoRealizado->procedimento->id,
|
|
'codigo' => $procedimentoRealizado->procedimento->codigo,
|
|
'descricao' => MaskUtil::getProcedimentoMasked($procedimentoRealizado->procedimento->codigo)
|
|
. " - {$procedimentoRealizado->procedimento->nome}",
|
|
'is_realizado' => true,
|
|
'data_executada' => is_null($procedimentoRealizado->data_executada)
|
|
? null
|
|
: $procedimentoRealizado->data_executada->format('d/m/Y'),
|
|
'unidade_executora_id' => $procedimentoRealizado->unidade_executora_id,
|
|
'ocupacao_executora' => is_null($procedimentoRealizado->ocupacao_executora_id)
|
|
? null
|
|
: [
|
|
'id' => $procedimentoRealizado->ocupacaoExecutora->id,
|
|
'codigo' => $procedimentoRealizado->ocupacaoExecutora->codigo,
|
|
'nome' => $procedimentoRealizado->ocupacaoExecutora->nome,
|
|
],
|
|
'usuario_executor' => $procedimentoRealizado->usuario_executor_nome,
|
|
]);
|
|
|
|
$etapasConcluidas = $acompanhamentoOci->etapasClinicasConcluidas()
|
|
->orderBy('id')
|
|
->get()
|
|
->map(fn ($e) => $e->etapaClinica->nome)
|
|
->unique()
|
|
->values()
|
|
->join(', ');
|
|
}
|
|
else if (isset($soapRascunho->oci)) {
|
|
|
|
$ociModel = $soapRascunho->oci;
|
|
|
|
$etapaClinicaAtual = EtapaClinica::findOrFail(
|
|
$ociModel->etapasClinicas()->where('id', EtapaClinicaEnum::ENTRADA_ALTA)->exists()
|
|
? EtapaClinicaEnum::ENTRADA_ALTA
|
|
: EtapaClinicaEnum::ENTRADA
|
|
);
|
|
}
|
|
|
|
if (!is_null($ociModel)) {
|
|
|
|
$oci = [
|
|
'id' => $ociModel->id,
|
|
'nome' => $ociModel->nome,
|
|
'linha_cuidado' => $ociModel->linha_cuidado,
|
|
'etapa_clinica_atual_id' => $etapaClinicaAtual->id ?? null,
|
|
'etapa_clinica_atual_nome' => $etapaClinicaAtual->nome ?? null,
|
|
'procedimentos_primarios' => $ociModel->procedimentosPrimarios->map(fn ($procedimento) => [
|
|
'id' => $procedimento->procedimento->id,
|
|
'codigo' => $procedimento->procedimento_codigo,
|
|
'descricao' => MaskUtil::getProcedimentoMasked($procedimento->procedimento->codigo)
|
|
. " - {$procedimento->procedimento->nome}",
|
|
]),
|
|
'procedimentos_secundarios' => $ociModel->procedimentosSecundarios
|
|
->filter(fn ($p) => !collect([
|
|
ProcedimentoEnum::CONSULTA_MEDICA_EM_ATENCAO_ESPECIALIZADA,
|
|
ProcedimentoEnum::TELECONSULTA_MEDICA_NA_ATENCAO_ESPECIALIZADA,
|
|
])->contains($p->procedimento_codigo))
|
|
->map(fn ($procedimento) => [
|
|
'id' => $procedimento->procedimento->id,
|
|
'codigo' => $procedimento->procedimento_codigo,
|
|
'descricao' => MaskUtil::getProcedimentoMasked($procedimento->procedimento->codigo)
|
|
. " - {$procedimento->procedimento->nome}",
|
|
])
|
|
->values(),
|
|
'procedimentos_consulta' => $ociModel->procedimentosSecundarios()
|
|
->whereIn('procedimento_codigo', [
|
|
ProcedimentoEnum::CONSULTA_MEDICA_EM_ATENCAO_ESPECIALIZADA,
|
|
ProcedimentoEnum::TELECONSULTA_MEDICA_NA_ATENCAO_ESPECIALIZADA,
|
|
])
|
|
->get()
|
|
->map(fn ($p) => $p->procedimento_codigo),
|
|
'cids' => self::getCidsOci($ociModel),
|
|
'etapas_clinicas' => $ociModel->etapasClinicas->map(fn ($ec) => $ec->id),
|
|
'etapas_concluidas' => $etapasConcluidas,
|
|
'prazo_validade' => $prazoValidade,
|
|
'usuario_que_iniciou' => $usuarioQueIniciou,
|
|
'exame_oci_realizado' => $procedimentoOciRealizado,
|
|
'unidades_executoras' => $ociModel->unidadesExecutoras->map(fn ($unidadeExecutora) => [
|
|
'id' => $unidadeExecutora->unidade->id,
|
|
'nome_fantasia' => $unidadeExecutora->unidade->nome_fantasia,
|
|
])->sortBy('nome_fantasia')->values(),
|
|
'procedimentos_realizados_previamente' => isset($soapRascunho)
|
|
? $soapRascunho->ociProcedimentosRealizados->map(fn ($procedimentoRealizado) => [
|
|
'id' => $procedimentoRealizado->procedimento->id,
|
|
'codigo' => $procedimentoRealizado->procedimento->codigo,
|
|
'is_realizado' => true,
|
|
'data_executada' => is_null($procedimentoRealizado->data_executada)
|
|
? null
|
|
: $procedimentoRealizado->data_executada->format('d/m/Y'),
|
|
'unidade_executora_id' => $procedimentoRealizado->unidade_executora_id,
|
|
'ocupacao_executora_id' => $procedimentoRealizado->ocupacao_executora_id,
|
|
'ocupacao_executora' => is_null($procedimentoRealizado->ocupacao_executora_id)
|
|
? null
|
|
: [
|
|
'id' => $procedimentoRealizado->ocupacaoExecutora->id,
|
|
'codigo' => $procedimentoRealizado->ocupacaoExecutora->codigo,
|
|
'nome' => $procedimentoRealizado->ocupacaoExecutora->nome,
|
|
],
|
|
'usuario_executor' => $procedimentoRealizado->usuario_executor_nome,
|
|
])
|
|
: [],
|
|
'procedimentos_realizados_previamente_saved' => $procedimentosRealizadosSaved,
|
|
];
|
|
}
|
|
}
|
|
|
|
return [
|
|
'oci' => $oci,
|
|
];
|
|
}
|
|
|
|
public static function getOci($id)
|
|
{
|
|
$oci = Oci::findOrFail($id);
|
|
|
|
$etapaClinicaAtual = EtapaClinica::findOrFail(
|
|
$oci->etapasClinicas()->where('id', EtapaClinicaEnum::ENTRADA_ALTA)->exists()
|
|
? EtapaClinicaEnum::ENTRADA_ALTA
|
|
: EtapaClinicaEnum::ENTRADA
|
|
);
|
|
|
|
return [
|
|
'id' => $oci->id,
|
|
'nome' => $oci->nome,
|
|
'linha_cuidado' => $oci->linha_cuidado,
|
|
'etapa_clinica_atual_id' => $etapaClinicaAtual->id,
|
|
'etapa_clinica_atual_nome' => $etapaClinicaAtual->nome,
|
|
'procedimentos_primarios' => $oci->procedimentosPrimarios->map(fn ($procedimento) => [
|
|
'id' => $procedimento->procedimento->id,
|
|
'codigo' => $procedimento->procedimento_codigo,
|
|
'descricao' => MaskUtil::getProcedimentoMasked($procedimento->procedimento->codigo)
|
|
. " - {$procedimento->procedimento->nome}",
|
|
]),
|
|
'procedimentos_secundarios' => $oci->procedimentosSecundarios
|
|
->filter(fn ($p) => !collect([
|
|
ProcedimentoEnum::CONSULTA_MEDICA_EM_ATENCAO_ESPECIALIZADA,
|
|
ProcedimentoEnum::TELECONSULTA_MEDICA_NA_ATENCAO_ESPECIALIZADA,
|
|
])->contains($p->procedimento_codigo))
|
|
->map(fn ($procedimento) => [
|
|
'id' => $procedimento->procedimento->id,
|
|
'codigo' => $procedimento->procedimento_codigo,
|
|
'descricao' => MaskUtil::getProcedimentoMasked($procedimento->procedimento->codigo)
|
|
. " - {$procedimento->procedimento->nome}",
|
|
])
|
|
->values(),
|
|
'procedimentos_consulta' => $oci->procedimentosSecundarios()
|
|
->whereIn('procedimento_codigo', [
|
|
ProcedimentoEnum::CONSULTA_MEDICA_EM_ATENCAO_ESPECIALIZADA,
|
|
ProcedimentoEnum::TELECONSULTA_MEDICA_NA_ATENCAO_ESPECIALIZADA,
|
|
])
|
|
->get()
|
|
->map(fn ($p) => $p->procedimento_codigo),
|
|
'cids' => self::getCidsOci($oci),
|
|
'etapas_clinicas' => $oci->etapasClinicas->map(fn ($ec) => $ec->id),
|
|
'etapas_concluidas' => null,
|
|
'prazo_validade' => null,
|
|
'usuario_que_iniciou' => null,
|
|
'unidades_executoras' => $oci->unidadesExecutoras->map(fn ($unidadeExecutora) => [
|
|
'id' => $unidadeExecutora->unidade->id,
|
|
'nome_fantasia' => $unidadeExecutora->unidade->nome_fantasia,
|
|
])->sortBy('nome_fantasia')->values(),
|
|
'procedimentos_realizados_previamente' => [],
|
|
];
|
|
}
|
|
|
|
private static function getCidsOci($oci)
|
|
{
|
|
return DB::table('sigtap.cid AS cid')
|
|
->whereExists(fn ($q) => $q
|
|
->selectRaw(1)
|
|
->from('sigtap.procedimento_cid AS procedimento_cid')
|
|
->join('sigtap.procedimento AS procedimento', 'procedimento.id', 'procedimento_cid.procedimento_id')
|
|
->whereColumn('procedimento_cid.cid_id', 'cid.id')
|
|
->where('procedimento_cid.competencia_id', DB::table('sigtap.competencia')->max('id'))
|
|
->where('procedimento.codigo', $oci->procedimento_codigo)
|
|
)
|
|
->select('cid.id')
|
|
->get()
|
|
->pluck('id');
|
|
}
|
|
|
|
private static function getLogData($model)
|
|
{
|
|
return [
|
|
'lotacao' => [
|
|
'ocupacao' => [
|
|
'id' => $model->createdLotacao->ocupacao->id ?? null,
|
|
'codigo' => $model->createdLotacao->ocupacao->codigo ?? null,
|
|
'nome' => $model->createdLotacao->ocupacao->nome ?? null,
|
|
],
|
|
'profissional' => [
|
|
'nome' => $model->createdLotacao->usuario->cidadao->nome ?? null,
|
|
],
|
|
],
|
|
'centro_custo' => [
|
|
'setor' => [
|
|
'nome' => $model->createdCentroCusto->setor->nome ?? null,
|
|
],
|
|
],
|
|
'data_hora' => $model->created_at->format('d/m/Y \à\s H:i'),
|
|
];
|
|
}
|
|
|
|
public static function store()
|
|
{
|
|
$fila = request()->fila_id ? Fila::find(request()->fila_id) : null;
|
|
$agendamento = request()->agendamento_id ? Agendamento::find(request()->agendamento_id) : null;
|
|
$atendimento = $fila->ambulatorioAtendimento ?? $agendamento->atendimento;
|
|
|
|
self::validateStore($fila);
|
|
|
|
if (request()->finalizacao['desfecho']['finalizado']) {
|
|
$protocoloFechamento = self::getProtocoloFechamento($atendimento->agendamento_id);
|
|
|
|
if (!is_null($protocoloFechamento) && $protocoloFechamento->controla_protocolo_fechamento == 1) {
|
|
if (request()->finalizacao['desfecho']['protocolo_fechamento'] !== $protocoloFechamento->numero) {
|
|
throw new ProtocoloFechamentoException();
|
|
}
|
|
}
|
|
}
|
|
|
|
$soap = DB::transaction(function () use ($fila, $atendimento) {
|
|
|
|
if ($atendimento->demanda_espontanea_id) {
|
|
|
|
$soap = new AtendimentoSoap();
|
|
|
|
} else if ($atendimento->agendamento_id) {
|
|
|
|
$jornada = $atendimento->agendamento->jornada;
|
|
|
|
$soap = optional(ParametrizacaoIntegracaoAplicativo::first())->habilita_integracao_aplicativo_feridas
|
|
? self::getOrCreateSoapAtendimento($atendimento->id)
|
|
: new AtendimentoSoap();
|
|
}
|
|
|
|
self::deleteSoapRascunho($atendimento);
|
|
|
|
self::savePaciente($atendimento);
|
|
|
|
$soap->fill(self::getSoapParams($atendimento));
|
|
|
|
$isRetroativo = is_null($fila);
|
|
$isNovoSoap = !$soap->exists();
|
|
|
|
if ($isRetroativo && $isNovoSoap) {
|
|
|
|
$dataHoraRetroativa = Carbon::create($atendimento->agendamento->jornada->data->format('Y-m-d')
|
|
. ' ' . $atendimento->agendamento->horario->format('H:i:s'));
|
|
|
|
$soap->created_at = $dataHoraRetroativa;
|
|
$soap->updated_at = $dataHoraRetroativa;
|
|
}
|
|
|
|
$soap->save();
|
|
|
|
$soap->motivos()->createMany(request()->subjetivo['motivos']);
|
|
$soap->condicoesAvaliadas()->sync(request()->avaliacao['condicoes_avaliadas']);
|
|
$soap->condicoesEmad()->sync(request()->avaliacao['condicoes_emad']);
|
|
$soap->doencasTransmissiveis()->sync(request()->avaliacao['doencas_transmissiveis']);
|
|
$soap->rastreamentos()->sync(request()->avaliacao['rastreamentos']);
|
|
$soap->intervencoes()->createMany(request()->plano['intervencoes']);
|
|
$soap->orientacoes()->createMany(request()->plano['orientacoes']);
|
|
$soap->cartasMedicas()->createMany(request()->plano['cartas_medicas']);
|
|
$soap->compartilhamentosCuidado()->createMany(request()->plano['compartilhamentos_cuidado']);
|
|
$soap->casosSuspeitos()->sync(request()->finalizacao['casos_suspeitos']);
|
|
$soap->condutas()->sync(request()->finalizacao['condutas']);
|
|
$soap->perfisEpidemiologicos()->sync(request()->perfis_epidemiologicos);
|
|
|
|
self::saveTestesRapidos($soap);
|
|
self::saveExamesAvaliados($soap);
|
|
self::saveTriagemNeonatal($soap);
|
|
self::saveExamesSolicitados($soap);
|
|
self::saveTriagensNeonatalSolicitados($soap);
|
|
self::saveOciProcedimentosRealizados($soap);
|
|
|
|
if ($soap->is_atendimento_puericultura) {
|
|
|
|
self::savePuericulturaAlteracoesFenotipicas($soap);
|
|
self::savePuericulturaFatoresRisco($soap);
|
|
self::savePuericulturaMarcosDesenvolvimento($soap);
|
|
self::savePuericulturaQuestionarioMChatR($soap);
|
|
}
|
|
|
|
if ($soap->is_atendimento_saude_bucal) {
|
|
|
|
$soap->saudeBucalVigilancias()->sync(request()->avaliacao['saude_bucal']['vigilancias']);
|
|
$soap->saudeBucalFornecimentos()->sync(request()->finalizacao['saude_bucal']['fornecimentos']);
|
|
|
|
self::saveOdontograma($soap);
|
|
}
|
|
|
|
$procedimentosEmad = array_map(function ($procedimento) {
|
|
return [
|
|
'codigo_procedimento' => $procedimento['codigo'],
|
|
];
|
|
}, request()->plano['procedimentos_emad']);
|
|
|
|
$soap->procedimentosEmad()->delete();
|
|
$soap->procedimentosEmad()->createMany($procedimentosEmad);
|
|
|
|
$soap->justificativaEmad()->sync(request()->finalizacao['emad_conclusao_justificativa']);
|
|
|
|
self::saveProblemasCondicoes($soap);
|
|
|
|
$acompanhamentoOci = null;
|
|
|
|
if (!self::isRascunho()) {
|
|
|
|
if (!$atendimento->is_demanda_espontanea && !is_null($soap->oci_id) && !request()->ultima_etapa_oci_realizada_mesmo_atendimento) {
|
|
|
|
$acompanhamentoOci = self::saveAcompanhamentoOci($soap);
|
|
}
|
|
}
|
|
|
|
if ($acompanhamentoOci || request()->acompanhamento_oci_id) {
|
|
|
|
if (is_null($acompanhamentoOci) && !is_null(request()->acompanhamento_oci_id)) {
|
|
|
|
$acompanhamentoOci = AcompanhamentoOci::findOrFail(request()->acompanhamento_oci_id);
|
|
}
|
|
|
|
$soap->update(['acompanhamento_oci_id' => $acompanhamentoOci->id]);
|
|
}
|
|
|
|
$procedimentosOci = is_null($acompanhamentoOci)
|
|
? collect()
|
|
: $acompanhamentoOci->oci->procedimentosPrimarios()->pluck('procedimento_codigo')
|
|
->concat($acompanhamentoOci->oci->procedimentosSecundarios()->pluck('procedimento_codigo'));
|
|
|
|
self::saveMedicoes($soap);
|
|
self::saveFeridas($soap);
|
|
self::saveMedicamentosEmUsoTratamentosInterrompidos($soap);
|
|
self::saveAntecedentes($soap);
|
|
self::saveAntropometria($soap);
|
|
self::saveSinaisVitais($soap);
|
|
self::saveGlicemiaCapilar($soap);
|
|
self::saveTria($soap);
|
|
self::saveMarcadoresConsumoAlimentar($soap);
|
|
self::saveResultadosExames($soap);
|
|
self::saveAlergiasReacoesAdversas($soap);
|
|
self::savePrescricoesMedicamentos($soap);
|
|
self::saveSolicitacaoExamesComuns($soap, $acompanhamentoOci, $procedimentosOci);
|
|
self::saveSolicitacaoExamesAltoCusto($soap, $acompanhamentoOci, $procedimentosOci);
|
|
self::saveSolicitacaoProcedimentosCirurgicos($soap);
|
|
self::saveAtestados($soap);
|
|
self::saveDeclaracoesComparecimento($soap);
|
|
self::saveEncaminhamentos($soap);
|
|
self::saveProcedimentos($soap, $acompanhamentoOci, $procedimentosOci);
|
|
self::saveRaas($soap);
|
|
self::saveFinalizacao($soap);
|
|
self::saveIvcf($soap);
|
|
self::saveTempoAtendimento($soap);
|
|
|
|
|
|
if(!empty(request()->risco_cardiovascular_framingham['pontuacao'])){
|
|
self::saveRiscoCardiovascularFramingham($soap);
|
|
}
|
|
|
|
if ($atendimento->demanda_espontanea_id) {
|
|
$demandaEspontanea = DemandaEspontanea::find($atendimento->demanda_espontanea_id);
|
|
|
|
if ($demandaEspontanea && is_null($demandaEspontanea->usuario_id)) {
|
|
$lotacaoSoap = $soap->createdLotacao;
|
|
|
|
if ($lotacaoSoap) {
|
|
$jornada = Jornada::where('lotacao_id', $lotacaoSoap->id)
|
|
->whereDate('data', $soap->created_at)
|
|
->first();
|
|
|
|
$demandaEspontanea->update([
|
|
'usuario_id' => $lotacaoSoap->usuario_id,
|
|
'ocupacao_id' => $lotacaoSoap->ocupacao_id,
|
|
'especialidade_id' => $jornada->especialidade_id ?? null,
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!self::isRascunho()) {
|
|
$atendimento->update(['atendimento_tipo_id' => request()->finalizacao['atendimento_tipo_id']]);
|
|
|
|
if ($soap->pos_consulta) {
|
|
|
|
$soap->atendimento()->update(['pos_consulta' => $soap->pos_consulta]);
|
|
}
|
|
|
|
try {
|
|
|
|
SoapAtencaoBasicaFichaService::store($soap, [
|
|
'marcador_consumo_alimentar' => request()->objetivo['marcador_consumo_alimentar'],
|
|
'exame_avaliado' => request()->objetivo['exame_avaliado'],
|
|
'exame_solicitado' => request()->plano['exame_solicitado'],
|
|
'orientacao_individual_em_saude' => request()->plano['orientacao_individual_em_saude'],
|
|
'triagem_neonatal' => request()->objetivo['triagem_neonatal'],
|
|
'triagem_neonatal_solicitado' => request()->plano['triagem_neonatal'],
|
|
'condicoes_emad' => request()->avaliacao['condicoes_emad'],
|
|
'procedimentos_emad' => request()->plano['procedimentos_emad'],
|
|
'problemas_condicoes' => request()->avaliacao['problemas_condicoes'],
|
|
'condicoes_avaliadas' => request()->avaliacao['condicoes_avaliadas'],
|
|
'doencas_transmissiveis' => request()->avaliacao['doencas_transmissiveis'],
|
|
'rastreamentos' => request()->avaliacao['rastreamentos'],
|
|
'emad_conclusao_justificativa' => request()->finalizacao['emad_conclusao_justificativa'],
|
|
'ficha_avaliacao' => request()->finalizacao['ficha_avaliacao'],
|
|
]);
|
|
}
|
|
catch (Exception $e) {
|
|
|
|
throw new NaoPodeCriarFichaAtencaoBasicaException();
|
|
}
|
|
|
|
if (!is_null($fila)) {
|
|
|
|
if (request()->finalizacao['desfecho']['centro_custo_encaminhamento_id']) {
|
|
|
|
FilaService::forward($fila->id, request()->finalizacao['desfecho']['centro_custo_encaminhamento_id']);
|
|
} else {
|
|
|
|
FilaService::dispatch($fila->centro_custo_id);
|
|
}
|
|
}
|
|
}
|
|
|
|
return $soap->fresh();
|
|
});
|
|
|
|
return [
|
|
'atendimentoId' => $atendimento->id,
|
|
'id' => $soap->id,
|
|
];
|
|
}
|
|
|
|
private static function saveTempoAtendimento($soap){
|
|
$soap->update([
|
|
'tempo_atendimento' => request()->tempo_atendimento
|
|
]);
|
|
}
|
|
|
|
private static function deleteSoapRascunho($atendimento)
|
|
{
|
|
$soapRascunho = $atendimento->soaps()->where('is_atendimento_enfermagem', false)->where('is_rascunho', true)->first();
|
|
|
|
if (is_null($soapRascunho)) {
|
|
|
|
return;
|
|
}
|
|
|
|
$solicitacoes = RegulacaoSolicitacao::where('soap_id', $soapRascunho->id)->get();
|
|
|
|
$soapRascunho->prescricaoMedicamentoTratamentosInterrompidos->each(function ($prescricaoItem) {
|
|
|
|
$prescricaoItem->update([
|
|
'tratamento_interrompido_from_rascunho' => false,
|
|
'tratamento_interrompido_em' => null,
|
|
'tratamento_interrompido_justificativa' => null,
|
|
'tratamento_interrompido_soap_id' => null,
|
|
]);
|
|
});
|
|
|
|
foreach ($solicitacoes as $solicitacao) {
|
|
$solicitacao->delete();
|
|
}
|
|
|
|
$solicitacoesSoap = AtendimentoSoapSolicitacaoExame::where('soap_id', $soapRascunho->id)->get();
|
|
|
|
foreach ($solicitacoesSoap as $solicitacao) {
|
|
|
|
$itens = AtendimentoSoapSolicitacaoExameItem::where(
|
|
'solicitacao_exame_id',
|
|
$solicitacao->id
|
|
)->get();
|
|
|
|
foreach ($itens as $item) {
|
|
AgendamentoExame::where('soap_solicitacao_exame_item_id', $item->id)->delete();
|
|
AgendamentoExameImagem::where('soap_solicitacao_exame_item_id', $item->id)->delete();
|
|
$item->delete();
|
|
}
|
|
|
|
$solicitacao->delete();
|
|
}
|
|
|
|
|
|
$soapRascunho->delete();
|
|
}
|
|
|
|
private static function saveAcompanhamentoOci($soap)
|
|
{
|
|
$acompanhamentoOci = AcompanhamentoOci::where('oci_id', $soap->oci_id)
|
|
->where('paciente_id', $soap->atendimento->paciente->id)
|
|
->where('ocupacao_id', $soap->atendimento->ocupacao->id)
|
|
->whereNull('finalizado_em')
|
|
->first();
|
|
|
|
if (is_null($acompanhamentoOci)) {
|
|
|
|
if ($soap->oci->etapasClinicas()->where('id', EtapaClinicaEnum::ENTRADA_ALTA)->exists()) {
|
|
|
|
$acompanhamentoOci = AcompanhamentoOci::create([
|
|
'paciente_id' => $soap->atendimento->paciente->id,
|
|
'ocupacao_id' => $soap->atendimento->ocupacao->id,
|
|
'oci_id' => $soap->oci_id,
|
|
'etapa_clinica_atual_id' => EtapaClinicaEnum::ALTA,
|
|
'status_id' => AcompanhamentoOciStatus::ENCERRADO_AUTOMATICAMENTE,
|
|
'iniciado_em' => Carbon::now(),
|
|
'iniciado_lotacao_id' => self::getCurrentLotacao()->id,
|
|
'finalizado_em' => Carbon::now(),
|
|
'finalizado_lotacao_id' => self::getCurrentLotacao()->id,
|
|
'motivo_saida_permanencia_id' => $soap->apac_motivo_saida_permanencia_id,
|
|
]);
|
|
|
|
$acompanhamentoOci->etapasClinicasConcluidas()->create([
|
|
'etapa_clinica_id' => EtapaClinicaEnum::ENTRADA,
|
|
'soap_id' => $soap->id,
|
|
]);
|
|
|
|
$acompanhamentoOci->etapasClinicasConcluidas()->create([
|
|
'etapa_clinica_id' => EtapaClinicaEnum::ALTA,
|
|
'soap_id' => $soap->id,
|
|
]);
|
|
|
|
self::saveProcedimentoOci($soap, $acompanhamentoOci);
|
|
}
|
|
else {
|
|
|
|
$acompanhamentoOci = AcompanhamentoOci::create([
|
|
'paciente_id' => $soap->atendimento->paciente->id,
|
|
'ocupacao_id' => $soap->atendimento->ocupacao->id,
|
|
'oci_id' => $soap->oci_id,
|
|
'etapa_clinica_atual_id' => EtapaClinicaEnum::RETORNO,
|
|
'status_id' => AcompanhamentoOciStatus::EM_ANDAMENTO,
|
|
'iniciado_em' => Carbon::now(),
|
|
'iniciado_lotacao_id' => self::getCurrentLotacao()->id
|
|
]);
|
|
|
|
$acompanhamentoOci->etapasClinicasConcluidas()->create([
|
|
'etapa_clinica_id' => EtapaClinicaEnum::ENTRADA,
|
|
'soap_id' => $soap->id,
|
|
]);
|
|
}
|
|
}
|
|
else {
|
|
|
|
$params = [
|
|
'etapa_clinica_atual_id' => $soap->oci_desfecho_etapa_clinica_id,
|
|
];
|
|
|
|
$acompanhamentoOci->etapasClinicasConcluidas()->create([
|
|
'etapa_clinica_id' => $acompanhamentoOci->etapa_clinica_atual_id,
|
|
'soap_id' => $soap->id,
|
|
]);
|
|
|
|
if ($soap->oci_desfecho_etapa_clinica_id === EtapaClinicaEnum::ALTA) {
|
|
|
|
$params['finalizado_em'] = Carbon::now();
|
|
$params['finalizado_lotacao_id'] = self::getCurrentLotacao()->id;
|
|
$params['status_id'] = AcompanhamentoOciStatus::ENCERRADO_AUTOMATICAMENTE;
|
|
$params['motivo_saida_permanencia_id'] = $soap->apac_motivo_saida_permanencia_id;
|
|
|
|
$acompanhamentoOci->etapasClinicasConcluidas()->create([
|
|
'etapa_clinica_id' => EtapaClinicaEnum::ALTA,
|
|
'soap_id' => $soap->id,
|
|
]);
|
|
|
|
if (Carbon::now() <= self::getPrazoValidadeOci($acompanhamentoOci)) {
|
|
|
|
self::saveProcedimentoOci($soap, $acompanhamentoOci);
|
|
}
|
|
}
|
|
|
|
$acompanhamentoOci->update($params);
|
|
}
|
|
|
|
foreach (request()->oci_procedimentos_realizados_previamente as $procedimento) {
|
|
|
|
$acompanhamentoOci->procedimentosRealizados()->create([
|
|
'soap_id' => $soap->id,
|
|
'procedimento_id' => $procedimento['id'],
|
|
'data_executada' => is_null($procedimento['data_executada'])
|
|
? null : Carbon::createFromFormat('d/m/Y', $procedimento['data_executada']),
|
|
'unidade_executora_id' => $procedimento['unidade_executora_id'],
|
|
'ocupacao_executora_id' => $procedimento['ocupacao_executora_id'],
|
|
'usuario_executor_nome' => $procedimento['usuario_executor'],
|
|
]);
|
|
}
|
|
|
|
return $acompanhamentoOci;
|
|
}
|
|
|
|
private static function saveProcedimentoOci($soap, $acompanhamentoOci)
|
|
{
|
|
$cidsOci = self::getCidsOci($acompanhamentoOci->oci);
|
|
|
|
$soapEntrada = $acompanhamentoOci->etapasClinicasConcluidas()
|
|
->where('etapa_clinica_id', EtapaClinicaEnum::ENTRADA)
|
|
->first()
|
|
->soap;
|
|
|
|
$problemaCondicao = $soapEntrada->problemasCondicoes()
|
|
->whereHas('cid', fn ($q) => $q->whereIn('id', $cidsOci))
|
|
->first();
|
|
|
|
$atendimentoProcedimento = $soap->procedimentos()
|
|
->create([
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
'procedimento_id' => $acompanhamentoOci->oci->procedimento->id,
|
|
'cid_id' => $problemaCondicao->cid_id,
|
|
'quantidade' => 1,
|
|
'automatico' => true,
|
|
'ocupacao_id' => $soap->atendimento->ocupacao->id,
|
|
'especialidade_id' => $soap->atendimento->especialidade->id,
|
|
'usuario_id' => $soap->atendimento->usuario->id,
|
|
]);
|
|
|
|
$soap->procedimentosAdministrativos()
|
|
->create(['atendimento_procedimento_id' => $atendimentoProcedimento->id]);
|
|
}
|
|
|
|
private static function getPrazoValidadeOci($acompanhamentoOci)
|
|
{
|
|
return $acompanhamentoOci->iniciado_em->copy()->addMonth()->endOfMonth()->endOfDay();
|
|
}
|
|
|
|
private static function prepareStoreRegulacao($data, $soap)
|
|
{
|
|
|
|
$unidadeSolicitanteId = DB::table('regulacao_parametrizacao_solicitante')
|
|
->where('infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id)
|
|
->value('id');
|
|
|
|
if ($unidadeSolicitanteId) {
|
|
|
|
$solicitanteRegulador = DB::table('regulacao_parametrizacao_solicitante_regulador')
|
|
->where('solicitante_id', $unidadeSolicitanteId)
|
|
->pluck('regulador_id', 'id')
|
|
->toArray();
|
|
}
|
|
|
|
if ($data['origem'] == 'especialidade') {
|
|
|
|
foreach($data['solicitacoes'] as $solicitacao) {
|
|
|
|
if (!empty($solicitanteRegulador)) {
|
|
|
|
$solicitanteEspecialidade = DB::table('regulacao_parametrizacao_solicitante_regulador_especialidade')
|
|
->whereIn('solicitante_regulador_id', array_keys($solicitanteRegulador))
|
|
->where('especialidade_id', $solicitacao['procedimentos'][0]['id'])
|
|
->first();
|
|
|
|
$regulador = DB::table('regulacao_parametrizacao_regulador_especialidade')
|
|
->where('especialidade_id', $solicitacao['procedimentos'][0]['id'])
|
|
->where('ativo', true)
|
|
->whereIn('regulador_id', $solicitanteRegulador)
|
|
->first();
|
|
|
|
$reguladorId = $regulador->regulador_id ?? null;
|
|
$solicitacao['regulador_id'] = $reguladorId;
|
|
|
|
if (!is_null($reguladorId) && !is_null($solicitanteEspecialidade)) {
|
|
|
|
self::storeRegulacao($solicitacao, $soap);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if ($data['origem'] == 'exame_imagem') {
|
|
|
|
$solicitacaoRegulada =[];
|
|
|
|
foreach($data['solicitacoes'] as $solicitacao) {
|
|
foreach($solicitacao['procedimentos'] as $procedimento) {
|
|
|
|
if (!empty($solicitanteRegulador)) {
|
|
|
|
$solicitanteExameImagem = DB::table('regulacao_parametrizacao_solicitante_regulador_exame')
|
|
->whereIn('solicitante_regulador_id', array_keys($solicitanteRegulador))
|
|
->where('exame_id', $procedimento['id'])
|
|
->first();
|
|
|
|
|
|
$regulador = DB::table('regulacao_parametrizacao_regulador_exame')
|
|
->where('exame_id', $procedimento['id'])
|
|
->where('ativo', true)
|
|
->whereIn('regulador_id', $solicitanteRegulador)
|
|
->first();
|
|
|
|
$reguladorId = $regulador->regulador_id ?? null;
|
|
|
|
if(!is_null($reguladorId) && !is_null($solicitanteExameImagem)) {
|
|
|
|
$solicitacaoRegulada[] = [
|
|
'regulador_id' => $reguladorId,
|
|
'cid_id' => $solicitacao['cid_id'],
|
|
'ciap_id' => $solicitacao['ciap_id'] ?? null,
|
|
'observacao' => $solicitacao['observacao'],
|
|
'hipotese_diagnostica_justificativa' => $solicitacao['hipotese_diagnostica_justificativa'],
|
|
'prioridade_id' => $solicitacao['prioridade_id'],
|
|
'acompanhamento_oci_id' => $solicitacao['acompanhamento_oci_id'],
|
|
'procedimentos' => [$procedimento]
|
|
];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if(count($solicitacaoRegulada) > 0) {
|
|
|
|
foreach($solicitacaoRegulada as $solicitacao) {
|
|
self::storeRegulacao($solicitacao, $soap);
|
|
}
|
|
}
|
|
}
|
|
|
|
if ($data['origem'] == 'exame_laboratorio') {
|
|
|
|
foreach($data['solicitacoes'] as $solicitacao) {
|
|
|
|
$solicitacoesPorReguladorTipo = [];
|
|
|
|
foreach ($solicitacao['procedimentos'] as $procedimento) {
|
|
|
|
if (!empty($solicitanteRegulador)) {
|
|
|
|
$solicitanteExameLaboratorial = DB::table('regulacao_parametrizacao_solicitante_regulador_exame')
|
|
->whereIn('solicitante_regulador_id', array_keys($solicitanteRegulador))
|
|
->where('exame_id', $procedimento['id'])
|
|
->first();
|
|
|
|
$regulador = DB::table('regulacao_parametrizacao_regulador_exame')
|
|
->where('exame_id', $procedimento['id'])
|
|
->where('ativo', true)
|
|
->whereIn('regulador_id', $solicitanteRegulador)
|
|
->first();
|
|
|
|
$reguladorId = $regulador->regulador_id ?? null;
|
|
$regulacaoTipoId = Exame::where('id', $procedimento['id'])
|
|
->first()
|
|
->regulacao_tipo_id;
|
|
|
|
if (!is_null($reguladorId) && !is_null($solicitanteExameLaboratorial)) {
|
|
|
|
$key = $reguladorId . '_' . $regulacaoTipoId;
|
|
|
|
if (!isset($solicitacoesPorReguladorTipo[$key])) {
|
|
$solicitacoesPorReguladorTipo[$key] = [
|
|
'regulador_id' => $reguladorId,
|
|
'regulacao_tipo_id' => $regulacaoTipoId,
|
|
'cid_id' => $solicitacao['cid_id'],
|
|
'ciap_id' => $solicitacao['ciap_id'] ?? null,
|
|
'observacao' => $solicitacao['observacao'],
|
|
'hipotese_diagnostica_justificativa' => $solicitacao['hipotese_diagnostica_justificativa'],
|
|
'prioridade_id' => $solicitacao['prioridade_id'],
|
|
'acompanhamento_oci_id' => $solicitacao['acompanhamento_oci_id'],
|
|
'procedimentos' => []
|
|
];
|
|
}
|
|
|
|
$solicitacoesPorReguladorTipo[$key]['procedimentos'][] = $procedimento;
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
foreach ($solicitacoesPorReguladorTipo as $solicitacaoDividida) {
|
|
self::storeRegulacao($solicitacaoDividida, $soap);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private static function storeRegulacao($solicitacaoTratada, $soap)
|
|
{
|
|
if (self::isRascunho()) {
|
|
|
|
return;
|
|
}
|
|
|
|
$solicitacao = new RegulacaoSolicitacao();
|
|
|
|
$checkAutomatico = RegulacaoParametrizacao::value('solicitacao_automatica_ambulatorio');
|
|
|
|
$statusId = Status::where('ativo', true)->where('tipo_id', RegulacaoStatusTipo::SOLICITADO)->first()->id ?? null;
|
|
|
|
|
|
$solicitacaoTratadaProcedimentos = collect($solicitacaoTratada['procedimentos']);
|
|
$solicitacaoTratadaProcedimentosFirst = $solicitacaoTratadaProcedimentos->first();
|
|
|
|
$getPrioridadeId = function ($classificacaoRiscoId) {
|
|
|
|
switch ($classificacaoRiscoId) {
|
|
case ClassificacaoRiscoEnum::ALTA: {
|
|
return SolicitacaoPrioridadeEnum::EMERGENCIA;
|
|
}
|
|
case ClassificacaoRiscoEnum::INTERMEDIARIA: {
|
|
return SolicitacaoPrioridadeEnum::URGENCIA;
|
|
}
|
|
case ClassificacaoRiscoEnum::BAIXA: {
|
|
return SolicitacaoPrioridadeEnum::PRIORITARIO;
|
|
}
|
|
default: {
|
|
return SolicitacaoPrioridadeEnum::ELETIVO;
|
|
}
|
|
}
|
|
};
|
|
|
|
$regulacaoPrioridadeId = $getPrioridadeId($solicitacaoTratada['prioridade_id']);
|
|
|
|
$solicitacaoItemData = (object) [
|
|
'origem' => $solicitacaoTratadaProcedimentosFirst['origem'],
|
|
'exame_id' => $solicitacaoTratadaProcedimentosFirst['origem'] === 'exame'
|
|
? $solicitacaoTratadaProcedimentosFirst['id'] : null,
|
|
'especialidade_id' => $solicitacaoTratadaProcedimentosFirst['origem'] === 'especialidade'
|
|
? $solicitacaoTratadaProcedimentosFirst['id'] : null,
|
|
];
|
|
|
|
$posicoes = RegulacaoSolicitacaoService::getProximasPosicoes(
|
|
$regulacaoPrioridadeId,
|
|
$solicitacaoTratada['regulador_id'],
|
|
$solicitacaoItemData
|
|
);
|
|
|
|
$posicaoPortal = RegulacaoSolicitacaoService::getProximaPosicaoPortal(
|
|
$regulacaoPrioridadeId,
|
|
$solicitacaoItemData
|
|
);
|
|
|
|
$solicitacao->fill([
|
|
'numero' => RegulacaoSolicitacaoService::getNovoNumeroSolicitacao(),
|
|
'posicao_municipal' => $posicoes->posicao_municipal,
|
|
'posicao_regulador' => $posicoes->posicao_regulador,
|
|
'posicao_portal' => $posicaoPortal,
|
|
'data' => Carbon::today(),
|
|
'paciente_id' => $soap->atendimento->agendamento->paciente->id ?? $soap->atendimento->demandaEspontanea->paciente->id,
|
|
'status_id' => $statusId,
|
|
'infraestrutura_solicitante_id' => self::getCurrentCentroCusto()->infraestrutura_id,
|
|
'usuario_solicitante_id' => $soap->atendimento->usuario->id ?? $soap->createdLotacao->usuario_id,
|
|
'usuario_solicitante_especialidade_id' => $soap->atendimento->especialidade->id ?? null,
|
|
'data_desejada' => null,
|
|
'confirmado_em' => $checkAutomatico ? Carbon::now() : null,
|
|
'confirmado_lotacao_id' => $checkAutomatico ? self::getCurrentLotacao()->id : null,
|
|
'prioridade_id' => $regulacaoPrioridadeId,
|
|
'cid_id' => $solicitacaoTratada['cid_id'],
|
|
'ciap_id' => $solicitacaoTratada['ciap_id'] ?? null,
|
|
'hipotese_diagnostica_justificativa' => $solicitacaoTratada['hipotese_diagnostica_justificativa'],
|
|
'observacao' => $solicitacaoTratada['observacao'],
|
|
'peso' => $soap->objetivoAntropometria->atendimentoAntropometria->peso ?? null,
|
|
'altura' => $soap->objetivoAntropometria->atendimentoAntropometria->altura ?? null,
|
|
'regulador_id' => $solicitacaoTratada['regulador_id'],
|
|
'acompanhamento_oci_id' => $solicitacaoTratada['acompanhamento_oci_id'] ?? null,
|
|
'soap_id' => $soap->id,
|
|
'unidade_usuario_id' => self::getCurrentCentroCusto()->infraestrutura->unidade_id,
|
|
'infraestrutura_usuario_id' => self::getCurrentCentroCusto()->infraestrutura_id,
|
|
'ocupacao_usuario_id' => self::getCurrentLotacao()->ocupacao_id,
|
|
'lotaca_usuario_id' => self::getCurrentLotacao()->id,
|
|
]);
|
|
|
|
$solicitacao->save();
|
|
|
|
$solicitacaoTratadaProcedimentos->each(function ($procedimento) use ($solicitacao) {
|
|
|
|
$solicitacao->itens()->create([
|
|
'exame_id' => $procedimento['origem'] === 'exame' ? $procedimento['id'] : null,
|
|
'procedimento_cirurgico_id' => null,
|
|
'especialidade_id' => $procedimento['origem'] === 'especialidade' ? $procedimento['id'] : null,
|
|
'soap_solicitacao_item_id' => $procedimento['solicitacao_item_id'] ?? null,
|
|
'faz_parte_oci' => $procedimento['faz_parte_oci'] ?? false,
|
|
]);
|
|
});
|
|
|
|
RegulacaoSolicitacaoService::saveHistorico($solicitacao);
|
|
}
|
|
|
|
private static function savePaciente($atendimento)
|
|
{
|
|
if (!is_null(request()->paciente['telefone_principal']['id']) && request()->paciente['telefone_principal']['atualizado']) {
|
|
|
|
CidadaoTelefone::find(request()->paciente['telefone_principal']['id'])
|
|
->update(request()->paciente['telefone_principal']);
|
|
}
|
|
|
|
if (!is_null(request()->objetivo['dum'])) {
|
|
|
|
$atendimento->paciente->dum()->updateOrCreate(
|
|
['paciente_id' => $atendimento->paciente->id],
|
|
['data_ultima_menstruacao' => Carbon::createFromFormat('d/m/Y', request()->objetivo['dum'])]
|
|
);
|
|
|
|
if (self::isAtendimentoPreNatal() && !$atendimento->paciente->cidadao->fatoresRisco->contains(FatorRiscoEnum::GESTANTE)) {
|
|
|
|
$atendimento->paciente->cidadao->fatoresRisco()->attach(FatorRiscoEnum::GESTANTE);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static function getSoapParams($atendimento)
|
|
{
|
|
$params = [
|
|
'is_rascunho' => request()->is_rascunho,
|
|
'atendimento_id' => $atendimento->id,
|
|
'equipe_id' => request()->finalizacao['equipe_id'],
|
|
'atencao_basica_local_atendimento_id' => request()->finalizacao['atencao_basica_local_atendimento_id'],
|
|
'turno_id' => request()->finalizacao['turno_id'],
|
|
'subjetivo_descricao' => request()->subjetivo['descricao'],
|
|
'objetivo_descricao' => request()->objetivo['descricao'],
|
|
'dum' => is_null(request()->objetivo['dum'])
|
|
? null
|
|
: Carbon::createFromFormat('d/m/Y', request()->objetivo['dum']),
|
|
'vacinacao_em_dia' => request()->objetivo['vacinacao_em_dia'],
|
|
'avaliacao_descricao' => request()->avaliacao['descricao'],
|
|
'plano_descricao' => request()->plano['descricao'],
|
|
'orientacao_individual_em_saude' => request()->plano['orientacao_individual_em_saude'],
|
|
'atendimento_tipo_id' => request()->finalizacao['atendimento_tipo_id'],
|
|
'emad_tipo_atendimento_id' => request()->finalizacao['emad_tipo_atendimento_id'],
|
|
'emad_modalidade_id' => request()->finalizacao['emad_modalidade_id'],
|
|
'emad_conduta_desfecho_id' => request()->finalizacao['emad_conduta_desfecho_id'],
|
|
'emad_cid_primario_id' => request()->finalizacao['emad_cid_primario_id'],
|
|
'emad_conclusao_id' => request()->finalizacao['emad_conclusao_id'],
|
|
'emad_cuidador_id' => request()->finalizacao['emad_cuidador_id'],
|
|
'emad_cns_cuidador' => str_replace(' ', '', request()->finalizacao['emad_cns_cuidador']),
|
|
'emad_cpf_cuidador' => str_replace([' ', '.', '-'], '', request()->finalizacao['emad_cpf_cuidador']),
|
|
'emad_procedencia_id' => request()->finalizacao['emad_procedencia_id'],
|
|
'atendimento_compartilhado_usuario_id' => request()->finalizacao['atendimento_compartilhado_usuario_id'],
|
|
'racionalidade_saude_id' => request()->finalizacao['racionalidade_saude_id'],
|
|
'paciente_liberado' => request()->finalizacao['desfecho']['finalizado'],
|
|
'is_tratamento_concluido' => request()->finalizacao['is_tratamento_concluido'],
|
|
'pos_consulta' => is_null(request()->finalizacao['desfecho']['centro_custo_encaminhamento_id'])
|
|
|| CentroCusto::findOrFail(request()->finalizacao['desfecho']['centro_custo_encaminhamento_id'])->setor->tipo_id !== SetorTipo::ENFERMAGEM
|
|
? null
|
|
: request()->finalizacao['desfecho']['pos_consulta'],
|
|
'observacao_perfil_epidemiologico' => request()->observacao_perfil_epidemiologico,
|
|
];
|
|
|
|
if (!$atendimento->is_demanda_espontanea && request()->oci_id) {
|
|
|
|
$params['oci_id'] = request()->oci_id;
|
|
$params['oci_desfecho_etapa_clinica_id'] = request()->finalizacao['oci_desfecho_etapa_clinica_id'];
|
|
$params['apac_motivo_saida_permanencia_id'] = request()->finalizacao['apac_motivo_saida_permanencia_id'];
|
|
}
|
|
|
|
self::setParamsPreNatal($atendimento->paciente, $params);
|
|
|
|
if (!is_null($atendimento->paciente->cidadao->idade)
|
|
&& $atendimento->paciente->cidadao->idade['anos'] >= self::IDADE_ANOS_INICIAL_IDOSO
|
|
) {
|
|
|
|
$params['is_atendimento_idoso'] = true;
|
|
}
|
|
|
|
if (request()->objetivo['is_atendimento_puericultura']) {
|
|
|
|
$params['is_atendimento_puericultura'] = true;
|
|
|
|
self::setParamsPuericultura($params);
|
|
}
|
|
|
|
if (self::isProfissionalSaudeBucal()) {
|
|
|
|
$params['is_atendimento_saude_bucal'] = true;
|
|
|
|
self::setParamsSaudeBucal($params);
|
|
}
|
|
|
|
return $params;
|
|
}
|
|
|
|
private static function setParamsPreNatal($paciente, &$params)
|
|
{
|
|
if (self::isAtendimentoPreNatal()) {
|
|
|
|
if (self::isPrimeiroAtendimentoPreNatal($paciente)) {
|
|
|
|
$params['pre_natal_gravidez_tipo_id'] = request()->avaliacao['pre_natal']['gravidez_tipo_id'];
|
|
$params['pre_natal_altura_uterina'] = request()->avaliacao['pre_natal']['altura_uterina'];
|
|
$params['pre_natal_edema_id'] = request()->avaliacao['pre_natal']['edema_id'];
|
|
$params['pre_natal_movimentacao_fetal'] = request()->avaliacao['pre_natal']['movimentacao_fetal'];
|
|
$params['pre_natal_gravidez_planejada'] = request()->avaliacao['pre_natal']['gravidez_planejada'];
|
|
$params['pre_natal_batimento_cardiaco_fetal'] = request()->avaliacao['pre_natal']['batimento_cardiaco_fetal'];
|
|
}
|
|
else {
|
|
|
|
$params['pre_natal_gravidez_tipo_id'] = request()->objetivo['pre_natal']['gravidez_tipo_id'];
|
|
$params['pre_natal_altura_uterina'] = request()->objetivo['pre_natal']['altura_uterina'];
|
|
$params['pre_natal_edema_id'] = request()->objetivo['pre_natal']['edema_id'];
|
|
$params['pre_natal_movimentacao_fetal'] = request()->objetivo['pre_natal']['movimentacao_fetal'];
|
|
$params['pre_natal_gravidez_planejada'] = request()->objetivo['pre_natal']['gravidez_planejada'];
|
|
$params['pre_natal_batimento_cardiaco_fetal'] = request()->objetivo['pre_natal']['batimento_cardiaco_fetal'];
|
|
}
|
|
|
|
$params['is_atendimento_pre_natal'] = true;
|
|
}
|
|
else if (self::hasDesfechoGravidez()) {
|
|
|
|
$params['pre_natal_gravidez_tipo_id'] = request()->avaliacao['pre_natal']['gravidez_tipo_id'];
|
|
|
|
$params['pre_natal_desfecho_em'] = Carbon::createFromFormat(
|
|
'd/m/Y',
|
|
request()->avaliacao['pre_natal']['desfecho_em']
|
|
);
|
|
}
|
|
}
|
|
|
|
private static function isAtendimentoPreNatal()
|
|
{
|
|
$ciaps = collect(array_merge(
|
|
self::CIAPS_GRAVIDEZ_NORMAL,
|
|
self::CIAPS_GRAVIDEZ_ALTO_RISCO,
|
|
));
|
|
|
|
$cids = collect(array_merge(
|
|
self::CIDS_GRAVIDEZ_NORMAL,
|
|
self::CIDS_GRAVIDEZ_ALTO_RISCO,
|
|
));
|
|
|
|
foreach (request()->avaliacao['problemas_condicoes'] as $problemaCondicao) {
|
|
|
|
$ciap = Ciap::find($problemaCondicao['ciap_id']);
|
|
$cid = Cid::find($problemaCondicao['cid_id']);
|
|
|
|
if (($ciaps->contains($ciap->codigo ?? null) || $cids->contains($cid->codigo ?? null))
|
|
&& $problemaCondicao['situacao_id'] != ProblemaCondicaoSituacaoEnum::RESOLVIDO
|
|
) {
|
|
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private static function isPrimeiroAtendimentoPreNatal($paciente)
|
|
{
|
|
return is_null(self::getUltimoSoapPreNatalNaoResolvido($paciente));
|
|
}
|
|
|
|
private static function hasDesfechoGravidez()
|
|
{
|
|
$ciaps = collect(self::CIAPS_DESFECHO_GRAVIDEZ);
|
|
$cids = collect(self::CIDS_DESFECHO_GRAVIDEZ);
|
|
|
|
foreach (request()->avaliacao['problemas_condicoes'] as $problemaCondicao) {
|
|
|
|
$ciap = Ciap::find($problemaCondicao['ciap_id']);
|
|
$cid = Cid::find($problemaCondicao['cid_id']);
|
|
|
|
if (($ciaps->contains($ciap->codigo ?? null) || $cids->contains($cid->codigo ?? null))
|
|
&& is_null($problemaCondicao['id'])
|
|
) {
|
|
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private static function setParamsPuericultura(&$params)
|
|
{
|
|
$params['puericultura_gravidez_tipo_id'] = request()->objetivo['puericultura']['gravidez_tipo_id'];
|
|
$params['puericultura_parto_tipo_id'] = request()->objetivo['puericultura']['parto_tipo_id'];
|
|
$params['puericultura_idade_gestacional_semanas'] = request()->objetivo['puericultura']['idade_gestacional_semanas'];
|
|
$params['puericultura_idade_gestacional_dias'] = request()->objetivo['puericultura']['idade_gestacional_dias'];
|
|
$params['puericultura_apgar_primeiro_minuto'] = request()->objetivo['puericultura']['apgar_primeiro_minuto'];
|
|
$params['puericultura_apgar_quinto_minuto'] = request()->objetivo['puericultura']['apgar_quinto_minuto'];
|
|
$params['puericultura_apgar_decimo_minuto'] = request()->objetivo['puericultura']['apgar_decimo_minuto'];
|
|
$params['puericultura_peso'] = request()->objetivo['puericultura']['peso'];
|
|
$params['puericultura_comprimento'] = request()->objetivo['puericultura']['comprimento'];
|
|
$params['puericultura_perimetro_cefalico'] = request()->objetivo['puericultura']['perimetro_cefalico'];
|
|
$params['puericultura_aleitamento_tipo_id'] = request()->objetivo['puericultura']['aleitamento_tipo_id'];
|
|
}
|
|
|
|
private static function setParamsSaudeBucal(&$params)
|
|
{
|
|
$params['paciente_com_necessidade_especial'] = request()->objetivo['paciente_com_necessidade_especial'];
|
|
|
|
$params['saude_bucal_necessidade_protese_inferior_superior'] =
|
|
request()->avaliacao['saude_bucal']['necessidade_protese_inferior_superior'];
|
|
|
|
$params['saude_bucal_consulta_tipo_id'] = request()->finalizacao['saude_bucal']['consulta_tipo_id'];
|
|
}
|
|
|
|
private static function saveTestesRapidos($soap)
|
|
{
|
|
$testesRapidos = [];
|
|
|
|
foreach (request()->plano['testes_rapidos'] as $testeRapido) {
|
|
|
|
$testesRapidos[$testeRapido['id']] = [
|
|
'resultado' => $testeRapido['resultado']
|
|
];
|
|
}
|
|
|
|
$soap->testesRapidos()->sync($testesRapidos);
|
|
}
|
|
|
|
private static function saveExamesAvaliados($soap)
|
|
{
|
|
$examesAvaliados = [];
|
|
|
|
foreach (request()->objetivo['exame_avaliado'] as $exameAvaliado) {
|
|
|
|
$examesAvaliados[$exameAvaliado['id']] = [
|
|
'resultado' => $exameAvaliado['resultado']
|
|
];
|
|
|
|
if (isset($exameAvaliado['solicitado_em'])) {
|
|
$examesAvaliados[$exameAvaliado['id']]['solicitado_em'] = Carbon::createFromFormat('d/m/Y', $exameAvaliado['solicitado_em']);
|
|
}
|
|
|
|
if (isset($exameAvaliado['realizado_em'])) {
|
|
$examesAvaliados[$exameAvaliado['id']]['realizado_em'] = Carbon::createFromFormat('d/m/Y', $exameAvaliado['realizado_em']);
|
|
}
|
|
|
|
if (isset($exameAvaliado['resultado_em'])) {
|
|
$examesAvaliados[$exameAvaliado['id']]['resultado_em'] = Carbon::createFromFormat('d/m/Y', $exameAvaliado['resultado_em']);
|
|
}
|
|
}
|
|
|
|
$soap->examesAvaliados()->sync($examesAvaliados);
|
|
}
|
|
|
|
private static function saveExamesSolicitados($soap)
|
|
{
|
|
|
|
if (!empty(request()->plano['exame_solicitado']['exames'])) {
|
|
|
|
$examesSolicitados = [];
|
|
|
|
$atendimentoSoapExameSolicitado = $soap->atendimentoSoapExameSolicitado()->create([
|
|
'cid_id' => request()->plano['exame_solicitado']['cid_id'],
|
|
'ciap_id' => request()->plano['exame_solicitado']['ciap_id'],
|
|
'justificativa' => request()->plano['exame_solicitado']['justificativa'],
|
|
'observacao' => request()->plano['exame_solicitado']['observacao'],
|
|
]);
|
|
|
|
foreach (request()->plano['exame_solicitado']['exames'] as $exameSolicitado) {
|
|
|
|
$examesSolicitados[] = [
|
|
'exame_solicitado_avaliado_id' => $exameSolicitado['exame_id'],
|
|
'soap_exame_solicitado_id' => $atendimentoSoapExameSolicitado->id,
|
|
];
|
|
}
|
|
|
|
$soap->atendimentoSoapExameSolicitado->examesSolicitados()->sync($examesSolicitados);
|
|
}
|
|
}
|
|
|
|
private static function saveTriagensNeonatalSolicitados($soap)
|
|
{
|
|
|
|
if (!empty(request()->plano['triagem_neonatal']['exames'])) {
|
|
|
|
$examesSolicitados = [];
|
|
|
|
$atendimentoSoapExameSolicitado = $soap->atendimentoSoapTriagemNeonatalSolicitado()->create([
|
|
'cid_id' => request()->plano['triagem_neonatal']['cid_id'],
|
|
'ciap_id' => request()->plano['triagem_neonatal']['ciap_id'],
|
|
'justificativa' => request()->plano['triagem_neonatal']['justificativa'],
|
|
'observacao' => request()->plano['triagem_neonatal']['observacao'],
|
|
]);
|
|
|
|
foreach (request()->plano['triagem_neonatal']['exames'] as $exameSolicitado) {
|
|
|
|
$examesSolicitados[] = [
|
|
'triagem_neonatal_id' => $exameSolicitado['exame_id'],
|
|
'soap_triagem_neonatal_id' => $atendimentoSoapExameSolicitado->id,
|
|
];
|
|
}
|
|
|
|
$soap->atendimentoSoapTriagemNeonatalSolicitado->triagensNeonatalSolicitados()->sync($examesSolicitados);
|
|
}
|
|
}
|
|
|
|
private static function saveTriagemNeonatal($soap)
|
|
{
|
|
$triagensNeonatal = [];
|
|
|
|
foreach (request()->objetivo['triagem_neonatal'] as $triagemNeonatal) {
|
|
|
|
$triagensNeonatal[$triagemNeonatal['id']] = [
|
|
'resultado' => $triagemNeonatal['resultado']
|
|
];
|
|
|
|
if (isset($triagemNeonatal['solicitado_em'])) {
|
|
$triagensNeonatal[$triagemNeonatal['id']]['solicitado_em'] = Carbon::createFromFormat('d/m/Y', $triagemNeonatal['solicitado_em']);
|
|
}
|
|
|
|
if (isset($triagemNeonatal['realizado_em'])) {
|
|
$triagensNeonatal[$triagemNeonatal['id']]['realizado_em'] = Carbon::createFromFormat('d/m/Y', $triagemNeonatal['realizado_em']);
|
|
}
|
|
|
|
if (isset($triagemNeonatal['resultado_em'])) {
|
|
$triagensNeonatal[$triagemNeonatal['id']]['resultado_em'] = Carbon::createFromFormat('d/m/Y', $triagemNeonatal['resultado_em']);
|
|
}
|
|
}
|
|
|
|
$soap->triagensNeonatal()->sync($triagensNeonatal);
|
|
}
|
|
|
|
private static function saveOciProcedimentosRealizados($soap)
|
|
{
|
|
foreach (request()->oci_procedimentos_realizados_previamente as $procedimento) {
|
|
|
|
$soap->ociProcedimentosRealizados()->create([
|
|
'procedimento_id' => $procedimento['id'],
|
|
'data_executada' => is_null($procedimento['data_executada'])
|
|
? null : Carbon::createFromFormat('d/m/Y', $procedimento['data_executada']),
|
|
'unidade_executora_id' => $procedimento['unidade_executora_id'],
|
|
'ocupacao_executora_id' => $procedimento['ocupacao_executora_id'],
|
|
'usuario_executor_nome' => $procedimento['usuario_executor'],
|
|
]);
|
|
}
|
|
}
|
|
|
|
private static function savePuericulturaAlteracoesFenotipicas($soap)
|
|
{
|
|
$alteracoesFenotipicas = collect(request()->objetivo['puericultura']['alteracoes_fenotipicas'])
|
|
->filter(fn ($alteracao) => !is_null($alteracao['is_presente']))
|
|
->map(fn ($alteracao) => [
|
|
'alteracao_fenotipica_id' => $alteracao['id'],
|
|
'is_presente' => $alteracao['is_presente'],
|
|
]);
|
|
|
|
$soap->puericulturaAlteracoesFenotipicas()->createMany($alteracoesFenotipicas);
|
|
}
|
|
|
|
private static function savePuericulturaFatoresRisco($soap)
|
|
{
|
|
$fatoresRisco = collect(request()->objetivo['puericultura']['fatores_risco'])
|
|
->filter(fn ($fator) => !is_null($fator['is_presente']))
|
|
->map(fn ($fator) => [
|
|
'fator_risco_id' => $fator['id'],
|
|
'is_presente' => $fator['is_presente'],
|
|
]);
|
|
|
|
$soap->puericulturaFatoresRisco()->createMany($fatoresRisco);
|
|
}
|
|
|
|
private static function savePuericulturaMarcosDesenvolvimento($soap)
|
|
{
|
|
$marcosDesenvolvimento = collect(request()->objetivo['puericultura']['marcos_desenvolvimento'])
|
|
->filter(fn ($marco) => !is_null($marco['is_presente']))
|
|
->map(fn ($marco) => [
|
|
'marco_desenvolvimento_id' => $marco['id'],
|
|
'is_presente' => $marco['is_presente'],
|
|
'alcancado_com_anos' => $marco['alcancado_com_anos'],
|
|
'alcancado_com_meses' => $marco['alcancado_com_meses'],
|
|
]);
|
|
|
|
$soap->puericulturaMarcosDesenvolvimento()
|
|
->createMany($marcosDesenvolvimento);
|
|
}
|
|
|
|
private static function saveOdontograma($soap)
|
|
{
|
|
$odontograma = $soap->odontograma()->create([
|
|
'possui_aparelho' => request()->plano['saude_bucal']['odontograma']['possui_aparelho'],
|
|
'possui_contencao' => request()->plano['saude_bucal']['odontograma']['possui_contencao'],
|
|
]);
|
|
|
|
self::saveOdontogramaArcada(
|
|
$odontograma,
|
|
ArcadaDentaria::SUPERIOR,
|
|
request()->plano['saude_bucal']['odontograma']['arcadas']['superior']
|
|
);
|
|
|
|
self::saveOdontogramaArcada(
|
|
$odontograma,
|
|
ArcadaDentaria::INFERIOR,
|
|
request()->plano['saude_bucal']['odontograma']['arcadas']['inferior']
|
|
);
|
|
|
|
self::saveOdontogramaDentesSupranumerarios($odontograma);
|
|
}
|
|
|
|
private static function saveOdontogramaArcada($odontograma, $arcadaId, $params)
|
|
{
|
|
$odontogramaArcada = $odontograma->odontogramaArcadas()->create([
|
|
'arcada_id' => $arcadaId,
|
|
'possui_protese_total' => $params['possui_protese_total'],
|
|
'observacao' => $params['observacao'],
|
|
]);
|
|
|
|
self::saveOdontogramaArcadaProcedimentos($odontogramaArcada, $params['procedimentos']);
|
|
self::saveOdontogramaArcadaDentes($odontogramaArcada, $params['dentes']);
|
|
}
|
|
|
|
private static function saveOdontogramaArcadaProcedimentos($odontogramaArcada, $procedimentosParams)
|
|
{
|
|
$soap = $odontogramaArcada->odontograma->soap;
|
|
|
|
foreach ($procedimentosParams as $procedimentoParams) {
|
|
|
|
$atendimentoProcedimento = $soap->procedimentos()->create([
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
'procedimento_id' => $procedimentoParams['procedimento_id'],
|
|
'cid_id' => $procedimentoParams['cid_id'],
|
|
'quantidade' => $procedimentoParams['quantidade'],
|
|
'automatico' => false,
|
|
'ocupacao_id' => $soap->atendimento->ocupacao->id ?? $soap->createdLotacao->ocupacao_id,
|
|
'especialidade_id' => $soap->atendimento->especialidade->id ?? null,
|
|
'usuario_id' => $soap->atendimento->usuario->id ?? $soap->createdLotacao->usuario_id,
|
|
]);
|
|
|
|
$odontogramaArcada->atendimentoProcedimentos()->create([
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
]);
|
|
}
|
|
}
|
|
|
|
private static function saveOdontogramaArcadaDentes($odontogramaArcada, $dentesParams)
|
|
{
|
|
foreach ($dentesParams as $denteParams) {
|
|
|
|
$odontogramaArcadaDente = $odontogramaArcada->odontogramaArcadaDentes()->create([
|
|
'dente_id' => $denteParams['dente_id'],
|
|
'is_fragmento_esquerda_tratado' => $denteParams['fragmentos']['esquerda']['is_tratado'],
|
|
'is_fragmento_cima_tratado' => $denteParams['fragmentos']['cima']['is_tratado'],
|
|
'is_fragmento_direita_tratado' => $denteParams['fragmentos']['direita']['is_tratado'],
|
|
'is_fragmento_baixo_tratado' => $denteParams['fragmentos']['baixo']['is_tratado'],
|
|
'is_fragmento_centro_tratado' => $denteParams['fragmentos']['centro']['is_tratado'],
|
|
'observacao' => $denteParams['observacao'],
|
|
]);
|
|
|
|
if ($odontogramaArcada->possui_protese_total && !$odontogramaArcadaDente->dente->is_deciduo) {
|
|
|
|
if (!self::isRascunho()) {
|
|
|
|
$odontogramaArcadaDente->problemasCondicoes()->sync([SaudeBucalDenteProblemaCondicaoEnum::AUSENTE_A]);
|
|
}
|
|
}
|
|
else {
|
|
|
|
$odontogramaArcadaDente->problemasCondicoes()->sync($denteParams['problemas_condicoes']);
|
|
}
|
|
|
|
self::saveOdontogramaArcadaDentesProcedimentos($odontogramaArcadaDente, $denteParams['procedimentos']);
|
|
}
|
|
}
|
|
|
|
private static function saveOdontogramaArcadaDentesProcedimentos($odontogramaArcadaDente, $procedimentosParams)
|
|
{
|
|
$soap = $odontogramaArcadaDente->odontogramaArcada->odontograma->soap;
|
|
|
|
foreach ($procedimentosParams as $procedimentoParams) {
|
|
|
|
$atendimentoProcedimento = $soap->procedimentos()->create([
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
'procedimento_id' => $procedimentoParams['procedimento_id'],
|
|
'cid_id' => $procedimentoParams['cid_id'],
|
|
'quantidade' => $procedimentoParams['quantidade'],
|
|
'automatico' => false,
|
|
'ocupacao_id' => $soap->atendimento->ocupacao->id ?? $soap->createdLotacao->ocupacao_id,
|
|
'especialidade_id' => $soap->atendimento->especialidade->id ?? null,
|
|
'usuario_id' => $soap->atendimento->usuario->id ?? $soap->createdLotacao->usuario_id,
|
|
]);
|
|
|
|
$odontogramaArcadaDente->atendimentoProcedimentos()->create([
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
]);
|
|
}
|
|
}
|
|
|
|
private static function saveOdontogramaDentesSupranumerarios($odontograma)
|
|
{
|
|
foreach (request()->plano['saude_bucal']['odontograma']['dentes_supranumerarios'] as $denteParams) {
|
|
|
|
$denteSupranumerario = $odontograma->dentesSupranumerarios()->create([
|
|
'local' => $denteParams['local'],
|
|
'observacao' => $denteParams['observacao'],
|
|
]);
|
|
|
|
self::saveOdontogramaDentesSupranumerariosProcedimentos($denteSupranumerario, $denteParams['procedimentos']);
|
|
}
|
|
}
|
|
|
|
private static function saveOdontogramaDentesSupranumerariosProcedimentos($denteSupranumerario, $procedimentosParams)
|
|
{
|
|
$soap = $denteSupranumerario->odontograma->soap;
|
|
|
|
foreach ($procedimentosParams as $procedimentoParams) {
|
|
|
|
$atendimentoProcedimento = $soap->procedimentos()->create([
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
'procedimento_id' => $procedimentoParams['procedimento_id'],
|
|
'cid_id' => $procedimentoParams['cid_id'],
|
|
'quantidade' => $procedimentoParams['quantidade'],
|
|
'automatico' => false,
|
|
'ocupacao_id' => $soap->atendimento->ocupacao->id ?? $soap->createdLotacao->ocupacao_id,
|
|
'especialidade_id' => $soap->atendimento->especialidade->id ?? null,
|
|
'usuario_id' => $soap->atendimento->usuario->id ?? $soap->createdLotacao->usuario_id,
|
|
]);
|
|
|
|
$denteSupranumerario->atendimentoProcedimentos()->create([
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
]);
|
|
}
|
|
}
|
|
|
|
private static function saveMedicoes($soap)
|
|
{
|
|
self::saveMedicoesAntropometria($soap);
|
|
}
|
|
|
|
private static function saveMedicoesAntropometria($soap)
|
|
{
|
|
foreach (request()->medicoes['antropometrias'] as $antropometria) {
|
|
|
|
$antropometria['medido_em'] = Carbon::createFromFormat('d/m/Y', $antropometria['medido_em']);
|
|
|
|
$soap->antropometrias()->create(array_merge([
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
], $antropometria));
|
|
}
|
|
}
|
|
|
|
private static function saveFeridas($soap)
|
|
{
|
|
foreach (request()->feridas as $ferida) {
|
|
|
|
$ferida['data'] = Carbon::createFromFormat('d/m/Y', $ferida['data']);
|
|
|
|
$dados = [
|
|
'ferida_id' => $ferida['tipo_id'] ?? null,
|
|
'id_old' => $ferida['id'] ?? null,
|
|
'local_anatomico_id' => $ferida['local_anatomico_id'] ?? null,
|
|
'local_anatomico_regiao_id' => $ferida['local_anatomico_regiao_id'] ?? null,
|
|
'ferida_exsudato_id' => $ferida['exsudato_id'] ?? null,
|
|
'ferida_necrose' => $ferida['necrose_id'] ?? null,
|
|
'data' => $ferida['data'] ?? null,
|
|
'cicatrizada' => $ferida['cicatrizada'] ?? false,
|
|
'comprimento' => $ferida['comprimento'] ?? null,
|
|
'largura' => $ferida['largura'] ?? null,
|
|
'profundidade' => $ferida['profundidade'] ?? null,
|
|
'dor' => $ferida['dor'] ?? null,
|
|
'observacao' => $ferida['observacao'] ?? null,
|
|
];
|
|
|
|
if (is_numeric($ferida['id'] ?? null)) {
|
|
|
|
$registro = AtendimentoSoapFerida::find($ferida['id']);
|
|
|
|
if ($registro) {
|
|
$registro->update($dados);
|
|
|
|
if (isset($ferida['procedimentos']) && is_array($ferida['procedimentos'])) {
|
|
|
|
foreach ($ferida['procedimentos'] as $procedimento) {
|
|
|
|
if (isset($procedimento['id']) && is_numeric($procedimento['id'])) {
|
|
|
|
$feridaProcedimento = $registro->procedimentos()->find($procedimento['id']);
|
|
|
|
if ($feridaProcedimento) {
|
|
|
|
$atendimentoProcedimento = $feridaProcedimento->atendimentoProcedimento;
|
|
|
|
if ($atendimentoProcedimento) {
|
|
|
|
$atendimentoProcedimento->update([
|
|
'procedimento_id' => $procedimento['procedimento']['id'],
|
|
'cid_id' => $procedimento['cid']['id'] ?? null,
|
|
'quantidade' => $procedimento['quantidade'] ?? 1,
|
|
]);
|
|
|
|
$soap->procedimentosClinicos()
|
|
->where('atendimento_procedimento_id', $atendimentoProcedimento->id)
|
|
->update([
|
|
'observacao' => $procedimento['observacao'] ?? null,
|
|
]);
|
|
}
|
|
}
|
|
} else {
|
|
|
|
$atendimentoProcedimento = $soap->procedimentos()->create([
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
'procedimento_id' => $procedimento['procedimento']['id'],
|
|
'cid_id' => $procedimento['cid']['id'] ?? null,
|
|
'quantidade' => $procedimento['quantidade'] ?? 1,
|
|
'automatico' => false,
|
|
'ocupacao_id' => $soap->atendimento->ocupacao->id ?? $soap->createdLotacao->ocupacao_id,
|
|
'especialidade_id' => $soap->atendimento->especialidade->id ?? null,
|
|
'usuario_id' => $soap->atendimento->usuario->id ?? $soap->createdLotacao->usuario_id,
|
|
]);
|
|
|
|
$registro->procedimentos()->create([
|
|
'soap_id' => $soap->id,
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
]);
|
|
|
|
$soap->procedimentosClinicos()->create([
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
'observacao' => $procedimento['observacao'] ?? null,
|
|
]);
|
|
|
|
if (!empty($procedimento['procedimento']['materiais']) && is_array($procedimento['procedimento']['materiais'])) {
|
|
|
|
foreach ($procedimento['procedimento']['materiais'] as $material) {
|
|
|
|
if (!empty($material['id'])) {
|
|
|
|
$itemData = [
|
|
'material_id' => $material['id'],
|
|
'quantidade' => $material['quantidade'],
|
|
'escolheu_entrada_item_manualmente' => $material['material_escolheu_entrada_item_manualmente'] ?? false,
|
|
'entrada_itens' => $material['material_entrada_itens'] ?? [],
|
|
];
|
|
|
|
$saidaItem = AlmoxarifadoService::saveSaidaDeDispensacaoDoAmbulatorio($itemData);
|
|
|
|
AtendimentoSoapFeridaMaterial::create([
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
'material_id' => $material['id'],
|
|
'saida_item_id' => $saidaItem->id,
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
|
|
unset($dados['id']);
|
|
$registro = $soap->feridas()->create($dados);
|
|
|
|
foreach ($ferida['procedimentos'] as $procedimento) {
|
|
|
|
$atendimentoProcedimento = $soap->procedimentos()->create([
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
'procedimento_id' => $procedimento['procedimento']['id'],
|
|
'cid_id' => $procedimento['cid']['id'] ?? null,
|
|
'quantidade' => $procedimento['quantidade'] ?? 1,
|
|
'automatico' => false,
|
|
'ocupacao_id' => $soap->atendimento->ocupacao->id ?? $soap->createdLotacao->ocupacao_id,
|
|
'especialidade_id' => $soap->atendimento->especialidade->id ?? null,
|
|
'usuario_id' => $soap->atendimento->usuario->id ?? $soap->createdLotacao->usuario_id,
|
|
]);
|
|
|
|
$registro->procedimentos()->create([
|
|
'soap_id' => $soap->id,
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
]);
|
|
|
|
$soap->procedimentosClinicos()->create([
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
'observacao' => $procedimento['observacao'] ?? null,
|
|
]);
|
|
|
|
if (!empty($procedimento['procedimento']['materiais']) && is_array($procedimento['procedimento']['materiais'])) {
|
|
|
|
foreach ($procedimento['procedimento']['materiais'] as $material) {
|
|
|
|
if (!empty($material['id'])) {
|
|
|
|
$itemData = [
|
|
'material_id' => $material['id'],
|
|
'quantidade' => $material['quantidade'],
|
|
'escolheu_entrada_item_manualmente' => $material['material_escolheu_entrada_item_manualmente'] ?? false,
|
|
'entrada_itens' => $material['material_entrada_itens'] ?? [],
|
|
];
|
|
|
|
$saidaItem = AlmoxarifadoService::saveSaidaDeDispensacaoDoAmbulatorio($itemData);
|
|
|
|
DB::table('ambulatorio_atendimento_soap_ferida_material')->insert([
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
'material_id' => $material['id'],
|
|
'saida_item_id' => $saidaItem->id,
|
|
'created_at' => now(),
|
|
'updated_at' => now(),
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
private static function saveMedicamentosEmUsoTratamentosInterrompidos($soap)
|
|
{
|
|
foreach (request()->medicamentos_em_uso['medicamentos_com_tratamento_interrompido'] as $item) {
|
|
|
|
AtendimentoSoapPrescricaoMedicamentoItem::findOrFail($item['prescricao_medicamento_item_id'])
|
|
->update([
|
|
'tratamento_interrompido_from_rascunho' => $soap->is_rascunho,
|
|
'tratamento_interrompido_em' => Carbon::now(),
|
|
'tratamento_interrompido_justificativa' => $item['justificativa'],
|
|
'tratamento_interrompido_soap_id' => $soap->id,
|
|
]);
|
|
}
|
|
}
|
|
|
|
private static function saveAntecedentes($soap)
|
|
{
|
|
$antecedente = $soap->antecedente()->create([
|
|
'descricao' => request()->antecedente['descricao'],
|
|
'descricao_familiar' => request()->antecedente['descricao_familiar'],
|
|
'gestas_previas' => request()->antecedente['gestas_previas'],
|
|
'abortos' => request()->antecedente['abortos'],
|
|
'desfecho_gestacao_aconteceu_menos_um_ano' =>
|
|
request()->antecedente['desfecho_gestacao_aconteceu_menos_um_ano'],
|
|
'partos_realizados' => request()->antecedente['partos_realizados'],
|
|
'partos_vaginais' => request()->antecedente['partos_vaginais'],
|
|
'partos_cesareas' => request()->antecedente['partos_cesareas'],
|
|
'partos_domiciliares' => request()->antecedente['partos_domiciliares'],
|
|
'nascidos_vivos' => request()->antecedente['nascidos_vivos'],
|
|
'nascidos_mortos' => request()->antecedente['nascidos_mortos'],
|
|
'recem_nascidos_com_menos2500_gramas' =>
|
|
request()->antecedente['recem_nascidos_com_menos2500_gramas'],
|
|
'recem_nascidos_com_mais4500_gramas' =>
|
|
request()->antecedente['recem_nascidos_com_mais4500_gramas'],
|
|
'nascidos_vivos_vivem' => request()->antecedente['nascidos_vivos_vivem'],
|
|
'nascidos_vivos_mortos_primeira_semana' =>
|
|
request()->antecedente['nascidos_vivos_mortos_primeira_semana'],
|
|
'nascidos_vivos_mortos_depois_primeira_semana' =>
|
|
request()->antecedente['nascidos_vivos_mortos_depois_primeira_semana'],
|
|
]);
|
|
|
|
foreach (request()->antecedente['problemas_condicoes'] as $problemaCondicao) {
|
|
|
|
if (!is_null($problemaCondicao['inicio'])) {
|
|
|
|
$problemaCondicao['inicio'] = Carbon::createFromFormat('d/m/Y', $problemaCondicao['inicio']);
|
|
}
|
|
|
|
if (!is_null($problemaCondicao['fim'])) {
|
|
|
|
$problemaCondicao['fim'] = Carbon::createFromFormat('d/m/Y', $problemaCondicao['fim']);
|
|
}
|
|
|
|
$antecedente->problemasCondicoes()->create($problemaCondicao);
|
|
}
|
|
|
|
foreach (request()->antecedente['cirurgias_internacoes'] as $cirurgiaInternacao) {
|
|
|
|
if (!is_null($cirurgiaInternacao['realizada_em'])) {
|
|
|
|
$cirurgiaInternacao['realizada_em'] = Carbon::createFromFormat(
|
|
'd/m/Y',
|
|
$cirurgiaInternacao['realizada_em']
|
|
);
|
|
}
|
|
|
|
$antecedente->cirurgiasInternacoes()->create($cirurgiaInternacao);
|
|
}
|
|
|
|
$antecedente->problemasFamiliares()->createMany(request()->antecedente['problemas_familiares']);
|
|
}
|
|
|
|
private static function saveAntropometria($soap)
|
|
{
|
|
|
|
$payload = (array) (request()->objetivo['antropometria'] ?? []);
|
|
|
|
if (empty($payload)) {
|
|
|
|
return;
|
|
}
|
|
|
|
$medidoEm = $payload['medido_em'] ?? now()->toDateString();
|
|
$payload['medido_em'] = $medidoEm;
|
|
|
|
$camposPermitidos = [
|
|
'medido_em',
|
|
'peso',
|
|
'altura',
|
|
'perimetro_cefalico',
|
|
'circunferencia_abdominal',
|
|
'perimetro_panturrilha',
|
|
'comprimento_pe_direito',
|
|
'largura_pe_direito',
|
|
'circunferencia_pe_direito',
|
|
'comprimento_pe_esquerdo',
|
|
'largura_pe_esquerdo',
|
|
'circunferencia_pe_esquerdo',
|
|
];
|
|
|
|
$dados = ['atendimento_id' => $soap->atendimento_id];
|
|
|
|
foreach($camposPermitidos as $campo) {
|
|
|
|
if (array_key_exists($campo, $payload)) {
|
|
|
|
$dados[$campo] = $payload[$campo];
|
|
}
|
|
}
|
|
|
|
$antropometria = $soap->antropometrias()
|
|
->where('medido_em', $medidoEm)
|
|
->first();
|
|
|
|
if ($antropometria) {
|
|
|
|
$antropometria->fill($dados);
|
|
$antropometria->updated_at = now();
|
|
$antropometria->save();
|
|
} else {
|
|
|
|
$antropometria = $soap->antropometrias()
|
|
->create(array_merge($dados, [
|
|
'created_at' => now(),
|
|
]));
|
|
}
|
|
|
|
$soap->objetivoAntropometria()->updateOrCreate(
|
|
['atendimento_antropometria_id' => $antropometria->id],
|
|
);
|
|
}
|
|
|
|
private static function saveSinaisVitais($soap): void
|
|
{
|
|
$payload = (array) (request()->objetivo['sinal_vital'] ?? []);
|
|
|
|
if (empty($payload)) {
|
|
|
|
return;
|
|
}
|
|
|
|
$camposPermitidos = [
|
|
'pressao_arterial',
|
|
'frequencia_respiratoria',
|
|
'frequencia_cardiaca',
|
|
'temperatura',
|
|
'saturacao_o2',
|
|
];
|
|
|
|
$dados = [
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
];
|
|
|
|
foreach ($camposPermitidos as $campo) {
|
|
|
|
if (array_key_exists($campo, $payload)) {
|
|
|
|
$dados[$campo] = $payload[$campo];
|
|
}
|
|
}
|
|
|
|
$sinaisVitais = $soap->sinaisVitais()
|
|
->first();
|
|
|
|
if ($sinaisVitais) {
|
|
|
|
$sinaisVitais->fill($dados);
|
|
$sinaisVitais->updated_at = now();
|
|
$sinaisVitais->save();
|
|
} else {
|
|
|
|
$insert = array_merge($dados, [
|
|
'created_at' => now(),
|
|
'updated_at' => now(),
|
|
]);
|
|
|
|
$sinaisVitais = $soap->sinaisVitais()->create($insert);
|
|
}
|
|
|
|
$soap->objetivoSinalVital()->updateOrCreate(
|
|
['atendimento_sinal_vital_id' => $sinaisVitais->id],
|
|
);
|
|
|
|
}
|
|
private static function saveGlicemiaCapilar($soap)
|
|
{
|
|
if (self::hasData(collect(request()->objetivo['glicemia_capilar']))) {
|
|
|
|
$atendimentoGlicemiaCapilar = $soap->glicemiasCapilares()->create(array_merge([
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
], request()->objetivo['glicemia_capilar']));
|
|
|
|
$soap->objetivoGlicemiaCapilar()->create([
|
|
'atendimento_glicemia_capilar_id' => $atendimentoGlicemiaCapilar->id
|
|
]);
|
|
}
|
|
}
|
|
|
|
private static function saveTria($soap)
|
|
{
|
|
$paciente = optional($soap->atendimento)->paciente;
|
|
$pacienteId = optional($paciente)->id;
|
|
$hasCadastroIndividual = CadastroIndividual::where('paciente_id', $pacienteId)->exists();
|
|
|
|
$informacaoSocialAnterior = optional($paciente)->informacaoSocial;
|
|
|
|
$alimentosAtual = optional($informacaoSocialAnterior)->alimentos_acabaram;
|
|
$comeuAtual = optional($informacaoSocialAnterior)->comeu_alguns_alimentos;
|
|
|
|
$alimentosNovo = request()->input('objetivo.tria.alimentos_acabaram');
|
|
$comeuNovo = request()->input('objetivo.tria.comeu_alguns_alimentos');
|
|
|
|
$houveMudanca = self::houveMudancaInformacaoSocioeconomica($alimentosAtual,$comeuAtual,$alimentosNovo,$comeuNovo);
|
|
|
|
if (!$houveMudanca && !$hasCadastroIndividual) {
|
|
return;
|
|
}
|
|
|
|
$dataAtualizacaoTria = now();
|
|
|
|
$dados = [
|
|
'alimentos_acabaram' => $alimentosNovo,
|
|
'comeu_alguns_alimentos' => $comeuNovo,
|
|
'data_atualizacao_tria' => $dataAtualizacaoTria,
|
|
];
|
|
|
|
DB::transaction(function () use ($pacienteId, $dados, $soap, $houveMudanca) {
|
|
|
|
PacienteInformacaoSocial::where('paciente_id', $pacienteId)
|
|
->update($dados);
|
|
|
|
CadastroIndividual::where('paciente_id', $pacienteId)
|
|
->update($dados);
|
|
|
|
if ($houveMudanca && !self::isRascunho()) {
|
|
self::saveTriaHistorio($soap, $dados);
|
|
}
|
|
});
|
|
|
|
if ($houveMudanca && !self::isRascunho()) {
|
|
self::saveProcedimentoTria($soap, $pacienteId);
|
|
}
|
|
}
|
|
|
|
private static function saveTriaHistorio($soap, $dados)
|
|
{
|
|
AtendimentoSoapTriaHistorio::create([
|
|
'soap_id' => $soap->id,
|
|
'alimentos_acabaram' => $dados['alimentos_acabaram'],
|
|
'comeu_alguns_alimentos' => $dados['comeu_alguns_alimentos'],
|
|
'data_atualizacao_tria' => $dados['data_atualizacao_tria'],
|
|
]);
|
|
}
|
|
|
|
private static function isTriaDesatualizado($dataAtualizacaoTria)
|
|
{
|
|
|
|
$data = Carbon::make($dataAtualizacaoTria);
|
|
|
|
if (is_null($data)) {
|
|
return false;
|
|
}
|
|
|
|
return $data->lt(Carbon::today()->subMonths(3));
|
|
}
|
|
|
|
private static function saveProcedimentoTria($soap, $pacienteId)
|
|
{
|
|
if (self::hasProcedimentoTriaNoDia($pacienteId)) {
|
|
return;
|
|
}
|
|
|
|
$procedimentoId = self::getProcedimentoId(ProcedimentoEnum::PROCEDIMENTO_TRIA_CODIGO);
|
|
|
|
$atendimentoProcedimento = $soap->procedimentos()->create([
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
'procedimento_id' => $procedimentoId,
|
|
'quantidade' => 1,
|
|
'automatico' => true,
|
|
'ocupacao_id' => $soap->atendimento->ocupacao->id ?? $soap->createdLotacao->ocupacao_id,
|
|
'especialidade_id' => $soap->atendimento->especialidade->id ?? null,
|
|
'usuario_id' => $soap->atendimento->usuario->id ?? $soap->createdLotacao->usuario_id,
|
|
]);
|
|
|
|
$soap->procedimentosClinicos()->create([
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
]);
|
|
}
|
|
|
|
private static function hasProcedimentoTriaNoDia($pacienteId)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_procedimento as atendimento_procedimento')
|
|
->join('sigtap.procedimento as procedimento', 'procedimento.id', 'atendimento_procedimento.procedimento_id')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
|
|
->where('atendimento.paciente_id', $pacienteId)
|
|
->where('procedimento.codigo', ProcedimentoEnum::PROCEDIMENTO_TRIA_CODIGO)
|
|
->whereDate('atendimento_procedimento.created_at', Carbon::today())
|
|
->exists();
|
|
}
|
|
|
|
private static function hasData($items)
|
|
{
|
|
$has = false;
|
|
|
|
$items->each(function ($value) use (&$has) {
|
|
|
|
if (!is_null($value)) {
|
|
|
|
$has = true;
|
|
|
|
return false;
|
|
}
|
|
});
|
|
|
|
return $has;
|
|
}
|
|
|
|
private static function saveMarcadoresConsumoAlimentar($soap)
|
|
{
|
|
$marcadorConsumoAlimentar = request()->objetivo['marcador_consumo_alimentar'];
|
|
$respostaUnica = array_filter($marcadorConsumoAlimentar['pergunta_unica'], fn ($valor) => $valor !== null);
|
|
$respostaMultipla = array_filter($marcadorConsumoAlimentar['pergunta_multipla'], fn ($valor) => $valor !== null);
|
|
|
|
if (!empty($respostaUnica)) {
|
|
|
|
$marcadorConsumoAlimentarPerguntaUnica = [];
|
|
|
|
foreach ($respostaUnica as $pergunta => $resposta) {
|
|
|
|
$marcadorConsumoAlimentarPerguntaUnica[] = [
|
|
'pergunta_id' => $pergunta,
|
|
'resposta_id' => MarcadorConsumoAlimentarResposta::where('descricao', $resposta)->select('id')->value('id')
|
|
];
|
|
}
|
|
|
|
$soap->marcadorConsumoAlimentarPerguntasRespostas()->createMany($marcadorConsumoAlimentarPerguntaUnica);
|
|
}
|
|
|
|
if (!empty($respostaMultipla)) {
|
|
|
|
$marcadorConsumoAlimentarPerguntaMultipla = [];
|
|
|
|
$pergunta = MarcadorConsumoAlimentarPergunta::join(
|
|
'atencao_basica_marcador_consumo_alimentar_respostas',
|
|
'atencao_basica_marcador_consumo_alimentar_perguntas.grupo_resposta',
|
|
'=',
|
|
'atencao_basica_marcador_consumo_alimentar_respostas.codigo_grupo'
|
|
)
|
|
->where('atencao_basica_marcador_consumo_alimentar_respostas.descricao', '=', $respostaMultipla[0])
|
|
->select('atencao_basica_marcador_consumo_alimentar_perguntas.id')
|
|
->first();
|
|
|
|
foreach ($respostaMultipla as $resposta) {
|
|
|
|
$marcadorConsumoAlimentarPerguntaMultipla[] = [
|
|
'pergunta_id' => $pergunta->id,
|
|
'resposta_id' => MarcadorConsumoAlimentarResposta::where('descricao', $resposta)->select('id')->value('id')
|
|
];
|
|
}
|
|
|
|
$soap->marcadorConsumoAlimentarPerguntasRespostas()->createMany($marcadorConsumoAlimentarPerguntaMultipla);
|
|
}
|
|
}
|
|
|
|
private static function saveResultadosExames($soap)
|
|
{
|
|
$examesEco = collect([
|
|
ProcedimentoEnum::ULTRASSONOGRAFIA_DOPPLER_DE_FLUXO_OBSTETRICO,
|
|
ProcedimentoEnum::ULTRASSONOGRAFIA_OBSTETRICA_C_DOPPLER_COLORIDO_E_PULSADO,
|
|
ProcedimentoEnum::ULTRASSONOGRAFIA_OBSTETRICA,
|
|
]);
|
|
|
|
$examesPercentual = collect([
|
|
ProcedimentoEnum::DOSAGEM_DE_HEMOGLOBINA_GLICOSILADA,
|
|
]);
|
|
|
|
$examesResultadoTipo = collect([
|
|
ProcedimentoEnum::EMISSOES_OTOACUSTICAS_EVOCADAS_PARA_TRIAGEM_AUDITIVA_TESTE_DA_ORELHINHA,
|
|
ProcedimentoEnum::FUNDOSCOPIA,
|
|
ProcedimentoEnum::POTENCIAL_EVOCADO_AUDITIVO_PARA_TRIAGEM_AUDITIVA_TESTE_DA_ORELHINHA,
|
|
ProcedimentoEnum::RESSONANCIA_MAGNETICA_DE_CRANIO,
|
|
ProcedimentoEnum::TOMOGRAFIA_COMPUTADORIZADA_DO_CRANIO,
|
|
ProcedimentoEnum::ULTRASSONOGRAFIA_TRANSFONTANELA,
|
|
]);
|
|
|
|
foreach ((request()->objetivo['resultados_exames'] ?? []) as $resultadoExame) {
|
|
|
|
$exame = Exame::find($resultadoExame['exame_id']);
|
|
|
|
$resultadoExame['percentual'] = $examesPercentual->contains($exame->codigo)
|
|
? $resultadoExame['percentual'] : null;
|
|
|
|
if ($examesEco->contains($exame->codigo)) {
|
|
|
|
$resultadoExame['idade_gestacional_semanas_eco'] = $resultadoExame['idade_gestacional_semanas_eco'];
|
|
$resultadoExame['idade_gestacional_dias_eco'] = $resultadoExame['idade_gestacional_dias_eco'];
|
|
|
|
$resultadoExame['dpp_eco'] = is_null($resultadoExame['dpp_eco'])
|
|
? null : Carbon::createFromFormat('d/m/Y', $resultadoExame['dpp_eco']);
|
|
}
|
|
else {
|
|
|
|
$resultadoExame['idade_gestacional_semanas_eco'] = null;
|
|
$resultadoExame['idade_gestacional_dias_eco'] = null;
|
|
$resultadoExame['dpp_eco'] = null;
|
|
}
|
|
|
|
$resultado['resultado_tipo_id'] = $examesResultadoTipo->contains($exame->codigo)
|
|
? $resultadoExame['resultado_tipo_id'] : null;
|
|
|
|
if (isset($resultadoExame['solicitado_em'])) {
|
|
|
|
$resultadoExame['solicitado_em'] = Carbon::createFromFormat('d/m/Y', $resultadoExame['solicitado_em']);
|
|
}
|
|
|
|
if (isset($resultadoExame['realizado_em'])) {
|
|
|
|
$resultadoExame['realizado_em'] = Carbon::createFromFormat('d/m/Y', $resultadoExame['realizado_em']);
|
|
}
|
|
|
|
if (isset($resultadoExame['resultado_em'])) {
|
|
|
|
$resultadoExame['resultado_em'] = Carbon::createFromFormat('d/m/Y', $resultadoExame['resultado_em']);
|
|
}
|
|
|
|
$soap->resultadosExames()->create($resultadoExame);
|
|
}
|
|
}
|
|
|
|
private static function saveProblemasCondicoes($soap)
|
|
{
|
|
foreach (request()->avaliacao['problemas_condicoes'] as $problemaCondicao) {
|
|
$problemaCondicaoAutomatico = isset($problemaCondicao['automatico']) ? $problemaCondicao['automatico'] : false;
|
|
$problemaCondicaoId = isset($problemaCondicao['id']) ? $problemaCondicao['id'] : null;
|
|
$problemaCondicaoCiapId = isset($problemaCondicao['ciap_id']) ? $problemaCondicao['ciap_id'] : null;
|
|
$problemaCondicaoCidId = isset($problemaCondicao['cid_id']) ? $problemaCondicao['cid_id'] : null;
|
|
$problemaCondicaoSituacaoId = isset($problemaCondicao['situacao_id']) ? $problemaCondicao['situacao_id'] : null;
|
|
$problemaCondicaoInicio = isset($problemaCondicao['inicio']) ? $problemaCondicao['inicio'] : null;
|
|
$problemaCondicaoFim = isset($problemaCondicao['fim']) ? $problemaCondicao['fim'] : null;
|
|
$problemaCondicaoObservacao = isset($problemaCondicao['observacao']) ? $problemaCondicao['observacao'] : null;
|
|
|
|
$ciap = is_null($problemaCondicaoCiapId) ? null : Ciap::find($problemaCondicaoCiapId);
|
|
$cid = is_null($problemaCondicaoCidId) ? null : Cid::find($problemaCondicaoCidId);
|
|
|
|
$isGravidezNormal = collect(self::CIAPS_GRAVIDEZ_NORMAL)->contains($ciap->codigo ?? null)
|
|
|| collect(self::CIDS_GRAVIDEZ_NORMAL)->contains($cid->codigo ?? null);
|
|
|
|
$problemaCondicaoAnterior = is_null($problemaCondicaoId)
|
|
? null : AtendimentoSoapProblemaCondicao::find($problemaCondicaoId);
|
|
|
|
$data = [
|
|
'automatico' => $problemaCondicaoAutomatico,
|
|
'ciap_id' => $problemaCondicaoCiapId,
|
|
'cid_id' => $problemaCondicaoCidId,
|
|
'situacao_id' => $problemaCondicaoSituacaoId,
|
|
];
|
|
|
|
if (!is_null($problemaCondicaoSituacaoId)) {
|
|
|
|
$data['inicio'] = is_null($problemaCondicaoInicio)
|
|
? null
|
|
: Carbon::createFromFormat('d/m/Y', $problemaCondicaoInicio);
|
|
|
|
$data['fim'] = is_null($problemaCondicaoFim)
|
|
? null
|
|
: Carbon::createFromFormat('d/m/Y', $problemaCondicaoFim);
|
|
|
|
$data['observacao'] = $problemaCondicaoObservacao;
|
|
$data['problema_condicao_anterior_id'] = $problemaCondicaoId;
|
|
}
|
|
|
|
if (!self::isRascunho() && $isGravidezNormal) {
|
|
|
|
if (is_null($problemaCondicaoAnterior)) {
|
|
|
|
$data['paciente_gestacao_id'] = PacienteGestacao::create([
|
|
'paciente_id' => $soap->atendimento->paciente->id,
|
|
'inicio' => $data['inicio'] ?? Carbon::today(),
|
|
'fim' => $data['fim'] ?? null,
|
|
])->id;
|
|
}
|
|
else {
|
|
|
|
PacienteGestacao::where('id', $problemaCondicaoAnterior->paciente_gestacao_id)->update([
|
|
'inicio' => $data['inicio'] ?? Carbon::today(),
|
|
'fim' => $data['fim'] ?? null,
|
|
]);
|
|
|
|
$data['paciente_gestacao_id'] = $problemaCondicaoAnterior->paciente_gestacao_id;
|
|
}
|
|
}
|
|
|
|
$soap->problemasCondicoes()->create($data);
|
|
}
|
|
|
|
if (!self::isRascunho() && !is_null($soap->pre_natal_desfecho_em)) {
|
|
|
|
$problemaCondicao = self::getProblemaCondicaoGravidezNormalNaoResolvido($soap->atendimento->paciente);
|
|
|
|
if (!is_null($problemaCondicao)) {
|
|
|
|
$ciap = is_null($problemaCondicao->ciap_id) ? null : Ciap::find($problemaCondicao->ciap_id);
|
|
$cid = is_null($problemaCondicao->cid_id) ? null : Cid::find($problemaCondicao->cid_id);
|
|
|
|
$isGravidezNormal = collect(self::CIAPS_GRAVIDEZ_NORMAL)->contains($ciap->codigo ?? null)
|
|
|| collect(self::CIDS_GRAVIDEZ_NORMAL)->contains($cid->codigo ?? null);
|
|
|
|
if ($isGravidezNormal) {
|
|
|
|
PacienteGestacao::where('id', $problemaCondicao->paciente_gestacao_id)->update([
|
|
'fim' => $soap->pre_natal_desfecho_em,
|
|
]);
|
|
}
|
|
|
|
$soap->problemasCondicoes()->create([
|
|
'ciap_id' => $problemaCondicao->ciap_id,
|
|
'cid_id' => $problemaCondicao->cid_id,
|
|
'situacao_id' => ProblemaCondicaoSituacaoEnum::RESOLVIDO,
|
|
'inicio' => $problemaCondicao->inicio,
|
|
'fim' => $soap->pre_natal_desfecho_em,
|
|
'observacao' => $problemaCondicao->observacao,
|
|
'problema_condicao_anterior_id' => $problemaCondicao->id,
|
|
'resolvido_automaticamente' => true,
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
|
|
private static function getProblemaCondicaoGravidezNormalNaoResolvido($paciente)
|
|
{
|
|
return DB::table('ambulatorio_atendimento_soap_problema_condicao as problema_condicao')
|
|
->join('ambulatorio_atendimento_soap as soap', 'soap.id', 'problema_condicao.soap_id')
|
|
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
|
|
->where('soap.is_rascunho', false)
|
|
->where('atendimento.paciente_id', $paciente->id)
|
|
->where(fn ($q) => $q
|
|
->whereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('geral_ciap as ciap')
|
|
->whereColumn('ciap.id', 'problema_condicao.ciap_id')
|
|
->whereIn('ciap.codigo', self::CIAPS_GRAVIDEZ_NORMAL)
|
|
)
|
|
->orWhereExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('sigtap.cid as cid')
|
|
->whereColumn('cid.id', 'problema_condicao.cid_id')
|
|
->whereIn('cid.codigo', self::CIDS_GRAVIDEZ_NORMAL)
|
|
)
|
|
)
|
|
->where('problema_condicao.situacao_id', '<>', ProblemaCondicaoSituacaoEnum::RESOLVIDO)
|
|
->whereNotExists(fn ($q) => $q
|
|
->select(DB::raw(1))
|
|
->from('ambulatorio_atendimento_soap_problema_condicao as problema_condicao_posterior')
|
|
->whereColumn('problema_condicao_posterior.problema_condicao_anterior_id', 'problema_condicao.id')
|
|
)
|
|
->select(
|
|
'problema_condicao.id',
|
|
'problema_condicao.ciap_id',
|
|
'problema_condicao.cid_id',
|
|
'problema_condicao.inicio',
|
|
'problema_condicao.fim',
|
|
'problema_condicao.observacao',
|
|
'problema_condicao.paciente_gestacao_id'
|
|
)
|
|
->first();
|
|
}
|
|
|
|
private static function saveAlergiasReacoesAdversas($soap)
|
|
{
|
|
$alergias = [];
|
|
|
|
foreach (request()->avaliacao['alergias_reacoes_adversas'] as $alergia) {
|
|
|
|
$alergias[$alergia['alergia_id']] = [
|
|
'criticidade_id' => $alergia['criticidade_id'],
|
|
'reacoes_observacoes' => $alergia['reacoes_observacoes'] ?? null,
|
|
];
|
|
|
|
$alergiaCidadao = $soap->atendimento->paciente->cidadao->alergias()
|
|
->where('id', $alergia['alergia_id'])
|
|
->first();
|
|
|
|
if (is_null($alergiaCidadao) || (
|
|
$alergiaCidadao->cidadaoAlergia->criticidade_id != $alergia['criticidade_id']
|
|
|| $alergiaCidadao->cidadaoAlergia->reacoes_observacoes != $alergia['reacoes_observacoes']
|
|
)) {
|
|
|
|
$soap->alergias()->create($alergia);
|
|
}
|
|
}
|
|
|
|
$soap->atendimento->paciente->cidadao->alergias()->sync($alergias);
|
|
}
|
|
|
|
private static function savePrescricoesMedicamentos($soap)
|
|
{
|
|
|
|
foreach (request()->plano['prescricoes_medicamentos'] as $prescricaoParams) {
|
|
|
|
$dataPrincipal = [
|
|
'unidade_usuario_id' => self::getCurrentLotacao()->unidade_id,
|
|
'infraestrutura_usuario_id' => self::getCurrentLotacao()->infraestrutura_id,
|
|
'ocupacao_usuario_id' => self::getCurrentLotacao()->ocupacao_id,
|
|
'lotaca_usuario_id' => self::getCurrentLotacao()->id,
|
|
'anamnese' => request()->plano['prescricao_medicamento']['anamnese'],
|
|
'diagnostico' => request()->plano['prescricao_medicamento']['diagnostico'],
|
|
'tratamento_previo_status' => request()->plano['prescricao_medicamento']['tratamento_previo_status'] ?? false,
|
|
'tratamento_previo_relatar' => request()->plano['prescricao_medicamento']['tratamento_previo_relatar'] ?? null,
|
|
];
|
|
|
|
$prescricao = $soap->prescricoesMedicamentos()->create($dataPrincipal);
|
|
|
|
foreach ($prescricaoParams['medicamentos'] as $medicamento) {
|
|
|
|
$dataItem = [
|
|
'prescricao_id' => $prescricao->id,
|
|
'recomendacoes' => $medicamento['recomendacoes'],
|
|
'is_dose_unica' => $medicamento['is_dose_unica'] ?? false,
|
|
'is_uso_continuo' => $medicamento['is_uso_continuo'] ?? false,
|
|
'is_imprimir_separado' => $medicamento['is_imprimir_separado'] ?? false,
|
|
'is_remover_impressao' => $medicamento['is_remover_impressao'] ?? false,
|
|
'prescricao_medicamento_item_anterior_id' => $medicamento['prescricao_medicamento_item_anterior_id'] ?? null,
|
|
];
|
|
|
|
if ($medicamento['is_manual']) {
|
|
$dataItem['receita_tipo_id'] = $medicamento['receita_tipo_id'] ?? null;
|
|
$dataItem['descricao'] = $medicamento['descricao'] ?? null;
|
|
$dataItem['justificativa'] = $medicamento['justificativa'] ?? null;
|
|
}
|
|
else {
|
|
|
|
|
|
$dataItem['material_id'] = $medicamento['material_id'];
|
|
$dataItem['dose'] = $medicamento['dose'];
|
|
$dataItem['unidade_medida_id'] = $medicamento['unidade_medida_id'];
|
|
$dataItem['inicio'] = Carbon::createFromFormat('d/m/Y', $medicamento['inicio']);
|
|
|
|
|
|
|
|
|
|
if (!$medicamento['is_dose_unica']) {
|
|
|
|
if ($medicamento['frequencia_dose'] == PrescricaoFrequenciaDose::FREQUENCIA) {
|
|
|
|
$dataItem['frequencia_vezes'] = $medicamento['frequencia_vezes'];
|
|
}
|
|
else if ($medicamento['frequencia_dose'] == PrescricaoFrequenciaDose::TURNO) {
|
|
|
|
$dataItem['turno_id'] = $medicamento['turno_id'];
|
|
}
|
|
|
|
$dataItem['intervalo'] = $medicamento['intervalo'];
|
|
$dataItem['intervalo_medida_tempo_id'] = $medicamento['intervalo_medida_tempo_id'];
|
|
}
|
|
|
|
if ($medicamento['is_dose_unica']) {
|
|
|
|
$dataItem['duracao'] = 1;
|
|
$dataItem['duracao_medida_tempo_id'] = MedidaTempoEnum::DIAS;
|
|
}
|
|
else if (!$medicamento['is_uso_continuo']) {
|
|
|
|
$dataItem['duracao'] = $medicamento['duracao'];
|
|
$dataItem['duracao_medida_tempo_id'] = $medicamento['duracao_medida_tempo_id'];
|
|
}
|
|
}
|
|
|
|
$prescricao->itens()->create($dataItem);
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
private static function saveSolicitacaoExamesComuns($soap, $acompanhamentoOci, $procedimentosOci)
|
|
{
|
|
$examesRegulados = [
|
|
'origem' => 'exame_laboratorio',
|
|
'solicitacoes' => [],
|
|
];
|
|
|
|
foreach (request()->plano['solicitacoes_exames_comuns'] as $solicitacaoData) {
|
|
|
|
$solicitacaoRegulada = [
|
|
'cid_id' => $solicitacaoData['cid_id'] ?? Cid::where('codigo', CidEnum::EXAME_MEDICO_GERAL)->first()->id,
|
|
'ciap_id' => $solicitacaoData['ciap_id'] ?? null,
|
|
'observacao' => $solicitacaoData['observacao'],
|
|
'hipotese_diagnostica_justificativa' => $solicitacaoData['justificativa'],
|
|
'prioridade_id' => $solicitacaoData['classificacao_risco_id'],
|
|
'acompanhamento_oci_id' => $acompanhamentoOci->id ?? null,
|
|
'procedimentos' => []
|
|
];
|
|
|
|
$solicitacaoData['alto_custo'] = false;
|
|
|
|
$solicitacaoData['unidade_usuario_id'] = self::getCurrentLotacao()->unidade_id;
|
|
$solicitacaoData['infraestrutura_usuario_id'] = self::getCurrentLotacao()->infraestrutura_id;
|
|
$solicitacaoData['ocupacao_usuario_id'] = self::getCurrentLotacao()->ocupacao_id;
|
|
$solicitacaoData['lotaca_usuario_id'] = self::getCurrentLotacao()->id;
|
|
|
|
$solicitacao = $soap->solicitacoesExames()->create($solicitacaoData);
|
|
|
|
foreach ($solicitacaoData['exames'] as $exame) {
|
|
|
|
$exameModel = Exame::select('regulacao_tipo_id', 'codigo')
|
|
->where('id', $exame['exame_id'])
|
|
->first();
|
|
|
|
$exame['status_id'] = AtendimentoSoapSolicitacaoExameItemStatus::SOLICITADO;
|
|
$exame['faz_parte_oci'] = $procedimentosOci->contains($exameModel->codigo);
|
|
|
|
$solicitacaoItem = $solicitacao->itens()->create($exame);
|
|
|
|
if ($exameModel->is_regulado) {
|
|
|
|
$solicitacaoRegulada['procedimentos'][] = [
|
|
'origem' => 'exame',
|
|
'id' => $exame['exame_id'],
|
|
'solicitacao_item_id' => $solicitacaoItem->id,
|
|
'faz_parte_oci' => $exame['faz_parte_oci']
|
|
];
|
|
}
|
|
}
|
|
|
|
if (count($solicitacaoRegulada['procedimentos']) > 0) {
|
|
|
|
$examesRegulados['solicitacoes'][] = $solicitacaoRegulada;
|
|
}
|
|
}
|
|
|
|
if (count($examesRegulados['solicitacoes']) > 0) {
|
|
|
|
self::prepareStoreRegulacao($examesRegulados, $soap);
|
|
}
|
|
}
|
|
|
|
private static function saveSolicitacaoExamesAltoCusto($soap, $acompanhamentoOci, $procedimentosOci)
|
|
{
|
|
$examesRegulados = [
|
|
'origem' => 'exame_imagem',
|
|
'solicitacoes' => [],
|
|
];
|
|
|
|
foreach (request()->plano['solicitacoes_exames_alto_custo'] as $solicitacaoData) {
|
|
|
|
$solicitacaoRegulada = [
|
|
'cid_id' => $solicitacaoData['cid_id'],
|
|
'ciap_id' => $solicitacaoData['ciap_id'],
|
|
'observacao' => $solicitacaoData['observacao'],
|
|
'hipotese_diagnostica_justificativa' => $solicitacaoData['justificativa'],
|
|
'prioridade_id' => $solicitacaoData['classificacao_risco_id'],
|
|
'acompanhamento_oci_id' => $acompanhamentoOci->id ?? null,
|
|
'procedimentos' => []
|
|
];
|
|
|
|
$solicitacaoData['alto_custo'] = true;
|
|
|
|
$solicitacaoData['unidade_usuario_id'] = self::getCurrentLotacao()->unidade_id;
|
|
$solicitacaoData['infraestrutura_usuario_id'] = self::getCurrentLotacao()->infraestrutura_id;
|
|
$solicitacaoData['ocupacao_usuario_id'] = self::getCurrentLotacao()->ocupacao_id;
|
|
$solicitacaoData['lotaca_usuario_id'] = self::getCurrentLotacao()->id;
|
|
|
|
$solicitacao = $soap->solicitacoesExames()->create($solicitacaoData);
|
|
|
|
foreach ($solicitacaoData['exames'] as $exame) {
|
|
|
|
$exameModel = Exame::select('regulacao_tipo_id', 'codigo')
|
|
->where('id', $exame['exame_id'])
|
|
->first();
|
|
|
|
$exame['status_id'] = AtendimentoSoapSolicitacaoExameItemStatus::SOLICITADO;
|
|
$exame['faz_parte_oci'] = $procedimentosOci->contains($exameModel->codigo);
|
|
|
|
$solicitacaoItem = $solicitacao->itens()->create($exame);
|
|
|
|
if ($exameModel->is_regulado) {
|
|
|
|
$solicitacaoRegulada['procedimentos'][] = [
|
|
'origem' => 'exame',
|
|
'id' => $exame['exame_id'],
|
|
'solicitacao_item_id' => $solicitacaoItem->id,
|
|
'faz_parte_oci' => $exame['faz_parte_oci']
|
|
];
|
|
}
|
|
}
|
|
|
|
if (count($solicitacaoRegulada['procedimentos']) > 0) {
|
|
|
|
$examesRegulados['solicitacoes'][] = $solicitacaoRegulada;
|
|
}
|
|
}
|
|
|
|
if (count($examesRegulados['solicitacoes']) > 0) {
|
|
|
|
self::prepareStoreRegulacao($examesRegulados, $soap);
|
|
}
|
|
}
|
|
|
|
private static function saveSolicitacaoProcedimentosCirurgicos($soap)
|
|
{
|
|
foreach (request()->plano['solicitacoes_procedimentos_cirurgicos'] as $solicitacaoData) {
|
|
|
|
$solicitacao = $soap->solicitacoesProcedimentosCirurgicos()->create($solicitacaoData);
|
|
|
|
$solicitacao->itens()->createMany($solicitacaoData['procedimentos_cirurgicos']);
|
|
}
|
|
}
|
|
|
|
private static function saveAtestados($soap)
|
|
{
|
|
foreach (request()->plano['atestados'] as $atestado) {
|
|
$modeloId = (int) $atestado['modelo_id'];
|
|
|
|
$data = [
|
|
'modelo_id' => $modeloId,
|
|
];
|
|
|
|
if ($modeloId === AtestadoModeloEnum::EM_BRANCO) {
|
|
|
|
$data['descricao'] = $atestado['descricao'];
|
|
}
|
|
elseif (in_array($modeloId, [
|
|
AtestadoModeloEnum::PERIODO_MANHA,
|
|
AtestadoModeloEnum::PERIODO_TARDE,
|
|
AtestadoModeloEnum::PERIODO_NOITE,
|
|
], true)) {
|
|
|
|
$data['nome_acompanhante'] = $atestado['nome_acompanhante'];
|
|
$data['documento_tipo_id'] = $atestado['documento_tipo_id'];
|
|
$data['cpf'] = $atestado['documento_tipo_id'] == DocumentoTipoEnum::CPF ? $atestado['cpf'] : null;
|
|
$data['cns'] = $atestado['documento_tipo_id'] == DocumentoTipoEnum::CNS ? $atestado['cns'] : null;
|
|
$data['data'] = Carbon::createFromFormat('d/m/Y', $atestado['data']);
|
|
$data['cid_id'] = $atestado['cid_id'];
|
|
}
|
|
elseif ($modeloId === AtestadoModeloEnum::QUANTIDADE_HORAS) {
|
|
|
|
$data['nome_acompanhante'] = $atestado['nome_acompanhante'];
|
|
$data['documento_tipo_id'] = $atestado['documento_tipo_id'];
|
|
$data['cpf'] = $atestado['documento_tipo_id'] == DocumentoTipoEnum::CPF ? $atestado['cpf'] : null;
|
|
$data['cns'] = $atestado['documento_tipo_id'] == DocumentoTipoEnum::CNS ? $atestado['cns'] : null;
|
|
$data['data'] = Carbon::createFromFormat('d/m/Y', $atestado['data']);
|
|
$data['horario_inicial'] = !empty($atestado['horario_inicial']) ? $atestado['horario_inicial'] : null;
|
|
$data['quantidade_horas'] = !empty($atestado['quantidade_horas']) ? intval($atestado['quantidade_horas']) : null;
|
|
$data['cid_id'] = $atestado['cid_id'];
|
|
}
|
|
else {
|
|
|
|
$data['nome_acompanhante'] = $atestado['nome_acompanhante'];
|
|
$data['documento_tipo_id'] = $atestado['documento_tipo_id'];
|
|
$data['cpf'] = $atestado['documento_tipo_id'] == DocumentoTipoEnum::CPF ? $atestado['cpf'] : null;
|
|
$data['cns'] = $atestado['documento_tipo_id'] == DocumentoTipoEnum::CNS ? $atestado['cns'] : null;
|
|
$data['data'] = Carbon::createFromFormat('d/m/Y', $atestado['data']);
|
|
$data['horario'] = $atestado['horario'];
|
|
$data['dias'] = $atestado['dias'];
|
|
$data['cid_id'] = $atestado['cid_id'];
|
|
}
|
|
|
|
$soap->atestados()->create($data);
|
|
}
|
|
}
|
|
|
|
private static function saveDeclaracoesComparecimento($soap)
|
|
{
|
|
foreach (request()->plano['declaracoes_comparecimento'] as $declaracaoComparecimento) {
|
|
|
|
$data = [
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
'nome_acompanhante' => $declaracaoComparecimento['nome_acompanhante'],
|
|
'motivo_comparecimento' => $declaracaoComparecimento['motivo_comparecimento'],
|
|
];
|
|
|
|
if (is_null($declaracaoComparecimento['turno_id'])) {
|
|
|
|
$data['entrada'] = $declaracaoComparecimento['entrada'];
|
|
$data['saida'] = $declaracaoComparecimento['saida'];
|
|
}
|
|
else {
|
|
|
|
$data['turno_id'] = $declaracaoComparecimento['turno_id'];
|
|
}
|
|
|
|
$soap->declaracoesComparecimento()->create($data);
|
|
}
|
|
}
|
|
|
|
private static function saveEncaminhamentos($soap)
|
|
{
|
|
$especialidadesReguladas = [
|
|
'origem' => 'especialidade',
|
|
'solicitacoes' => [],
|
|
];
|
|
|
|
foreach (request()->plano['encaminhamentos'] as $encaminhamento) {
|
|
|
|
$data = [
|
|
'tipo_id' => $encaminhamento['tipo_id'],
|
|
];
|
|
|
|
if ($encaminhamento['tipo_id'] == EncaminhamentoEnum::ENCAMINHAMENTO_PARA_SERVICO_ESPECIALIZADO) {
|
|
|
|
$especialidadeRegulada = Especialidade::select('is_regulado')
|
|
->where('id', $encaminhamento['servico_especializado_especialidade_id'])
|
|
->get();
|
|
|
|
if ($especialidadeRegulada->first()->is_regulado) {
|
|
|
|
$solicitacao = [
|
|
'cid_id' => $encaminhamento['servico_especializado_cid_id'],
|
|
'observacao' => $encaminhamento['servico_especializado_observacao'],
|
|
'hipotese_diagnostica_justificativa' => $encaminhamento['servico_especializado_motivo'],
|
|
'prioridade_id' => $encaminhamento['servico_especializado_classificacao_risco_id'],
|
|
];
|
|
|
|
$solicitacao['procedimentos'][] = [
|
|
'origem' => 'especialidade',
|
|
'id' => $encaminhamento['servico_especializado_especialidade_id'],
|
|
];
|
|
|
|
$especialidadesReguladas['solicitacoes'][] = $solicitacao;
|
|
}
|
|
|
|
$data['servico_especializado_especialidade_id'] = $encaminhamento['servico_especializado_especialidade_id'];
|
|
$data['servico_especializado_complemento'] = $encaminhamento['servico_especializado_complemento'];
|
|
$data['servico_especializado_cid_id'] = $encaminhamento['servico_especializado_cid_id'];
|
|
$data['servico_especializado_ciap_id'] = $encaminhamento['servico_especializado_ciap_id'];
|
|
$data['servico_especializado_classificacao_risco_id'] = $encaminhamento['servico_especializado_classificacao_risco_id'];
|
|
$data['servico_especializado_motivo'] = $encaminhamento['servico_especializado_motivo'];
|
|
$data['servico_especializado_observacao'] = $encaminhamento['servico_especializado_observacao'];
|
|
}
|
|
else if ($encaminhamento['tipo_id'] == EncaminhamentoEnum::ENCAMINHAMENTO_INTERSETORIAL) {
|
|
|
|
$data['intersetorial_infraestrutura_id'] = $encaminhamento['intersetorial_infraestrutura_id'];
|
|
}
|
|
else if ($encaminhamento['tipo_id'] == EncaminhamentoEnum::ENCAMINHAMENTO_PARA_CAPS) {
|
|
|
|
$data['servico_especializado_motivo'] = $encaminhamento['servico_especializado_motivo'];
|
|
}
|
|
else if($encaminhamento['tipo_id'] == EncaminhamentoEnum::ENCAMINHAMENTO_PARA_INTERNACAO_HOSPITALAR){
|
|
|
|
$dataSolicitacao = isset($encaminhamento['internacao_hospitalar_data_solicitacao'])
|
|
? Carbon::parse($encaminhamento['internacao_hospitalar_data_solicitacao'])->format('Y-m-d')
|
|
: null;
|
|
|
|
$dataAutorizacao = isset($encaminhamento['internacao_hospitalar_data_autorizacao'])
|
|
? Carbon::parse($encaminhamento['internacao_hospitalar_data_autorizacao'])->format('Y-m-d')
|
|
: null;
|
|
$data['internacao_hospitalar_cid_principal_id'] = $encaminhamento['internacao_hospitalar_cid_principal_id'];
|
|
$data['internacao_hospitalar_cid_secundario_id'] = $encaminhamento['internacao_hospitalar_cid_secundario_id'] ?? null;
|
|
$data['internacao_hospitalar_cid_causas_associadas_id'] = $encaminhamento['internacao_hospitalar_cid_causas_associadas_id'] ?? null;
|
|
$data['internacao_hospitalar_unidade_solicitante_id'] = $encaminhamento['internacao_hospitalar_unidade_solicitante_id'];
|
|
$data['internacao_hosp_principais_resultados_de_provas_diagnosticas'] = $encaminhamento['internacao_hosp_principais_resultados_de_provas_diagnosticas'];
|
|
$data['internacao_hosp_condicoes_que_justificam_internacao'] = $encaminhamento['internacao_hosp_condicoes_que_justificam_internacao'];
|
|
$data['internacao_hosp_principais_sinais_sintomas_clinicos'] = $encaminhamento['internacao_hosp_principais_sinais_sintomas_clinicos'];
|
|
$data['internacao_hospitalar_procedimento_solicitado_id'] = $encaminhamento['internacao_hospitalar_procedimento_solicitado_id'];
|
|
$data['internacao_hospitalar_data_solicitacao'] = $dataSolicitacao;
|
|
$data['internacao_hospitalar_clinica_id'] = $encaminhamento['internacao_hospitalar_clinica_id'];
|
|
$data['internacao_hospitalar_carater_internacao_id'] = $encaminhamento['internacao_hospitalar_carater_internacao_id'];
|
|
$data['internacao_hospitalar_profissional_solicitante_assistente_id'] = $encaminhamento['internacao_hospitalar_profissional_solicitante_assistente_id'];
|
|
$data['internacao_hospitalar_profissional_solicitante_documento_tipo_id'] = $encaminhamento['internacao_hospitalar_profissional_solicitante_documento_tipo_id'];
|
|
$data['internacao_hospitalar_profissional_solicitante_documento_numero'] = $encaminhamento['internacao_hospitalar_profissional_solicitante_documento_numero'];
|
|
$data['internacao_hospitalar_causa_externa_id'] = $encaminhamento['internacao_hospitalar_causa_externa_id'] ?? null;
|
|
$data['internacao_hospitalar_cnpj_seguradora'] = $encaminhamento['internacao_hospitalar_cnpj_seguradora'] ?? null;
|
|
$data['internacao_hospitalar_numero_bilhete'] = $encaminhamento['internacao_hospitalar_numero_bilhete'] ?? null;
|
|
$data['internacao_hospitalar_serie'] = $encaminhamento['internacao_hospitalar_serie'] ?? null;
|
|
$data['internacao_hospitalar_cnpj_empresa'] = $encaminhamento['internacao_hospitalar_cnpj_empresa'] ?? null;
|
|
$data['internacao_hospitalar_cnae_empresa'] = $encaminhamento['internacao_hospitalar_cnae_empresa'] ?? null;
|
|
$data['internacao_hospitalar_cbor'] = $encaminhamento['internacao_hospitalar_cbor'] ?? null;
|
|
$data['internacao_hospitalar_vinculo_previdencia_id'] = $encaminhamento['internacao_hospitalar_vinculo_previdencia_id'] ?? null;
|
|
$data['internacao_hospitalar_profissional_autorizador_id'] = $encaminhamento['internacao_hospitalar_profissional_autorizador_id'] ?? null;
|
|
$data['internacao_hospitalar_data_autorizacao'] = $dataAutorizacao;
|
|
$data['internacao_hospitalar_codigo_orgao_emissor'] = $encaminhamento['internacao_hospitalar_codigo_orgao_emissor'] ?? null;
|
|
$data['internacao_hospitalar_profissional_autorizador_documento_tipo_id'] = $encaminhamento['internacao_hospitalar_profissional_autorizador_documento_tipo_id'] ?? null;
|
|
$data['internacao_hospitalar_profissional_autorizador_documento_numero'] = $encaminhamento['internacao_hospitalar_profissional_autorizador_documento_numero'] ?? null;
|
|
}
|
|
|
|
$data['servico_especializado_cid_id'] = $encaminhamento['servico_especializado_cid_id'];
|
|
$data['servico_especializado_ciap_id'] = $encaminhamento['servico_especializado_ciap_id'];
|
|
$data['unidade_usuario_id'] = self::getCurrentLotacao()->unidade_id;
|
|
$data['infraestrutura_usuario_id'] = self::getCurrentLotacao()->infraestrutura_id;
|
|
$data['ocupacao_usuario_id'] = self::getCurrentLotacao()->ocupacao_id;
|
|
$data['lotaca_usuario_id'] = self::getCurrentLotacao()->id;
|
|
|
|
$soap->encaminhamentos()->create($data);
|
|
}
|
|
|
|
count($especialidadesReguladas['solicitacoes']) > 0
|
|
? self::prepareStoreRegulacao($especialidadesReguladas, $soap)
|
|
: null;
|
|
}
|
|
|
|
private static function saveProcedimentos($soap, $acompanhamentoOci, $procedimentosOci)
|
|
{
|
|
self::saveProcedimentosClinicos($soap, $acompanhamentoOci, $procedimentosOci);
|
|
self::saveProcedimentosAdministrativos($soap, $acompanhamentoOci, $procedimentosOci);
|
|
}
|
|
|
|
private static function saveProcedimentosClinicos($soap, $acompanhamentoOci, $procedimentosOci)
|
|
{
|
|
foreach (request()->plano['procedimentos_clinicos'] as $procedimento) {
|
|
|
|
$procedimentoModel = DB::table('sigtap.procedimento')->where('id', $procedimento['procedimento_id'])->select('codigo')->first();
|
|
|
|
$atendimentoProcedimento = $soap->procedimentos()->create([
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
'procedimento_id' => $procedimento['procedimento_id'],
|
|
'cid_id' => $procedimento['cid_id'],
|
|
'quantidade' => $procedimento['quantidade'],
|
|
'automatico' => $procedimento['automatico'],
|
|
'ocupacao_id' => $soap->atendimento->ocupacao->id ?? $soap->createdLotacao->ocupacao_id,
|
|
'especialidade_id' => $soap->atendimento->especialidade->id ?? null,
|
|
'usuario_id' => $soap->atendimento->usuario->id ?? $soap->createdLotacao->usuario_id,
|
|
'acompanhamento_oci_id' => $procedimentosOci->contains($procedimentoModel->codigo)
|
|
? $acompanhamentoOci->id
|
|
: null
|
|
]);
|
|
|
|
$soap->procedimentosClinicos()->create([
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
'observacao' => $procedimento['observacao'],
|
|
]);
|
|
|
|
if (!empty($procedimento['materiais']) && is_array($procedimento['materiais'])) {
|
|
|
|
foreach ($procedimento['materiais'] as $material) {
|
|
|
|
if (!empty($material['material_id'])) {
|
|
|
|
$itemData = [
|
|
'material_id' => $material['material_id'],
|
|
'quantidade' => $material['material_quantidade'],
|
|
'escolheu_entrada_item_manualmente' => $material['material_escolheu_entrada_item_manualmente'] ?? false,
|
|
'entrada_itens' => $material['material_entrada_itens'] ?? [],
|
|
];
|
|
|
|
$saidaItem = AlmoxarifadoService::saveSaidaDeDispensacaoDoAmbulatorio($itemData);
|
|
|
|
DB::table('ambulatorio_procedimento_material')->insert([
|
|
'ambulatorio_atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
'saida_item_id' => $saidaItem->id,
|
|
'created_at' => now(),
|
|
'updated_at' => now(),
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
if (!self::isRascunho()) {
|
|
|
|
self::getAutomaticProcedimentosClinicos($soap)->each(function ($id) use ($soap) {
|
|
|
|
$atendimentoProcedimento = $soap->procedimentos()->create([
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
'procedimento_id' => $id,
|
|
'quantidade' => 1,
|
|
'automatico' => true,
|
|
'ocupacao_id' => $soap->atendimento->ocupacao->id ?? $soap->createdLotacao->ocupacao_id,
|
|
'especialidade_id' => $soap->atendimento->especialidade->id ?? null,
|
|
'usuario_id' => $soap->atendimento->usuario->id ?? $soap->createdLotacao->usuario_id,
|
|
]);
|
|
|
|
$soap->procedimentosClinicos()->create([
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
]);
|
|
});
|
|
}
|
|
}
|
|
|
|
private static function getAutomaticProcedimentosClinicos($soap)
|
|
{
|
|
$procedimentos = collect();
|
|
|
|
if (!is_null($soap->objetivoAntropometria)) {
|
|
|
|
$antropometria = $soap->objetivoAntropometria->atendimentoAntropometria;
|
|
|
|
if (!is_null($antropometria->peso) && !is_null($antropometria->altura)) {
|
|
|
|
$procedimentos->push(self::getProcedimentoId(ProcedimentoEnum::AVALIACAO_ANTROPOMETRICA));
|
|
}
|
|
else if (!is_null($antropometria->peso)) {
|
|
|
|
$procedimentos->push(self::getProcedimentoId(ProcedimentoEnum::MEDICAO_DE_PESO));
|
|
}
|
|
else if (!is_null($antropometria->altura)) {
|
|
|
|
$procedimentos->push(self::getProcedimentoId(ProcedimentoEnum::MEDICAO_DE_ALTURA));
|
|
}
|
|
}
|
|
|
|
if (!is_null($soap->objetivoSinalVital)) {
|
|
|
|
$sinalVital = $soap->objetivoSinalVital->atendimentoSinalVital;
|
|
|
|
if (!is_null($sinalVital->pressao_arterial)) {
|
|
|
|
$procedimentos->push(self::getProcedimentoId(ProcedimentoEnum::AFERICAO_PRESSAO_ARTERIAL));
|
|
}
|
|
|
|
if (!is_null($sinalVital->temperatura)) {
|
|
|
|
$procedimentos->push(self::getProcedimentoId(ProcedimentoEnum::AFERICAO_DE_TEMPERATURA));
|
|
}
|
|
}
|
|
|
|
if (!is_null($soap->objetivoGlicemiaCapilar)) {
|
|
|
|
$glicemiaCapilar = $soap->objetivoGlicemiaCapilar->atendimentoGlicemiaCapilar;
|
|
|
|
if (!is_null($glicemiaCapilar->valor)) {
|
|
|
|
$procedimentos->push(self::getProcedimentoId(ProcedimentoEnum::GLICEMIA_CAPILAR));
|
|
}
|
|
}
|
|
|
|
if ($soap->is_atendimento_puericultura) {
|
|
|
|
$procedimentos->push(self::getProcedimentoId(ProcedimentoEnum::AVALIACAO_DO_DESENVOLVIMENTO_DA_CRIANCA_NA_PUERICULTURA));
|
|
}
|
|
|
|
if ($soap->riscoCardiovascularFramingham()->exists()) {
|
|
|
|
$procedimentos->push(self::getProcedimentoId(ProcedimentoEnum::ESTRATIFICACAO_DO_RISCO_CARDIOVASCULAR));
|
|
}
|
|
|
|
return $procedimentos;
|
|
}
|
|
|
|
public static function isPacienteGestante($soap)
|
|
{
|
|
$hasGravidez = false;
|
|
|
|
self::getProblemasCondicoesAtivosOuLatentes($soap->atendimento->paciente)
|
|
->each(function ($problemaCondicao) use (&$hasGravidez) {
|
|
|
|
if (collect(self::CIAPS_GRAVIDEZ_NORMAL)->contains($problemaCondicao['ciap']['codigo'])
|
|
|| collect(self::CIDS_GRAVIDEZ_NORMAL)->contains($problemaCondicao['cid']['codigo'])
|
|
) {
|
|
|
|
$hasGravidez = true;
|
|
|
|
return false;
|
|
}
|
|
});
|
|
|
|
return $hasGravidez;
|
|
}
|
|
|
|
private static function saveProcedimentosAdministrativos($soap, $acompanhamentoOci, $procedimentosOci)
|
|
{
|
|
foreach (request()->finalizacao['procedimentos_administrativos'] as $procedimento) {
|
|
|
|
$procedimentoModel = DB::table('sigtap.procedimento')->where('id', $procedimento['procedimento_id'])->select('codigo')->first();
|
|
|
|
$atendimentoProcedimento = $soap->procedimentos()
|
|
->create([
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
'procedimento_id' => $procedimento['procedimento_id'],
|
|
'cid_id' => $procedimento['cid_id'],
|
|
'quantidade' => $procedimento['quantidade'],
|
|
'automatico' => $procedimento['automatico'],
|
|
'ocupacao_id' => $soap->atendimento->ocupacao->id ?? $soap->createdLotacao->ocupacao_id,
|
|
'especialidade_id' => $soap->atendimento->especialidade->id ?? null,
|
|
'usuario_id' => $soap->atendimento->usuario->id ?? $soap->createdLotacao->usuario_id,
|
|
'acompanhamento_oci_id' => $procedimentosOci->contains($procedimentoModel->codigo)
|
|
? $acompanhamentoOci->id
|
|
: null
|
|
]);
|
|
|
|
$soap->procedimentosAdministrativos()
|
|
->create(['atendimento_procedimento_id' => $atendimentoProcedimento->id]);
|
|
}
|
|
}
|
|
|
|
private static function getProcedimentoId($codigo)
|
|
{
|
|
return Procedimento::where('codigo', $codigo)->orderByDesc('competencia_id')->first('id')->id;
|
|
}
|
|
|
|
private static function saveFinalizacao($soap)
|
|
{
|
|
if (request()->finalizacao['desfecho']['finalizado']) {
|
|
|
|
$soap->atendimento->update([
|
|
'finalizado_em' => Carbon::now(),
|
|
'finalizado_lotacao_id' => self::getCurrentLotacao()->id,
|
|
]);
|
|
|
|
if ($soap->atendimento->fila) {
|
|
|
|
$soap->atendimento->fila->update(['finalizado' => true]);
|
|
}
|
|
|
|
if (!$soap->atendimento->is_demanda_espontanea) {
|
|
|
|
$soap->atendimento->agendamento->update(['status_id' => AgendamentoStatus::REALIZADO]);
|
|
|
|
if (!is_null($soap->atendimento->agendamento->regulacao_solicitacao_id)) {
|
|
|
|
RegulacaoSolicitacaoService::updateStatus(
|
|
$soap->atendimento->agendamento->regulacao_solicitacao_id,
|
|
RegulacaoStatusTipo::REALIZADO
|
|
);
|
|
}
|
|
}
|
|
}
|
|
else {
|
|
|
|
if ($soap->atendimento->is_demanda_espontanea) {
|
|
|
|
$soap->atendimento->demandaEspontanea()->update([
|
|
'ocupacao_id' => request()->finalizacao['desfecho']['ocupacao_id'],
|
|
'especialidade_id' => request()->finalizacao['desfecho']['especialidade_id'],
|
|
'usuario_id' => request()->finalizacao['desfecho']['usuario_id'],
|
|
]);
|
|
}
|
|
|
|
$soap->atendimento->update([
|
|
'responsavel_atual_ocupacao_id' => request()->finalizacao['desfecho']['ocupacao_id'],
|
|
'responsavel_atual_especialidade_id' => request()->finalizacao['desfecho']['especialidade_id'],
|
|
'responsavel_atual_usuario_id' => request()->finalizacao['desfecho']['usuario_id'],
|
|
'responsavel_encaminhamento_atual_lotacao_id' => is_null(request()->finalizacao['desfecho']['usuario_id'])
|
|
? null
|
|
: $soap->created_lotacao_id,
|
|
]);
|
|
|
|
if ($soap->atendimento->fila) {
|
|
|
|
$filaUpdateParams = [
|
|
'prioridade_id' => request()->finalizacao['desfecho']['prioridade_id']
|
|
];
|
|
|
|
if (!self::isRascunho()) {
|
|
|
|
$filaUpdateParams['status_id'] = PainelSenhaStatus::EM_ESPERA;
|
|
}
|
|
|
|
$soap->atendimento->fila->update($filaUpdateParams);
|
|
}
|
|
|
|
$soap->atendimento->servicos()->sync(request()->finalizacao['desfecho']['servicos']);
|
|
}
|
|
}
|
|
|
|
private static function saveRaas($soap)
|
|
{
|
|
if (!self::hasProcedimentoRaas($soap->atendimento, true)) {
|
|
|
|
return;
|
|
}
|
|
|
|
AtendimentoRaas::updateOrCreate(
|
|
['atendimento_id' => $soap->atendimento->id],
|
|
[
|
|
'origem_paciente_id' => request()->raas['origem_paciente_id'],
|
|
'destino_paciente_id' => request()->raas['destino_paciente_id'],
|
|
'motivo_saida_permanencia_id' => request()->raas['motivo_saida_permanencia_id'],
|
|
'carater_atendimento_id' => request()->raas['carater_atendimento_id'],
|
|
'numero_autorizacao' => self::hasProcedimentoRaasQuePrecisaDeAutorizacao($soap->atendimento, true)
|
|
? request()->raas['numero_autorizacao']
|
|
: null,
|
|
'classificacao_id' => self::hasProcedimentoRaasQuePrecisaDeClassificacao($soap->atendimento, true)
|
|
? request()->raas['classificacao_id']
|
|
: null,
|
|
'local_realizacao_exame_id' => request()->raas['local_realizacao_exame_id'],
|
|
]
|
|
);
|
|
}
|
|
|
|
private static function validateStore($fila = null)
|
|
{
|
|
request()->validate(array_merge(
|
|
[
|
|
'is_rascunho' => [
|
|
'required',
|
|
'boolean',
|
|
],
|
|
'fila_id' => [
|
|
'nullable',
|
|
'required_without:agendamento_id',
|
|
'integer',
|
|
Rule::exists(Fila::class, 'id'),
|
|
],
|
|
'agendamento_id' => [
|
|
'nullable',
|
|
'required_without:fila_id',
|
|
'integer',
|
|
Rule::exists(Agendamento::class, 'id'),
|
|
],
|
|
'ultima_etapa_oci_realizada_mesmo_atendimento' => [
|
|
'nullable',
|
|
'required_with:oci_id',
|
|
'boolean'
|
|
],
|
|
'oci_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Oci::class, 'id'),
|
|
],
|
|
'acompanhamento_oci_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(AcompanhamentoOci::class, 'id'),
|
|
],
|
|
'observacao_perfil_epidemiologico' => [
|
|
'nullable',
|
|
'max:500',
|
|
],
|
|
],
|
|
self::getOciProcedimentosRealizadosValidations(),
|
|
self::getPacienteValidations(),
|
|
self::getMedicoesValidations(),
|
|
self::getMedicamentosEmUsoValidations(),
|
|
self::getAntecedenteValidations(),
|
|
self::getSubjetivoValidations(),
|
|
self::getObjetivoValidations(),
|
|
self::getAvaliacaoValidations(),
|
|
self::getPlanoValidations(),
|
|
self::getRaasValidations(),
|
|
self::getFinalizacaoValidations($fila),
|
|
self::getPerfisEpidemiologicosValidations(),
|
|
));
|
|
}
|
|
|
|
private static function getOciProcedimentosRealizadosValidations()
|
|
{
|
|
return [
|
|
'oci_procedimentos_realizados_previamente' => [
|
|
'present',
|
|
'array'
|
|
],
|
|
'oci_procedimentos_realizados_previamente.*.id' => [
|
|
'required',
|
|
'integer',
|
|
],
|
|
'oci_procedimentos_realizados_previamente.*.data_executada' => [
|
|
'nullable',
|
|
'date_format:d/m/Y',
|
|
],
|
|
'oci_procedimentos_realizados_previamente.*.unidade_executora_id' => [
|
|
'nullable',
|
|
'integer',
|
|
],
|
|
'oci_procedimentos_realizados_previamente.*.ocupacao_executora_id' => [
|
|
'nullable',
|
|
'integer',
|
|
],
|
|
'oci_procedimentos_realizados_previamente.*.usuarioExecutor' => [
|
|
'nullable',
|
|
'string',
|
|
'max:100'
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getPacienteValidations()
|
|
{
|
|
return [
|
|
'paciente.telefone_principal.id' => [
|
|
'bail',
|
|
'nullable',
|
|
'integer',
|
|
'exclude_if:paciente.telefone_principal.atualizado,false',
|
|
Rule::exists(CidadaoTelefone::class, 'id'),
|
|
],
|
|
'paciente.telefone_principal.numero' => [
|
|
'bail',
|
|
'nullable',
|
|
'required_with:paciente.telefone_principal.id',
|
|
'exclude_if:paciente.telefone_principal.atualizado,false',
|
|
'digits_between:10,11',
|
|
],
|
|
'paciente.telefone_principal.autoriza_sms' => [
|
|
'bail',
|
|
'nullable',
|
|
'required_with:paciente.telefone_principal.id',
|
|
'exclude_if:paciente.telefone_principal.atualizado,false',
|
|
'boolean',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getMedicoesValidations()
|
|
{
|
|
return self::getMedicoesAntropomeriaValidations();
|
|
}
|
|
|
|
private static function getMedicoesAntropomeriaValidations()
|
|
{
|
|
return [
|
|
'medicoes.antropometrias' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'medicoes.antropometrias.*.medido_em' => [
|
|
'required',
|
|
'date_format:d/m/Y',
|
|
],
|
|
'medicoes.antropometrias.*.peso' => [
|
|
'nullable',
|
|
'numeric',
|
|
'between:0.5,500',
|
|
],
|
|
'medicoes.antropometrias.*.altura' => [
|
|
'nullable',
|
|
'numeric',
|
|
'between:20,250',
|
|
],
|
|
'medicoes.antropometrias.*.perimetro_cefalico' => [
|
|
'nullable',
|
|
'numeric',
|
|
'between:10,200',
|
|
],
|
|
'medicoes.antropometrias.*.circunferencia_abdominal' => [
|
|
'nullable',
|
|
'numeric',
|
|
'max:999',
|
|
],
|
|
'medicoes.antropometrias.*.perimetro_panturrilha' => [
|
|
'nullable',
|
|
'numeric',
|
|
'between:10,99',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getMedicamentosEmUsoValidations()
|
|
{
|
|
return [
|
|
'medicamentos_em_uso.medicamentos_com_tratamento_interrompido' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'medicamentos_em_uso.medicamentos_com_tratamento_interrompido.*.prescricao_medicamento_item_id' => [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(AtendimentoSoapPrescricaoMedicamentoItem::class, 'id'),
|
|
],
|
|
'medicamentos_em_uso.medicamentos_com_tratamento_interrompido.*.justificativa' => [
|
|
'required',
|
|
'string',
|
|
'max:500',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getAntecedenteValidations()
|
|
{
|
|
return array_merge(
|
|
[
|
|
'antecedente.descricao' => [
|
|
'nullable',
|
|
'string',
|
|
'max:5000'
|
|
],
|
|
'antecedente.descricao_familiar' => [
|
|
'nullable',
|
|
'string',
|
|
'max:5000'
|
|
],
|
|
'antecedente.gestas_previas' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:99'
|
|
],
|
|
'antecedente.abortos' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:99'
|
|
],
|
|
'antecedente.desfecho_gestacao_aconteceu_menos_um_ano' => [
|
|
'nullable',
|
|
'boolean',
|
|
],
|
|
'antecedente.partos_realizados' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:99'
|
|
],
|
|
'antecedente.partos_vaginais' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:99'
|
|
],
|
|
'antecedente.partos_cesareas' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:99'
|
|
],
|
|
'antecedente.partos_domiciliares' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:99'
|
|
],
|
|
'antecedente.nascidos_vivos' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:99'
|
|
],
|
|
'antecedente.nascidos_mortos' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:99'
|
|
],
|
|
'antecedente.recem_nascidos_com_menos2500_gramas' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:99'
|
|
],
|
|
'antecedente.recem_nascidos_com_mais4500_gramas' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:99'
|
|
],
|
|
'antecedente.nascidos_vivos_vivem' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:99'
|
|
],
|
|
'antecedente.nascidos_vivos_mortos_primeira_semana' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:99'
|
|
],
|
|
'antecedente.nascidos_vivos_mortos_depois_primeira_semana' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:99'
|
|
],
|
|
],
|
|
self::getAntecedenteProblemasCondicoesValidations(),
|
|
self::getAntecedenteCirurgiasInternacoesValidations(),
|
|
self::getAntecedenteProblemaFamiliarValidations()
|
|
);
|
|
}
|
|
|
|
private static function getAntecedenteProblemasCondicoesValidations()
|
|
{
|
|
$rules = [
|
|
'antecedente.problemas_condicoes' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
];
|
|
|
|
foreach ((request()->antecedente['problemas_condicoes'] ?? []) as $i => $problemaCondicao) {
|
|
|
|
$rules["antecedente.problemas_condicoes.{$i}.ciap_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !isset($problemaCondicao['cid_id'])),
|
|
'integer',
|
|
Rule::exists(Ciap::class, 'id'),
|
|
];
|
|
|
|
$rules["antecedente.problemas_condicoes.{$i}.cid_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !isset($problemaCondicao['ciap_id'])),
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id'),
|
|
];
|
|
|
|
$rules["antecedente.problemas_condicoes.{$i}.situacao_id"] = [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(ProblemaCondicaoSituacao::class, 'id'),
|
|
];
|
|
|
|
$rules["antecedente.problemas_condicoes.{$i}.inicio"] = [
|
|
'nullable',
|
|
'date_format:d/m/Y',
|
|
];
|
|
|
|
if (isset($problemaCondicao['fim'])) {
|
|
|
|
$rules["antecedente.problemas_condicoes.{$i}.inicio"][] =
|
|
'before_or_equal:' . $problemaCondicao['fim'];
|
|
}
|
|
|
|
$rules["antecedente.problemas_condicoes.{$i}.fim"] = [
|
|
'nullable',
|
|
'date_format:d/m/Y',
|
|
];
|
|
|
|
if (isset($problemaCondicao['inicio'])) {
|
|
|
|
$rules["antecedente.problemas_condicoes.{$i}.fim"][] =
|
|
'after_or_equal:' . $problemaCondicao['inicio'];
|
|
}
|
|
|
|
$rules["antecedente.problemas_condicoes.{$i}.observacao"] = [
|
|
'nullable',
|
|
'string',
|
|
'max:5000',
|
|
];
|
|
}
|
|
|
|
return $rules;
|
|
}
|
|
|
|
private static function getAntecedenteCirurgiasInternacoesValidations()
|
|
{
|
|
return [
|
|
'antecedente.cirurgias_internacoes' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'antecedente.cirurgias_internacoes.*.descricao' => [
|
|
'required',
|
|
'string',
|
|
'max:100'
|
|
],
|
|
'antecedente.cirurgias_internacoes.*.realizada_em' => [
|
|
'nullable',
|
|
'date_format:d/m/Y',
|
|
],
|
|
'antecedente.cirurgias_internacoes.*.observacao' => [
|
|
'nullable',
|
|
'string',
|
|
'max:500',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getAntecedenteProblemaFamiliarValidations()
|
|
{
|
|
return [
|
|
'antecedente.problemas_familiares' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'antecedente.problemas_familiares.*.ciap_id' => [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(Ciap::class, 'id'),
|
|
],
|
|
'antecedente.problemas_familiares.*.observacao' => [
|
|
'nullable',
|
|
'string',
|
|
'max:500',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getSubjetivoValidations()
|
|
{
|
|
return array_merge(
|
|
[
|
|
'subjetivo.descricao' => [
|
|
'nullable',
|
|
'string',
|
|
'max:5000',
|
|
],
|
|
],
|
|
self::getSubjetivoMotivosValidations()
|
|
);
|
|
}
|
|
|
|
private static function getSubjetivoMotivosValidations()
|
|
{
|
|
$rules = [
|
|
'subjetivo.motivos' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
];
|
|
|
|
foreach ((request()->subjetivo['motivos'] ?? []) as $i => $motivo) {
|
|
$rules["subjetivo.motivos.{$i}.ciap_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !isset($motivo['cid_id'])),
|
|
'integer',
|
|
Rule::exists(Ciap::class, 'id'),
|
|
];
|
|
|
|
$rules["subjetivo.motivos.{$i}.cid_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !isset($motivo['ciap_id'])),
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id'),
|
|
];
|
|
|
|
$rules["subjetivo.motivos.{$i}.observacao"] = [
|
|
'nullable',
|
|
'string',
|
|
'max:500',
|
|
];
|
|
}
|
|
|
|
return $rules;
|
|
}
|
|
|
|
private static function getObjetivoValidations()
|
|
{
|
|
return array_merge(
|
|
[
|
|
'objetivo.descricao' => [
|
|
'nullable',
|
|
'string',
|
|
'max:5000',
|
|
],
|
|
'objetivo.is_atendimento_puericultura' => [
|
|
'required',
|
|
'boolean',
|
|
],
|
|
'objetivo.dum' => [
|
|
'nullable',
|
|
'date_format:d/m/Y',
|
|
'before_or_equal:now',
|
|
],
|
|
'objetivo.vacinacao_em_dia' => [
|
|
'nullable',
|
|
'boolean',
|
|
],
|
|
'objetivo.paciente_com_necessidade_especial' => [
|
|
'nullable',
|
|
'boolean',
|
|
],
|
|
],
|
|
self::getObjetivoPreNatalValidations(),
|
|
self::getObjetivoPuericulturaValidations(),
|
|
self::getObjetivoAntropometriaValidations(),
|
|
self::getObjetivoSinalVitalValidations(),
|
|
self::getObjetivoGlicemiaCapilarValidations(),
|
|
self::getObjetivoResultadosExamesValidations(),
|
|
self::getObjetivoExameAvaliadoValidations(),
|
|
);
|
|
}
|
|
|
|
private static function getObjetivoPreNatalValidations()
|
|
{
|
|
return self::getPreNatalValidations('objetivo');
|
|
}
|
|
|
|
private static function getObjetivoPuericulturaValidations()
|
|
{
|
|
return array_merge(
|
|
[
|
|
'objetivo.puericultura.gravidez_tipo_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(GravidezTipo::class, 'id'),
|
|
],
|
|
'objetivo.puericultura.parto_tipo_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(PartoTipo::class, 'id'),
|
|
],
|
|
'objetivo.puericultura.idade_gestacional_semanas' => [
|
|
'nullable',
|
|
'integer',
|
|
'between:20,42',
|
|
],
|
|
'objetivo.puericultura.idade_gestacional_dias' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:6',
|
|
],
|
|
'objetivo.puericultura.apgar_primeiro_minuto' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:10',
|
|
],
|
|
'objetivo.puericultura.apgar_quinto_minuto' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:10',
|
|
],
|
|
'objetivo.puericultura.apgar_decimo_minuto' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:10',
|
|
],
|
|
'objetivo.puericultura.peso' => [
|
|
'nullable',
|
|
'numeric',
|
|
'between:0.5,500',
|
|
],
|
|
'objetivo.puericultura.comprimento' => [
|
|
'nullable',
|
|
'numeric',
|
|
'between:20,250',
|
|
],
|
|
'objetivo.puericultura.perimetro_cefalico' => [
|
|
'nullable',
|
|
'numeric',
|
|
'between:10,200',
|
|
],
|
|
'objetivo.puericultura.aleitamento_tipo_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(AleitamentoMaterno::class, 'id'),
|
|
],
|
|
],
|
|
self::getObjetivoPuericulturaAlteracoesFenotipicasValidations(),
|
|
self::getObjetivoPuericulturaFatoresRiscoValidations(),
|
|
self::getObjetivoPuericulturaMarcosDesenvolvimentoValidations(),
|
|
);
|
|
}
|
|
|
|
private static function getObjetivoPuericulturaAlteracoesFenotipicasValidations()
|
|
{
|
|
return [
|
|
'objetivo.puericultura.alteracoes_fenotipicas' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'objetivo.puericultura.alteracoes_fenotipicas.*.id' => [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(PuericulturaAlteracaoFenotipica::class, 'id'),
|
|
],
|
|
'objetivo.puericultura.alteracoes_fenotipicas.*.is_presente' => [
|
|
'nullable',
|
|
'boolean',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getObjetivoPuericulturaFatoresRiscoValidations()
|
|
{
|
|
return [
|
|
'objetivo.puericultura.fatores_risco' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'objetivo.puericultura.fatores_risco.*.id' => [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(PuericulturaFatorRisco::class, 'id'),
|
|
],
|
|
'objetivo.puericultura.fatores_risco.*.is_presente' => [
|
|
'nullable',
|
|
'boolean',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getObjetivoPuericulturaMarcosDesenvolvimentoValidations()
|
|
{
|
|
return [
|
|
'objetivo.puericultura.marcos_desenvolvimento' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'objetivo.puericultura.marcos_desenvolvimento.*.id' => [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(PuericulturaMarcoDesenvolvimento::class, 'id'),
|
|
],
|
|
'objetivo.puericultura.marcos_desenvolvimento.*.is_presente' => [
|
|
'nullable',
|
|
'boolean',
|
|
],
|
|
'objetivo.puericultura.marcos_desenvolvimento.*.alcancado_com_anos' => [
|
|
'nullable',
|
|
'integer',
|
|
],
|
|
'objetivo.puericultura.marcos_desenvolvimento.*.alcancado_com_meses' => [
|
|
'nullable',
|
|
'integer',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getObjetivoAntropometriaValidations()
|
|
{
|
|
return [
|
|
'objetivo.antropometria.peso' => [
|
|
'nullable',
|
|
'numeric',
|
|
'between:0.5,500',
|
|
],
|
|
'objetivo.antropometria.altura' => [
|
|
'nullable',
|
|
'numeric',
|
|
'between:20,250',
|
|
],
|
|
'objetivo.antropometria.perimetro_cefalico' => [
|
|
'nullable',
|
|
'numeric',
|
|
'between:10,200',
|
|
],
|
|
'objetivo.antropometria.circunferencia_abdominal' => [
|
|
'nullable',
|
|
'numeric',
|
|
'max:999',
|
|
],
|
|
'objetivo.antropometria.perimetro_panturrilha' => [
|
|
'nullable',
|
|
'numeric',
|
|
'between:10,99',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getObjetivoSinalVitalValidations()
|
|
{
|
|
return [
|
|
'objetivo.sinal_vital.pressao_arterial' => [
|
|
'nullable',
|
|
'string',
|
|
'max:7',
|
|
],
|
|
'objetivo.sinal_vital.frequencia_respiratoria' => [
|
|
'nullable',
|
|
'numeric',
|
|
'max:200',
|
|
],
|
|
'objetivo.sinal_vital.frequencia_cardiaca' => [
|
|
'nullable',
|
|
'numeric',
|
|
'max:999',
|
|
],
|
|
'objetivo.sinal_vital.temperatura' => [
|
|
'nullable',
|
|
'numeric',
|
|
'between:20,45',
|
|
],
|
|
'objetivo.sinal_vital.saturacao_o2' => [
|
|
'nullable',
|
|
'numeric',
|
|
'max:100',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getObjetivoGlicemiaCapilarValidations()
|
|
{
|
|
return [
|
|
'objetivo.glicemia_capilar.valor' => [
|
|
'nullable',
|
|
'numeric',
|
|
'max:800',
|
|
],
|
|
'objetivo.glicemia_capilar.momento_coleta_id' => [
|
|
'nullable',
|
|
'required_with:glicemia_capilar.valor',
|
|
'integer',
|
|
Rule::exists(GlicemiaCapilarMomentoColeta::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getObjetivoResultadosExamesValidations()
|
|
{
|
|
return [
|
|
'objetivo.resultados_exames' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'objetivo.resultados_exames.*.exame_id' => [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(Exame::class, 'id'),
|
|
],
|
|
'objetivo.resultados_exames.*.solicitado_em' => [
|
|
'nullable',
|
|
'date_format:d/m/Y',
|
|
],
|
|
'objetivo.resultados_exames.*.realizado_em' => [
|
|
'required',
|
|
'date_format:d/m/Y',
|
|
],
|
|
'objetivo.resultados_exames.*.resultado_em' => [
|
|
'nullable',
|
|
'date_format:d/m/Y',
|
|
],
|
|
'objetivo.resultados_exames.*.resultado' => [
|
|
'required',
|
|
'string',
|
|
'max:5000',
|
|
],
|
|
'objetivo.resultados_exames.*.percentual' => [
|
|
'nullable',
|
|
'numeric',
|
|
'max:100',
|
|
],
|
|
'objetivo.resultados_exames.*.idade_gestacional_semanas_eco' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:42',
|
|
],
|
|
'objetivo.resultados_exames.*.idade_gestacional_dias_eco' => [
|
|
'nullable',
|
|
'integer',
|
|
'max:6',
|
|
],
|
|
'objetivo.resultados_exames.*.dpp_eco' => [
|
|
'nullable',
|
|
'date_format:d/m/Y',
|
|
],
|
|
'objetivo.resultados_exames.*.resultado_tipo_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(ExameResultadoTipo::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getObjetivoExameAvaliadoValidations()
|
|
{
|
|
return [
|
|
'objetivo.exame_avaliado' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'objetivo.exame_avaliado.*.id' => [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(ExameSolicitadoAvaliado::class, 'id'),
|
|
],
|
|
'objetivo.exame_avaliado.*.solicitado_em' => [
|
|
'nullable',
|
|
'date_format:d/m/Y',
|
|
],
|
|
'objetivo.exame_avaliado.*.realizado_em' => [
|
|
'required',
|
|
'date_format:d/m/Y',
|
|
],
|
|
'objetivo.exame_avaliado.*.resultado_em' => [
|
|
'nullable',
|
|
'date_format:d/m/Y',
|
|
],
|
|
'objetivo.exame_avaliado.*.resultado' => [
|
|
'required',
|
|
'string',
|
|
'max:5000',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getAvaliacaoValidations()
|
|
{
|
|
return array_merge(
|
|
[
|
|
'avaliacao.descricao' => [
|
|
'nullable',
|
|
'string',
|
|
'max:5000',
|
|
],
|
|
],
|
|
self::getAvaliacaoCondicoesAvaliadasValidations(),
|
|
self::getAvaliacaoDoencasTransmissiveisValidations(),
|
|
self::getAvaliacaoRastreamentosValidations(),
|
|
self::getAvaliacaoProblemasCondicoesValidations(),
|
|
self::getAvaliacaoPreNatalValidations(),
|
|
self::getAvaliacaoAlergiasReacoesAdversasValidations(),
|
|
self::getAvaliacaoSaudeBucalValidations()
|
|
);
|
|
}
|
|
|
|
private static function getAvaliacaoCondicoesAvaliadasValidations()
|
|
{
|
|
return [
|
|
'avaliacao.condicoes_avaliadas' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'avaliacao.condicoes_avaliadas.*' => [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(CondicaoAvaliada::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getAvaliacaoDoencasTransmissiveisValidations()
|
|
{
|
|
return [
|
|
'avaliacao.doencas_transmissiveis' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'avaliacao.doencas_transmissiveis.*' => [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(DoencaTransmissivel::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getAvaliacaoRastreamentosValidations()
|
|
{
|
|
return [
|
|
'avaliacao.rastreamentos' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'avaliacao.rastreamentos.*' => [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(Rastreamento::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getAvaliacaoProblemasCondicoesValidations()
|
|
{
|
|
$rules = [
|
|
'avaliacao.problemas_condicoes' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
];
|
|
|
|
foreach ((request()->avaliacao['problemas_condicoes'] ?? []) as $i => $problemaCondicao) {
|
|
|
|
$rules["avaliacao.problemas_condicoes.{$i}.id"] = [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(AtendimentoSoapProblemaCondicao::class, 'id'),
|
|
];
|
|
|
|
$rules["avaliacao.problemas_condicoes.{$i}.automatico"] = [
|
|
'nullable',
|
|
'boolean',
|
|
];
|
|
|
|
$rules["avaliacao.problemas_condicoes.{$i}.ciap_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !isset($problemaCondicao['cid_id'])),
|
|
'integer',
|
|
Rule::exists(Ciap::class, 'id'),
|
|
];
|
|
|
|
$rules["avaliacao.problemas_condicoes.{$i}.cid_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !isset($problemaCondicao['ciap_id'])),
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id'),
|
|
];
|
|
|
|
$rules["avaliacao.problemas_condicoes.{$i}.situacao_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => isset($problemaCondicao['id'])),
|
|
'integer',
|
|
Rule::exists(ProblemaCondicaoSituacao::class, 'id'),
|
|
];
|
|
|
|
$rules["avaliacao.problemas_condicoes.{$i}.observacao"] = [
|
|
'nullable',
|
|
'string',
|
|
'max:5000',
|
|
];
|
|
|
|
if (!isset($problemaCondicao['situacao_id'])) {
|
|
|
|
continue;
|
|
}
|
|
|
|
$rules["avaliacao.problemas_condicoes.{$i}.inicio"] = [
|
|
'nullable',
|
|
'date_format:d/m/Y',
|
|
];
|
|
|
|
if (isset($problemaCondicao['fim'])) {
|
|
|
|
$rules["avaliacao.problemas_condicoes.{$i}.inicio"][] =
|
|
'before_or_equal:' . $problemaCondicao['fim'];
|
|
}
|
|
|
|
$rules["avaliacao.problemas_condicoes.{$i}.fim"] = [
|
|
'nullable',
|
|
'date_format:d/m/Y',
|
|
];
|
|
|
|
if (isset($problemaCondicao['inicio'])) {
|
|
|
|
$rules["avaliacao.problemas_condicoes.{$i}.fim"][] =
|
|
'after_or_equal:' . $problemaCondicao['inicio'];
|
|
}
|
|
}
|
|
|
|
return $rules;
|
|
}
|
|
|
|
private static function getAvaliacaoPreNatalValidations()
|
|
{
|
|
return array_merge(self::getPreNatalValidations('avaliacao'), [
|
|
'avaliacao.pre_natal.desfecho_em' => [
|
|
'nullable',
|
|
'date_format:d/m/Y'
|
|
],
|
|
]);
|
|
}
|
|
|
|
private static function getPreNatalValidations($prefix)
|
|
{
|
|
return [
|
|
"{$prefix}.pre_natal.gravidez_tipo_id" => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(GravidezTipo::class, 'id'),
|
|
],
|
|
"{$prefix}.pre_natal.altura_uterina" => [
|
|
'nullable',
|
|
'integer',
|
|
'max:99',
|
|
],
|
|
"{$prefix}.pre_natal.edema_id" => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(GravidezEdema::class, 'id'),
|
|
],
|
|
"{$prefix}.pre_natal.movimentacao_fetal" => [
|
|
'nullable',
|
|
'boolean',
|
|
],
|
|
"{$prefix}.pre_natal.gravidez_planejada" => [
|
|
'nullable',
|
|
'boolean',
|
|
],
|
|
"{$prefix}.pre_natal.batimento_cardiaco_fetal" => [
|
|
'nullable',
|
|
'integer',
|
|
'max:999',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getAvaliacaoAlergiasReacoesAdversasValidations()
|
|
{
|
|
return [
|
|
'avaliacao.alergias_reacoes_adversas' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'avaliacao.alergias_reacoes_adversas.*.alergia_id' => [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(Alergia::class, 'id'),
|
|
],
|
|
'avaliacao.alergias_reacoes_adversas.*.criticidade_id' => [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(AlergiaCriticidade::class, 'id'),
|
|
],
|
|
'avaliacao.alergias_reacoes_adversas.*.reacoes_observacoes' => [
|
|
'nullable',
|
|
'string',
|
|
'between:3,100',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getAvaliacaoSaudeBucalValidations()
|
|
{
|
|
return array_merge(
|
|
[
|
|
'avaliacao.saude_bucal.necessidade_protese_inferior_superior' => [
|
|
'nullable',
|
|
'boolean',
|
|
],
|
|
],
|
|
self::getAvaliacaoSaudeBucalVigilanciasValidations()
|
|
);
|
|
}
|
|
|
|
private static function getAvaliacaoSaudeBucalVigilanciasValidations()
|
|
{
|
|
return [
|
|
'avaliacao.saude_bucal.vigilancias' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'avaliacao.saude_bucal.vigilancias.*' => [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(SaudeBucalVigilancia::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getPlanoValidations()
|
|
{
|
|
return array_merge(
|
|
[
|
|
'plano.descricao' => [
|
|
'nullable',
|
|
'string',
|
|
'max:5000',
|
|
],
|
|
],
|
|
self::getPlanoIntervencoesValidations(),
|
|
self::getPlanoProcedimentosClinicosValidations(),
|
|
self::getPlanoSaudeBucalValidations(),
|
|
self::getPlanoPrescricoesMedicamentosValidations(),
|
|
self::getPlanoSolicitacaoExamesComunsValidations(),
|
|
self::getPlanoExamesSolicitadosValidations(),
|
|
self::getPlanoTriagensNeonatalSolicitadosValidations(),
|
|
self::getPlanoSolicitacaoExamesAltoCustoValidations(),
|
|
self::getPlanoSolicitacaoProcedimentosCirurgicosValidations(),
|
|
self::getPlanoTestesRapidoValidations(),
|
|
self::getPlanoAtestadosValidations(),
|
|
self::getPlanoDeclaracoesComparecimentoValidations(),
|
|
self::getPlanoOrientacoesValidations(),
|
|
self::getPlanoCartasMedicasValidations(),
|
|
self::getPlanoEncaminhamentosValidations(),
|
|
self::getPlanoCompartilhamentosCuidadoValidations()
|
|
);
|
|
}
|
|
|
|
private static function getPlanoIntervencoesValidations()
|
|
{
|
|
return [
|
|
'plano.intervencoes' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'plano.intervencoes.*.ciap_id' => [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(Ciap::class, 'id'),
|
|
],
|
|
'plano.intervencoes.*.observacao' => [
|
|
'nullable',
|
|
'string',
|
|
'max:500',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getPlanoProcedimentosClinicosValidations()
|
|
{
|
|
$rules = [
|
|
'plano.procedimentos_clinicos' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
];
|
|
|
|
foreach ((request()->plano['procedimentos_clinicos'] ?? []) as $i => $procedimento) {
|
|
|
|
$rules["plano.procedimentos_clinicos.{$i}.procedimento_id"] = [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(Procedimento::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.procedimentos_clinicos.{$i}.cid_id"] = [
|
|
|
|
function ($attribute, $value, $fail) use ($procedimento) {
|
|
|
|
$procedimentoModel = Procedimento::find($procedimento['procedimento_id']);
|
|
|
|
$hasCidPrincipal = $procedimentoModel->has_cid_principal ?? false;
|
|
|
|
if (!$hasCidPrincipal) {
|
|
return;
|
|
}
|
|
|
|
if (empty($value)) {
|
|
$fail("O CID é obrigatório para o procedimento {$procedimentoModel->nome}.");
|
|
return;
|
|
}
|
|
|
|
if (!filter_var($value, FILTER_VALIDATE_INT)) {
|
|
$fail("O CID informado para o procedimento {$procedimentoModel->nome} deve ser um número inteiro.");
|
|
return;
|
|
}
|
|
|
|
if (!Cid::where('id', $value)->exists()) {
|
|
$fail("O CID informado para o procedimento {$procedimentoModel->nome} não existe.");
|
|
}
|
|
},
|
|
];
|
|
|
|
$rules["plano.procedimentos_clinicos.{$i}.automatico"] = [
|
|
'required',
|
|
'boolean',
|
|
];
|
|
|
|
$rules["plano.procedimentos_clinicos.{$i}.quantidade"] = [
|
|
'required',
|
|
'integer',
|
|
new QuantidadeIsValidForProcedimento($procedimento['procedimento_id']),
|
|
];
|
|
|
|
$rules["plano.procedimentos_clinicos.{$i}.observacao"] = [
|
|
'nullable',
|
|
'string',
|
|
'max:500',
|
|
];
|
|
}
|
|
|
|
return $rules;
|
|
}
|
|
|
|
private static function getPlanoSaudeBucalValidations()
|
|
{
|
|
$isProfissionalSaudeBucal = self::isProfissionalSaudeBucal();
|
|
|
|
return array_merge(
|
|
self::getPlanoSaudeBucalOdontogramaValidations($isProfissionalSaudeBucal)
|
|
);
|
|
}
|
|
|
|
private static function getPlanoSaudeBucalOdontogramaValidations($isProfissionalSaudeBucal)
|
|
{
|
|
return array_merge(
|
|
[
|
|
'plano.saude_bucal.odontograma.possui_aparelho' => [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => $isProfissionalSaudeBucal),
|
|
'boolean',
|
|
],
|
|
'plano.saude_bucal.odontograma.possui_contencao' => [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => $isProfissionalSaudeBucal),
|
|
'boolean',
|
|
],
|
|
],
|
|
self::getPlanoSaudeBucalOdontogramaArcadasValidations($isProfissionalSaudeBucal, 'superior'),
|
|
self::getPlanoSaudeBucalOdontogramaArcadasValidations($isProfissionalSaudeBucal, 'inferior'),
|
|
self::getPlanoSaudeBucalOdontogramaDentesSupranumerariosValidations($isProfissionalSaudeBucal)
|
|
);
|
|
}
|
|
|
|
private static function getPlanoSaudeBucalOdontogramaArcadasValidations($isProfissionalSaudeBucal, $posicao)
|
|
{
|
|
return array_merge(
|
|
[
|
|
"plano.saude_bucal.odontograma.arcadas.{$posicao}.possui_protese_total" => [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => $isProfissionalSaudeBucal),
|
|
'boolean',
|
|
],
|
|
"plano.saude_bucal.odontograma.arcadas.{$posicao}.observacao" => [
|
|
'nullable',
|
|
'string',
|
|
'max:5000',
|
|
],
|
|
],
|
|
self::getPlanoSaudeBucalOdontogramaArcadasProcedimentosValidations($posicao),
|
|
self::getPlanoSaudeBucalOdontogramaArcadasDentesValidations($posicao),
|
|
);
|
|
}
|
|
|
|
private static function getPlanoSaudeBucalOdontogramaArcadasProcedimentosValidations($posicao)
|
|
{
|
|
$rules = [
|
|
"plano.saude_bucal.odontograma.arcadas.{$posicao}.procedimentos" => [
|
|
'present',
|
|
'array',
|
|
],
|
|
];
|
|
|
|
$procedimentos = request()->plano['saude_bucal']['odontograma']['arcadas'][$posicao]['procedimentos'] ?? [];
|
|
|
|
foreach ($procedimentos as $i => $procedimento) {
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.procedimentos.{$i}.procedimento_id"] = [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(Procedimento::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.procedimentos.{$i}.cid_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => Procedimento::find($procedimento['procedimento_id'])->has_cid_principal ?? false),
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.procedimentos.{$i}.quantidade"] = [
|
|
'required',
|
|
'integer',
|
|
new QuantidadeIsValidForProcedimento($procedimento['procedimento_id']),
|
|
];
|
|
}
|
|
|
|
return $rules;
|
|
}
|
|
|
|
private static function getPlanoSaudeBucalOdontogramaArcadasDentesValidations($posicao)
|
|
{
|
|
$rules = [
|
|
"plano.saude_bucal.odontograma.arcadas.{$posicao}.dentes" => [
|
|
'present',
|
|
'array',
|
|
],
|
|
];
|
|
|
|
$dentes = request()->plano['saude_bucal']['odontograma']['arcadas'][$posicao]['dentes'] ?? [];
|
|
|
|
foreach ($dentes as $i => $dente) {
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.dentes.{$i}.dente_id"] = [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(Dente::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.dentes.{$i}.fragmentos.esquerda.is_tratado"] = [
|
|
'nullable',
|
|
'boolean',
|
|
];
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.dentes.{$i}.fragmentos.cima.is_tratado"] = [
|
|
'nullable',
|
|
'boolean',
|
|
];
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.dentes.{$i}.fragmentos.direita.is_tratado"] = [
|
|
'nullable',
|
|
'boolean',
|
|
];
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.dentes.{$i}.fragmentos.baixo.is_tratado"] = [
|
|
'nullable',
|
|
'boolean',
|
|
];
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.dentes.{$i}.fragmentos.centro.is_tratado"] = [
|
|
'nullable',
|
|
'boolean',
|
|
];
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.dentes.{$i}.problemas_condicoes"] = [
|
|
'present',
|
|
'array',
|
|
];
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.dentes.{$i}.problemas_condicoes.*"] = [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(SaudeBucalDenteProblemaCondicao::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.dentes.{$i}.observacao"] = [
|
|
'nullable',
|
|
'string',
|
|
'max:5000',
|
|
];
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.dentes.{$i}.procedimentos"] = [
|
|
'present',
|
|
'array',
|
|
];
|
|
|
|
$procedimentos = $dente['procedimentos'] ?? [];
|
|
|
|
foreach ($procedimentos as $j => $procedimento) {
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.dentes.{$i}.procedimentos.{$j}.procedimento_id"] = [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(Procedimento::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.dentes.{$i}.procedimentos.{$j}.cid_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => Procedimento::find($procedimento['procedimento_id'])->has_cid_principal ?? false),
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.saude_bucal.odontograma.arcadas.{$posicao}.dentes.{$i}.procedimentos.{$j}.quantidade"] = [
|
|
'required',
|
|
'integer',
|
|
new QuantidadeIsValidForProcedimento($procedimento['procedimento_id']),
|
|
];
|
|
}
|
|
}
|
|
|
|
return $rules;
|
|
}
|
|
|
|
private static function getPlanoSaudeBucalOdontogramaDentesSupranumerariosValidations($isProfissionalSaudeBucal)
|
|
{
|
|
$rules = [
|
|
'plano.saude_bucal.odontograma.dentes_supranumerarios' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'plano.saude_bucal.odontograma.dentes_supranumerarios.*.local' => [
|
|
'required',
|
|
'string',
|
|
'max:100',
|
|
],
|
|
'plano.saude_bucal.odontograma.dentes_supranumerarios.*.procedimentos' => [
|
|
'required',
|
|
'array',
|
|
],
|
|
'plano.saude_bucal.odontograma.dentes_supranumerarios.*.observacao' => [
|
|
'nullable',
|
|
'string',
|
|
'max:5000',
|
|
],
|
|
];
|
|
|
|
$procedimentos = request()->plano['saude_bucal']['odontograma']['dentes_supranumerarios']['procedimentos'] ?? [];
|
|
|
|
foreach ($procedimentos as $i => $procedimento) {
|
|
|
|
$rules["plano.saude_bucal.odontograma.dentes_supranumerarios.procedimentos.{$i}.procedimento_id"] = [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(Procedimento::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.saude_bucal.odontograma.dentes_supranumerarios.procedimentos.{$i}.cid_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => Procedimento::find($procedimento['procedimento_id'])->has_cid_principal ?? false),
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id'),
|
|
];
|
|
|
|
|
|
$rules["plano.saude_bucal.odontograma.dentes_supranumerarios.procedimentos.{$i}.quantidade"] = [
|
|
'required',
|
|
'integer',
|
|
new QuantidadeIsValidForProcedimento($procedimento['procedimento_id']),
|
|
];
|
|
}
|
|
|
|
return $rules;
|
|
}
|
|
|
|
private static function getPlanoPrescricoesMedicamentosValidations()
|
|
{
|
|
$rules = [
|
|
'plano.prescricoes_medicamentos' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
];
|
|
|
|
foreach ((request()->plano['prescricoes_medicamentos'] ?? []) as $i => $prescricao) {
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos"] = [
|
|
'required',
|
|
'array',
|
|
];
|
|
|
|
foreach (($prescricao['medicamentos'] ?? []) as $j => $medicamento) {
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.is_manual"] = [
|
|
'required',
|
|
'boolean',
|
|
];
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.recomendacoes"] = [
|
|
'nullable',
|
|
'string',
|
|
];
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.prescricao_medicamento_item_anterior_id"] = [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(AtendimentoSoapPrescricaoMedicamentoItem::class, 'id')
|
|
];
|
|
|
|
if (!isset($medicamento['is_manual'])) {
|
|
|
|
continue;
|
|
}
|
|
|
|
if ($medicamento['is_manual']) {
|
|
|
|
$parametrizacao = ParametrizacaoAtendimento::first();
|
|
|
|
$receitaNaoPadronizadaJustificativaObrigatoria = $parametrizacao
|
|
&& $parametrizacao->receita_nao_padronizada_justificativa_obrigatoria ? true : false;
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.descricao"] = [
|
|
'required',
|
|
'string',
|
|
'max:5000',
|
|
];
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.justificativa"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => $receitaNaoPadronizadaJustificativaObrigatoria),
|
|
'string',
|
|
'max:300',
|
|
];
|
|
}
|
|
else {
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.material_id"] = [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(Material::class, 'id'),
|
|
];
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.unidade_medida_id"] = [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(UnidadeMedida::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.dose"] = [
|
|
'required',
|
|
'string',
|
|
'max:50',
|
|
];
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.is_dose_unica"] = [
|
|
'required',
|
|
'boolean',
|
|
];
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.is_uso_continuo"] = [
|
|
'required',
|
|
'boolean',
|
|
];
|
|
|
|
if (!isset($medicamento['is_dose_unica'])
|
|
|| !isset($medicamento['is_uso_continuo'])
|
|
) {
|
|
|
|
continue;
|
|
}
|
|
|
|
if ($medicamento['is_dose_unica'] && $medicamento['is_uso_continuo']) {
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.is_dose_unica"][] =
|
|
"different:plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.is_uso_continuo";
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.is_uso_continuo"][] =
|
|
"different:plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.is_dose_unica";
|
|
}
|
|
else {
|
|
|
|
$frequenciaDose = $medicamento['frequencia_dose'] ?? null;
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.frequencia_dose"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !$medicamento['is_dose_unica']),
|
|
Rule::in([
|
|
PrescricaoFrequenciaDose::INTERVALO,
|
|
PrescricaoFrequenciaDose::FREQUENCIA,
|
|
PrescricaoFrequenciaDose::TURNO,
|
|
]),
|
|
];
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.frequencia_vezes"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn() => $frequenciaDose === PrescricaoFrequenciaDose::FREQUENCIA && !$medicamento['is_dose_unica']),
|
|
'integer',
|
|
'max:99'
|
|
];
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.turno_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => $frequenciaDose === PrescricaoFrequenciaDose::TURNO && !$medicamento['is_dose_unica']),
|
|
'integer',
|
|
Rule::exists(Turno::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.intervalo"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !$medicamento['is_dose_unica']),
|
|
'integer',
|
|
'max:99',
|
|
];
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.intervalo_medida_tempo_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !$medicamento['is_dose_unica']),
|
|
'integer',
|
|
Rule::exists(MedidaTempo::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.inicio"] = [
|
|
'required',
|
|
'date_format:d/m/Y',
|
|
];
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.duracao"] = [
|
|
'nullable',
|
|
'integer',
|
|
'max:999',
|
|
];
|
|
|
|
$rules["plano.prescricoes_medicamentos.{$i}.medicamentos.{$j}.duracao_medida_tempo_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => isset($medicamento['duracao'])),
|
|
'integer',
|
|
Rule::exists(MedidaTempo::class, 'id'),
|
|
];
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return $rules;
|
|
}
|
|
|
|
private static function getPlanoSolicitacaoExamesComunsValidations()
|
|
{
|
|
return [
|
|
'plano.solicitacoes_exames_comuns' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'plano.solicitacoes_exames_comuns.*.cid_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id'),
|
|
],
|
|
'plano.solicitacoes_exames_comuns.*.ciap_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Ciap::class, 'id'),
|
|
],
|
|
'plano.solicitacoes_exames_comuns.*.classificacao_risco_id' => [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(ClassificacaoRisco::class, 'id'),
|
|
],
|
|
'plano.solicitacoes_exames_comuns.*.justificativa' => [
|
|
'required',
|
|
'string',
|
|
'max:5000',
|
|
],
|
|
'plano.solicitacoes_exames_comuns.*.observacao' => [
|
|
'nullable',
|
|
'string',
|
|
'max:500',
|
|
],
|
|
'plano.solicitacoes_exames_comuns.*.exames' => [
|
|
'required',
|
|
'array',
|
|
],
|
|
'plano.solicitacoes_exames_comuns.*.exames.*.exame_id' => [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(Exame::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getPlanoExamesSolicitadosValidations()
|
|
{
|
|
return [
|
|
'plano.exame_solicitado' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'plano.exame_solicitado.cid_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id'),
|
|
],
|
|
'plano.exame_solicitado.ciap_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Ciap::class, 'id'),
|
|
],
|
|
'plano.exame_solicitado.justificativa' => [
|
|
'nullable',
|
|
'string',
|
|
'max:500',
|
|
],
|
|
'plano.exame_solicitado.observacao' => [
|
|
'nullable',
|
|
'string',
|
|
'max:500',
|
|
],
|
|
'plano.exame_solicitado.exames' => [
|
|
'nullable',
|
|
'array',
|
|
],
|
|
'plano.exame_solicitado.exames.*.exame_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Exame::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getPlanoTriagensNeonatalSolicitadosValidations()
|
|
{
|
|
return [
|
|
'plano.triagem_neonatal' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'plano.triagem_neonatal.cid_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id'),
|
|
],
|
|
'plano.triagem_neonatal.ciap_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Ciap::class, 'id'),
|
|
],
|
|
'plano.triagem_neonatal.justificativa' => [
|
|
'nullable',
|
|
'string',
|
|
'max:500',
|
|
],
|
|
'plano.triagem_neonatal.observacao' => [
|
|
'nullable',
|
|
'string',
|
|
'max:500',
|
|
],
|
|
'plano.triagem_neonatal.exames' => [
|
|
'nullable',
|
|
'array',
|
|
],
|
|
'plano.triagem_neonatal.exames.*.exame_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Exame::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getPlanoSolicitacaoExamesAltoCustoValidations()
|
|
{
|
|
|
|
$rules = [
|
|
'plano.solicitacoes_exames_alto_custo' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
];
|
|
|
|
foreach ((request()->plano['solicitacoes_exames_alto_custo'] ?? []) as $i => $solicitacao) {
|
|
|
|
$rules["plano.solicitacoes_exames_alto_custo.{$i}.ciap_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !isset($solicitacao['cid_id'])),
|
|
'integer',
|
|
Rule::exists(Ciap::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.solicitacoes_exames_alto_custo.{$i}.cid_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !isset($solicitacao['ciap_id'])),
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.solicitacoes_exames_alto_custo.{$i}.classificacao_risco_id"] = [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(ClassificacaoRisco::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.solicitacoes_exames_alto_custo.{$i}.justificativa"] = [
|
|
'nullable',
|
|
'string',
|
|
'max:5000',
|
|
];
|
|
|
|
$rules["plano.solicitacoes_exames_alto_custo.{$i}.observacao"] = [
|
|
'nullable',
|
|
'string',
|
|
'max:1500',
|
|
];
|
|
|
|
$rules["plano.solicitacoes_exames_alto_custo.{$i}.exames"] = [
|
|
'required',
|
|
'array',
|
|
];
|
|
|
|
$rules["plano.solicitacoes_exames_alto_custo.{$i}.exames.*.exame_id"] = [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(Exame::class, 'id'),
|
|
];
|
|
}
|
|
|
|
return $rules;
|
|
}
|
|
|
|
private static function getPlanoSolicitacaoProcedimentosCirurgicosValidations()
|
|
{
|
|
$rules = [
|
|
'plano.solicitacoes_procedimentos_cirurgicos' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
];
|
|
|
|
foreach ((request()->plano['solicitacoes_procedimentos_cirurgicos'] ?? []) as $i => $solicitacao) {
|
|
|
|
$rules["plano.solicitacoes_procedimentos_cirurgicos.{$i}.ciap_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !isset($solicitacao['cid_id'])),
|
|
'integer',
|
|
Rule::exists(Ciap::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.solicitacoes_procedimentos_cirurgicos.{$i}.cid_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !isset($solicitacao['ciap_id'])),
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.solicitacoes_procedimentos_cirurgicos.{$i}.classificacao_risco_id"] = [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(ClassificacaoRisco::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.solicitacoes_procedimentos_cirurgicos.{$i}.justificativa"] = [
|
|
'nullable',
|
|
'string',
|
|
'max:5000',
|
|
];
|
|
|
|
$rules["plano.solicitacoes_procedimentos_cirurgicos.{$i}.observacao"] = [
|
|
'nullable',
|
|
'string',
|
|
'max:1500',
|
|
];
|
|
|
|
$rules["plano.solicitacoes_procedimentos_cirurgicos.{$i}.procedimentos_cirurgicos"] = [
|
|
'required',
|
|
'array',
|
|
];
|
|
|
|
$rules["plano.solicitacoes_procedimentos_cirurgicos.{$i}.procedimentos_cirurgicos.*.procedimento_cirurgico_id"] = [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(ProcedimentoCirurgico::class, 'id'),
|
|
];
|
|
}
|
|
|
|
return $rules;
|
|
}
|
|
|
|
private static function getPlanoTestesRapidoValidations()
|
|
{
|
|
return [
|
|
'plano.testes_rapidos' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'plano.testes_rapidos.*.id' => [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(TesteRapido::class, 'id'),
|
|
],
|
|
'plano.testes_rapidos.*.resultado' => [
|
|
'nullable',
|
|
'string',
|
|
'max:500',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getPlanoAtestadosValidations()
|
|
{
|
|
return [
|
|
'plano.atestados' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'plano.atestados.*.modelo_id' => [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(AtestadoModelo::class, 'id'),
|
|
],
|
|
'plano.atestados.*.descricao' => [
|
|
'nullable',
|
|
'required_if:atestados.*.modelo_id,' . AtestadoModeloEnum::EM_BRANCO,
|
|
'string',
|
|
'max:5000',
|
|
],
|
|
'plano.atestados.*.nome_acompanhante' => [
|
|
'nullable',
|
|
'string',
|
|
'max:150',
|
|
],
|
|
'plano.atestados.*.documento_tipo_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(DocumentoTipo::class, 'id'),
|
|
],
|
|
'plano.atestados.*.cpf' => [
|
|
'nullable',
|
|
'required_if:atestados.*.documento_tipo_id,' . DocumentoTipoEnum::CPF,
|
|
new Cpf,
|
|
],
|
|
'plano.atestados.*.cns' => [
|
|
'nullable',
|
|
'required_if:atestados.*.documento_tipo_id,' . DocumentoTipoEnum::CNS,
|
|
new Cns,
|
|
],
|
|
'plano.atestados.*.data' => [
|
|
'nullable',
|
|
'required_if:atestados.*.modelo_id,' . AtestadoModeloEnum::PADRAO,
|
|
'required_if:atestados.*.modelo_id,' . AtestadoModeloEnum::PERIODO_MANHA,
|
|
'required_if:atestados.*.modelo_id,' . AtestadoModeloEnum::PERIODO_TARDE,
|
|
'required_if:atestados.*.modelo_id,' . AtestadoModeloEnum::PERIODO_NOITE,
|
|
'required_if:atestados.*.modelo_id,' . AtestadoModeloEnum::QUANTIDADE_HORAS,
|
|
'date_format:d/m/Y'
|
|
],
|
|
'plano.atestados.*.horario' => [
|
|
'nullable',
|
|
'required_if:atestados.*.modelo_id,' . AtestadoModeloEnum::PADRAO,
|
|
'date_format:H:i'
|
|
],
|
|
'plano.atestados.*.dias' => [
|
|
'nullable',
|
|
'required_if:atestados.*.modelo_id,' . AtestadoModeloEnum::PADRAO,
|
|
'integer',
|
|
'max:999'
|
|
],
|
|
'plano.atestados.*.horario_inicial' => [
|
|
'nullable',
|
|
'required_if:atestados.*.modelo_id,' . AtestadoModeloEnum::QUANTIDADE_HORAS,
|
|
'date_format:H:i'
|
|
],
|
|
'plano.atestados.*.quantidade_horas' => [
|
|
'nullable',
|
|
'required_if:atestados.*.modelo_id,' . AtestadoModeloEnum::QUANTIDADE_HORAS,
|
|
'integer',
|
|
'min:1',
|
|
'max:23'
|
|
],
|
|
'plano.atestados.*.cid_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id')
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getPlanoDeclaracoesComparecimentoValidations()
|
|
{
|
|
return [
|
|
'plano.declaracoes_comparecimento' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'plano.declaracoes_comparecimento.*.nome_acompanhante' => [
|
|
'nullable',
|
|
'string',
|
|
'max:150',
|
|
],
|
|
'plano.declaracoes_comparecimento.*.motivo_comparecimento' => [
|
|
'nullable',
|
|
'string',
|
|
'max:1500',
|
|
],
|
|
'plano.declaracoes_comparecimento.*.turno_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Turno::class, 'id'),
|
|
],
|
|
'plano.declaracoes_comparecimento.*.entrada' => [
|
|
'nullable',
|
|
'required_without:plano.declaracoes_comparecimento.*.turno_id',
|
|
'date_format:H:i',
|
|
],
|
|
'plano.declaracoes_comparecimento.*.saida' => [
|
|
'nullable',
|
|
'required_without:plano.declaracoes_comparecimento.*.turno_id',
|
|
'date_format:H:i',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getPlanoOrientacoesValidations()
|
|
{
|
|
return [
|
|
'plano.orientacoes' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'plano.orientacoes.*.descricao' => [
|
|
'required',
|
|
'string',
|
|
'max:5000',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getPlanoCartasMedicasValidations()
|
|
{
|
|
return [
|
|
'plano.cartas_medicas' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'plano.cartas_medicas.*.descricao' => [
|
|
'required',
|
|
'string',
|
|
'max:5000',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getPlanoEncaminhamentosValidations()
|
|
{
|
|
$rules = [
|
|
'plano.encaminhamentos' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
];
|
|
|
|
foreach ((request()->plano['encaminhamentos'] ?? []) as $i => $encaminhamento) {
|
|
|
|
$rules["plano.encaminhamentos.{$i}.servico_especializado_ciap_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !isset($encaminhamento['servico_especializado_cid_id'])
|
|
&& $encaminhamento['tipo_id'] === EncaminhamentoEnum::ENCAMINHAMENTO_PARA_SERVICO_ESPECIALIZADO),
|
|
'integer',
|
|
Rule::exists(Ciap::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.encaminhamentos.{$i}.servico_especializado_cid_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !isset($encaminhamento['servico_especializado_ciap_id'])
|
|
&& $encaminhamento['tipo_id'] === EncaminhamentoEnum::ENCAMINHAMENTO_PARA_SERVICO_ESPECIALIZADO),
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.encaminhamentos.{$i}.tipo_id"] = [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(Encaminhamento::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.encaminhamentos.{$i}.servico_especializado_especialidade_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => $encaminhamento['tipo_id'] === EncaminhamentoEnum::ENCAMINHAMENTO_PARA_SERVICO_ESPECIALIZADO),
|
|
'integer',
|
|
Rule::exists(Especialidade::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.encaminhamentos.{$i}.servico_especializado_complemento"] = [
|
|
'nullable',
|
|
'string',
|
|
'max:100',
|
|
];
|
|
|
|
$rules["plano.encaminhamentos.{$i}.servico_especializado_classificacao_risco_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => $encaminhamento['tipo_id'] === EncaminhamentoEnum::ENCAMINHAMENTO_PARA_SERVICO_ESPECIALIZADO),
|
|
'integer',
|
|
Rule::exists(ClassificacaoRisco::class, 'id'),
|
|
];
|
|
|
|
$rules["plano.encaminhamentos.{$i}.servico_especializado_motivo"] = [
|
|
'nullable',
|
|
'string',
|
|
'max:5000',
|
|
];
|
|
|
|
$rules["plano.encaminhamentos.{$i}.servico_especializado_observacao"] = [
|
|
'nullable',
|
|
'string',
|
|
'max:500',
|
|
];
|
|
|
|
$rules["plano.encaminhamentos.{$i}.intersetorial_infraestrutura_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => $encaminhamento['tipo_id'] === EncaminhamentoEnum::ENCAMINHAMENTO_INTERSETORIAL),
|
|
'integer',
|
|
Rule::exists(Infraestrutura::class, 'id'),
|
|
];
|
|
}
|
|
|
|
return $rules;
|
|
}
|
|
|
|
private static function getPlanoCompartilhamentosCuidadoValidations()
|
|
{
|
|
return [
|
|
'plano.compartilhamentos_cuidado' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'plano.compartilhamentos_cuidado.*.especialidade_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Especialidade::class, 'id'),
|
|
],
|
|
'plano.compartilhamentos_cuidado.*.usuario_id' => [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(Usuario::class, 'id'),
|
|
],
|
|
'plano.compartilhamentos_cuidado.*.ciap_id' => [
|
|
'nullable',
|
|
'required_without:plano.compartilhamentos_cuidado.*.cid_id',
|
|
'integer',
|
|
Rule::exists(Ciap::class, 'id'),
|
|
],
|
|
'plano.compartilhamentos_cuidado.*.cid_id' => [
|
|
'nullable',
|
|
'required_without:plano.compartilhamentos_cuidado.*.ciap_id',
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id'),
|
|
],
|
|
'plano.compartilhamentos_cuidado.*.classificacao_risco_id' => [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(ClassificacaoRisco::class, 'id'),
|
|
],
|
|
'plano.compartilhamentos_cuidado.*.discussao_caso_clinico' => [
|
|
'required',
|
|
'string',
|
|
'max:500',
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getRaasValidations()
|
|
{
|
|
return [
|
|
'raas' => [
|
|
'present',
|
|
'array'
|
|
],
|
|
'raas.origem_paciente_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(OrigemPaciente::class, 'id'),
|
|
],
|
|
'raas.destino_paciente_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(DestinoPaciente::class, 'id'),
|
|
],
|
|
'raas.motivo_saida_permanencia_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(MotivoSaidaPermanencia::class, 'id'),
|
|
],
|
|
'raas.carater_atendimento_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(CaraterAtendimento::class, 'id'),
|
|
],
|
|
'raas.numero_autorizacao' => [
|
|
'nullable',
|
|
'digits_between:1,13',
|
|
],
|
|
'raas.classificacao_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(SigtapClassificacao::class, 'id'),
|
|
],
|
|
'raas.local_realizacao_exame_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(LocalRealizacaoExame::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getFinalizacaoValidations($fila = null)
|
|
{
|
|
return array_merge(
|
|
[
|
|
'finalizacao.atendimento_tipo_id' => [
|
|
'required',
|
|
'integer',
|
|
Rule::exists(TipoAtendimento::class, 'id'),
|
|
],
|
|
'finalizacao.atendimento_compartilhado_usuario_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Usuario::class, 'id'),
|
|
],
|
|
'finalizacao.racionalidade_saude_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(RacionalidadeSaude::class, 'id'),
|
|
],
|
|
'finalizacao.equipe_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Equipe::class, 'id'),
|
|
],
|
|
'finalizacao.atencao_basica_local_atendimento_id' => [
|
|
'nullable',
|
|
'required_with:finalizacao.equipe_id',
|
|
'integer',
|
|
Rule::exists(LocalAtendimento::class, 'id'),
|
|
],
|
|
'finalizacao.turno_id' => [
|
|
'nullable',
|
|
'required_with:finalizacao.equipe_id',
|
|
'integer',
|
|
Rule::exists(Turno::class, 'id'),
|
|
],
|
|
'finalizacao.oci_desfecho_etapa_clinica_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(EtapaClinica::class, 'id'),
|
|
],
|
|
'finalizacao.apac_motivo_saida_permanencia_id' => [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => request()->finalizacao['oci_desfecho_etapa_clinica_id'] === EtapaClinicaEnum::ALTA),
|
|
'integer',
|
|
Rule::exists(ApacMotivoSaidaPermanencia::class, 'id'),
|
|
],
|
|
],
|
|
self::getFinalizacaoProcedimentosAdministrativosValidations(),
|
|
self::getFinalizacaoCasosSuspeitosValidations(),
|
|
self::getFinalizacaoCondutasValidations(),
|
|
self::getFinalizacaoSaudeBucalValidations(),
|
|
self::getFinalizacaoDesfechoValidations($fila),
|
|
);
|
|
}
|
|
|
|
private static function getFinalizacaoProcedimentosAdministrativosValidations()
|
|
{
|
|
$rules = [
|
|
'finalizacao.procedimentos_administrativos' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
];
|
|
|
|
foreach ((request()->finalizacao['procedimentos_administrativos'] ?? null) as $i => $procedimento) {
|
|
|
|
$rules["finalizacao.procedimentos_administrativos.{$i}.procedimento_id"] = [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(Procedimento::class, 'id'),
|
|
];
|
|
|
|
$rules["finalizacao.procedimentos_administrativos.{$i}.cid_id"] = [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => Procedimento::find($procedimento['procedimento_id'])->has_cid_principal ?? false),
|
|
'integer',
|
|
Rule::exists(Cid::class, 'id'),
|
|
];
|
|
|
|
$rules["finalizacao.procedimentos_administrativos.{$i}.automatico"] = [
|
|
'required',
|
|
'boolean',
|
|
];
|
|
|
|
$rules["finalizacao.procedimentos_administrativos.{$i}.quantidade"] = [
|
|
'required',
|
|
'integer',
|
|
new QuantidadeIsValidForProcedimento($procedimento['procedimento_id']),
|
|
];
|
|
}
|
|
|
|
return $rules;
|
|
}
|
|
|
|
private static function getFinalizacaoCasosSuspeitosValidations()
|
|
{
|
|
return [
|
|
'finalizacao.casos_suspeitos' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'finalizacao.casos_suspeitos.*' => [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(CasoSuspeito::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getFinalizacaoCondutasValidations()
|
|
{
|
|
return [
|
|
'finalizacao.condutas' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'finalizacao.condutas.*' => [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(Conduta::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getFinalizacaoSaudeBucalValidations()
|
|
{
|
|
$isProfissionalSaudeBucal = self::isProfissionalSaudeBucal();
|
|
|
|
return array_merge(
|
|
[
|
|
'finalizacao.saude_bucal.consulta_tipo_id' => [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => $isProfissionalSaudeBucal && !self::isRascunho()),
|
|
'integer',
|
|
Rule::exists(TipoConsulta::class, 'id'),
|
|
],
|
|
],
|
|
self::getFinalizacaoSaudeBucalFornecimentosValidations()
|
|
);
|
|
}
|
|
|
|
private static function getFinalizacaoSaudeBucalFornecimentosValidations()
|
|
{
|
|
return [
|
|
'finalizacao.saude_bucal.fornecimentos' => [
|
|
'present',
|
|
'array'
|
|
],
|
|
'finalizacao.saude_bucal.fornecimentos.*' => [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(SaudeBucalFornecimento::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getFinalizacaoDesfechoValidations($fila = null)
|
|
{
|
|
return array_merge(
|
|
[
|
|
'finalizacao.desfecho.finalizado' => [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => !self::isRascunho()),
|
|
'boolean',
|
|
],
|
|
'finalizacao.desfecho.usuario_id' => [
|
|
'nullable',
|
|
'required_with:finalizacao.desfecho.ocupacao_id',
|
|
'integer',
|
|
Rule::exists(Usuario::class, 'id'),
|
|
],
|
|
'finalizacao.desfecho.ocupacao_id' => [
|
|
'nullable',
|
|
'required_with:finalizacao.desfecho.especialidade_id',
|
|
'integer',
|
|
Rule::exists(Ocupacao::class, 'id'),
|
|
],
|
|
'finalizacao.desfecho.especialidade_id' => [
|
|
'nullable',
|
|
'integer',
|
|
Rule::exists(Especialidade::class, 'id'),
|
|
],
|
|
'finalizacao.desfecho.prioridade_id' => [
|
|
'nullable',
|
|
Rule::requiredIf(fn () => $fila->opcaoEntrada->prioridade_obrigatoria ?? false),
|
|
Rule::exists(Prioridade::class, 'id'),
|
|
],
|
|
'finalizacao.desfecho.pos_consulta' => [
|
|
'nullable',
|
|
'required_with:finalizacao.desfecho.centro_custo_encaminhamento_id',
|
|
'boolean',
|
|
],
|
|
],
|
|
self::getFinalizacaoDesfechoServicosValidations(),
|
|
);
|
|
}
|
|
|
|
private static function getFinalizacaoDesfechoServicosValidations()
|
|
{
|
|
return [
|
|
'finalizacao.desfecho.servicos' => [
|
|
'present',
|
|
'array'
|
|
],
|
|
'finalizacao.desfecho.servicos.*' => [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(Servico::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function isRascunho()
|
|
{
|
|
return request()->is_rascunho === true;
|
|
}
|
|
|
|
private static function isProfissionalSaudeBucal()
|
|
{
|
|
return Str::startsWith(self::getCurrentLotacao()->ocupacao->codigo, '2232');
|
|
}
|
|
|
|
private static function faturaProcedimentoRaas()
|
|
{
|
|
return ParametrizacaoInfraestrutura::where('infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id)
|
|
->pluck('fatura_procedimento_raas')
|
|
->first();
|
|
}
|
|
|
|
private static function getProtocoloFechamento($agendamentoId)
|
|
{
|
|
return DB::table('ambulatorio_agendamento')
|
|
->select([
|
|
'regulacao_parametrizacao_prestador_interno.controla_protocolo_fechamento',
|
|
'regulacao_solicitacao.numero',
|
|
])
|
|
->join('regulacao_solicitacao', 'regulacao_solicitacao.id', 'ambulatorio_agendamento.regulacao_solicitacao_id')
|
|
->join('regulacao_parametrizacao_prestador_interno', 'regulacao_parametrizacao_prestador_interno.id', 'regulacao_solicitacao.prestador_interno_id')
|
|
->where('ambulatorio_agendamento.id', $agendamentoId)
|
|
->where('regulacao_parametrizacao_prestador_interno.infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id)
|
|
->first();
|
|
}
|
|
|
|
private static function precisaInformarConclusaoTratamento($atendimento)
|
|
{
|
|
return self::isProfissionalSaudeBucal() && ($atendimento->especialidade->precisa_informar_conclusao_tratamento ?? false);
|
|
}
|
|
|
|
public static function saveLogImpressao($atendimentoId, $impressaoTipoId)
|
|
{
|
|
return AtendimentoImpressaoLog::create([
|
|
'atendimento_id' => $atendimentoId,
|
|
'impressao_tipo_id' => $impressaoTipoId,
|
|
'lotacao_id' => self::getCurrentLotacao()->id,
|
|
'impresso_em' => Carbon::now(),
|
|
]);
|
|
}
|
|
|
|
private static function criaFichaAtencaoBasica()
|
|
{
|
|
$isOocupacaoParametrizadaMarcadorConsumoAlimentar = OutrosPermissaoOcupacao::where(
|
|
'ocupacao',
|
|
self::getCurrentLotacao()->ocupacao->codigo
|
|
)
|
|
->where('permissao_id', AtencaoBasicaPermissao::MARCADORES_DE_CONSUMO_ALIMENTAR)
|
|
->exists();
|
|
|
|
return (self::isProfissionalSaudeBucal() ? self::criaFicha('atendimento-odontologico') : self::criaFicha('atendimento-individual'))
|
|
|| self::criaFicha('atendimento-domiciliar')
|
|
|| self::criaFicha('avaliacao')
|
|
|| (self::criaFicha('marcador-consumo-alimentar') && $isOocupacaoParametrizadaMarcadorConsumoAlimentar);
|
|
}
|
|
|
|
public static function storeFeridaProcedimento()
|
|
{
|
|
$soapId = request()->soap_id;
|
|
$feridaData = request()->ferida;
|
|
$procedimentoData = request()->procedimento;
|
|
|
|
$soap = AtendimentoSoap::findOrFail($soapId);
|
|
|
|
return DB::transaction(function () use ($soap, $feridaData, $procedimentoData) {
|
|
|
|
$dadosFerida = [];
|
|
|
|
if (isset($feridaData['data'])) {
|
|
$feridaData['data'] = Carbon::createFromFormat('d/m/Y', $feridaData['data']);
|
|
$dadosFerida['data'] = $feridaData['data'];
|
|
}
|
|
|
|
if (array_key_exists('tipo_id', $feridaData)) $dadosFerida['ferida_id'] = $feridaData['tipo_id'];
|
|
if (array_key_exists('local_anatomico_id', $feridaData)) $dadosFerida['local_anatomico_id'] = $feridaData['local_anatomico_id'];
|
|
if (array_key_exists('local_anatomico_regiao_id', $feridaData)) $dadosFerida['local_anatomico_regiao_id'] = $feridaData['local_anatomico_regiao_id'];
|
|
if (array_key_exists('exsudato_id', $feridaData)) $dadosFerida['ferida_exsudato_id'] = $feridaData['exsudato_id'];
|
|
if (array_key_exists('necrose_id', $feridaData)) $dadosFerida['ferida_necrose'] = $feridaData['necrose_id'];
|
|
if (array_key_exists('cicatrizada', $feridaData)) $dadosFerida['cicatrizada'] = $feridaData['cicatrizada'];
|
|
if (array_key_exists('comprimento', $feridaData)) $dadosFerida['comprimento'] = $feridaData['comprimento'];
|
|
if (array_key_exists('largura', $feridaData)) $dadosFerida['largura'] = $feridaData['largura'];
|
|
if (array_key_exists('profundidade', $feridaData)) $dadosFerida['profundidade'] = $feridaData['profundidade'];
|
|
if (array_key_exists('dor', $feridaData)) $dadosFerida['dor'] = $feridaData['dor'];
|
|
if (array_key_exists('observacao', $feridaData)) $dadosFerida['observacao'] = $feridaData['observacao'];
|
|
|
|
$ferida = null;
|
|
|
|
if (isset($feridaData['id']) && is_numeric($feridaData['id'])) {
|
|
|
|
$ferida = AtendimentoSoapFerida::find($feridaData['id']);
|
|
|
|
if ($ferida && !empty($dadosFerida)) {
|
|
|
|
$ferida->update($dadosFerida);
|
|
}
|
|
}
|
|
|
|
if (!$ferida) {
|
|
|
|
$ferida = $soap->feridas()->create($dadosFerida);
|
|
}
|
|
|
|
$feridaProcedimento = null;
|
|
$feridaProcedimentoId = request()->id;
|
|
|
|
if ($feridaProcedimentoId) {
|
|
$feridaProcedimento = AtendimentoSoapFeridaProcedimento::find($feridaProcedimentoId);
|
|
}
|
|
|
|
if ($feridaProcedimento) {
|
|
|
|
$atendimentoProcedimento = $feridaProcedimento->atendimentoProcedimento;
|
|
|
|
if ($atendimentoProcedimento) {
|
|
$atendimentoProcedimento->update([
|
|
'procedimento_id' => $procedimentoData['procedimento']['id'],
|
|
'cid_id' => data_get($procedimentoData, 'cid.id'),
|
|
'quantidade' => $procedimentoData['quantidade'] ?? null,
|
|
]);
|
|
}
|
|
|
|
$procedimentoClinico = $soap->procedimentosClinicos()
|
|
->where('atendimento_procedimento_id', $atendimentoProcedimento->id)
|
|
->first();
|
|
|
|
if ($procedimentoClinico) {
|
|
|
|
$procedimentoClinico->update([
|
|
'observacao' => $procedimentoData['observacao'] ?? null,
|
|
]);
|
|
} else {
|
|
|
|
$soap->procedimentosClinicos()->create([
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
'observacao' => $procedimentoData['observacao'] ?? null,
|
|
]);
|
|
}
|
|
|
|
} else {
|
|
|
|
$ocupacaoId = $soap->atendimento->ocupacao->id ?? $soap->createdLotacao->ocupacao_id;
|
|
|
|
if (!ProcedimentoIsValidForOcupacao::isValid($ocupacaoId, $procedimentoData['procedimento']['id'])) {
|
|
throw ValidationException::withMessages([
|
|
'procedimento' => ['O procedimento não é permitido para o CBO do profissional.']
|
|
]);
|
|
}
|
|
|
|
$atendimentoProcedimento = $soap->procedimentos()->create([
|
|
'atendimento_id' => $soap->atendimento_id,
|
|
'procedimento_id' => $procedimentoData['procedimento']['id'],
|
|
'cid_id' => $procedimentoData['cid']['id'] ?? null,
|
|
'quantidade' => $procedimentoData['quantidade'] ?? null,
|
|
'automatico' => false,
|
|
'ocupacao_id' => $soap->atendimento->ocupacao->id ?? $soap->createdLotacao->ocupacao_id,
|
|
'especialidade_id' => $soap->atendimento->especialidade->id ?? null,
|
|
'usuario_id' => $soap->atendimento->usuario->id ?? $soap->createdLotacao->usuario_id,
|
|
]);
|
|
|
|
$feridaProcedimento = $ferida->procedimentos()->create([
|
|
'soap_id' => $soap->id,
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
]);
|
|
|
|
$soap->procedimentosClinicos()->create([
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
'observacao' => $procedimentoData['observacao'] ?? null,
|
|
]);
|
|
}
|
|
|
|
if (!empty($procedimentoData['procedimento']['materiais']) && is_array($procedimentoData['procedimento']['materiais'])) {
|
|
|
|
foreach ($procedimentoData['procedimento']['materiais'] as $material) {
|
|
|
|
if (!empty($material['id'])) {
|
|
|
|
$itemData = [
|
|
'material_id' => $material['id'],
|
|
'quantidade' => $material['quantidade'],
|
|
'escolheu_entrada_item_manualmente' => $material['material_escolheu_entrada_item_manualmente'] ?? false,
|
|
'entrada_itens' => $material['material_entrada_itens'] ?? [],
|
|
];
|
|
|
|
$saidaItem = AlmoxarifadoService::saveSaidaDeDispensacaoDoAmbulatorio($itemData);
|
|
|
|
AtendimentoSoapFeridaMaterial::create([
|
|
'atendimento_procedimento_id' => $atendimentoProcedimento->id,
|
|
'material_id' => $material['id'],
|
|
'saida_item_id' => $saidaItem->id,
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
|
|
return [
|
|
'ferida_id' => $ferida->id,
|
|
'procedimento' => [
|
|
'id' => $feridaProcedimento->id,
|
|
'procedimento' => $procedimentoData['procedimento'],
|
|
'cid' => $procedimentoData['cid'] ?? null,
|
|
'quantidade' => $procedimentoData['quantidade'] ?? null,
|
|
'automatico' => false
|
|
]
|
|
];
|
|
});
|
|
}
|
|
|
|
public static function validarProcedimentosCbo()
|
|
{
|
|
$procedimentoIds = request()->procedimento_ids;
|
|
$ocupacaoId = self::getCurrentLotacao()->ocupacao_id;
|
|
|
|
return collect($procedimentoIds)->filter(function ($id) use ($ocupacaoId) {
|
|
return ProcedimentoIsValidForOcupacao::isValid($ocupacaoId, $id);
|
|
})->values();
|
|
}
|
|
|
|
public static function destroyFeridaProcedimento($id)
|
|
{
|
|
return DB::transaction(function () use ($id) {
|
|
|
|
$feridaProcedimento = AtendimentoSoapFeridaProcedimento::find($id);
|
|
|
|
if (!$feridaProcedimento) {
|
|
|
|
return true;
|
|
}
|
|
|
|
$atendimentoProcedimentoId = $feridaProcedimento->atendimento_procedimento_id;
|
|
|
|
$feridaProcedimento->delete();
|
|
|
|
AtendimentoSoapFeridaMaterial::where('atendimento_procedimento_id', $atendimentoProcedimentoId)->delete();
|
|
|
|
AtendimentoSoapProcedimentoClinico::where('atendimento_procedimento_id', $atendimentoProcedimentoId)
|
|
->delete();
|
|
|
|
AtendimentoProcedimento::where('id', $atendimentoProcedimentoId)
|
|
->delete();
|
|
|
|
return true;
|
|
});
|
|
}
|
|
|
|
private static function getPerfisEpidemiologicosValidations()
|
|
{
|
|
return [
|
|
'perfis_epidemiologicos' => [
|
|
'present',
|
|
'array',
|
|
],
|
|
'perfis_epidemiologicos.*' => [
|
|
'required',
|
|
'integer',
|
|
'distinct',
|
|
Rule::exists(CadastroPerfilEpidemiologico::class, 'id'),
|
|
],
|
|
];
|
|
}
|
|
|
|
private static function getPuericulturaQuestionarioMChatR($soapRascunho)
|
|
{
|
|
return PuericulturaQuestionarioMChatR::orderBy('id')->get()->map(function ($query) use ($soapRascunho) {
|
|
if (!is_null($soapRascunho)) {
|
|
$questionarioMChatRRascunho = $soapRascunho->puericulturaQuestionarioMChatR()
|
|
->where('questionario_m_chat_r_id', $query->id)
|
|
->first();
|
|
|
|
return [
|
|
'id' => $query->id,
|
|
'descricao' => $query->descricao,
|
|
'valor_resposta_sim' => $query->valor_resposta_sim,
|
|
'valor_resposta_nao' => $query->valor_resposta_nao,
|
|
'resposta' => $questionarioMChatRRascunho->resposta ?? null,
|
|
];
|
|
}
|
|
|
|
return [
|
|
'id' => $query->id,
|
|
'descricao' => $query->descricao,
|
|
'valor_resposta_sim' => $query->valor_resposta_sim,
|
|
'valor_resposta_nao' => $query->valor_resposta_nao,
|
|
'resposta' => null,
|
|
];
|
|
});
|
|
}
|
|
|
|
private static function savePuericulturaQuestionarioMChatR($soap)
|
|
{
|
|
$questionarioMChatR = collect(request()->objetivo['puericultura']['questionario_mchat_r'])
|
|
->filter(fn ($questionario) => !is_null($questionario['resposta']))
|
|
->map(fn ($questionario) => [
|
|
'questionario_m_chat_r_id' => $questionario['id'],
|
|
'resposta' => $questionario['resposta'],
|
|
]);
|
|
|
|
$soap->puericulturaQuestionarioMChatR()->createMany($questionarioMChatR);
|
|
}
|
|
|
|
private static function getSoapsByPaciente($pacienteId)
|
|
{
|
|
return AtendimentoSoap::where('is_rascunho', false)
|
|
->whereHas('atendimento', function ($query) use ($pacienteId) {
|
|
$query->where('paciente_id', $pacienteId);
|
|
})
|
|
->get();
|
|
}
|
|
|
|
|
|
private static function saveIvcf($soap)
|
|
{
|
|
if (request()->ivcf && request()->ivcf['deseja_preencher'] === true) {
|
|
|
|
$soap->ivcf()->create([
|
|
'estado_saude_geral' => request()->ivcf['estado_saude_geral'],
|
|
'limitacao_compras' => request()->ivcf['limitacao_compras'],
|
|
'limitacao_gestao_financeira' => request()->ivcf['limitacao_gestao_financeira'],
|
|
'limitacao_tarefas_domesticas' => request()->ivcf['limitacao_tarefas_domesticas'],
|
|
'banho_independencia' => request()->ivcf['banho_independencia'],
|
|
'relato_esquecimento_por_terceiros' => request()->ivcf['relato_esquecimento_por_terceiros'],
|
|
'esquecimento_piorando' => request()->ivcf['esquecimento_piorando'],
|
|
'esquecimento_impacta_atividades' => request()->ivcf['esquecimento_impacta_atividades'],
|
|
'humor_tristeza_desanimo' => request()->ivcf['humor_tristeza_desanimo'],
|
|
'perda_interesse_atividades' => request()->ivcf['perda_interesse_atividades'],
|
|
'limitacao_elevar_bracos' => request()->ivcf['limitacao_elevar_bracos'],
|
|
'limitacao_motricidade_fina' => request()->ivcf['limitacao_motricidade_fina'],
|
|
'perda_peso_nao_intencional' => request()->ivcf['perda_peso_nao_intencional'],
|
|
'imc_abaixo_22' => request()->ivcf['imc_abaixo_22'],
|
|
'panturrilha_abaixo_31' => request()->ivcf['panturrilha_abaixo_31'],
|
|
'marcha_lenta_4m_maior_5s' => request()->ivcf['marcha_lenta_4m_maior_5s'],
|
|
'dificuldade_caminhar_impacto_atividades' => request()->ivcf['dificuldade_caminhar_impacto_atividades'],
|
|
'quedas_recorrentes' => request()->ivcf['quedas_recorrentes'],
|
|
'incontinencia' => request()->ivcf['incontinencia'],
|
|
'problema_visao_impacto_atividades' => request()->ivcf['problema_visao_impacto_atividades'],
|
|
'problema_audicao_impacto_atividades' => request()->ivcf['problema_audicao_impacto_atividades'],
|
|
'doencas_cronicas_multiplas' => request()->ivcf['doencas_cronicas_multiplas'],
|
|
'polifarmacia_5_ou_mais_medicamentos' => request()->ivcf['polifarmacia_5_ou_mais_medicamentos'],
|
|
'internacao_ultimos_6_meses' => request()->ivcf['internacao_ultimos_6_meses'],
|
|
]);
|
|
} else {
|
|
$soap->ivcf()->delete();
|
|
}
|
|
}
|
|
|
|
private static function saveRiscoCardiovascularFramingham($soap)
|
|
{
|
|
|
|
if (request()->risco_cardiovascular_framingham && request()->risco_cardiovascular_framingham['colesterol_total']) {
|
|
$soap->riscoCardiovascularFramingham()->create([
|
|
'colesterol_total' => request()->risco_cardiovascular_framingham['colesterol_total'],
|
|
'colesterol_hdl' => request()->risco_cardiovascular_framingham['colesterol_hdl'],
|
|
'toma_remedio_hipertensao' => request()->risco_cardiovascular_framingham['toma_remedio_hipertensao'],
|
|
'tabagista' => request()->risco_cardiovascular_framingham['tabagista'],
|
|
'diabetico' => request()->risco_cardiovascular_framingham['diabetico'],
|
|
]);
|
|
}
|
|
}
|
|
|
|
private static function getHistoricoRiscoCardiovascularFraminghamFormData($atendimento)
|
|
{
|
|
$sexoId = $atendimento->paciente->cidadao->sexo->id ?? null;
|
|
|
|
return $atendimento->soaps()
|
|
->where('is_rascunho', false)
|
|
->whereHas('riscoCardiovascularFramingham')
|
|
->with(['riscoCardiovascularFramingham'])
|
|
->get()
|
|
->map(function ($soap) use ($sexoId) {
|
|
$idade = $soap->created_at->diffInYears($soap->atendimento->paciente->cidadao->data_nascimento);
|
|
$riscoCardiovascularFramingham = $soap->riscoCardiovascularFramingham;
|
|
$pressaoArterial = $soap->objetivoSinalVital->atendimentoSinalVital->pressao_arterial ?? null;
|
|
|
|
$resultadoRiscoCardiovascularFramingham = self::getResultaRiscoCardiovascularFramingham(
|
|
$sexoId,
|
|
$idade,
|
|
$riscoCardiovascularFramingham->colesterol_total,
|
|
$riscoCardiovascularFramingham->colesterol_hdl,
|
|
$pressaoArterial,
|
|
$riscoCardiovascularFramingham->toma_remedio_hipertensao,
|
|
$riscoCardiovascularFramingham->tabagista,
|
|
$riscoCardiovascularFramingham->diabetico,
|
|
);
|
|
|
|
return [
|
|
'id' => $soap->id,
|
|
'data_hora_atendimento' => $soap->created_at->format('d/m/Y \à\s H:i'),
|
|
'usuario_nome' => $soap->createdLotacao->usuario->cidadao->nome ?? null,
|
|
'pontuacao' => $resultadoRiscoCardiovascularFramingham['pontuacao'],
|
|
'classificacao' => $resultadoRiscoCardiovascularFramingham['classificacao'],
|
|
'porcentagem' => $resultadoRiscoCardiovascularFramingham['porcentagem'],
|
|
];
|
|
});
|
|
}
|
|
|
|
private static function getResultaRiscoCardiovascularFramingham($sexoId, $idade, $colesterolTotal, $colesterolHdl, $pressaoArterial, $tomaRemedioHipertensao, $tabagista, $diabetico)
|
|
{
|
|
$pontuacao = 0;
|
|
|
|
$pontuacao += self::getPontuacaoIdadeRiscoCardiovascularFramingham($sexoId, $idade);
|
|
$pontuacao += self::getPontuacaoColesterolTotalRiscoCardiovascularFramingham($sexoId, $idade, $colesterolTotal);
|
|
$pontuacao += self::getPontuacaoColesterolHdlRiscoCardiovascularFramingham($colesterolHdl);
|
|
$pontuacao += self::getPontuacaoPressaoArterialRiscoCardiovascularFramingham($sexoId, $pressaoArterial, $tomaRemedioHipertensao);
|
|
$pontuacao += self::getPontuacaoTabagismoRiscoCardiovascularFramingham($sexoId, $idade, $tabagista);
|
|
$pontuacao += self::getPontuacaoDiabetesRiscoCardiovascularFramingham($sexoId, $diabetico);
|
|
|
|
$porcentagem = self::getPorcentagemRiscoCardiovascularFramingham($sexoId, $pontuacao);
|
|
|
|
if ($porcentagem < 10) {
|
|
$classificacao = 'Baixo risco';
|
|
} elseif ($porcentagem < 20) {
|
|
$classificacao = 'Risco intermediário';
|
|
} else {
|
|
$classificacao = 'Alto risco';
|
|
}
|
|
|
|
return [
|
|
'pontuacao' => $pontuacao,
|
|
'classificacao' => $classificacao,
|
|
'porcentagem' => $porcentagem,
|
|
];
|
|
}
|
|
|
|
private static function getPontuacaoIdadeRiscoCardiovascularFramingham($sexoId, $idade)
|
|
{
|
|
if ($sexoId === Sexo::MASCULINO) {
|
|
if ($idade >= 20 && $idade <= 34) return -9;
|
|
if ($idade >= 35 && $idade <= 39) return -4;
|
|
if ($idade >= 40 && $idade <= 44) return 0;
|
|
if ($idade >= 45 && $idade <= 49) return 3;
|
|
if ($idade >= 50 && $idade <= 54) return 6;
|
|
if ($idade >= 55 && $idade <= 59) return 8;
|
|
if ($idade >= 60 && $idade <= 64) return 10;
|
|
if ($idade >= 65 && $idade <= 69) return 11;
|
|
if ($idade >= 70 && $idade <= 74) return 12;
|
|
if ($idade >= 75) return 13;
|
|
} else {
|
|
if ($idade >= 20 && $idade <= 34) return -7;
|
|
if ($idade >= 35 && $idade <= 39) return -3;
|
|
if ($idade >= 40 && $idade <= 44) return 0;
|
|
if ($idade >= 45 && $idade <= 49) return 3;
|
|
if ($idade >= 50 && $idade <= 54) return 6;
|
|
if ($idade >= 55 && $idade <= 59) return 8;
|
|
if ($idade >= 60 && $idade <= 64) return 10;
|
|
if ($idade >= 65 && $idade <= 69) return 12;
|
|
if ($idade >= 70 && $idade <= 74) return 14;
|
|
if ($idade >= 75) return 16;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
private static function getPontuacaoColesterolTotalRiscoCardiovascularFramingham($sexoId, $idade, $colesterolTotal)
|
|
{
|
|
if ($colesterolTotal < 160) return 0;
|
|
|
|
if ($sexoId === Sexo::MASCULINO) {
|
|
if ($idade >= 20 && $idade <= 39) {
|
|
if ($colesterolTotal <= 199) return 4;
|
|
if ($colesterolTotal <= 239) return 7;
|
|
if ($colesterolTotal <= 279) return 9;
|
|
return 11;
|
|
} elseif ($idade >= 40 && $idade <= 49) {
|
|
if ($colesterolTotal <= 199) return 3;
|
|
if ($colesterolTotal <= 239) return 5;
|
|
if ($colesterolTotal <= 279) return 6;
|
|
return 8;
|
|
} elseif ($idade >= 50 && $idade <= 59) {
|
|
if ($colesterolTotal <= 199) return 2;
|
|
if ($colesterolTotal <= 239) return 3;
|
|
if ($colesterolTotal <= 279) return 4;
|
|
return 5;
|
|
} elseif ($idade >= 60 && $idade <= 69) {
|
|
if ($colesterolTotal <= 199) return 1;
|
|
if ($colesterolTotal <= 239) return 1;
|
|
if ($colesterolTotal <= 279) return 2;
|
|
return 3;
|
|
} else {
|
|
if ($colesterolTotal <= 199) return 0;
|
|
elseif ($colesterolTotal <= 239) return 1;
|
|
elseif ($colesterolTotal <= 279) return 1;
|
|
return 1;
|
|
}
|
|
} else {
|
|
if ($idade >= 20 && $idade <= 39) {
|
|
if ($colesterolTotal <= 199) return 4;
|
|
if ($colesterolTotal <= 239) return 8;
|
|
if ($colesterolTotal <= 279) return 11;
|
|
return 13;
|
|
} elseif ($idade >= 40 && $idade <= 49) {
|
|
if ($colesterolTotal <= 199) return 3;
|
|
if ($colesterolTotal <= 239) return 6;
|
|
if ($colesterolTotal <= 279) return 8;
|
|
return 10;
|
|
} elseif ($idade >= 50 && $idade <= 59) {
|
|
if ($colesterolTotal <= 199) return 2;
|
|
if ($colesterolTotal <= 239) return 4;
|
|
if ($colesterolTotal <= 279) return 5;
|
|
return 7;
|
|
} elseif ($idade >= 60 && $idade <= 69) {
|
|
if ($colesterolTotal <= 199) return 1;
|
|
if ($colesterolTotal <= 239) return 2;
|
|
if ($colesterolTotal <= 279) return 3;
|
|
return 4;
|
|
} else {
|
|
if ($colesterolTotal <= 199) return 1;
|
|
if ($colesterolTotal <= 239) return 1;
|
|
if ($colesterolTotal <= 279) return 2;
|
|
return 2;
|
|
}
|
|
}
|
|
}
|
|
|
|
private static function getPontuacaoColesterolHdlRiscoCardiovascularFramingham($colesterolHdl)
|
|
{
|
|
if ($colesterolHdl >= 60) return -1;
|
|
if ($colesterolHdl >= 50) return 0;
|
|
if ($colesterolHdl >= 40) return 1;
|
|
|
|
return 2;
|
|
}
|
|
|
|
private static function getPontuacaoPressaoArterialRiscoCardiovascularFramingham($sexoId, $pressaoArterial, $tomaRemedioHipertensao)
|
|
{
|
|
if (!$pressaoArterial) {
|
|
return 0;
|
|
}
|
|
|
|
$partes = explode('/', $pressaoArterial);
|
|
$sistolica = (int) ($partes[0] ?? 0);
|
|
|
|
if ($sexoId === Sexo::MASCULINO) {
|
|
if ($tomaRemedioHipertensao) {
|
|
if ($sistolica < 120) return 0;
|
|
if ($sistolica <= 129) return 1;
|
|
if ($sistolica <= 139) return 2;
|
|
if ($sistolica <= 159) return 2;
|
|
return 3;
|
|
} else {
|
|
if ($sistolica < 120) return 0;
|
|
if ($sistolica <= 129) return 0;
|
|
if ($sistolica <= 139) return 1;
|
|
if ($sistolica <= 159) return 1;
|
|
return 2;
|
|
}
|
|
} else {
|
|
if ($tomaRemedioHipertensao) {
|
|
if ($sistolica < 120) return 0;
|
|
if ($sistolica <= 129) return 3;
|
|
if ($sistolica <= 139) return 4;
|
|
if ($sistolica <= 159) return 5;
|
|
return 6;
|
|
} else {
|
|
if ($sistolica < 120) return 0;
|
|
if ($sistolica <= 129) return 1;
|
|
if ($sistolica <= 139) return 2;
|
|
if ($sistolica <= 159) return 3;
|
|
return 4;
|
|
}
|
|
}
|
|
}
|
|
|
|
private static function getPontuacaoTabagismoRiscoCardiovascularFramingham($sexoId, $idade, $tabagista)
|
|
{
|
|
if (!$tabagista) {
|
|
return 0;
|
|
}
|
|
|
|
if ($sexoId === Sexo::MASCULINO) {
|
|
if ($idade >= 20 && $idade <= 39) return 8;
|
|
if ($idade >= 40 && $idade <= 49) return 5;
|
|
if ($idade >= 50 && $idade <= 59) return 3;
|
|
if ($idade >= 60 && $idade <= 69) return 1;
|
|
return 1;
|
|
} else {
|
|
if ($idade >= 20 && $idade <= 39) return 9;
|
|
if ($idade >= 40 && $idade <= 49) return 7;
|
|
if ($idade >= 50 && $idade <= 59) return 4;
|
|
if ($idade >= 60 && $idade <= 69) return 2;
|
|
return 1;
|
|
}
|
|
}
|
|
|
|
private static function getPontuacaoDiabetesRiscoCardiovascularFramingham($sexoId, $diabetico)
|
|
{
|
|
if (!$diabetico) {
|
|
return 0;
|
|
}
|
|
|
|
return $sexoId === Sexo::MASCULINO ? 2 : 4;
|
|
}
|
|
|
|
private static function getPorcentagemRiscoCardiovascularFramingham($sexoId, $pontuacao)
|
|
{
|
|
if ($sexoId === Sexo::MASCULINO) {
|
|
if ($pontuacao <= 4) return 1;
|
|
if ($pontuacao <= 6) return 2;
|
|
if ($pontuacao === 7) return 3;
|
|
if ($pontuacao === 8) return 4;
|
|
if ($pontuacao === 9) return 5;
|
|
if ($pontuacao === 10) return 6;
|
|
if ($pontuacao === 11) return 8;
|
|
if ($pontuacao === 12) return 10;
|
|
if ($pontuacao === 13) return 12;
|
|
if ($pontuacao === 14) return 16;
|
|
if ($pontuacao === 15) return 20;
|
|
if ($pontuacao === 16) return 25;
|
|
return 30;
|
|
} else {
|
|
if ($pontuacao <= 12) return 1;
|
|
if ($pontuacao <= 14) return 2;
|
|
if ($pontuacao === 15) return 3;
|
|
if ($pontuacao === 16) return 4;
|
|
if ($pontuacao === 17) return 5;
|
|
if ($pontuacao === 18) return 6;
|
|
if ($pontuacao === 19) return 8;
|
|
if ($pontuacao === 20) return 11;
|
|
if ($pontuacao === 21) return 14;
|
|
if ($pontuacao === 22) return 17;
|
|
if ($pontuacao === 23) return 22;
|
|
if ($pontuacao === 24) return 27;
|
|
return 30;
|
|
}
|
|
}
|
|
|
|
private static function demandaEspontaneaObservaVagaAtendimento($especialidadeId)
|
|
{
|
|
$response = false;
|
|
|
|
if (isset($especialidadeId)) {
|
|
$currentCentroCusto = self::getCurrentCentroCusto();
|
|
|
|
$response = ParametrizacaoInfraestruturaEspecialidade::where('especialidade_id', $especialidadeId)
|
|
->whereHas('parametrizacaoInfraestrutura', fn ($q) => $q->where('infraestrutura_id', $currentCentroCusto->infraestrutura_id))
|
|
->first()->demanda_espontanea_observa_vaga_atendimento ?? false;
|
|
}
|
|
|
|
return $response;
|
|
}
|
|
|
|
private static function getStatusLiberamHorario()
|
|
{
|
|
return [
|
|
AgendamentoStatus::REAGENDADO_PELO_PACIENTE,
|
|
AgendamentoStatus::REAGENDADO_PELO_MEDICO,
|
|
AgendamentoStatus::CANCELADO_PELO_PACIENTE,
|
|
AgendamentoStatus::CANCELADO_PELO_MEDICO,
|
|
];
|
|
}
|
|
|
|
private static function getJornadas($params)
|
|
{
|
|
return Jornada::setEagerLoads([])
|
|
->whereHas('lotacao', fn ($q) => $q
|
|
->where('usuario_id', $params->usuario_id)
|
|
->where('ocupacao_id', $params->ocupacao_id)
|
|
->where('infraestrutura_id', $params->infraestrutura_id)
|
|
)
|
|
->whereNotNull('quantidade_consulta')
|
|
->whereNull('situacao_id')
|
|
->whereDate('data', $params->data)
|
|
->orderBy('inicio')
|
|
->get()
|
|
->map(function ($jornada) {
|
|
$quantidadeAgendamentos = $jornada->agendamentos()
|
|
->whereNotIn('status_id', self::getStatusLiberamHorario())
|
|
->where('tipo_id', AgendamentoTipo::CONSULTA)
|
|
->count();
|
|
|
|
$quantidadeDemandasEspontaneas = $jornada->demandasEspontaneas()->count();
|
|
|
|
$quantidadeUtilizada = $quantidadeAgendamentos + $quantidadeDemandasEspontaneas;
|
|
|
|
$quantidadeConsulta = $jornada->quantidade_consulta;
|
|
|
|
return [
|
|
'id' => $jornada->id,
|
|
'quantidade_utilizada' => $quantidadeUtilizada,
|
|
'quantidade_consulta' => $quantidadeConsulta,
|
|
'inicio' => $jornada->inicio->format('H:i'),
|
|
'fim' => $jornada->fim->format('H:i'),
|
|
'descricao' => $jornada->inicio->format('d/m/Y H:i') . ' - ' . $quantidadeUtilizada . '/' . $quantidadeConsulta,
|
|
];
|
|
});
|
|
}
|
|
|
|
private static function houveMudancaInformacaoSocioeconomica($alimentosAtual, $comeuAtual, $alimentosNovo, $comeuNovo)
|
|
{
|
|
return $alimentosAtual !== $alimentosNovo || $comeuAtual !== $comeuNovo;
|
|
}
|
|
|
|
private static function getDemandaTipos()
|
|
{
|
|
return [
|
|
['value' => DemandaTipo::AGENDADA, 'text' => 'Demanda agendada'],
|
|
['value' => DemandaTipo::ESPONTANEA, 'text' => 'Demanda espontânea'],
|
|
];
|
|
}
|
|
}
|