get('origem')) { case 'agendamento': { return [ 'model' => [ 'agendamentos' => self::getAgendamentos(request()->all()), ], ]; } case 'atendimento': { return [ 'model' => [ 'atendimentos' => self::getAtendimentos(request()->all()), ], ]; } case 'atendido-evadido': { return [ 'model' => [ 'atendidos_evadidos' => self::getAtendidosEvadidos(request()->all()), ], ]; } default: { $today = Carbon::today()->format('d/m/Y'); return [ 'additionals' => [ 'data_atual' => $today, 'possui_atendimento_retroativo_nao_finalizado' => self::possuiAtendimentoRetroativoNaoFinalizado(), ], 'model' => [ 'data' => $today, 'agendamentos' => self::getAgendamentos(['data' => $today]), 'atendimentos' => self::getAtendimentos(), 'atendidos_evadidos' => self::getAtendidosEvadidos(), ], ]; } } } private static function possuiAtendimentoRetroativoNaoFinalizado() { $exibeMensagemAtendimentoRetroativoNaoFinalizado = ParametrizacaoAtendimento::first() ->exibe_mensagem_atendimento_retroativo_nao_finalizado ?? false; if (!$exibeMensagemAtendimentoRetroativoNaoFinalizado) { return false; } return DB::table('ambulatorio_atendimento as atendimento') ->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'atendimento.created_centro_custo_id') ->leftJoin('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id') ->leftJoin('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id') ->leftJoin('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id') ->where('centro_custo.infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id) ->whereNull('atendimento.finalizado_em') ->where(fn ($q) => $q ->whereDate('jornada.data', '<', Carbon::today()) ->orWhereDate('demanda_espontanea.data', '<', Carbon::today()) ) ->exists(); } public static function getAgendamentos($params = []) { $params['data'] = isset($params['data']) ? Carbon::createFromFormat('d/m/Y', $params['data'])->startOfDay() : null; $hoje = Carbon::today()->startOfDay(); if ($params['data'] && $params['data']->gt($hoje)) { return collect(); } $agendamentos = self::getAgendamentosInfraestruturaLogada($params) ->unionAll(self::getAgendamentosInfraestruturaVinculadaComALogada($params)) ->get(); $parametrizacao = ParametrizacaoAgendamento::first(); $agendamentos->each(function ($agendamento) use ($parametrizacao) { $agendamento->cns_valido = Cns::isValid($agendamento->paciente_cns); $agendamento->avisa_cns_provisorio = ($parametrizacao->avisa_cns_provisorio ?? false) && Str::startsWith($agendamento->paciente_cns, [5, 7, 8, 9]); $tempoAtrasoHoras = floor($agendamento->tempo_atraso / 60); $tempoAtrasoMinutos = $agendamento->tempo_atraso % 60; $agendamento->tempo_atraso = $agendamento->tempo_atraso > 0 ? "{$tempoAtrasoHoras}h {$tempoAtrasoMinutos}m" : null; $agendamento->pode_reagendar = is_null($agendamento->regulacao_solicitacao_id); $agendamento->pode_desfazer_falta = is_null($agendamento->regulacao_solicitacao_id); $agendamento->paciente_cpf = MaskUtil::getCpfMasked($agendamento->paciente_cpf); $agendamento->paciente_cns = MaskUtil::getCnsMasked($agendamento->paciente_cns); $agendamento->paciente_idade_anos = self::getIdade($agendamento->paciente_data_nascimento); unset($agendamento->regulacao_solicitacao_id); }); return $agendamentos; } private static function getAgendamentosInfraestruturaLogada($params) { $parametrizacao = ParametrizacaoAgendamento::first(); $bloqueiaPacienteTemporario = (int) $parametrizacao->bloqueia_paciente_temporario ?? false; $query = DB::table('ambulatorio_agendamento as agendamento') ->join( 'cadastro_paciente as paciente', 'paciente.id', 'agendamento.paciente_id' ) ->join( 'cadastro_cidadao as paciente_cidadao', 'paciente_cidadao.id', 'paciente.cidadao_id' ) ->join( 'ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id' ) ->join( 'cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id' ) ->join( 'cadastro_usuario as usuario', 'usuario.id', 'lotacao.usuario_id' ) ->join( 'cadastro_cidadao as usuario_cidadao', 'usuario_cidadao.id', 'usuario.cidadao_id' ) ->join( 'cadastro_especialidade as especialidade', 'especialidade.id', 'jornada.especialidade_id' ) ->leftJoin( 'cadastro_sexo as paciente_cidadao_sexo', 'paciente_cidadao_sexo.id', 'paciente_cidadao.sexo_id' ) ->whereIn('agendamento.status_id', [ AgendamentoStatus::AGENDADO, AgendamentoStatus::FALTA_DO_PACIENTE, ]) ->when(isset($params['data']), fn ($q) => $q->whereDate('jornada.data', $params['data']), fn ($q) => $q->whereDate('jornada.data', '<=', Carbon::today()) ) ->where('lotacao.infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id) ->whereNotExists(fn ($q) => $q ->select(DB::raw(1)) ->from('ambulatorio_atendimento as atendimento') ->whereColumn('atendimento.agendamento_id', 'agendamento.id') ) ->select([ 'agendamento.id', 'agendamento.observacao', 'agendamento.status_id', 'agendamento.regulacao_solicitacao_id', DB::raw("TIMESTAMP(jornada.data, agendamento.horario) as data_horario"), DB::raw("TIMESTAMPDIFF(MINUTE, TIMESTAMP(jornada.data, agendamento.horario), CURRENT_TIMESTAMP) as tempo_atraso"), 'paciente.id as paciente_id', 'paciente_cidadao.nome as paciente_nome', 'paciente_cidadao.nome_social as paciente_nome_social', 'paciente_cidadao.preferencia_nome_id as paciente_preferencia_nome_id', DB::raw("DATE_FORMAT(paciente_cidadao.data_nascimento, '%d/%m/%Y') as paciente_data_nascimento"), 'paciente_cidadao.cpf as paciente_cpf', 'paciente_cidadao.cns as paciente_cns', 'paciente_cidadao.nome_mae as paciente_nome_mae', DB::raw("LPAD(paciente.prontuario, 6, '0') as paciente_prontuario"), 'paciente_cidadao_sexo.descricao as paciente_sexo_descricao', 'usuario_cidadao.nome as usuario_nome', 'especialidade.nome as especialidade_nome', DB::raw(" CASE WHEN {$bloqueiaPacienteTemporario} = 1 AND EXISTS ( SELECT 1 FROM cadastro_paciente as p WHERE p.id = agendamento.paciente_id AND CURRENT_DATE > p.validade_fim ) THEN 1 ELSE 0 END as cadastro_paciente_vencido "), DB::raw("IF (jornada.data < CURRENT_DATE, 0, 1) as permite_confirmar_chegada") ]); return $query; } private static function getAgendamentosInfraestruturaVinculadaComALogada($params) { $parametrizacao = ParametrizacaoAgendamento::first(); $bloqueiaPacienteTemporario = (int) $parametrizacao->bloqueia_paciente_temporario ?? false; $query = DB::table('ambulatorio_agendamento as agendamento') ->join( 'cadastro_paciente as paciente', 'paciente.id', 'agendamento.paciente_id' ) ->join( 'cadastro_cidadao as paciente_cidadao', 'paciente_cidadao.id', 'paciente.cidadao_id' ) ->join( 'ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id' ) ->join( 'cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id' ) ->join( 'cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id' ) ->join( 'cadastro_usuario as usuario', 'usuario.id', 'lotacao.usuario_id' ) ->join( 'cadastro_cidadao as usuario_cidadao', 'usuario_cidadao.id', 'usuario.cidadao_id' ) ->join( 'cadastro_especialidade as especialidade', 'especialidade.id', 'jornada.especialidade_id' ) ->leftJoin( 'cadastro_sexo as paciente_cidadao_sexo', 'paciente_cidadao_sexo.id', 'paciente_cidadao.sexo_id' ) ->whereIn('agendamento.status_id', [ AgendamentoStatus::AGENDADO, AgendamentoStatus::FALTA_DO_PACIENTE, ]) ->when(isset($params['data']), fn ($q) => $q->whereDate('jornada.data', $params['data']), fn ($q) => $q->whereDate('jornada.data', '<=', Carbon::today()) ) ->where('infraestrutura.infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id) ->whereNotExists(fn ($q) => $q ->select(DB::raw(1)) ->from('ambulatorio_atendimento as atendimento') ->whereColumn('atendimento.agendamento_id', 'agendamento.id') ) ->select([ 'agendamento.id', 'agendamento.observacao', 'agendamento.status_id', 'agendamento.regulacao_solicitacao_id', DB::raw("TIMESTAMP(jornada.data, agendamento.horario) as data_horario"), DB::raw("TIMESTAMPDIFF(MINUTE, TIMESTAMP(jornada.data, agendamento.horario), CURRENT_TIMESTAMP) as tempo_atraso"), 'paciente.id as paciente_id', 'paciente_cidadao.nome as paciente_nome', 'paciente_cidadao.nome_social as paciente_nome_social', 'paciente_cidadao.preferencia_nome_id as paciente_preferencia_nome_id', DB::raw("DATE_FORMAT(paciente_cidadao.data_nascimento, '%d/%m/%Y') as paciente_data_nascimento"), 'paciente_cidadao.cpf as paciente_cpf', 'paciente_cidadao.cns as paciente_cns', 'paciente_cidadao.nome_mae as paciente_nome_mae', DB::raw("LPAD(paciente.prontuario, 6, '0') as paciente_prontuario"), 'paciente_cidadao_sexo.descricao as paciente_sexo_descricao', 'usuario_cidadao.nome as usuario_nome', 'especialidade.nome as especialidade_nome', DB::raw(" CASE WHEN {$bloqueiaPacienteTemporario} = 1 AND EXISTS ( SELECT 1 FROM cadastro_paciente as p WHERE p.id = agendamento.paciente_id AND CURRENT_DATE > p.validade_fim ) THEN 1 ELSE 0 END as cadastro_paciente_vencido "), DB::raw("IF (jornada.data < CURRENT_DATE, 0, 1) as permite_confirmar_chegada") ]); return $query; } public static function getAtendimentos($params = []) { $params['data'] = isset($params['data']) ? Carbon::createFromFormat('d/m/Y', $params['data'])->startOfDay() : null; $hoje = Carbon::today()->startOfDay(); if ($params['data'] && $params['data']->gt($hoje)) { return collect(); } $filas = DB::table('ambulatorio_atendimento as atendimento') ->leftJoin( 'painel_senha_fila as fila', 'fila.id', 'atendimento.fila_id' ) ->leftJoin( 'painel_senha_status as fila_status', 'fila_status.id', 'fila.status_id' ) ->leftJoin( 'cadastro_centro_custo AS centro_custo', 'centro_custo.id', 'fila.centro_custo_id' ) ->leftJoin( 'cadastro_setor AS setor', 'setor.id', 'centro_custo.setor_id' ) ->leftJoin( 'painel_senha_opcao_entrada as opcao_entrada', 'opcao_entrada.id', 'fila.opcao_entrada_id' ) ->leftJoin( 'ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id' ) ->leftJoin( 'ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id' ) ->leftJoin( 'cadastro_lotacao as jornada_lotacao', 'jornada_lotacao.id', 'jornada.lotacao_id' ) ->leftJoin( 'ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id' ) ->leftJoin( 'cadastro_paciente as paciente', 'paciente.id', DB::raw("COALESCE(demanda_espontanea.paciente_id, agendamento.paciente_id)") ) ->leftJoin( 'cadastro_cidadao as paciente_cidadao', 'paciente_cidadao.id', 'paciente.cidadao_id' ) ->leftJoin( 'cadastro_sexo as paciente_cidadao_sexo', 'paciente_cidadao_sexo.id', 'paciente_cidadao.sexo_id' ) ->leftJoin( 'cadastro_usuario as usuario', 'usuario.id', DB::raw("COALESCE(demanda_espontanea.usuario_id, jornada_lotacao.usuario_id)") ) ->leftJoin( 'cadastro_cidadao as usuario_cidadao', 'usuario_cidadao.id', 'usuario.cidadao_id' ) ->leftJoin( 'cadastro_especialidade as especialidade', 'especialidade.id', DB::raw("COALESCE(demanda_espontanea.especialidade_id, jornada.especialidade_id)") ) ->whereNull('fila.deleted_at') ->where('fila.finalizado', false) ->where('opcao_entrada.modulo_id', ModuloService::getId(Modulo::AMBULATORIO)) ->where('centro_custo.infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id) ->select(DB::raw("atendimento.id")) ->select(DB::raw(" fila.id as fila_id, atendimento.id, fila_status.id as fila_status_id, CONCAT(opcao_entrada.sigla, fila.senha) as senha, paciente_cidadao.nome as paciente_nome, paciente_cidadao.nome_social as paciente_nome_social, paciente_cidadao.preferencia_nome_id as paciente_preferencia_nome_id, DATE_FORMAT(paciente_cidadao.data_nascimento, '%d/%m/%Y') as paciente_data_nascimento, paciente_cidadao.cpf as paciente_cpf, paciente_cidadao.cns as paciente_cns, paciente_cidadao.nome_mae as paciente_nome_mae, LPAD(paciente.prontuario, 6, '0') as paciente_prontuario, paciente_cidadao_sexo.descricao as paciente_sexo_descricao, usuario_cidadao.nome as usuario_nome, especialidade.nome as especialidade_nome, DATE_FORMAT(agendamento.horario, '%H:%i') as horario_agendado, DATE_FORMAT(fila.created_at, '%H:%i') as horario_chegada, setor.nome as setor_nome, fila_status.nome as fila_status_nome, jornada.data as data_atendimento, DATE(fila.created_at) as data_fila, atendimento.demanda_espontanea_id ")) ->addSelect([ 'has_pre_atendimento' => function ($query) { $query->select(DB::raw(1)) ->from('ambulatorio_atendimento_pre_atendimento as pre_atendimento') ->whereColumn('pre_atendimento.atendimento_id', 'atendimento.id') ->limit(1); }, 'has_soap' => function ($query) { $query->select(DB::raw(1)) ->from('ambulatorio_atendimento_soap as soap') ->whereColumn('soap.atendimento_id', 'atendimento.id') ->where('soap.is_rascunho', false) ->limit(1); }, 'has_declaracao_comparecimento' => function ($query) { $query->select(DB::raw(1)) ->from('ambulatorio_atendimento_declaracao_comparecimento as declaracao_comparecimento') ->whereColumn('declaracao_comparecimento.atendimento_id', 'atendimento.id') ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_atendimento_soap as soap') ->whereColumn('soap.id', 'declaracao_comparecimento.soap_id') ->where('soap.is_rascunho', false) ) ->orWhereNotExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_atendimento_soap as soap') ->whereColumn('soap.id', 'declaracao_comparecimento.soap_id') ) ) ->limit(1); }, ]) ->get(); if (isset($params['data'])) { $params['data'] = explode(' ', $params['data'])[0]; }else{ $params['data'] = explode(' ', Carbon::today())[0]; } $filasFiltro = $filas->filter(function ($fila) use ($params) { $retroativo = $fila->data_atendimento < $fila->data_fila; return ($retroativo && $fila->data_atendimento == $params['data']) || (!$retroativo && $fila->data_fila == $params['data']) || ($fila->demanda_espontanea_id && $fila->data_fila == $params['data']); }); $filasFiltro = $filasFiltro->values(); $filasFiltro = $filasFiltro->map(function ($fila) { $fila->paciente_cpf = MaskUtil::getCpfMasked($fila->paciente_cpf); $fila->paciente_cns = MaskUtil::getCnsMasked($fila->paciente_cns); $fila->paciente_idade_anos = self::getIdade($fila->paciente_data_nascimento); $fila->pode_desfazer_chegada = !$fila->has_pre_atendimento && !$fila->has_soap && !$fila->has_declaracao_comparecimento; $fila->tempo_espera = FilaService::getTempoEspera($fila->fila_id); unset($fila->has_pre_atendimento, $fila->has_soap, $fila->has_declaracao_comparecimento, $fila->fila_id); return $fila; }); return $filasFiltro; } public static function getAtendidosEvadidos($params = []) { $params['data'] = isset($params['data']) ? Carbon::createFromFormat('d/m/Y', $params['data'])->startOfDay() : null; $hoje = Carbon::today()->startOfDay(); if ($params['data'] && $params['data']->gt($hoje)) { return collect(); } $filas = DB::table('ambulatorio_atendimento as atendimento') ->leftJoin( 'painel_senha_fila as fila', 'fila.id', 'atendimento.fila_id' ) ->leftJoin( 'cadastro_centro_custo AS centro_custo', 'centro_custo.id', 'fila.centro_custo_id' ) ->leftJoin( 'painel_senha_opcao_entrada as opcao_entrada', 'opcao_entrada.id', 'fila.opcao_entrada_id' ) ->leftJoin( 'ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id' ) ->leftJoin( 'ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id' ) ->leftJoin( 'cadastro_lotacao as jornada_lotacao', 'jornada_lotacao.id', 'jornada.lotacao_id' ) ->leftJoin( 'ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id' ) ->leftJoin( 'cadastro_paciente as paciente', 'paciente.id', DB::raw("COALESCE(demanda_espontanea.paciente_id, agendamento.paciente_id)") ) ->leftJoin( 'cadastro_cidadao as paciente_cidadao', 'paciente_cidadao.id', 'paciente.cidadao_id' ) ->leftJoin( 'cadastro_sexo as paciente_cidadao_sexo', 'paciente_cidadao_sexo.id', 'paciente_cidadao.sexo_id' ) ->leftJoin( 'cadastro_lotacao as demanda_lotacao', 'demanda_lotacao.id', 'atendimento.finalizado_lotacao_id' ) ->leftJoin( 'cadastro_usuario as usuario', 'usuario.id', DB::raw("COALESCE(jornada_lotacao.usuario_id, demanda_lotacao.usuario_id)") ) ->leftJoin( 'cadastro_cidadao as usuario_cidadao', 'usuario_cidadao.id', 'usuario.cidadao_id' ) ->leftJoin( 'cadastro_especialidade as especialidade', 'especialidade.id', DB::raw("COALESCE(demanda_espontanea.especialidade_id, jornada.especialidade_id)") ) ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereNull('atendimento.fila_id') ->whereNotNull('atendimento.finalizado_em') ->when(isset($params['data']), fn ($q) => $q->whereDate('atendimento.created_at', $params['data']), fn ($q) => $q->whereDate('atendimento.created_at', Carbon::today()) ) ) ->orWhere(fn ($q) => $q ->whereNotNull('atendimento.fila_id') ->whereNull('fila.deleted_at') ->where('fila.finalizado', true) ->when(isset($params['data']), fn ($q) => $q->whereDate('fila.created_at', $params['data']), fn ($q) => $q->whereDate('fila.created_at', Carbon::today()) ) ->where('opcao_entrada.modulo_id', ModuloService::getId(Modulo::AMBULATORIO)) ) ) ->where('centro_custo.infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id) ->select(DB::raw(" fila.id as fila_id, atendimento.id as atendimento_id, CONCAT(opcao_entrada.sigla, fila.senha) as senha, paciente_cidadao.nome as paciente_nome, paciente_cidadao.nome_social as paciente_nome_social, paciente_cidadao.preferencia_nome_id as paciente_preferencia_nome_id, DATE_FORMAT(paciente_cidadao.data_nascimento, '%d/%m/%Y') as paciente_data_nascimento, paciente_cidadao.cpf as paciente_cpf, paciente_cidadao.cns as paciente_cns, paciente_cidadao.nome_mae as paciente_nome_mae, LPAD(paciente.prontuario, 6, '0') as paciente_prontuario, paciente_cidadao_sexo.descricao as paciente_sexo_descricao, usuario_cidadao.nome as usuario_nome, especialidade.nome as especialidade_nome, DATE_FORMAT(agendamento.horario, '%H:%i') as horario_agendado, DATE_FORMAT(fila.created_at, '%H:%i') as horario_chegada, fila.evadido, fila.motivo_evasao ")) ->get(); $filas->each(function ($fila) { $fila->paciente_cpf = MaskUtil::getCpfMasked($fila->paciente_cpf); $fila->paciente_cns = MaskUtil::getCnsMasked($fila->paciente_cns); $fila->paciente_idade_anos = self::getIdade($fila->paciente_data_nascimento); $fila->tempo_espera = FilaService::getTempoEspera($fila->fila_id); }); return $filas; } private static function getIdade($dataNascimento) { if (is_null($dataNascimento)) { return null; } $idade = AgeService::getAge(Carbon::createFromFormat('d/m/Y', $dataNascimento)); $yearsText = $idade->years > 1 ? 'anos' : 'ano'; return "{$idade->years} {$yearsText}"; } public static function create() { $params = (object) request()->all(); switch (request()->origem) { case 'declaracao-comparecimento': { return self::getDeclaracaoComparecimentoCreate($params); } case 'chegada': { return self::getChegadaCreate(); } } } private static function getDeclaracaoComparecimentoCreate($params) { $params->atendimento = Atendimento::findOrFail($params->atendimento_id); return [ 'form' => self::getDeclaracaoComparecimentoFormData($params), 'model' => self::getDeclaracaoComparecimentoModelData($params), ]; } private static function getDeclaracaoComparecimentoFormData($params) { return [ 'paciente' => [ 'nome' => $params->atendimento->paciente->cidadao->nome, 'nome_social' => $params->atendimento->paciente->cidadao->nome_social, 'cpf' => MaskUtil::getCpfMasked($params->atendimento->paciente->cidadao->cpf), 'cns' => MaskUtil::getCnsMasked($params->atendimento->paciente->cidadao->cns), ], 'turnos' => Turno::orderBy('id')->get(['id', 'nome']), ]; } private static function getDeclaracaoComparecimentoModelData($params) { return [ 'turno_id' => null, 'entrada' => $params->atendimento->fila->created_at->format('H:i'), 'saida' => Carbon::now()->format('H:i'), 'nome_acompanhante' => null, ]; } private static function getChegadaCreate() { return [ 'form' => self::getChegadaFormData(), 'model' => self::getChegadaModelData(), ]; } private static function getChegadaFormData() { return [ 'opcoes_entrada' => self::getOpcoesEntrada(), 'prioridades' => self::getPrioridades(), 'servicos' => self::getServicos(), 'centros_custo_encaminhamento' => self::getCentrosCustoEncaminhamento(), ]; } private static function getOpcoesEntrada() { return OpcaoEntrada::where('centro_custo_id', self::getCurrentCentroCusto()->id) ->where('modulo_id', ModuloService::getId(Modulo::AMBULATORIO)) ->orderBy('nome') ->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', 'nome', 'tipo_id']); } 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::ENFERMAGEM, SetorTipo::CONSULTORIO ]) ) ) ->get() ->map(fn ($encaminhamento) => [ 'id' => $encaminhamento->centroCustoPara->id, 'setor_nome' => $encaminhamento->centroCustoPara->setor->nome, ]); } private static function getChegadaModelData() { return [ 'opcao_entrada_id' => null, 'prioridade_id' => null, 'servicos' => [], 'centro_custo_encaminhamento_id' => null, ]; } public static function store() { switch (request()->origem) { case 'declaracao-comparecimento': { return self::storeDeclaracaoComparecimento(); } case 'chegada': { return self::storeChegada(); } } } private static function storeDeclaracaoComparecimento() { self::validateStoreDeclaracaoComparecimento(); $declaracaoComparecimento = new AtendimentoDeclaracaoComparecimento(); DB::transaction(function () use ($declaracaoComparecimento) { if (is_null(request()->turno_id)) { $declaracaoComparecimento->fill( request()->only(['atendimento_id', 'nome_acompanhante', 'motivo_comparecimento', 'entrada', 'saida']) ); } else { $declaracaoComparecimento->fill( request()->only(['atendimento_id', 'nome_acompanhante', 'motivo_comparecimento', 'turno_id']) ); } $declaracaoComparecimento->pre_atendimento_id = request()->pre_atendimento_id ?? null; $declaracaoComparecimento->save(); }); return $declaracaoComparecimento->fresh(); } private static function validateStoreDeclaracaoComparecimento() { request()->validate([ 'atendimento_id' => [ 'required', 'integer', Rule::exists(Atendimento::class, 'id'), ], 'pre_atendimento_id' => [ 'nullable', 'integer', Rule::exists(AtendimentoPreAtendimento::class, 'id'), ], 'nome_acompanhante' => [ 'nullable', 'string', 'max:150', ], 'motivo_comparecimento' => [ 'nullable', 'string', 'max:1500', ], 'turno_id' => [ 'nullable', 'integer', Rule::exists(Turno::class, 'id'), ], 'entrada' => [ 'nullable', 'required_without:turno_id', 'date_format:H:i', ], 'saida' => [ 'nullable', 'required_without:turno_id', 'date_format:H:i', ], ]); } public static function getDeclaracaoComparecimentoPrintData($id) { $declaracaoComparecimento = AtendimentoDeclaracaoComparecimento::findOrFail($id); $paciente = $declaracaoComparecimento->atendimento->paciente; $lotacao = $declaracaoComparecimento->createdLotacao; return [ 'paciente' => [ 'nome' => $paciente->cidadao->nome, 'nome_social' => $paciente->cidadao->nome_social, ], 'nome_acompanhante' => $declaracaoComparecimento->nome_acompanhante, 'motivo_comparecimento' => $declaracaoComparecimento->motivo_comparecimento, 'data' => $declaracaoComparecimento->created_at->format('d/m/Y'), 'entrada' => is_null($declaracaoComparecimento->turno_id) ? $declaracaoComparecimento->entrada->format('H:i') : null, 'saida' => is_null($declaracaoComparecimento->turno_id) ? $declaracaoComparecimento->saida->format('H:i') : null, 'unidade' => $declaracaoComparecimento->createdCentroCusto->infraestrutura->unidade->nome_fantasia, 'infraestrutura' => $declaracaoComparecimento->createdCentroCusto->infraestrutura->nome, 'turno' => is_null($declaracaoComparecimento->turno_id) ? null : Str::lower($declaracaoComparecimento->turno->nome), 'informacoes_administrativas' => [ 'usuario_nome' => $lotacao->usuario->cidadao->nome, 'ocupacao_descricao' => $lotacao->ocupacao->codigo . ' - ' . $lotacao->ocupacao->nome, 'documento' => $lotacao->usuario->registro_tipo_id ? ($lotacao->usuario->registro_tipo_id === TipoRegistroUsuario::OUTRO ? $lotacao->usuario->registro_tipo_outro : $lotacao->usuario->registroTipo->sigla ) . ": {$lotacao->usuario->registro_numero}" : 'Conselho profissional: NÃO INFORMADO', ], ]; } private static function storeChegada() { self::validateStoreChegada(); $atendimento = new Atendimento(); DB::transaction(function () use ($atendimento) { $agendamento = Agendamento::findOrFail(request()->agendamento_id); $fila = FilaService::store((object) array_merge( request()->only(['opcao_entrada_id', 'prioridade_id']), [ 'paciente_id' => $agendamento->paciente_id, 'centro_custo_id' => self::getCurrentCentroCusto()->id, ] )); $atendimento->fill([ 'fila_id' => $fila->id, 'paciente_id' => $agendamento->paciente_id, 'agendamento_id' => $agendamento->id, ]); $atendimento->save(); $atendimento->servicos()->sync(request()->servicos); FilaService::forward($fila->id, request()->centro_custo_encaminhamento_id); }); return $atendimento->fresh(); } private static function validateStoreChegada() { request()->validate([ 'agendamento_id' => [ 'required', 'integer', Rule::exists(Agendamento::class, 'id'), ], 'opcao_entrada_id' => [ 'required', 'integer', Rule::exists(OpcaoEntrada::class, 'id'), ], 'prioridade_id' => [ 'nullable', Rule::requiredIf(fn () => OpcaoEntrada::find(request()->opcao_entrada_id) ->prioridade_obrigatoria ?? false ), Rule::exists(Prioridade::class, 'id'), ], 'servicos' => [ 'present', 'array' ], 'servicos.*' => [ 'required', 'integer', Rule::exists(Servico::class, 'id'), ], 'centro_custo_encaminhamento_id' => [ 'required', 'integer', Rule::in(self::getCentrosCustoEncaminhamento()->pluck('id')), ], ]); } }