select([ 'cadastro_cidadao.caracteristicas_fisicas', 'cadastro_cidadao.nome AS paciente_nome', 'cadastro_cidadao.preferencia_nome_id AS preferencia_nome_id', 'cadastro_cidadao.nome_social AS nome_social', 'cadastro_paciente.prontuario', 'cadastro_paciente.sequencial_desconhecido', 'pronto_atendimento_faa.id as faa_id', 'pronto_atendimento_faa.numero as faa_numero', 'pronto_atendimento_faa.deleted_at AS faa_cancelada', 'pronto_atendimento_atendimento_procedimento.atendimento_id as procedimento_id', 'cadastro_cidadao.nome AS procedimento', DB::raw('DATE_FORMAT(pronto_atendimento_atendimento_recepcao.atendido_em, "%H:%i") AS hora'), DB::raw('DATE_FORMAT(pronto_atendimento_atendimento_recepcao.atendido_em, "%d/%m/%Y") AS data'), DB::raw(' ( CASE WHEN cadastro_cidadao.nome_mae IS NULL THEN "Não informado" ELSE cadastro_cidadao.nome_mae END ) as nome_mae' ), DB::raw(' ( CASE WHEN DATE_FORMAT(cadastro_cidadao.data_nascimento, "%d/%m/%Y") IS NULL THEN "Não informada" ELSE DATE_FORMAT(cadastro_cidadao.data_nascimento, "%d/%m/%Y") END ) as data_nascimento '), 'cadastro_setor.nome AS setor_atual', DB::raw(' ( SELECT TRUE FROM painel_senha_fila_historico INNER JOIN cadastro_centro_custo ON cadastro_centro_custo.id = painel_senha_fila_historico.centro_custo_id WHERE painel_senha_fila_historico.fila_id = painel_senha_fila.id AND cadastro_centro_custo.setor_id IN ( ' . SetorTipo::CONSULTORIO .', ' . SetorTipo::ENFERMAGEM .', ' . SetorTipo::EXAMES .', ' . SetorTipo::OBSERVACAO .' ) LIMIT 1 ) bloqueado '), 'pronto_atendimento_faa.finalizado', 'pronto_atendimento_faa.cancelado', 'painel_senha_fila.centro_custo_id', DB::raw(' ( CASE WHEN pronto_atendimento_faa.deleted_at IS NOT NULL THEN "FAA EXCLUÍDA" WHEN pronto_atendimento_faa.cancelado = 1 THEN "FAA CANCELADA" WHEN pronto_atendimento_faa.finalizado = 1 THEN "ATENDIMENTO FINALIZADO" ELSE CASE WHEN cadastro_setor.nome IS NULL THEN "RECEPÇÃO - ATENDIMENTO RETROATIVO" ELSE pronto_atendimento_faa_desfecho.nome END END ) AS desfecho '), ]) ->distinct() ->join( 'pronto_atendimento_faa', 'pronto_atendimento_faa.id', 'pronto_atendimento_atendimento.faa_id' ) ->leftJoin ( 'pronto_atendimento_faa_desfecho', 'pronto_atendimento_faa_desfecho.id', 'pronto_atendimento_faa.desfecho_id' ) ->join( 'cadastro_centro_custo as centro_custo_atendimento', 'centro_custo_atendimento.id', 'pronto_atendimento_atendimento.created_centro_custo_id' ) ->join( 'pronto_atendimento_atendimento_recepcao', 'pronto_atendimento_atendimento_recepcao.atendimento_id', 'pronto_atendimento_atendimento.id' ) ->join( 'cadastro_paciente', 'cadastro_paciente.id', 'pronto_atendimento_faa.paciente_id' ) ->join( 'cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id' ) ->leftJoin( 'painel_senha_fila', 'painel_senha_fila.id', 'pronto_atendimento_atendimento.fila_id' ) ->leftJoin( 'cadastro_centro_custo', 'cadastro_centro_custo.id', 'painel_senha_fila.centro_custo_id' ) ->leftJoin( 'cadastro_setor', 'cadastro_setor.id', 'cadastro_centro_custo.setor_id' ) ->leftJoin( 'pronto_atendimento_atendimento_procedimento', 'pronto_atendimento_atendimento_procedimento.atendimento_id', 'pronto_atendimento_atendimento.id' ) ->where('centro_custo_atendimento.infraestrutura_id', $this->getCentroCustoLogado()->infraestrutura_id); if (!request()->get('order')) { $historico->orderByDesc('pronto_atendimento_atendimento_recepcao.atendido_em'); } return datatables() ->of($historico) ->filterColumn('data', function ($query, $keyword) { $query->whereRaw("DATE_FORMAT(pronto_atendimento_atendimento_recepcao.atendido_em, '%d/%m/%Y') like ?", ["%{$keyword}%"]) ->orWhereRaw( "CONCAT( SUBSTR(pronto_atendimento_atendimento_recepcao.atendido_em,9,2), SUBSTR(pronto_atendimento_atendimento_recepcao.atendido_em,6,2), SUBSTR(pronto_atendimento_atendimento_recepcao.atendido_em,1,4) ) like ?", ["%{$keyword}%"] ); }) ->filterColumn('hora', function ($query, $keyword) { $query->whereRaw("DATE_FORMAT(pronto_atendimento_atendimento_recepcao.atendido_em, '%H:%i') like ?", ["%{$keyword}%"]); }) ->filterColumn('setor_atual', function ($query, $keyword) { $query->whereRaw(' CASE WHEN pronto_atendimento_faa.deleted_at IS NOT NULL THEN "FAA EXCLUÍDA" WHEN pronto_atendimento_faa.finalizado = 1 THEN "ATENDIMENTO FINALIZADO" ELSE cadastro_setor.nome END like ?', ["%{$keyword}%"] ); }) ->orderColumn('data', function ($query, $order) { $query->orderBy('pronto_atendimento_atendimento_recepcao.atendido_em', $order); }) ->orderColumn('hora', function ($query, $order) { $query->orderByRaw('DATE_FORMAT(pronto_atendimento_atendimento_recepcao.atendido_em, "%H:%i") ' . $order); }) ->orderColumn('setor_atual', function ($query, $order) { $query->orderByRaw( ' CASE WHEN pronto_atendimento_faa.deleted_at IS NOT NULL THEN "FAA EXCLUÍDA" WHEN pronto_atendimento_faa.finalizado = 1 THEN "ATENDIMENTO FINALIZADO" ELSE cadastro_setor.nome END ' . $order ); }) ->skipTotalRecords() ->make(true); } public function create() { return response()->json([ 'form' => [ 'centros_custo_encaminhamento' => self::getCentroCustoLogado()->infraestrutura->centrosCusto() ->whereHas('setor', function ($query) { $query->whereNotIn('tipo_id', [ SetorTipo::RECEPCAO ]); }) ->get() ->map(fn ($cc) => [ 'id' => $cc->id, 'setor_nome' => $cc->setor->nome ]) ->sortBy('setor_nome') ->values(), ] ], Response::HTTP_OK); } public function show($id) { $this->auth(__FUNCTION__); $atendimento = Faa::withTrashed()->findOrFail($id)->atendimentos()->withTrashed()->first(); $atendimentos = collect(); $atendimentoExcluido = Faa::withTrashed()->findOrFail($id); if ($atendimentoExcluido->trashed()) { $centroCusto = CentroCusto::with(['setor'])->findOrFail($atendimentoExcluido->deleted_centro_custo_id); if($centroCusto->setor->id == SetorTipo::TRIAGEM){ $atendimento->atendimentosTriagem->each(fn ($atendimentoTriagem) => $atendimentos->push([ 'is_observacao' => false, 'setor' => $atendimentoTriagem->createdCentroCusto->setor->nome, 'data_hora' => $atendimentoTriagem->created_at, 'usuario' => Lotacao::find($atendimentoExcluido->deleted_lotacao_id)->usuario->cidadao->nome, 'data_exclusao' => $atendimentoExcluido->deleted_at, 'cbo' => $this->retornaCbo($atendimentoExcluido->deleted_lotacao_id), ])); } else if ($centroCusto->setor->id == SetorTipo::RECEPCAO){ $usuario = Lotacao::find($atendimento->created_lotacao_id)->usuario->cidadao->nome; $atendimentos->push([ 'is_observacao' => false, 'setor' => 'RECEPÇÃO', 'data_hora' => new Carbon($atendimento->recepcao->atendido_em), 'usuario' => $usuario, 'cbo' => $this->retornaCbo($atendimentoExcluido->deleted_lotacao_id), 'data_exclusao' => $atendimentoExcluido->deleted_at, ]); } } else { if ($atendimento->recepcao) { $lotacaoLocal = Lotacao::find($atendimento->updated_lotacao_id); $atendimentos->push(collect([ 'is_observacao' => false, 'setor' => is_null($atendimento->fila) ? 'RECEPÇÃO - ATENDIMENTO RETROATIVO' : $atendimento->recepcao->createdCentroCusto->setor->nome, 'data_hora' => new Carbon($atendimento->recepcao->atendido_em), 'usuario' => $lotacaoLocal->usuario->cidadao->nome ?? null, 'cbo' => $lotacaoLocal->ocupacao->nome ?? null, ])); } } $atendimento->atendimentosTriagem->each(fn ($atendimentoTriagem) => $atendimentos->push([ 'is_observacao' => false, 'setor' => $atendimentoTriagem->createdCentroCusto->setor->nome, 'data_hora' => $atendimentoTriagem->created_at, 'usuario' => Lotacao::find($atendimentoTriagem->updated_lotacao_id)->usuario->cidadao->nome, 'cbo' => Lotacao::find($atendimentoTriagem->updated_lotacao_id)->ocupacao->nome, ])); $atendimento->atendimentosMedico->each(fn ($atendimentoMedico) => $atendimentos->push([ 'is_observacao' => false, 'setor' => $atendimentoMedico->createdCentroCusto->setor->nome, 'data_hora' => $atendimentoMedico->created_at, 'usuario' => Lotacao::find($atendimentoMedico->updated_lotacao_id)->usuario->cidadao->nome, 'cbo' => Lotacao::find($atendimentoMedico->updated_lotacao_id)->ocupacao->nome, ])); $atendimento->atendimentosEnfermagem->each(fn ($atendimentoEnfermagem) => $atendimentos->push([ 'is_observacao' => false, 'setor' => $atendimentoEnfermagem->automatico ? 'ENFERMAGEM' : $atendimentoEnfermagem->createdCentroCusto->setor->nome, 'data_hora' => $atendimentoEnfermagem->created_at, 'usuario' => Lotacao::find($atendimentoEnfermagem->updated_lotacao_id)->usuario->cidadao->nome ?? null, 'cbo' => Lotacao::find($atendimentoEnfermagem->updated_lotacao_id)->ocupacao->nome ?? null, ])); $atendimento->atendimentosExameImagem->each(fn ($atendimentoExameImagem) => $atendimentos->push([ 'is_observacao' => false, 'setor' => $atendimentoExameImagem->createdCentroCusto->setor->nome, 'data_hora' => $atendimentoExameImagem->created_at, 'usuario' => Lotacao::find($atendimentoExameImagem->updated_lotacao_id)->usuario->cidadao->nome, 'cbo' => Lotacao::find($atendimentoExameImagem->updated_lotacao_id)->ocupacao->nome, ])); $atendimento->pacienteObservacoes->each(fn ($atendimentoObservacao) => $atendimentos->push([ 'is_observacao' => true, 'setor' => $atendimentoObservacao->createdCentroCusto->setor->nome, 'data_hora' => $atendimentoObservacao->created_at, ])); if (isset($atendimento->fila->historico)) { $atendimento->fila->historico->each(function ($historico) use ($atendimentos) { if ($historico->evadido) { $atendimentos->push([ 'is_observacao' => false, 'setor' => 'EVASÃO', 'data_hora' => $historico->created_at, 'usuario' => Lotacao::find($historico->created_lotacao_id)->usuario->cidadao->nome, 'motivo_evasao' => $historico->motivo_evasao, 'cbo' => Lotacao::find($historico->created_lotacao_id)->ocupacao->nome, ]); } else { if ($atendimentos->last()['setor'] == 'EVASÃO') { $atendimentos->push([ 'is_observacao' => false, 'setor' => 'CANCELAMENTO DA EVASÃO', 'data_hora' => $historico->created_at, 'usuario' => Lotacao::find($historico->created_lotacao_id)->usuario->cidadao->nome, 'motivo_cancelamento_evasao' => $historico->motivo_cancelamento_evasao, 'cbo' => Lotacao::find($historico->created_lotacao_id)->ocupacao->nome, ]); } } }); } if ($atendimento->fila && !$atendimento->faa->finalizado) { $lotacaoLocal = Lotacao::find($atendimento->created_lotacao_id); $atendimentos->push([ 'is_observacao' => false, 'setor' => $atendimento->fila->centroCusto->setor->nome, 'data_hora' => $atendimento->fila->updated_at, ]); } elseif (!$atendimento->fila) { if ($atendimentoExcluido->deleted_centro_custo_id) { $centroCusto = CentroCusto::with(['setor'])->findOrFail($atendimentoExcluido->deleted_centro_custo_id); $novoAtendimento = [ 'is_observacao' => false, 'data_hora' => new Carbon($atendimento->recepcao->atendido_em), 'usuario' => Lotacao::find($atendimentoExcluido->deleted_lotacao_id)->usuario->cidadao->nome, 'cbo' => Lotacao::find($atendimentoExcluido->deleted_lotacao_id)->ocupacao->nome, ]; $setoresOrigemRecepcao = collect([ SetorTipo::TRIAGEM, SetorTipo::CONSULTORIO, SetorTipo::ENFERMAGEM, SetorTipo::EXAMES, SetorTipo::ADMINISTRACAO, SetorTipo::OBSERVACAO ]); if ($setoresOrigemRecepcao->contains($centroCusto->setor->id)) { $novoAtendimento['setor'] = 'RECEPÇÃO'; $novoAtendimento['usuario'] = Lotacao::find($atendimento->created_lotacao_id)->usuario->cidadao->nome; $novoAtendimento['cbo'] = $this->retornaCbo($atendimento->created_lotacao_id); } else if ($centroCusto->setor->id == SetorTipo::RECEPCAO) { $novoAtendimento['setor'] = 'TRIAGEM'; $novoAtendimento['usuario'] = Lotacao::find($atendimento->created_lotacao_id)->usuario->cidadao->nome; $novoAtendimento['cbo'] = $this->retornaCbo($atendimento->created_lotacao_id); } $atendimentos->prepend($novoAtendimento); $atendimentos = $atendimentos->sortBy(function ($item) { return $item['setor']; }); $atendimentos->push([ 'is_observacao' => false, 'setor' => 'FAA EXCLUÍDA', 'data_hora' => $atendimentoExcluido->deleted_at, 'usuario' => Lotacao::find($atendimentoExcluido->deleted_lotacao_id)->usuario->cidadao->nome, 'data_exclusao' => $atendimentoExcluido->deleted_at, 'cbo' => Lotacao::find($atendimentoExcluido->deleted_lotacao_id)->ocupacao->nome, ]); } } elseif ($atendimento->faa->finalizado && !$atendimento->faa->cancelado){ if($atendimento->faa->desfecho_id != DesfechoEnum::EVASAO){ $atendimentos->push([ 'is_observacao' => false, 'setor' => 'ATENDIMENTO FINALIZADO', 'data_hora' => $atendimento->faa->updated_at, 'usuario' => Lotacao::find($atendimento->faa->updated_lotacao_id)->usuario->cidadao->nome, 'cbo' => $this->retornaCbo($atendimento->faa->updated_lotacao_id), ]); } } if ($atendimento->faa->cancelado){ $atendimentos->push([ 'is_observacao' => false, 'setor' => 'FAA CANCELADA', 'data_hora' => $atendimento->faa->updated_at, 'usuario' => Lotacao::find($atendimento->faa->updated_lotacao_id)->usuario->cidadao->nome, 'cbo' => $this->retornaCbo($atendimento->faa->updated_lotacao_id), 'motivo_cancelamento' => $atendimento->faa->motivo_cancelamento, ]); } $faaReaberturas = FaaReabertura::with('createdLotacao.usuario.cidadao') // Eager loading ->where('faa_id', $id) ->get(); foreach ($faaReaberturas as $reabertura) { $atendimentos->push([ 'is_observacao' => false, 'setor' => 'FAA REABERTA', 'data_hora' => $reabertura->created_at, 'usuario' => $reabertura->createdLotacao->usuario->cidadao->nome, 'cbo' => $reabertura->createdLotacao->ocupacao->nome ]); } $isObservacao = false; $atendimentos = $atendimentos ->sortBy(function ($atendimento) { return $atendimento['data_hora']->format('Y-m-d H:i') . ($atendimento['setor'] === 'FAA REABERTA' ? 'a' : 'b'); }) ->values(); $lastIndex = $atendimentos->count() - 1; $atendimentos = $atendimentos->map(function ($atendimento, $index) use (&$isObservacao, $lastIndex) { if ($atendimento['is_observacao']) { $isObservacao = true; } $isLastEntry = $index === $lastIndex; $usuarioIsEmpty = empty($atendimento['usuario']); $cboIsEmpty = empty($atendimento['cbo']); if ($isLastEntry || (!$usuarioIsEmpty && !$cboIsEmpty)) { return [ 'setor' => $atendimento['setor'] . ($isObservacao ? ' (OBSERVAÇÃO)' : ''), 'data' => $atendimento['data_hora']->format('d/m/Y'), 'hora' => $atendimento['data_hora']->format('H:i'), 'evadido' => isset($atendimento['evadido']) && $atendimento['evadido'] == 1 ? 'Sim' : 'Não', 'motivo_evasao' => $atendimento['motivo_evasao'] ?? null, 'motivo_cancelamento_evasao' => $atendimento['motivo_cancelamento_evasao'] ?? null, 'usuario' => $atendimento['usuario'] ?? '-', 'cbo' => $atendimento['cbo'] ?? '-', 'data_exclusao' => isset($atendimento['data_exclusao']) ? $atendimento['data_exclusao']->format('d/m/Y') : null, 'hora_exclusao' => isset($atendimento['data_exclusao']) ? $atendimento['data_exclusao']->format('H:i') : null, 'motivo_cancelamento' => $atendimento['motivo_cancelamento'] ?? null, ]; } return null; }); $atendimentos = $atendimentos->filter()->values(); return response()->json($atendimentos, Response::HTTP_OK); } private function retornaCbo($lotacaoId) { return Lotacao::find($lotacaoId)->ocupacao->nome; } public function realocar($id) { $this->auth(__FUNCTION__); $faa = Faa::findOrFail($id); DB::transaction(function () use ($faa) { $fila = $faa->atendimentos()->first()->fila; FilaService::forward([ 'centro_custo_id_para' => request()->centro_custo_id, ], $fila->id); }); return response()->json($faa->fresh(), Response::HTTP_OK); } public function destroy($id) { $this->auth(__FUNCTION__); $atendimento = Atendimento::where('faa_id', $id)->firstOrFail(); DB::transaction(function () use ($atendimento) { Faa::findOrFail($atendimento->faa_id)->delete(); if($atendimento->fila_id !== null){ Fila::findOrFail($atendimento->fila_id)->delete(); } }); return response()->json(null, Response::HTTP_NO_CONTENT); } private function getCentroCustoLogado() { return CentroCusto::findOrFail(auth()->payload()->get('centro_custo_id')); } }