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), ]; } } } public static function create() { $fila = Fila::findOrFail(request()->fila_id); FilaService::answer($fila->id); $data = [ 'additionals' => self::getAdditionalsData($fila), 'form' => self::getFormData($fila), 'model' => self::getModelData($fila), ]; if ($data['form']['pre-atendimento']['equipes']->count() === 1) { $data['model']['pre-atendimento']['equipe_id'] = $data['form']['pre-atendimento']['equipes']->first()['id']; } return $data; } private static function getAdditionalsData($fila) { return [ 'data_atual' => Carbon::today()->format('d/m/Y'), 'hora_inicio_atendimento' => Carbon::now()->format('H:i'), 'is_demanda_espontanea' => $fila->ambulatorioAtendimento->is_demanda_espontanea, 'has_pre_atendimento' => $fila->ambulatorioAtendimento->preAtendimento()->exists(), 'fatura_procedimento_raas' => self::faturaProcedimentoRaas(), 'pode_alterar_classificacao_risco' => self::podeAlterarClassificacaoRisco(), 'pode_finalizar_atendimento' => self::podeFinalizarAtendimento($fila), 'registro_vacinacao' => [ 'data_atual' => Carbon::now()->format('Y-m-d'), 'parametrizacao' => RegistroVacinacaoService::getParametrizacao(), 'sala_vacinacao_logada' => RegistroVacinacaoService::getSalaVacinacaoLogada(), ], ]; } private static function getFormData($fila) { $especialidadeId = $fila->ambulatorioAtendimento->is_demanda_espontanea ? ($fila->ambulatorioAtendimento->especialidade->id ?? null) : null; $demandaEspontaneaObservaVagaAtendimento = self::demandaEspontaneaObservaVagaAtendimento($especialidadeId); $unidade = $fila->centroCusto->infraestrutura->unidade; $cliente = Cliente::where('link', app('config')->get('database.default'))->firstOrFail(); $paciente = $fila->ambulatorioAtendimento->paciente; $atendimento = $fila->ambulatorioAtendimento; $usuarios = []; $ocupacoes = []; $especialidades = []; $jornadas = []; if ($fila->ambulatorioAtendimento->is_demanda_espontanea) { $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); if (!is_null($fila->ambulatorioAtendimento->usuario)) { $ocupacoes = self::getOcupacoesWithJornada((object) array_merge($desfechoParams, [ 'usuario_id' => $fila->ambulatorioAtendimento->usuario->id, ])); } if (!is_null($fila->ambulatorioAtendimento->ocupacao)) { $especialidades = self::getEspecialidadesWithJornada((object) array_merge($desfechoParams, [ 'usuario_id' => $fila->ambulatorioAtendimento->usuario->id, 'ocupacao_id' => $fila->ambulatorioAtendimento->ocupacao->id, ])); } 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'], ]); } } } $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) ]); return [ 'unidade' => [ 'cnes' => $unidade->cnes, ], 'antropometria' => null, 'paciente' => self::getPacienteData($paciente), 'usuario' => [ 'nome' => $atendimento->usuario->nome ?? null, 'ocupacao_codigo' => $atendimento->ocupacao->codigo ?? null, 'especialidade_nome' => $atendimento->especialidade->nome ?? null, ], 'pre-atendimento' => [ 'ultima_dum' => AtendimentoService::getUltimaDum($paciente), 'data_ultimo_atendimento_pre_natal' => self::getDataUltimoAtendimentoPreNatal($paciente), 'glicemia_capilar' => [ 'momentos_coleta' => self::getGlicemiaCapilarMomentosColeta(), ], 'classificacoes_risco' => self::getClassificacoesRisco(), 'testes_rapidos' => self::getTestesRapidos($paciente), 'administracoes_medicamentos' => ViaAdministracao::orderBy('descricao')->get(['id', 'codigo_procedimento', 'descricao']), 'outros_procedimentos' => OutroProcedimento::orderBy('nome')->get(['id', 'codigo', 'nome']), 'coletas_materiais' => self::getColetasMateriais($paciente), 'demanda_tipos' => self::getDemandaTipos(), 'atendimento_tipos' => $atendimentoTipos, 'equipes' => self::getEquipesUsuarioLogado(), 'locais_atendimento' => LocalAtendimento::orderBy('descricao')->get(['id', 'descricao']), 'turnos' => Turno::orderBy('id')->get(['id', 'nome']), 'desfecho' => [ 'usuarios' => $usuarios, 'ocupacoes' => $ocupacoes, 'especialidades' => $especialidades, 'jornadas' => $jornadas, 'opcoes_entrada' => self::getOpcoesEntrada($fila), 'prioridades' => self::getPrioridades(), 'servicos' => self::getServicos(), 'centros_custo_encaminhamento' => self::getCentrosCustoEncaminhamento(), ], ], 'historico' => AtendimentoService::getHistorico($paciente->id), 'medicoes' => AtendimentoService::getMedicoesFormData($fila->ambulatorioAtendimento), 'coleta_exame_laboratorial' => [ 'unidade' => self::getCurrentCentroCusto()->infraestrutura->unidade->nome_fantasia, 'unidades_faturamento' => LancamentoColetaService::getUnidadesFaturamento(), 'sistema' => [ 'ramo_atividade' => [ 'nome' => $cliente->sistema->ramoAtividade->nome ?? null, ], 'nome' => $cliente->sistema->nome ?? null, 'versao' => $cliente->sistema->versao ?? null, ], 'status' => Status::whereIn('id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, ])->get(['id', 'descricao']) ], 'registro_vacinacao' => [ 'unidades' => [], 'salas_vacinacao' => [], 'lotes' => [], 'doses' => [], 'produtores' => [], 'grupos_atendimento' => RegistroVacinacaoService::getGruposAtendimento(), 'estrategias' => [], 'turnos' => Turno::all(), 'vias_administracao' => RegistroVacinacaoService::getViasAdministracao(), 'locais_aplicacao' => [], 'locais' => LocalAtendimento::whereIn('id', [ AtencaoBasicaLocalAtendimento::UBS, AtencaoBasicaLocalAtendimento::UNIDADE_MOVEL, AtencaoBasicaLocalAtendimento::RUA, AtencaoBasicaLocalAtendimento::DOMICILIO, AtencaoBasicaLocalAtendimento::ESCOLA_CRECHE, AtencaoBasicaLocalAtendimento::OUTROS, AtencaoBasicaLocalAtendimento::POLO, AtencaoBasicaLocalAtendimento::INSTITUICAO, AtencaoBasicaLocalAtendimento::UNIDADE_PRISIONAL_CONGENERES, AtencaoBasicaLocalAtendimento::UNIDADE_SOCIOEDUCATIVA ])->orderBy('descricao')->get(), 'ocupacoes' => [], 'equipes' => [] ], ]; } 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 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_identificador' => $paciente->cidadao->sexo->identificador, 'sexo_descricao' => $paciente->cidadao->sexo->descricao, 'data_nascimento' => is_null($paciente->cidadao->data_nascimento) ? null : (new Carbon($paciente->cidadao->data_nascimento))->format('d/m/Y'), 'idade' => $paciente->cidadao->idade_formatada, '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 && $paciente->cidadao->telefone_principal->numero ? $paciente->cidadao->telefone_principal->id : null, 'telefone_numero' => $paciente->cidadao->telefone_principal && $paciente->cidadao->telefone_principal->numero ? MaskUtil::getPhoneMasked($paciente->cidadao->telefone_principal->numero) : null, 'telefone_autoriza_sms' => $paciente->cidadao->telefone_principal->autoriza_sms ?? 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_id' => $paciente->cidadao->racaCorId, ]; } private static function getDataUltimoAtendimentoPreNatal($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('is_atendimento_pre_natal', true) ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->select(DB::raw(1)) ->from('ambulatorio_agendamento as agendamento') ->whereColumn('agendamento.id', 'atendimento.agendamento_id') ->where('agendamento.paciente_id', $paciente->id) ) ->orWhereExists(fn ($q) => $q ->select(DB::raw(1)) ->from('ambulatorio_demanda_espontanea as demanda_espontanea') ->whereColumn('demanda_espontanea.id', 'atendimento.demanda_espontanea_id') ->where('demanda_espontanea.paciente_id', $paciente->id) ) ) ->select(DB::raw(" DATE_FORMAT(soap.created_at, '%d/%m/%Y') as data ")) ->orderByDesc('soap.created_at') ->first()->data ?? null; } private static function getGlicemiaCapilarMomentosColeta() { return GlicemiaCapilarMomentoColeta::orderBy('id')->get(['id', 'nome']); } private static function getClassificacoesRisco() { return ClassificacaoRisco::orderBy('id')->get(['id', 'nome', 'cor']); } private static function getTestesRapidos($paciente) { return TesteRapido::orderBy('nome') ->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 ] ) ->get(['id', 'codigo', 'nome']) ->filter(function ($testeRapido) use ($paciente) { if (is_null($testeRapido->codigo) || is_null($paciente->cidadao->sexo)) { return true; } $procedimento = ProcedimentoSigtap::where('codigo', $testeRapido->codigo) ->orderByDesc('competencia_id') ->first(); return (new ProcedimentoValidationService($procedimento))->isSexoValid($paciente->cidadao->sexo); }) ->values(); } private static function getColetasMateriais($paciente) { return ColetaMaterial::orderBy('nome') ->get(['id', 'codigo', 'nome']) ->filter(function ($coletaMaterial) use ($paciente) { if (is_null($coletaMaterial->codigo) || is_null($paciente->cidadao->sexo)) { return true; } $procedimento = ProcedimentoSigtap::where('codigo', $coletaMaterial->codigo) ->orderByDesc('competencia_id') ->first(); return (new ProcedimentoValidationService($procedimento))->isSexoValid($paciente->cidadao->sexo); }) ->values(); } private static function getOpcoesEntrada($fila) { return OpcaoEntrada::where('id', $fila->opcao_entrada_id) ->get(['id', 'nome', 'prioridade_obrigatoria']); } private static function getPrioridades() { return Prioridade::orderBy('nome')->get(['id', 'nome']); } private static function getServicos() { return Servico::orderBy('nome') ->whereHas('parametrizacoesInfraestrutura', fn ($q) => $q ->where('infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id) ) ->get(['id', 'tipo_id', 'nome']); } private static function getCentrosCustoEncaminhamento() { return Encaminhamento::where('centro_custo_id_de', self::getCurrentCentroCusto()->id) ->whereHas('centroCustoPara', fn ($q) => $q ->whereHas('setor', fn ($q) => $q ->whereIn('tipo_id', [ SetorTipo::CONSULTORIO, SetorTipo::ENFERMAGEM, ]) ) ) ->get() ->map(fn ($encaminhamento) => [ 'id' => $encaminhamento->centroCustoPara->id, 'setor_tipo_id' => $encaminhamento->centroCustoPara->setor->tipo_id, 'setor_nome' => $encaminhamento->centroCustoPara->setor->nome, ]); } 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) ) ) ->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) ) ) ) ->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) ) ->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($fila) { $centroCustoLogado = self::getCurrentCentroCusto(); $lotacaoLogada = self::getCurrentLotacao(); $parametrizacaoOcupacao = ParametrizacaoInfraestruturaOcupacao::whereHas('parametrizacaoInfraestrutura', fn ($q) => $q ->where('infraestrutura_id', $lotacaoLogada->infraestrutura_id) ) ->where('ocupacao_id', $lotacaoLogada->ocupacao_id) ->first(); return [ 'pre-atendimento' => [ 'ciap' => null, 'motivo_atendimento' => null, 'antropometria' => [ 'peso' => null, 'altura' => null, 'imc' => [ 'imc' => null, 'classificacao' => null, 'grau_obesidade' => null, ], 'perimetro_cefalico' => null, 'circunferencia_abdominal' => null, 'perimetro_panturrilha' => null, ], 'sinal_vital' => [ 'pressao_arterial' => null, 'frequencia_respiratoria' => null, 'frequencia_cardiaca' => null, 'temperatura' => null, 'saturacao_o2' => null, ], 'glicemia_capilar' => [ 'valor' => null, 'momento_coleta_id' => null, ], 'vacinacao_em_dia' => null, 'dum' => $fila->paciente->dum && $fila->paciente->dum->data_ultima_menstruacao ? $fila->paciente->dum->data_ultima_menstruacao : null, 'procedimentos' => [], 'medicamentos' => [], 'classificacao_risco_id' => $fila->ambulatorioAtendimento->is_demanda_espontanea && self::podeAlterarClassificacaoRisco() ? null : ClassificacaoRiscoEnum::NAO_AGUDA, 'testes_rapidos' => [], 'administracoes_medicamentos' => [], 'outros_procedimentos' => [], 'coletas_materiais' => [], 'demanda_tipo' => $fila->ambulatorioAtendimento->is_demanda_espontanea ? DemandaTipo::ESPONTANEA : DemandaTipo::AGENDADA, 'atendimento_tipo_id' => $fila->ambulatorioAtendimento->atendimento_tipo_id ?? null, 'equipe_id' => null, 'atencao_basica_local_atendimento_id' => LocalAtendimentoEnum::UBS, 'turno_id' => self::getTurnoMomento(), 'orientacao_individual_em_saude' => false, 'desfecho' => [ 'finalizado' => $fila->ambulatorioAtendimento->is_demanda_espontanea ? null : 'encaminhar', 'ocupacao_id' => $fila->ambulatorioAtendimento->is_demanda_espontanea ? ($fila->ambulatorioAtendimento->ocupacao->id ?? null) : null, 'especialidade_id' => $fila->ambulatorioAtendimento->is_demanda_espontanea ? ($fila->ambulatorioAtendimento->especialidade->id ?? null) : null, 'usuario_id' => $fila->ambulatorioAtendimento->is_demanda_espontanea ? ($fila->ambulatorioAtendimento->usuario->id ?? null) : null, 'jornada_id' => $fila->ambulatorioAtendimento->demandaEspontanea->jornada_id ?? null, 'opcao_entrada_id' => $fila->opcao_entrada_id ?? null, 'prioridade_id' => $fila->prioridade_id ?? null, 'servicos' => $fila->ambulatorioAtendimento->servicos->pluck('id'), 'centro_custo_encaminhamento_id' => null, 'pos_consulta' => $parametrizacaoOcupacao->pos_consulta ?? false, ], ], 'medicoes' => [ 'antropometrias' => [], ], 'coleta_exame_laboratorial' => [ 'coleta_infraestrutura_id' => $centroCustoLogado->infraestrutura_id, 'agendamentos' => self::getAgendamentosExameLaboratorial( $fila->ambulatorioAtendimento->paciente, $centroCustoLogado->infraestrutura ), ], 'registro_vacinacao' => array_merge( RegistroVacinacaoService::getPaciente($fila->ambulatorioAtendimento->paciente->id), [ 'registros' => array_merge( RegistroVacinacaoService::getRegistrosAplicacao($fila->ambulatorioAtendimento->paciente->id)->toArray(), RegistroVacinacaoService::getRegistrosAtualizacao($fila->ambulatorioAtendimento->paciente->id)->toArray(), ), 'aprazamentos' => RegistroVacinacaoService::getRegistrosAprazamento($fila->ambulatorioAtendimento->paciente->id), ] ), ]; } 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; } } public static function getAgendamentosExameLaboratorial($paciente, $infraestruturaColeta) { $now = Carbon::now(); $currentDate = $now->format('Y-m-d'); return DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento.id AS agendamento_id', 'exame_laboratorial_agendamento.agendamento_numero AS agendamento_numero', 'exame_laboratorial_agendamento.coleta_infraestrutura_id AS coleta_infraestrutura_id', 'exame_laboratorial_agendamento.coleta_unidade_id AS coleta_unidade_id', 'exame_laboratorial_agendamento.data AS data', 'exame_laboratorial_agendamento.ultima_menstruacao AS ultima_menstruacao', 'exame_laboratorial_agendamento.gestante AS gestante', DB::raw('TIME_FORMAT(exame_laboratorial_agendamento.horario, "%h:%i") AS hora_inicial'), 'exame_laboratorial_agendamento.infraestrutura_id AS infraestrutura_id', 'exame_laboratorial_agendamento.jornada_id AS jornada_id', 'exame_laboratorial_agendamento.laboratorio_infraestrutura_id AS laboratorio_infraestrutura_id', 'exame_laboratorial_agendamento.laboratorio_unidade_id AS laboratorio_id', 'exame_laboratorial_agendamento.medico_id AS medico_id', 'cadastro_cidadao_medico.nome AS medico_nome', 'exame_laboratorial_agendamento.observacao AS observacao', 'exame_laboratorial_agendamento.responsavel AS responsavel', 'exame_laboratorial_agendamento.suspeita_clinica AS suspeita', 'exame_laboratorial_agendamento.ultima_menstruacao AS data_menstruacao', 'exame_laboratorial_agendamento.unidade_id AS unidade_id', 'exame_laboratorial_agendamento.urgente AS urgente', 'exame_laboratorial_agendamento.uso_medicamento AS uso_medicamento', DB::raw('group_concat(parametrizacao_exame.sigla_exame separator ", ") as sigla_exame'), 'cadastro_paciente.id AS paciente_id', 'cadastro_cidadao.nome AS paciente_nome', 'cadastro_unidade.nome_fantasia as unidade_nome', 'cadastro_unidade_laboratorio.nome_fantasia as laboratorio_unidade_nome', 'cadastro_cidadao.preferencia_nome_id AS paciente_preferencia_nome_id', 'cadastro_cidadao.nome_social AS paciente_nome_social', 'cadastro_cidadao.sexo_id AS paciente_sexo_id', DB::raw('LPAD(cadastro_paciente.prontuario,7,0) as paciente_prontuario'), DB::raw('DATE_FORMAT(cadastro_cidadao.data_nascimento, "%d/%m/%Y") AS data_nascimento'), DB::raw('CONCAT(TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, exame_laboratorial_agendamento.data), " anos") AS paciente_idade'), DB::raw(' CASE WHEN cadastro_infraestrutura.principal THEN cadastro_unidade.nome_fantasia ELSE cadastro_infraestrutura.nome END AS infraestrutura_nome' ), DB::raw('CONCAT( cadastro_unidade_coleta.nome_fantasia, " - ", CASE WHEN cadastro_infraestrutura_coleta.principal THEN cadastro_unidade_coleta.nome_fantasia ELSE cadastro_infraestrutura_coleta.nome END) AS coleta_infraestrutura_nome'), DB::raw(' CASE WHEN cadastro_infraestrutura_laboratorio.principal THEN cadastro_unidade_laboratorio.nome_fantasia ELSE cadastro_infraestrutura_laboratorio.nome END AS laboratorio_infraestrutura_nome'), ]) ->leftJoin('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->leftJoin('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->leftJoin('cadastro_grupo', 'cadastro_grupo.id', 'parametrizacao_exame.grupo_tipo_id') ->leftJoin('cadastro_paciente', 'cadastro_paciente.id', 'exame_laboratorial_agendamento.paciente_id') ->leftJoin('cadastro_usuario', 'cadastro_usuario.id', 'exame_laboratorial_agendamento.medico_id') ->leftJoin('cadastro_cidadao as cadastro_cidadao_medico', 'cadastro_cidadao_medico.id', 'cadastro_usuario.cidadao_id') ->leftJoin('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id') ->leftJoin('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'exame_laboratorial_agendamento.infraestrutura_id') ->leftJoin('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->leftJoin('cadastro_infraestrutura as cadastro_infraestrutura_coleta', 'cadastro_infraestrutura_coleta.id', 'exame_laboratorial_agendamento.coleta_infraestrutura_id') ->leftJoin('cadastro_unidade as cadastro_unidade_coleta', 'cadastro_unidade_coleta.id', 'cadastro_infraestrutura_coleta.unidade_id') ->leftJoin('cadastro_infraestrutura as cadastro_infraestrutura_laboratorio', 'cadastro_infraestrutura_laboratorio.id', 'exame_laboratorial_agendamento.laboratorio_infraestrutura_id') ->leftJoin('cadastro_unidade as cadastro_unidade_laboratorio', 'cadastro_unidade_laboratorio.id', 'cadastro_infraestrutura_laboratorio.unidade_id') ->where('exame_laboratorial_agendamento.data', $currentDate) ->where('exame_laboratorial_agendamento.paciente_id', $paciente->id) ->where('exame_laboratorial_agendamento.coleta_unidade_id', $infraestruturaColeta->unidade_id) ->where('exame_laboratorial_agendamento.coleta_infraestrutura_id', $infraestruturaColeta->id) ->where('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::AGENDADO) ->groupBy('exame_laboratorial_agendamento.id') ->get() ->map(fn ($agendamento) => [ 'data' => $agendamento->data ?? null, 'hora_inicial' => $agendamento->hora_inicial ?? null, 'agendamento_id' => $agendamento->agendamento_id ?? null, 'agendamento_numero' => $agendamento->agendamento_numero ?? null, 'ultima_menstruacao' => $agendamento->ultima_menstruacao ?? null, 'coleta_infraestrutura_id' => $agendamento->coleta_infraestrutura_id ?? null, 'coleta_unidade_id' => $agendamento->coleta_unidade_id ?? null, 'gestante' => $agendamento->gestante ?? null, 'paciente_nome' => $agendamento->paciente_nome ?? null, 'paciente_nome_social' => $agendamento->paciente_nome_social, 'paciente_preferencia_nome' => $agendamento->paciente_preferencia_nome_id === PreferenciaNome::NOME_SOCIAL, 'paciente_prontuario' => $agendamento->paciente_prontuario, 'paciente_nascimento' => $agendamento->data_nascimento, 'paciente_idade' => $agendamento->paciente_idade, 'unidade_nome' => $agendamento->unidade_nome, 'infraestrutura_nome' => $agendamento->infraestrutura_nome, 'coleta_infraestrutura_nome' => $agendamento->coleta_infraestrutura_nome, 'laboratorio_infraestrutura_nome' => $agendamento->laboratorio_infraestrutura_nome, 'medico_nome' => $agendamento->medico_nome, 'data' => $agendamento->data ?? null, 'sigla_exame' => $agendamento->sigla_exame ?? null, 'observacao' => $agendamento->observacao, 'medicamentos' => $agendamento->uso_medicamento, 'suspeita' => $agendamento->suspeita, 'urgente' => $agendamento->urgente, 'exames' => self::getExamesAgendamentoExameLaboratorial($agendamento), ]); } public static function getExamesAgendamentoExameLaboratorial($agendamento) { $agendamentosComGrupo = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento.jornada_id AS jornada_id', 'cadastro_grupo.id AS exame_grupo_id', 'cadastro_grupo.nome AS exame_grupo_nome', DB::raw('group_concat(parametrizacao_exame.sigla_exame separator ", ") as sigla_exame'), DB::raw('true AS pertence_grupo'), 'exame_laboratorial_agendamento_exame.status_id AS status_id', 'exame_laboratorial_agendamento_exame.usuario_id AS usuario_id', 'exame_laboratorial_agendamento_exame.ocupacao_id AS ocupacao_id', ]) ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->join('cadastro_grupo', 'cadastro_grupo.id', 'parametrizacao_exame.grupo_tipo_id') ->where('parametrizacao_exame.mapa_agrupado', true) ->where('exame_laboratorial_agendamento.id', $agendamento->agendamento_id) ->where('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::AGENDADO) ->groupBy([ 'exame_laboratorial_agendamento.id', 'cadastro_grupo.id', ]) ->get() ->toArray(); $agendamentosSemMapaAgrupado = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'parametrizacao_exame.id AS exame_grupo_id', 'parametrizacao_exame.nome AS exame_grupo_nome', DB::raw('group_concat(parametrizacao_exame.sigla_exame separator ", ") as sigla_exame'), DB::raw('false AS pertence_grupo'), 'exame_laboratorial_agendamento_exame.status_id AS status_id', 'exame_laboratorial_agendamento_exame.usuario_id AS usuario_id', 'exame_laboratorial_agendamento_exame.ocupacao_id AS ocupacao_id', ]) ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->where(function ($query) { $query->where('parametrizacao_exame.mapa_agrupado', false) ->orWhereNull('parametrizacao_exame.mapa_agrupado'); }) ->where('exame_laboratorial_agendamento.id', $agendamento->agendamento_id) ->where('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::AGENDADO) ->groupBy([ 'exame_laboratorial_agendamento.id', 'parametrizacao_exame.id', ]) ->get() ->toArray(); $agendamentosSemGrupo = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'parametrizacao_exame.id AS exame_grupo_id', 'parametrizacao_exame.nome AS exame_grupo_nome', 'parametrizacao_exame.sigla_exame AS sigla_exame', DB::raw('false AS pertence_grupo'), 'exame_laboratorial_agendamento_exame.status_id AS status_id', 'exame_laboratorial_agendamento_exame.usuario_id AS usuario_id', 'exame_laboratorial_agendamento_exame.ocupacao_id AS ocupacao_id', ]) ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->whereNull('parametrizacao_exame.grupo_tipo_id') ->where('exame_laboratorial_agendamento.id', request()->agendamento_id) ->where('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::AGENDADO) ->get() ->toArray(); return array_merge($agendamentosComGrupo, $agendamentosSemGrupo, $agendamentosSemMapaAgrupado); } public static function store() { $fila = Fila::find(request()->fila_id); self::validateStore($fila); $preAtendimento = new AtendimentoPreAtendimento(); DB::transaction(function () use ($preAtendimento, $fila) { $atendimento = $fila->ambulatorioAtendimento; self::savePaciente($atendimento->paciente); $existeProcedimentos = request()->procedimentos ? true : false; $preAtendimento->fill([ 'atendimento_id' => $atendimento->id, 'atendimento_tipo_id' => request()->atendimento_tipo_id, 'ciap_id' => request()->ciap_id, 'motivo_atendimento' => request()->motivo_atendimento, 'vacinacao_em_dia' => request()->vacinacao_em_dia, 'dum' => is_null(request()->dum) ? null : Carbon::createFromFormat('d/m/Y', request()->dum), 'classificacao_risco_id' => request()->classificacao_risco_id, 'orientacao_individual_em_saude' => request()->orientacao_individual_em_saude, 'equipe_id' => request()->equipe_id, 'atencao_basica_local_atendimento_id' => request()->atencao_basica_local_atendimento_id, 'turno_id' => request()->turno_id, 'paciente_liberado' => request()->desfecho['finalizado'], 'paciente_mantido_fila' => !request()->desfecho['finalizado'] && is_null(request()->desfecho['centro_custo_encaminhamento_id']), 'pos_consulta' => is_null(request()->desfecho['centro_custo_encaminhamento_id']) || CentroCusto::findOrFail(request()->desfecho['centro_custo_encaminhamento_id'])->setor->tipo_id !== SetorTipo::ENFERMAGEM ? null : request()->desfecho['pos_consulta'], ]); $preAtendimento->save(); $preAtendimento->administracoesMedicamentos()->sync(request()->administracoes_medicamentos); $preAtendimento->outrosProcedimentos()->sync(request()->outros_procedimentos); $preAtendimento->coletasMateriais()->sync(request()->coletas_materiais); self::saveTestesRapidos($preAtendimento); self::saveAvaliacaoAntropometrica($preAtendimento); self::saveSinaisVitais($preAtendimento); self::saveGlicemiaCapilar($preAtendimento); self::saveColetasExameLaboratorial($preAtendimento); if(!is_null(RegistroVacinacaoService::getSalaVacinacaoLogada())){ self::saveRegistrosVacinacao($preAtendimento); }; self::saveProcedimentos($preAtendimento); self::saveMedicamentos($preAtendimento); $atendimento->update(['atendimento_tipo_id' => request()->atendimento_tipo_id]); if (request()->desfecho['finalizado']) { $atendimento->update([ 'finalizado_em' => Carbon::now(), 'finalizado_lotacao_id' => self::getCurrentLotacao()->id, ]); $atendimento->fila->update(['finalizado' => true]); if (!$atendimento->is_demanda_espontanea) { $atendimento->agendamento->update(['status_id' => AgendamentoStatus::REALIZADO]); if (!is_null($atendimento->agendamento->regulacao_solicitacao_id)) { RegulacaoSolicitacaoService::updateStatus( $atendimento->agendamento->regulacao_solicitacao_id, RegulacaoStatusTipo::REALIZADO ); } } if($existeProcedimentos){ self::storeFichaAtencaoBasica($preAtendimento); } } else { if ($atendimento->is_demanda_espontanea) { $atendimento->demandaEspontanea()->update([ 'ocupacao_id' => request()->desfecho['ocupacao_id'], 'especialidade_id' => request()->desfecho['especialidade_id'], 'usuario_id' => request()->desfecho['usuario_id'], ]); } $fila->update([ 'prioridade_id' => request()->desfecho['prioridade_id'], 'status_id' => PainelSenhaStatus::EM_ESPERA ]); $atendimento->servicos()->sync(request()->desfecho['servicos']); if($existeProcedimentos){ self::storeFichaAtencaoBasica($preAtendimento); } } if ($preAtendimento->pos_consulta) { $preAtendimento->atendimento()->update(['pos_consulta' => $preAtendimento->pos_consulta]); } if (request()->desfecho['centro_custo_encaminhamento_id']) { FilaService::forward($fila->id, request()->desfecho['centro_custo_encaminhamento_id']); } else { FilaService::dispatch($atendimento->fila->centro_custo_id); } }); return $preAtendimento->fresh(); } private static function validateStore($fila) { $rules = [ 'paciente.telefone_principal.id' => [ 'nullable', 'integer', Rule::exists(CidadaoTelefone::class, 'id'), ], 'paciente.telefone_principal.numero' => [ 'nullable', 'required_with:paciente.telefone_principal.id', 'digits_between:10,11', ], 'paciente.telefone_principal.autoriza_sms' => [ 'nullable', 'required_with:paciente.telefone_principal.id', 'boolean', ], 'fila_id' => [ 'required', 'integer', Rule::exists(Fila::class, 'id'), ], 'ciap_id' => [ 'nullable', 'integer', Rule::exists(Ciap::class, 'id'), ], 'motivo_atendimento' => [ 'nullable', 'string', 'max:5000' ], 'antropometria.peso' => [ 'nullable', 'numeric', 'between:0.5,500', ], 'antropometria.altura' => [ 'nullable', 'numeric', 'between:20,250', ], 'antropometria.perimetro_cefalico' => [ 'nullable', 'numeric', 'between:10,200', ], 'antropometria.circunferencia_abdominal' => [ 'nullable', 'numeric', 'max:999', ], 'antropometria.perimetro_panturrilha' => [ 'nullable', 'numeric', 'between:10,99', ], 'sinal_vital.pressao_arterial' => [ 'nullable', 'string', 'max:7', ], 'sinal_vital.frequencia_respiratoria' => [ 'nullable', 'numeric', 'max:200', ], 'sinal_vital.frequencia_cardiaca' => [ 'nullable', 'numeric', 'max:999', ], 'sinal_vital.temperatura' => [ 'nullable', 'numeric', 'between:20,45', ], 'sinal_vital.saturacao_o2' => [ 'nullable', 'numeric', 'max:100', ], 'glicemia_capilar.valor' => [ 'nullable', 'numeric', 'max:800', ], 'glicemia_capilar.momento_coleta_id' => [ 'nullable', 'required_with:glicemia_capilar.valor', 'integer', Rule::exists(GlicemiaCapilarMomentoColeta::class, 'id'), ], 'vacinacao_em_dia' => [ 'nullable', 'boolean', ], 'dum' => [ 'nullable', 'date_format:d/m/Y', 'before_or_equal:now', ], 'classificacao_risco_id' => [ 'required', 'integer', Rule::exists(ClassificacaoRisco::class, 'id'), ], 'orientacao_individual_em_saude' => [ 'required', 'boolean', ], 'testes_rapidos' => [ 'present', 'array' ], 'testes_rapidos.*.id' => [ 'required', 'integer', Rule::exists(TesteRapido::class, 'id'), ], 'testes_rapidos.*.resultado' => [ 'nullable', 'string', 'max:500', ], 'administracoes_medicamentos' => [ 'present', 'array' ], 'administracoes_medicamentos.*' => [ 'required', 'integer', Rule::exists(ViaAdministracao::class, 'id'), ], 'outros_procedimentos' => [ 'present', 'array' ], 'outros_procedimentos.*' => [ 'required', 'integer', Rule::exists(OutroProcedimento::class, 'id'), ], 'coletas_materiais' => [ 'present', 'array' ], 'coletas_materiais.*' => [ 'required', 'integer', Rule::exists(ColetaMaterial::class, 'id'), ], 'atendimento_tipo_id' => [ 'required', 'integer', Rule::exists(TipoAtendimento::class, 'id'), ], 'equipe_id' => [ 'nullable', 'integer', Rule::exists(Equipe::class, 'id'), ], 'atencao_basica_local_atendimento_id' => [ 'required_with:equipe_id', 'integer', Rule::exists(LocalAtendimento::class, 'id'), ], 'turno_id' => [ 'required_with:equipe_id', 'integer', Rule::exists(Turno::class, 'id'), ], 'desfecho.usuario_id' => [ 'nullable', 'required_with:desfecho.ocupacao_id', 'integer', Rule::exists(Usuario::class, 'id'), ], 'desfecho.ocupacao_id' => [ 'nullable', 'required_with:desfecho.especialidade_id', 'integer', Rule::exists(Ocupacao::class, 'id'), ], 'desfecho.especialidade_id' => [ 'nullable', 'integer', Rule::exists(Especialidade::class, 'id'), ], 'desfecho.prioridade_id' => [ 'nullable', Rule::requiredIf(fn () => $fila->opcaoEntrada->prioridade_obrigatoria ?? false), Rule::exists(Prioridade::class, 'id'), ], 'desfecho.servicos' => [ 'array' ], 'desfecho.servicos.*' => [ 'required', 'integer', Rule::exists(Servico::class, 'id'), ], 'desfecho.finalizado' => [ 'required', 'boolean', ], 'desfecho.centro_custo_encaminhamento_id' => [ 'nullable', 'integer', Rule::in(self::getCentrosCustoEncaminhamento()->pluck('id')), ], 'desfecho.pos_consulta' => [ 'nullable', 'boolean', ], 'coleta_exame_laboratorial.agendamentos' => [ 'present', 'array' ], 'registro_vacinacao.aplicacoes' => [ 'present', 'array', ], 'registro_vacinacao.atualizacoes' => [ 'present', 'array', ], 'procedimentos' => [ 'present', 'array', ], 'medicamentos' => [ 'present', 'array', ], 'medicamentos.*.id' => [ 'required', 'integer', Rule::exists(Material::class, 'id'), ], 'medicamentos.*.quantidade' => [ 'required', 'integer', ], ]; foreach (request()->procedimentos as $i => $procedimento) { $procedimentoModel = ProcedimentoSigtap::find($procedimento['procedimento_id']); $rules["procedimentos.{$i}.procedimento_id"] = [ 'required', 'integer', 'distinct', Rule::exists(ProcedimentoSigtap::class, 'id'), new OcupacaoSigtap($procedimentoModel,self::getCurrentLotacao()->ocupacao), ]; $rules["procedimentos.{$i}.material_id"] = [ 'nullable', 'integer', Rule::exists(Material::class, 'id'), ]; $rules["procedimentos.{$i}.automatico"] = [ 'required', 'boolean', ]; $rules["procedimentos.{$i}.quantidade"] = [ 'required', 'integer', new QuantidadeIsValidForProcedimento($procedimento['procedimento_id']), ]; $rules["procedimentos.{$i}.material_quantidade"] = [ 'nullable', 'integer', ]; $rules["procedimentos.{$i}.local_curativo"] = [ 'nullable', 'string', 'max:500', ]; } request()->validate($rules); RegistroVacinacaoService::validate([ 'paciente_id' => $fila->ambulatorioAtendimento->paciente->id, 'aplicacoes' => request()->registro_vacinacao['aplicacoes'], 'atualizacoes' => request()->registro_vacinacao['atualizacoes'], 'aprazamentos' => [] ]); } private static function storeFichaAtencaoBasica($preAtendimento) { try { PreAtendimentoAtencaoBasicaFichaService::store($preAtendimento); } catch (Exception $e) { throw new NaoPodeCriarFichaAtencaoBasicaException(); } } private static function savePaciente($paciente) { if (!is_null(request()->paciente['telefone_principal']['id'])) { CidadaoTelefone::find(request()->paciente['telefone_principal']['id']) ->update(request()->paciente['telefone_principal']); } if (!is_null(request()->dum)) { $paciente->dum()->updateOrCreate( ['paciente_id' => $paciente->id], ['data_ultima_menstruacao' => Carbon::createFromFormat('d/m/Y', request()->dum)] ); } if (!is_null(request()->ciap_id) && self::isIdadeGestacional($paciente)) { $ciap = Ciap::find(request()->ciap_id); $isGravidezNormal = collect(self::CIAPS_GRAVIDEZ_NORMAL)->contains($ciap->codigo ?? null); $isGravidezAltoRisco = collect(self::CIAPS_GRAVIDEZ_ALTO_RISCO)->contains($ciap->codigo ?? null); if (($isGravidezNormal || $isGravidezAltoRisco) && !$paciente->cidadao->fatoresRisco->contains(FatorRiscoEnum::GESTANTE)) { $paciente->cidadao->fatoresRisco()->attach(FatorRiscoEnum::GESTANTE); } } } private static function isIdadeGestacional($paciente) { if (!$paciente->cidadao->data_nascimento || !$paciente->cidadao->sexo_id) { return false; } $dataNascimento = new DateTime($paciente->cidadao->data_nascimento); $dataResponsavel = new DateTime(Carbon::now()->format('Y-m-d')); $idade = $dataNascimento->diff($dataResponsavel)->y; return $paciente->cidadao->sexo->id === Sexo::FEMININO && ($idade >= 9 && $idade <= 60); } private static function saveTestesRapidos($preAtendimento) { $testesRapidos = []; foreach (request()->testes_rapidos as $testeRapido) { $testesRapidos[$testeRapido['id']] = [ 'resultado' => $testeRapido['resultado'] ]; } $preAtendimento->testesRapidos()->sync($testesRapidos); } private static function saveAvaliacaoAntropometrica($preAtendimento) { if (self::hasData(collect(request()->antropometria))) { $preAtendimento->antropometria()->create(array_merge([ 'atendimento_id' => $preAtendimento->atendimento_id, ], request()->antropometria)); } } private static function saveSinaisVitais($preAtendimento) { if (self::hasData(collect(request()->sinal_vital))) { $preAtendimento->sinalVital()->create(array_merge([ 'atendimento_id' => $preAtendimento->atendimento_id, ], request()->sinal_vital)); } } private static function saveGlicemiaCapilar($preAtendimento) { if (self::hasData(collect(request()->glicemia_capilar))) { $preAtendimento->glicemiaCapilar()->create(array_merge([ 'atendimento_id' => $preAtendimento->atendimento_id, ], request()->glicemia_capilar)); } } 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 saveColetasExameLaboratorial($preAtendimento) { LancamentoColetaService::saveStatusExame( request()->coleta_exame_laboratorial['agendamentos'], ['pre_atendimento_id' => $preAtendimento->id] ); } private static function saveRegistrosVacinacao($preAtendimento) { RegistroVacinacaoService::storeRegistrosAplicacao( $preAtendimento->atendimento->paciente->id, collect(request()->registro_vacinacao['aplicacoes']), ['pre_atendimento_id' => $preAtendimento->id] ); RegistroVacinacaoService::storeRegistrosAtualizacao( $preAtendimento->atendimento->paciente->id, collect(request()->registro_vacinacao['atualizacoes']), ['pre_atendimento_id' => $preAtendimento->id] ); } private static function saveProcedimentos($preAtendimento) { $procedimentos = collect(); foreach (request()->procedimentos as $procedimento) { $procedimentoCriado = $preAtendimento->procedimentos()->create([ 'atendimento_id' => $preAtendimento->atendimento_id, 'procedimento_id' => $procedimento['procedimento_id'], 'quantidade' => $procedimento['quantidade'], 'automatico' => $procedimento['automatico'], 'ocupacao_id' => $preAtendimento->createdLotacao->ocupacao_id, 'especialidade_id' => null, 'usuario_id' => $preAtendimento->createdLotacao->usuario_id, 'local_curativo' => $procedimento['local_curativo'] ?? null, ]); 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' => $procedimentoCriado->id, 'saida_item_id' => $saidaItem->id, 'created_at' => now(), 'updated_at' => now(), ]); } } } $procedimentos->push($procedimentoCriado); } } private static function saveMedicamentos($preAtendimento) { $medicamentos = collect(request()->medicamentos)->map(function($medicamento) use ($preAtendimento) { $itemData = [ 'material_id' => $medicamento['id'], 'quantidade' => $medicamento['quantidade'], 'escolheu_entrada_item_manualmente' => $medicamento['escolheu_entrada_item_manualmente'], 'entrada_itens' => $medicamento['entrada_itens'], ]; $saidaItem = AlmoxarifadoService::saveSaidaDeDispensacaoDoAmbulatorio($itemData); return [ 'atendimento_id' => $preAtendimento->atendimento_id, 'saida_item_id' => $saidaItem->id ]; }); $preAtendimento->medicamentos()->createMany($medicamentos); } public static function getPrintData($id) { $preAtendimento = AtendimentoPreAtendimento::findOrFail($id); $unideMedidaQuilogramasSigla = UnidadeMedida::findOrFail(UnidadeMedidaEnum::QUILOGRAMAS)->sigla; $unideMedidaCentimetrosSigla = UnidadeMedida::findOrFail(UnidadeMedidaEnum::CENTIMETROS)->sigla; return [ 'dataHora' => $preAtendimento->created_at->format('d/m/Y à\s H:i'), 'paciente' => (object) self::getPacienteData($preAtendimento->atendimento->paciente), 'isDemandaEspontanea' => isset($preAtendimento->atendimento->is_demanda_espontanea), 'ciapDescricao' => is_null($preAtendimento->ciap_id) ? null : "{$preAtendimento->ciap->codigo} - {$preAtendimento->ciap->descricao}", 'motivoAtendimento' => $preAtendimento->motivo_atendimento, 'antropometria' => (object) [ 'peso' => $preAtendimento->antropometria->peso ?? null, 'peso_unidade_medida_sigla' => $unideMedidaQuilogramasSigla, 'altura' => $preAtendimento->antropometria->altura ?? null, 'altura_unidade_medida_sigla' => $unideMedidaCentimetrosSigla, 'imc' => isset($preAtendimento->antropometria->peso) && isset($preAtendimento->antropometria->altura) ? (object) ImcService::calculate( UnidadeMedidaEnum::QUILOGRAMAS, $preAtendimento->antropometria->peso, UnidadeMedidaEnum::CENTIMETROS, $preAtendimento->antropometria->altura ) : (object) [ 'imc' => null, 'classificacao' => null, 'grau_obesidade' => null, ], 'perimetro_cefalico' => $preAtendimento->antropometria->perimetro_cefalico ?? null, 'perimetro_cefalico_unidade_medida_sigla' => $unideMedidaCentimetrosSigla, 'circunferencia_abdominal' => $preAtendimento->antropometria->circunferencia_abdominal ?? null, 'circunferencia_abdominal_unidade_medida_sigla' => $unideMedidaCentimetrosSigla, 'perimetro_panturrilha' => $preAtendimento->antropometria->perimetro_panturrilha ?? null, 'perimetro_panturrilha_unidade_medida_sigla' => $unideMedidaCentimetrosSigla, ], 'sinalVital' => (object) [ 'pressao_arterial' => $preAtendimento->sinalVital->pressao_arterial ?? null, 'pressao_arterial_unidade_medida_sigla' => UnidadeMedida::findOrFail( UnidadeMedidaEnum::MILIMETROS_DE_MERCURIO)->sigla, 'frequencia_respiratoria' => $preAtendimento->sinalVital->frequencia_respiratoria ?? null, 'frequencia_respiratoria_unidade_medida_sigla' => UnidadeMedida::findOrFail( UnidadeMedidaEnum::MOVIMENTOS_POR_MINUTO)->sigla, 'frequencia_cardiaca' => $preAtendimento->sinalVital->frequencia_cardiaca ?? null, 'frequencia_cardiaca_unidade_medida_sigla' => UnidadeMedida::findOrFail( UnidadeMedidaEnum::BATIMENTOS_POR_MINUTO)->sigla, 'temperatura' => $preAtendimento->sinalVital->temperatura ?? null, 'temperatura_unidade_medida_sigla' => UnidadeMedida::findOrFail( UnidadeMedidaEnum::CELSIUS)->sigla, 'saturacao_o2' => $preAtendimento->sinalVital->saturacao_o2 ?? null, 'saturacao_o2_unidade_medida_sigla' => UnidadeMedida::findOrFail( UnidadeMedidaEnum::PORCENTAGEM)->sigla, ], 'glicemiaCapilar' => (object) [ 'valor' => $preAtendimento->glicemiaCapilar->valor ?? null, 'glicemia_capilar_unidade_medida_sigla' => UnidadeMedida::findOrFail( UnidadeMedidaEnum::MILIGRAMAS_POR_DECILITRO)->sigla, 'momento_coleta_nome' => $preAtendimento->glicemiaCapilar->momentoColeta->nome ?? null, ], 'procedimentos' => $preAtendimento->procedimentos->map(fn ($procedimento) => (object) [ 'codigo' => $procedimento->procedimento->codigo, 'nome' => $procedimento->procedimento->nome, 'quantidade' => $procedimento->quantidade, 'automatico' => $procedimento->automatico, 'local_curativo' => $procedimento->local_curativo, 'material_descricao_completa' => $procedimento->almoxarifadoSaidaItem->material->descricaoCompleta ?? null, 'material_quantidade' => $procedimento->almoxarifadoSaidaItem->quantidade ?? null, ]), 'medicamentos' => $preAtendimento->medicamentos->map(fn ($medicamento) => (object) [ 'descricao_completa' => $medicamento->almoxarifadoSaidaItem->material->descricaoCompleta ?? null, 'quantidade' => $medicamento->almoxarifadoSaidaItem->quantidade, ]), 'classificacaoRiscoNome' => $preAtendimento->classificacaoRisco->nome ?? null, 'desfecho' => $preAtendimento->paciente_liberado ? Desfecho::PACIENTE_LIBERADO : ($preAtendimento->paciente_mantido_fila ? Desfecho::MANTER_NA_FILA : Desfecho::PACIENTE_ENCAMINHADO), 'informacoesAdministrativas' => (object) [ 'usuario_nome' => $preAtendimento->createdLotacao->usuario->cidadao->nome, 'ocupacao_descricao' => $preAtendimento->createdLotacao->ocupacao->codigo . ' - ' . $preAtendimento->createdLotacao->ocupacao->nome, 'documento' => $preAtendimento->createdLotacao->usuario->registro_tipo_id ? ($preAtendimento->createdLotacao->usuario->registro_tipo_id === TipoRegistroUsuario::OUTRO ? $preAtendimento->createdLotacao->usuario->registro_tipo_outro : $preAtendimento->createdLotacao->usuario->registroTipo->sigla ) . ": {$preAtendimento->createdLotacao->usuario->registro_numero}" : 'Conselho profissional: NÃO INFORMADO', ], ]; } private static function faturaProcedimentoRaas() { return ParametrizacaoInfraestrutura::where('infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id) ->pluck('fatura_procedimento_raas') ->first(); } private static function podeAlterarClassificacaoRisco() { return collect([ OcupacaoEnum::ENFERMEIRO, OcupacaoEnum::ENFERMEIRO_ESTOMATERAPEUTA, OcupacaoEnum::ENFERMEIRO_AUDITOR, OcupacaoEnum::ENFERMEIRO_BORDO, OcupacaoEnum::ENFERMEIRO_CENTRO_CIRURGICO, OcupacaoEnum::ENFERMEIRO_TERAPIA_INTENSIVA, OcupacaoEnum::ENFERMEIRO_TRABALHO, OcupacaoEnum::ENFERMEIRO_NEFROLOGISTA, OcupacaoEnum::ENFERMEIRO_NEONATOLOGISTA, OcupacaoEnum::ENFERMEIRO_OBSTETRICO, OcupacaoEnum::ENFERMEIRO_PSIQUIATRICO, OcupacaoEnum::ENFERMEIRO_PUERICULTOR_PEDIATRICO, OcupacaoEnum::ENFERMEIRO_SANITARISTA, OcupacaoEnum::ENFERMEIRO_ESTRATEGIA_SAUDE_FAMILIA, ])->contains(self::getCurrentLotacao()->ocupacao->codigo); } private static function podeFinalizarAtendimento($fila) { return $fila->ambulatorioAtendimento->is_demanda_espontanea || $fila->ambulatorioAtendimento->agendamento->jornada->lotacao_id === self::getCurrentLotacao()->id; } 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 getDemandaTipos() { return [ ['value' => DemandaTipo::AGENDADA, 'text' => 'Demanda agendada'], ['value' => DemandaTipo::ESPONTANEA, 'text' => 'Demanda espontânea'], ]; } }