3045 lines
118 KiB
PHP
3045 lines
118 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\ProntoAtendimento\Atendimento\Observacao;
|
|
|
|
use App\Enums\Cadastro\SujeitoAtencao\Deficiencia;
|
|
use App\Enums\Cadastro\SujeitoAtencao\FatorRisco as FatorRiscoEnum;
|
|
use App\Enums\Cadastro\SujeitoAtencao\Sexo;
|
|
use App\Enums\Cadastro\UnidadeMedida as UnidadeMedidaEnum;
|
|
use App\Enums\Geral\TipoMedidaAltura as TipoMedidaAlturaEnum;
|
|
use App\Enums\Parametrizacao\Exame\Status as ExameStatusEnum;
|
|
use App\Enums\Parametrizacao\Exame\Tipo as ExameTipo;
|
|
use App\Enums\ProntoAtendimento\Atendimento\Desfecho as DesfechoEnum;
|
|
use App\Enums\ProntoAtendimento\Atendimento\DorToracica as DorToracicaEnum;
|
|
use App\Enums\ProntoAtendimento\TipoFormularioAcidenteTrabalho;
|
|
use App\Enums\Sigtap\Ocupacao;
|
|
use App\Enums\Sigtap\Procedimento as ProcedimentoEnum;
|
|
use App\Exceptions\ProntoAtendimento\Atendimento\Enfermagem\PedidoExameCannotChangeStatusException;
|
|
use App\Exceptions\ProntoAtendimento\Atendimento\Enfermagem\PedidoExameItemCannotChangeStatusException;
|
|
use App\Exceptions\ProntoAtendimento\Atendimento\Enfermagem\PrescricaoInternaAplicacaoCannotChangeStatusException;
|
|
use App\Exceptions\ProntoAtendimento\Atendimento\Enfermagem\ServicoEnfermagemCannotChangeStatusException;
|
|
use App\Http\Controllers\Controller;
|
|
use App\Http\Controllers\Impressao\ProntoAtendimento\FaaEletronicaController;
|
|
use App\Http\Requests\ProntoAtendimento\Atendimento\ObservacaoRequest;
|
|
use App\Models\Cadastro\Estabelecimento\Unidade;
|
|
use App\Models\Cadastro\Medicamento\ViaAdministracao;
|
|
use App\Models\Cadastro\SujeitoAtencao\AlergiaCriticidade;
|
|
use App\Models\Cadastro\SujeitoAtencao\AlergiaTipo;
|
|
use App\Models\Cadastro\SujeitoAtencao\FatorRisco;
|
|
use App\Models\Cadastro\SujeitoAtencao\Lotacao;
|
|
use App\Models\Cadastro\UnidadeMedida;
|
|
use App\Models\ExameLaboratorial\Parametrizacao\LaboratorioFatura;
|
|
use App\Models\ExameLaboratorial\Parametrizacao\LaboratorioFaturaUsuario;
|
|
use App\Models\ExameLaboratorial\Parametrizacao\UnidadeFaturamento;
|
|
use App\Models\ExameLaboratorial\Parametrizacao\UnidadeFaturamentoUsuario;
|
|
use App\Models\Geral\GlasgowAberturaOcular;
|
|
use App\Models\Geral\GlasgowInterpretacaoResultado;
|
|
use App\Models\Geral\GlasgowReatividadePupilar;
|
|
use App\Models\Geral\GlasgowRespostaMotora;
|
|
use App\Models\Geral\GlasgowRespostaVerbal;
|
|
use App\Models\Geral\MedidaTempo;
|
|
use App\Models\Parametrizacao\Exame\ExameStatus;
|
|
use App\Models\Parametrizacao\Procedimento as ParametrizacaoProcedimento;
|
|
use App\Models\ProntoAtendimento\Atendimento\Atendimento;
|
|
use App\Models\ProntoAtendimento\Atendimento\Desfecho as ModelDesfecho;
|
|
use App\Models\ProntoAtendimento\Atendimento\Enfermagem\Anotacao;
|
|
use App\Models\ProntoAtendimento\Atendimento\Enfermagem\Avaliacao;
|
|
use App\Models\ProntoAtendimento\Atendimento\Enfermagem\Diagnostico;
|
|
use App\Models\ProntoAtendimento\Atendimento\Enfermagem\Historico;
|
|
use App\Models\ProntoAtendimento\Atendimento\Enfermagem\Implementacao;
|
|
use App\Models\ProntoAtendimento\Atendimento\Enfermagem\Planejamento;
|
|
use App\Models\ProntoAtendimento\Atendimento\EscalaComaGlasgow;
|
|
use App\Models\ProntoAtendimento\Atendimento\Observacao\PacienteObservacao;
|
|
use App\Models\ProntoAtendimento\Atendimento\PacienteTraumaStatus;
|
|
use App\Models\ProntoAtendimento\Atendimento\PrescricaoInterna;
|
|
use App\Models\ProntoAtendimento\Atendimento\PrescricaoInternaMedicamentoAplicacao;
|
|
use App\Models\ProntoAtendimento\Atendimento\ServicoEnfermagem;
|
|
use App\Models\ProntoAtendimento\Atendimento\Triagem\FormularioDorToracica;
|
|
use App\Models\ProntoAtendimento\Atendimento\Triagem\OrigemDorToracica;
|
|
use App\Models\ProntoAtendimento\Atendimento\Triagem\RelacionadoFormularioDorToracica;
|
|
use App\Models\ProntoAtendimento\ClassificacaoRisco\ClassificacaoRisco;
|
|
use App\Models\ProntoAtendimento\Parametrizacao\Parametrizacao;
|
|
use App\Models\ProntoAtendimento\PedidoExame\Observacao;
|
|
use App\Models\ProntoAtendimento\PedidoExame\PedidoExame;
|
|
use App\Models\ProntoAtendimento\PrescricaoInternaLocalAplicacao;
|
|
use App\Models\Sigtap\Procedimento;
|
|
use App\Services\Cadastro\SujeitoAtencao\ObitoService;
|
|
use App\Services\Parametrizacao\ProntoAtendimento\AtendimentoMedicoService;
|
|
use App\Services\ProntoAtendimento\AcidenteTrabalhoService;
|
|
use App\Services\ProntoAtendimento\Atendimento\AtendimentoService;
|
|
use App\Services\ProntoAtendimento\Atendimento\RaatService;
|
|
use App\Services\ProntoAtendimento\Fila\FilaService;
|
|
use App\Services\ProntoAtendimento\Impressao\ImpressaoService;
|
|
use App\Services\ProntoAtendimento\PedidoExame\LaudoService;
|
|
use App\Services\ProntoAtendimento\PlantaoService;
|
|
use App\Services\Sigtap\ProcedimentoValidationService;
|
|
use Carbon\Carbon;
|
|
use Exception;
|
|
use Illuminate\Http\Response;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
class PacienteObservacaoController extends Controller
|
|
{
|
|
protected $modulo = 'pronto-atendimento';
|
|
protected $funcionalidade = 'paciente-observacao';
|
|
|
|
public function index()
|
|
{
|
|
$plantao = PlantaoService::getCurrentPlantao(true);
|
|
|
|
return response()->json(
|
|
[
|
|
'additionals' => [
|
|
'plantao_id' => $plantao->id ?? null,
|
|
'plantao_faixa_etaria_id' => $plantao->faixa_etaria_id ?? null,
|
|
],
|
|
'fila' => FilaService::index(request()->all())
|
|
],
|
|
Response::HTTP_OK
|
|
);
|
|
}
|
|
|
|
public function storeFaaAssinada($id)
|
|
{
|
|
$path = 'assinatura-eletronica' . DIRECTORY_SEPARATOR . app('config')->get('database.default') . DIRECTORY_SEPARATOR . 'pronto-atendimento' . DIRECTORY_SEPARATOR . 'paciente-observacao';
|
|
$arquivo = "{$id}.PDF";
|
|
|
|
$pacienteObservacao = PacienteObservacao::findOrFail($id);
|
|
|
|
if (!is_null($pacienteObservacao)) {
|
|
$pdf = base64_decode(request()->faa_assinada['data']);
|
|
|
|
if (!Storage::disk('local')->put($path . DIRECTORY_SEPARATOR . $arquivo, $pdf)) {
|
|
throw new Exception('Erro ao assinar o arquivo.');
|
|
} else {
|
|
$pacienteObservacao->update(['is_faa_assinada' => true]);
|
|
}
|
|
}
|
|
|
|
return response($pacienteObservacao->fresh(), Response::HTTP_OK);
|
|
}
|
|
|
|
public function create($id)
|
|
{
|
|
$this->auth(__FUNCTION__);
|
|
|
|
$atendimento = Atendimento::where('fila_id', $id)
|
|
->orderBy('created_at', 'desc')
|
|
->firstOrFail();
|
|
|
|
$lotacaoLogada = Lotacao::find(auth()->payload()->get('lotacao_id'));
|
|
|
|
return response()->json(
|
|
[
|
|
'form' => $this->getFormData($atendimento),
|
|
'model' => $this->getModelData($atendimento),
|
|
'additionals' => [
|
|
'is_enfermeiro' => $lotacaoLogada->ocupacao->codigo === Ocupacao::ENFERMEIRO,
|
|
'is_auxiliar_tecnico_enfermagem' => collect([
|
|
Ocupacao::TECNICO_ENFERMAGEM,
|
|
Ocupacao::TECNICO_ENFERMAGEM_TERAPIA_INTENSIVA,
|
|
Ocupacao::TECNICO_ENFERMAGEM_TRABALHO,
|
|
Ocupacao::TECNICO_ENFERMAGEM_PSIQUIATRICA,
|
|
Ocupacao::TECNICO_ENFERMAGEM_ESTRATEGIA_SAUDE_FAMILIA,
|
|
Ocupacao::AUXILIAR_ENFERMAGEM,
|
|
Ocupacao::AUXILIAR_ENFERMAGEM_TRABALHO,
|
|
Ocupacao::AUXILIAR_ENFERMAGEM_ESTRATEGIA_SAUDE_FAMILIA,
|
|
])->contains($lotacaoLogada->ocupacao->codigo),
|
|
'timeline' => AtendimentoService::getTimelineItems($id),
|
|
]
|
|
],
|
|
Response::HTTP_OK
|
|
);
|
|
}
|
|
|
|
private function getFormData($atendimento)
|
|
{
|
|
$parametrizacao = AtendimentoMedicoService::get($this->getCurrentCentroCusto()->infraestrutura_id);
|
|
$pacienteObservacoes = $atendimento->pacienteObservacoes()->orderBy('created_at')->get();
|
|
$firstPacienteObservacao = $pacienteObservacoes->first();
|
|
$firstAtendimentoMedico = $atendimento->atendimentosMedico()->orderBy('created_at')->first();
|
|
$entradaObservacao = null;
|
|
|
|
if (!is_null($firstPacienteObservacao)) {
|
|
|
|
$entradaObservacao = $firstPacienteObservacao->created_at->format('d/m/Y H:i:s');
|
|
}
|
|
|
|
return [
|
|
'tipo_atendimento_id' => $parametrizacao->tipo_id,
|
|
'atendimento_id' => $atendimento->id,
|
|
'dataAtual' => Carbon::now()->format('d/m/Y'),
|
|
'entrada_observacao' => $entradaObservacao,
|
|
'tempo_em_observacao' => $this->getTempoEmObservacao($atendimento),
|
|
'paciente_atingiu24horas' => $this->isPacienteAtingiu24Horas($atendimento),
|
|
'lotacao' => $this->getLotacao(),
|
|
'prescricao_interna_locais_aplicacao' => PrescricaoInternaLocalAplicacao::orderBy('descricao')->get(),
|
|
'medico_responsavel' => [
|
|
'id' => $firstAtendimentoMedico->createdLotacao->usuario->id ?? null,
|
|
'nome' => $firstAtendimentoMedico->createdLotacao->usuario->nome ?? null,
|
|
'ocupacao' => [
|
|
'codigo' => $firstAtendimentoMedico->createdLotacao->ocupacao->codigo ?? null,
|
|
'nome' => $firstAtendimentoMedico->createdLotacao->ocupacao->nome ?? null,
|
|
],
|
|
],
|
|
'alergia_tipos' => $this->getAlergiaTipos(),
|
|
'alergia_criticidades' => $this->getAlergiaCriticidades(),
|
|
'classificacoes_risco' => $this->getClassificacoesRisco(),
|
|
'fatores_risco' => $this->getFatoresRisco(),
|
|
'fatores_risco_gestante' => $this->getFatoresRiscoGestante(),
|
|
'traumas' => $this->getTraumas(),
|
|
'statusExame' => ExameStatus::all(),
|
|
'profissionais_atendimento' => $this->getProfissionaisAtendimento($atendimento),
|
|
'glasgow' => [
|
|
'aberturas_ocular' => $this->getGlasgowAberturaOcular(),
|
|
'reatividades_Pupilar' => $this->getGlasgowReatividadePupilar(),
|
|
'respostas_motora' => $this->getGlasgowRespostaMotora(),
|
|
'respostas_verbal' => $this->getGlasgowRespostaVerbal(),
|
|
],
|
|
'paciente' => $this->getPaciente($atendimento),
|
|
'recepcao' => [
|
|
'motivo_atendimento' => $atendimento->recepcao->motivo_atendimento ?? null,
|
|
],
|
|
'unidades' => Unidade::all()->map(function ($unidade) {
|
|
|
|
return [
|
|
'id' => $unidade->id,
|
|
'nome_fantasia' => $unidade->nome_fantasia,
|
|
];
|
|
}),
|
|
'unidades_medida' => $this->getUnidadesMedida(),
|
|
'unidades_medida_tempo' => MedidaTempo::all(),
|
|
'raat' => RaatService::getOptionsParecerMedico(),
|
|
'atendimento_medico' => [
|
|
'atendimentos_gerais' => $this->getAreaAtendimentoMedicoByKey($atendimento, 'atendimento_geral'),
|
|
'observacoes_enfermagem' => $this->getAreaAtendimentoMedicoByKey($atendimento, 'observacoes_enfermagem'),
|
|
'evolucoes' => $this->getAreaAtendimentoMedicoByKey($atendimento, 'evolucao'),
|
|
'queixas_principal_duracao' => $this->getAreaAtendimentoMedicoByKey($atendimento, 'queixa_principal_duracao'),
|
|
'historias' => $this->getAreaAtendimentoMedicoByKey($atendimento, 'historia'),
|
|
'exames_fisico' => $this->getAreaAtendimentoMedicoByKey($atendimento, 'exame_fisico'),
|
|
'diagnosticos' => $this->getAreaAtendimentoMedicoByKey($atendimento, 'diagnostico'),
|
|
'condutas' => $this->getAreaAtendimentoMedicoByKey($atendimento, 'conduta'),
|
|
'procedimentos' => $this->getProcedimentos($atendimento, 'atendimento_medico'),
|
|
'solicitou_reavaliacao' => $this->getSolicitacaoReavaliacao($atendimento)
|
|
],
|
|
'atendimento_enfermagem' => [
|
|
'anotacoes' => $this->getAnotacoes($atendimento),
|
|
'historicos' => $this->getAreaAtendimentoEnfermagemByKey($atendimento, 'historico'),
|
|
'diagnosticos' => $this->getAreaAtendimentoEnfermagemByKey($atendimento, 'diagnostico'),
|
|
'planejamentos' => $this->getAreaAtendimentoEnfermagemByKey($atendimento, 'planejamento'),
|
|
'implementacoes' => $this->getAreaAtendimentoEnfermagemByKey($atendimento, 'implementacao'),
|
|
'avaliacoes' => $this->getAreaAtendimentoEnfermagemByKey($atendimento, 'avaliacao'),
|
|
'procedimentos' => $this->getProcedimentos($atendimento, 'atendimento_enfermagem'),
|
|
],
|
|
'atendimento_triagem' => [
|
|
'outras_avaliacoes_condicoes' => $this->getOutrasAvaliacoesCondicoes($atendimento),
|
|
'procedimentos' => $this->getProcedimentos($atendimento, 'atendimento_triagem'),
|
|
],
|
|
'atendimento_exame_imagem' => [
|
|
'procedimentos' => $this->getProcedimentos($atendimento, 'exame_imagem'),
|
|
],
|
|
'medicamentos_uso' => $this->getMedicamentosUso($atendimento),
|
|
'sinais_vitais' => $this->getSinaisVitais($atendimento),
|
|
'servicos_enfermagem' => $this->getServicosEnfermagem($atendimento, true),
|
|
'prescricoes_interna' => $this->getPrescricoesInterna($atendimento, true),
|
|
'escalas_coma_glasgow' => $this->getEscalasComaGlasgow($atendimento),
|
|
'procedimentos' => $this->getProcedimentos($atendimento, 'paciente_observacao'),
|
|
'vias_administracao' => viaAdministracao::all(),
|
|
'pedidos_exames' => $this->getPedidosExames($atendimento, true),
|
|
'formulario_dor_toracica' => [
|
|
'dor_toracica_data_sintoma' => null,
|
|
'dor_toracica_hora_ecg_admissao' => null,
|
|
'hora_sintoma' => null,
|
|
'hora_ecg_admissao' => null,
|
|
'dispneia' => null,
|
|
'caracteristica_dor' => $this->getCaracteristicaDor(),
|
|
'localizacao_dor' => $this->getLocalizacaoDor(),
|
|
'fator_desencadeante' => $this->getFatorDesencadeante(),
|
|
'fatores_risco_toracica' => $this->getFatoresRiscoToracica(),
|
|
'duracao_dor' => $this->getDuracaoDor(),
|
|
],
|
|
'desfechos' => ModelDesfecho::get(),
|
|
'unidades_faturamento' => self::getUnidadesFaturamento(),
|
|
'laboratorios_faturamento' => self::getLaboratoriosFaturamento(),
|
|
];
|
|
}
|
|
|
|
public static function getUnidadesFaturamento()
|
|
{
|
|
|
|
$lotacaoLogada = Lotacao::findOrFail(auth()->payload()->get('lotacao_id'));
|
|
|
|
return UnidadeFaturamentoUsuario::where(function ($query) use ($lotacaoLogada){
|
|
|
|
$query->whereHas('unidadeFaturamentoAutomatico', function ($query) use ($lotacaoLogada){
|
|
|
|
$query
|
|
->where('infraestrutura_id', $lotacaoLogada->infraestrutura_id)
|
|
->orWhere(function ($query) use ($lotacaoLogada){
|
|
|
|
$query->whereHas('unidadeFaturamentoUnidade', function ($query) use ($lotacaoLogada){
|
|
|
|
$query->where('infraestrutura_id', $lotacaoLogada->infraestrutura_id);
|
|
});
|
|
});
|
|
});
|
|
})
|
|
->groupBy('usuario_id')
|
|
->get()
|
|
->map(fn ($query) => [
|
|
'id' => $query->usuario_id,
|
|
'usuario_ocupacao' => $query->usuario->nome . ' - ' . $query->ocupacao->codigo,
|
|
'ocupacao_id' => $query->ocupacao_id,
|
|
'infraestrutura_id' => $query->unidadeFaturamentoAutomatico->infraestrutura_id,
|
|
]);
|
|
}
|
|
|
|
public static function getLaboratoriosFaturamento()
|
|
{
|
|
|
|
$lotacaoLogada = Lotacao::findOrFail(auth()->payload()->get('lotacao_id'));
|
|
|
|
return LaboratorioFaturaUsuario::where(function ($query) use ($lotacaoLogada){
|
|
|
|
$query->whereHas('laboratorioFaturaAutomatico', function ($query) use ($lotacaoLogada){
|
|
|
|
$query
|
|
->where('infraestrutura_id', $lotacaoLogada->infraestrutura_id)
|
|
->orWhere(function ($query) use ($lotacaoLogada){
|
|
|
|
$query->whereHas('laboratorioFaturaUnidade', function ($query) use ($lotacaoLogada){
|
|
|
|
$query->where('infraestrutura_id', $lotacaoLogada->infraestrutura_id);
|
|
});
|
|
});
|
|
});
|
|
})
|
|
->groupBy('usuario_id')
|
|
->get()
|
|
->map(fn ($query) => [
|
|
'id' => $query->usuario_id,
|
|
'usuario_ocupacao' => $query->usuario->nome . ' - ' . $query->ocupacao->codigo,
|
|
'ocupacao_id' => $query->ocupacao_id,
|
|
'infraestrutura_id' => $query->laboratorioFaturaAutomatico->infraestrutura_id,
|
|
]);
|
|
}
|
|
|
|
private function handleUsuarioLaboratorio($pedidoExames)
|
|
{
|
|
$usuarios = self::getLaboratoriosFaturamento();
|
|
|
|
if ($usuarios->count() === 1) {
|
|
return [
|
|
'id' => $usuarios->first()['id'],
|
|
'ocupacao_id' => $usuarios->first()['ocupacao_id'] ?? null,
|
|
'infraestrutura_id' => $usuarios->first()['infraestrutura_id'] ?? null,
|
|
];
|
|
}
|
|
|
|
if ($pedidoExames->laboratorio_usuario_id) {
|
|
$usuarioEncontrado = $usuarios->firstWhere('id', $pedidoExames->laboratorio_usuario_id);
|
|
|
|
if ($usuarioEncontrado) {
|
|
return [
|
|
'id' => $usuarioEncontrado['id'],
|
|
'ocupacao_id' => $usuarioEncontrado['ocupacao_id'] ?? null,
|
|
'infraestrutura_id' => $usuarioEncontrado['infraestrutura_id'] ?? null,
|
|
];
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private function handleUsuarioUnidade($pedidoExames)
|
|
{
|
|
$usuarios = self::getUnidadesFaturamento();
|
|
|
|
if ($usuarios->count() === 1) {
|
|
return [
|
|
'id' => $usuarios->first()['id'],
|
|
'ocupacao_id' => $usuarios->first()['ocupacao_id'] ?? null,
|
|
'infraestrutura_id' => $usuarios->first()['infraestrutura_id'] ?? null,
|
|
];
|
|
}
|
|
|
|
if ($pedidoExames->usuario_id) {
|
|
$usuarioEncontrado = $usuarios->firstWhere('id', $pedidoExames->usuario_id);
|
|
|
|
if ($usuarioEncontrado) {
|
|
return [
|
|
'id' => $usuarioEncontrado['id'],
|
|
'ocupacao_id' => $usuarioEncontrado['ocupacao_id'] ?? null,
|
|
'infraestrutura_id' => $usuarioEncontrado['infraestrutura_id'] ?? null,
|
|
];
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
private function getOutrasAvaliacoesCondicoes($atendimento)
|
|
{
|
|
return $atendimento->atendimentosTriagem()->whereNotNull('outras_avaliacoes_condicoes')
|
|
->get()
|
|
->map(function($query) {
|
|
return [
|
|
'centro_custo' => [
|
|
'setor' => [
|
|
'nome' => $query->createdCentroCusto->setor->nome ?? null,
|
|
],
|
|
],
|
|
'classificacao_risco' => [
|
|
'nome' => $query->classificacaoRisco->classificacaoRisco->nome ?? null,
|
|
],
|
|
'data_hora' => $query->created_at->format('d/m/Y H:i:s'),
|
|
'descricao' => $query->outras_avaliacoes_condicoes,
|
|
'lotacao' => [
|
|
'ocupacao' => [
|
|
'nome' => $query->createdLotacao->ocupacao->nome ?? null,
|
|
],
|
|
'profissional' => [
|
|
'nome' => $query->createdLotacao->usuario->cidadao->nome ?? null,
|
|
],
|
|
],
|
|
];
|
|
})
|
|
->values();
|
|
}
|
|
|
|
private function getSolicitacaoReavaliacao(Atendimento $atendimento)
|
|
{
|
|
$atendimentoMedico = $atendimento->atendimentosMedico()
|
|
->orderBy('created_at', 'desc')
|
|
->first();
|
|
|
|
return $atendimentoMedico->solicitou_reavaliacao ?? null;
|
|
}
|
|
|
|
private function getTempoEmObservacao($atendimento)
|
|
{
|
|
$firstPacienteObservacao = $atendimento->pacienteObservacoes
|
|
? $atendimento->pacienteObservacoes()->orderBy('created_at')->first()
|
|
: null;
|
|
|
|
if (is_null($firstPacienteObservacao)) {
|
|
|
|
return '00:00:00';
|
|
}
|
|
|
|
$diff = $firstPacienteObservacao->created_at->diff(Carbon::now());
|
|
|
|
$msg = "{$diff->format('%H:%I:%S')}";
|
|
|
|
if ($diff->d >= 1) {
|
|
|
|
$createdAtPacienteObservacao = new Carbon($firstPacienteObservacao->created_at);
|
|
$timeReach24Hours = $createdAtPacienteObservacao->modify('+24 hours');
|
|
|
|
$msg = "{$timeReach24Hours->format('H:i:s')}";
|
|
}
|
|
|
|
return $msg;
|
|
}
|
|
|
|
private function isPacienteAtingiu24Horas($atendimento)
|
|
{
|
|
$firstPacienteObservacao = $atendimento->pacienteObservacoes
|
|
? $atendimento->pacienteObservacoes()->orderBy('created_at')->first()
|
|
: null;
|
|
|
|
if (is_null($firstPacienteObservacao)) {
|
|
|
|
return false;
|
|
}
|
|
|
|
$diff = $firstPacienteObservacao->created_at->diff(Carbon::now());
|
|
|
|
return $diff->d >= 1;
|
|
}
|
|
|
|
private function getLotacao()
|
|
{
|
|
$lotacao = $this->getLotacaoLogado();
|
|
|
|
return [
|
|
'ocupacao' => [
|
|
'codigo' => $lotacao->ocupacao->codigo,
|
|
'nome' => $lotacao->ocupacao->nome,
|
|
],
|
|
'profissional' => [
|
|
'id' => $lotacao->usuario->id,
|
|
'nome' => $lotacao->usuario->cidadao->nome,
|
|
],
|
|
];
|
|
}
|
|
|
|
private function getLotacaoLogado()
|
|
{
|
|
return Lotacao::findOrFail(auth()->payload()->get('lotacao_id'));
|
|
}
|
|
|
|
private function getAlergiaTipos()
|
|
{
|
|
return AlergiaTipo::all()->map(function($query) {
|
|
return [
|
|
'id' => $query->id,
|
|
'descricao' => $query->descricao,
|
|
];
|
|
});
|
|
}
|
|
|
|
private function getAlergiaCriticidades()
|
|
{
|
|
return AlergiaCriticidade::all()->map(function($query) {
|
|
return [
|
|
'id' => $query->id,
|
|
'nome' => $query->nome,
|
|
];
|
|
});
|
|
}
|
|
|
|
private function getClassificacoesRisco()
|
|
{
|
|
return ClassificacaoRisco::all()->map(function($query) {
|
|
return [
|
|
'id' => $query->id,
|
|
'nome' => $query->nome,
|
|
'cor' => $query->tipo->cor,
|
|
'cor_nome' => $query->tipo->cor_nome,
|
|
];
|
|
});
|
|
}
|
|
|
|
private static function getFatoresRisco()
|
|
{
|
|
$result = FatorRisco::orderBy('id')
|
|
->whereIn('id', [
|
|
FatorRiscoEnum::CANCERO,
|
|
FatorRiscoEnum::DIABETES,
|
|
FatorRiscoEnum::ETILISMO,
|
|
FatorRiscoEnum::HIPERTENSAO,
|
|
FatorRiscoEnum::OBESIDADE,
|
|
FatorRiscoEnum::PERFIL_SANGUINEO_ALTERADO,
|
|
FatorRiscoEnum::RADIOTERAPIA,
|
|
FatorRiscoEnum::TABAGISMO,
|
|
FatorRiscoEnum::USO_DE_MEDICAMENTOS_ANTINEOPLASICOS_OU_IMUNOSSUPRESSORES,
|
|
FatorRiscoEnum::OUTRO,
|
|
])
|
|
->get()
|
|
->map(fn ($fatorRisco) => [
|
|
'id' => $fatorRisco->id,
|
|
'nome' => $fatorRisco->nome,
|
|
]);
|
|
|
|
return $result;
|
|
}
|
|
|
|
private static function getFatoresRiscoGestante()
|
|
{
|
|
$result = FatorRisco::orderBy('nome')
|
|
->whereIn('id', [
|
|
FatorRiscoEnum::CANCERO,
|
|
FatorRiscoEnum::DIABETES,
|
|
FatorRiscoEnum::ETILISMO,
|
|
FatorRiscoEnum::HIPERTENSAO,
|
|
FatorRiscoEnum::OBESIDADE,
|
|
FatorRiscoEnum::PERFIL_SANGUINEO_ALTERADO,
|
|
FatorRiscoEnum::RADIOTERAPIA,
|
|
FatorRiscoEnum::TABAGISMO,
|
|
FatorRiscoEnum::USO_DE_MEDICAMENTOS_ANTINEOPLASICOS_OU_IMUNOSSUPRESSORES,
|
|
FatorRiscoEnum::OUTRO,
|
|
FatorRiscoEnum::GESTANTE,
|
|
])
|
|
->get()
|
|
->map(fn ($fatorRisco) => [
|
|
'id' => $fatorRisco->id,
|
|
'nome' => $fatorRisco->nome,
|
|
]);
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function getTraumas()
|
|
{
|
|
return PacienteTraumaStatus::all()
|
|
->map(function ($pacienteTrauma) {
|
|
|
|
return [
|
|
'id' => $pacienteTrauma->id,
|
|
'nome' => $pacienteTrauma->nome,
|
|
];
|
|
});
|
|
}
|
|
|
|
private function getProfissionaisAtendimento($atendimento)
|
|
{
|
|
return $atendimento->atendimentosMedico
|
|
->map(fn ($atendimentoMedico) => [
|
|
'id' => $atendimentoMedico->createdLotacao->usuario->id,
|
|
'lotacao_id' => $atendimentoMedico->createdLotacao->id,
|
|
'nome' => "{$atendimentoMedico->createdLotacao->usuario->nome} - "
|
|
. $atendimentoMedico->createdLotacao->ocupacao->nome,
|
|
])
|
|
->unique('lotacao_id')
|
|
->values();
|
|
}
|
|
|
|
private function getDesfecho($atendimento)
|
|
{
|
|
$result = [
|
|
'has_previous_desfecho' => false,
|
|
'desfecho_id' => null,
|
|
'profissional' => [
|
|
'nome' => null,
|
|
],
|
|
'alta_medica' => [
|
|
'lotacao_id' => null,
|
|
],
|
|
'evasao' => [
|
|
'motivo' => null,
|
|
],
|
|
'encaminhamento_hospitalar' => [
|
|
'lotacao_id' => null,
|
|
'unidade_id' => null,
|
|
'unidade_outra' => false,
|
|
'unidade_nome' => null,
|
|
'quarto' => null,
|
|
'leito' => null,
|
|
'cid' => null,
|
|
'medico_hospitalar' => null,
|
|
'observacoes' => null,
|
|
],
|
|
'obito' => [
|
|
'obito_em' => null,
|
|
'declaracao' => null,
|
|
'causa' => null,
|
|
'cid' => null,
|
|
'lotacao_id' => null,
|
|
],
|
|
];
|
|
|
|
$atendimentoMedico = $atendimento->atendimentosMedico()
|
|
->whereNotNull('desfecho_id')
|
|
->orderByDesc('created_at')
|
|
->first();
|
|
|
|
if (!is_null($atendimentoMedico)) {
|
|
|
|
$result['has_previous_desfecho'] = true;
|
|
$result['desfecho_id'] = $atendimentoMedico->desfecho_id;
|
|
$result['profissional']['nome'] = $atendimentoMedico->createdLotacao->usuario->cidadao->nome;
|
|
|
|
switch($atendimentoMedico->desfecho_id) {
|
|
|
|
case DesfechoEnum::ALTA_MEDICA: {
|
|
|
|
$result['alta_medica']['lotacao_id'] = $atendimentoMedico->created_lotacao_id;
|
|
|
|
break;
|
|
}
|
|
case DesfechoEnum::EVASAO: {
|
|
|
|
$result['evasao']['motivo'] = $atendimentoMedico->motivo_evasao;
|
|
|
|
break;
|
|
}
|
|
case DesfechoEnum::ENCAMINHAMENTO_HOSPITALAR: {
|
|
|
|
$result['encaminhamento_hospitalar'] = [
|
|
'lotacao_id' => $atendimentoMedico->created_lotacao_id,
|
|
'unidade_id' => $atendimentoMedico->encaminhamentoHospitalar->unidade_id,
|
|
'unidade_outra' => is_null($atendimentoMedico->encaminhamentoHospitalar->unidade_id),
|
|
'unidade_nome' => $atendimentoMedico->encaminhamentoHospitalar->unidade_nome,
|
|
'quarto' => $atendimentoMedico->encaminhamentoHospitalar->quarto,
|
|
'leito' => $atendimentoMedico->encaminhamentoHospitalar->leito,
|
|
'cid' => [
|
|
'id' => $atendimentoMedico->encaminhamentoHospitalar->cid->id,
|
|
'codigo' => $atendimentoMedico->encaminhamentoHospitalar->cid->codigo,
|
|
'nome' => $atendimentoMedico->encaminhamentoHospitalar->cid->nome,
|
|
],
|
|
'medico_hospitalar' => $atendimentoMedico->encaminhamentoHospitalar->medico_hospitalar,
|
|
'observacoes' => $atendimentoMedico->encaminhamentoHospitalar->observacoes,
|
|
];
|
|
|
|
break;
|
|
}
|
|
case DesfechoEnum::OBITO: {
|
|
|
|
$obitoService = new ObitoService($atendimentoMedico->atendimento->faa->paciente->cidadao);
|
|
$obito = $obitoService->get();
|
|
|
|
$result['obito'] = [
|
|
'obito_em' => $obito->obito_em,
|
|
'declaracao' => $obito->declaracao,
|
|
'causa' => $obito->causa,
|
|
'cid' => [
|
|
'id' => $obito->cid->id,
|
|
'nome' => $obito->cid->nome,
|
|
],
|
|
'cidadao' => [
|
|
'nome' => $atendimentoMedico->atendimento->faa->paciente->cidadao->nome,
|
|
],
|
|
'lotacao_id' => $atendimentoMedico->created_lotacao_id,
|
|
];
|
|
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function getGlasgowAberturaOcular()
|
|
{
|
|
return GlasgowAberturaOcular::all()
|
|
->map(function ($aberturaOcular) {
|
|
|
|
return [
|
|
'id' => $aberturaOcular->id,
|
|
'descricao' => $aberturaOcular->descricao,
|
|
'pontos' => $aberturaOcular->pontos,
|
|
];
|
|
});
|
|
}
|
|
|
|
private function getGlasgowReatividadePupilar()
|
|
{
|
|
return GlasgowReatividadePupilar::all()
|
|
->map(function ($reatividadePupilar) {
|
|
|
|
return [
|
|
'id' => $reatividadePupilar->id,
|
|
'descricao' => $reatividadePupilar->descricao,
|
|
'pontos' => $reatividadePupilar->pontos,
|
|
];
|
|
});
|
|
}
|
|
|
|
private function getGlasgowRespostaMotora()
|
|
{
|
|
return GlasgowRespostaMotora::all()
|
|
->map(function ($respostaMotora) {
|
|
|
|
return [
|
|
'id' => $respostaMotora->id,
|
|
'descricao' => $respostaMotora->descricao,
|
|
'pontos' => $respostaMotora->pontos,
|
|
];
|
|
});
|
|
}
|
|
|
|
private function getGlasgowRespostaVerbal()
|
|
{
|
|
return GlasgowRespostaVerbal::all()
|
|
->map(function ($respostaVerbal) {
|
|
|
|
return [
|
|
'id' => $respostaVerbal->id,
|
|
'descricao' => $respostaVerbal->descricao,
|
|
'pontos' => $respostaVerbal->pontos,
|
|
];
|
|
});
|
|
}
|
|
|
|
private function getPaciente($atendimento)
|
|
{
|
|
return [
|
|
'id' => $atendimento->faa->paciente->id,
|
|
'nome' => $atendimento->faa->paciente->cidadao->nome,
|
|
'nome_social' => $atendimento->faa->paciente->cidadao->nome_social,
|
|
'preferencia_nome_id' => $atendimento->faa->paciente->cidadao->preferencia_nome_id,
|
|
'prontuario' => $atendimento->faa->paciente->prontuario,
|
|
'data_nascimento' => $atendimento->faa->paciente->cidadao->data_nascimento,
|
|
'idade' => $atendimento->faa->paciente->cidadao->idade,
|
|
'sexo' => $atendimento->faa->paciente->cidadao->sexo,
|
|
'is_desconhecido' => $atendimento->faa->paciente->is_desconhecido,
|
|
'pcd' => $this->getPcd($atendimento->faa->paciente->cidadao)
|
|
];
|
|
}
|
|
|
|
private function getPcd($cidadao)
|
|
{
|
|
if ($cidadao->deficiencia_id === null) {
|
|
|
|
return null;
|
|
}
|
|
|
|
$deficiencia = [
|
|
'id' => $cidadao->deficiencia->id,
|
|
'deficiencia_base_id' => $cidadao->deficiencia->deficiencia_base_id,
|
|
'descricao' => $cidadao->deficiencia->descricao,
|
|
];
|
|
|
|
if ($cidadao->deficiencia->deficiencia_base_id === Deficiencia::OUTRA) {
|
|
|
|
$deficiencia['deficiencia_outro'] = $cidadao->deficiencia_outro;
|
|
|
|
return $deficiencia;
|
|
}
|
|
|
|
return $deficiencia;
|
|
}
|
|
|
|
private function getUnidadesMedida()
|
|
{
|
|
return UnidadeMedida::all()->map(function($query) {
|
|
return [
|
|
'id' => $query->id,
|
|
'nome' => $query->nome,
|
|
'sigla' => $query->sigla,
|
|
];
|
|
});
|
|
}
|
|
|
|
private function getAreaAtendimentoMedicoByKey($atendimento, $key)
|
|
{
|
|
$atendimentosMedico = $atendimento->atendimentosMedico()
|
|
->whereNotNull($key)
|
|
->orderBy('created_at')
|
|
->get();
|
|
|
|
$result = [];
|
|
|
|
$fieldsAtendimentoSimples = array('evolucao', 'atendimento_geral', 'observacoes_enfermagem');
|
|
$fieldsAtendimentoEstruturado = array(
|
|
'evolucao',
|
|
'queixa_principal_duracao',
|
|
'historia',
|
|
'exame_fisico',
|
|
'diagnostico',
|
|
'conduta',
|
|
'observacoes_enfermagem',
|
|
);
|
|
|
|
foreach ($atendimentosMedico as $atendimentoMedico) {
|
|
|
|
if ($atendimentoMedico->simples) {
|
|
|
|
if (in_array($key, $fieldsAtendimentoSimples)) {
|
|
|
|
$result[] = array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($atendimentoMedico, $atendimentoMedico->atendimento),
|
|
[
|
|
'descricao' => $atendimentoMedico->$key
|
|
]
|
|
);
|
|
}
|
|
|
|
continue;
|
|
}
|
|
|
|
if (in_array($key, $fieldsAtendimentoEstruturado)) {
|
|
|
|
$result[] = array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($atendimentoMedico, $atendimentoMedico->atendimento),
|
|
[
|
|
'descricao' => $atendimentoMedico->$key
|
|
]
|
|
);
|
|
}
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function getAreaAtendimentoEnfermagemByKey($atendimento, $key)
|
|
{
|
|
switch($key) {
|
|
|
|
case 'historico': {
|
|
|
|
return Historico::where('atendimento_id', $atendimento->id)
|
|
->orderBy('created_at')
|
|
->get()
|
|
->map(function ($historico) use ($atendimento) {
|
|
|
|
return array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($historico, $atendimento),
|
|
[
|
|
'descricao' => $historico->descricao,
|
|
]
|
|
);
|
|
});
|
|
}
|
|
|
|
case 'diagnostico': {
|
|
|
|
return Diagnostico::where('atendimento_id', $atendimento->id)
|
|
->orderBy('created_at')
|
|
->get()
|
|
->map(function ($diagnostico) use ($atendimento) {
|
|
|
|
return array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($diagnostico, $atendimento),
|
|
[
|
|
'descricao' => $diagnostico->descricao,
|
|
''
|
|
]
|
|
);
|
|
});
|
|
}
|
|
|
|
case 'planejamento': {
|
|
|
|
return Planejamento::where('atendimento_id', $atendimento->id)
|
|
->orderBy('created_at')
|
|
->get()
|
|
->map(function ($planejamento) use ($atendimento) {
|
|
|
|
return array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($planejamento, $atendimento),
|
|
[
|
|
'descricao' => $planejamento->descricao,
|
|
]
|
|
);
|
|
});
|
|
}
|
|
|
|
case 'implementacao': {
|
|
|
|
return Implementacao::where('atendimento_id', $atendimento->id)
|
|
->orderBy('created_at')
|
|
->get()
|
|
->map(function ($implementacao) use ($atendimento) {
|
|
|
|
return array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($implementacao, $atendimento),
|
|
[
|
|
'descricao' => $implementacao->descricao,
|
|
]
|
|
);
|
|
});
|
|
}
|
|
|
|
case 'avaliacao': {
|
|
|
|
return Avaliacao::where('atendimento_id', $atendimento->id)
|
|
->orderBy('created_at')
|
|
->get()
|
|
->map(function ($avaliacao) use ($atendimento) {
|
|
|
|
return array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($avaliacao, $atendimento),
|
|
[
|
|
'descricao' => $avaliacao->descricao,
|
|
]
|
|
);
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
private function getMedicamentosUso($atendimento)
|
|
{
|
|
return $atendimento->medicamentosUso->map(function($query) {
|
|
return array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($query, $query->atendimento),
|
|
[
|
|
'descricao' => $query->descricao,
|
|
]
|
|
);
|
|
});
|
|
}
|
|
|
|
private function getSinaisVitais($atendimento)
|
|
{
|
|
$sinaisVitais = $atendimento->sinaisVitais()->get();
|
|
$result = [];
|
|
|
|
foreach ($sinaisVitais as $sinalVital) {
|
|
|
|
$result[] = [
|
|
'id' => $sinalVital->id,
|
|
'pa' => $sinalVital->pa,
|
|
'pa_unidade_medida_id' => $sinalVital->pa_unidade_medida_id,
|
|
'glicemia' => $sinalVital->glicemia,
|
|
'glicemia_unidade_medida_id' => UnidadeMedidaEnum::MILIGRAMAS_POR_DECILITRO,
|
|
'temperatura' => $sinalVital->temperatura,
|
|
'temperatura_unidade_medida_id' => UnidadeMedidaEnum::CELSIUS,
|
|
'pulso' => $sinalVital->pulso,
|
|
'pulso_unidade_medida_id' => UnidadeMedidaEnum::BATIMENTOS_POR_MINUTO,
|
|
'respiracao' => $sinalVital->respiracao,
|
|
'respiracao_unidade_medida_id' => UnidadeMedidaEnum::MOVIMENTOS_POR_MINUTO,
|
|
'saturacao' => $sinalVital->saturacao,
|
|
'saturacao_unidade_medida_id' => UnidadeMedidaEnum::PORCENTAGEM,
|
|
'intensidade_dor' => $sinalVital->intensidade_dor,
|
|
'intensidade_dor_unidade_medida_id' => UnidadeMedidaEnum::NIVEL_DE_DOR,
|
|
'cintura' => $sinalVital->cintura,
|
|
'cintura_unidade_medida_id' => UnidadeMedidaEnum::CENTIMETROS,
|
|
'lotacao' => [
|
|
'ocupacao' => [
|
|
'id' => $sinalVital->createdLotacao->ocupacao->id ?? null,
|
|
'codigo' => $sinalVital->createdLotacao->ocupacao->codigo ?? null,
|
|
'nome' => $sinalVital->createdLotacao->ocupacao->nome ?? null,
|
|
],
|
|
'profissional' => [
|
|
'nome' => $sinalVital->createdLotacao->usuario->cidadao->nome ?? null,
|
|
],
|
|
],
|
|
'centro_custo' => [
|
|
'setor' => [
|
|
'nome' => $sinalVital->createdCentroCusto->setor->nome ?? null,
|
|
],
|
|
],
|
|
'classificacao_risco' => [
|
|
'nome' => ($sinalVital->atendimentoTriagem->classificacaoRisco
|
|
?? $sinalVital->atendimentoMedico->classificacaoRisco
|
|
?? $sinalVital->atendimentoEnfermagem->classificacaoRisco
|
|
?? $sinalVital->pacienteObservacao->classificacaoRisco
|
|
?? null
|
|
)->classificacaoRisco->nome ?? null,
|
|
],
|
|
'data_hora' => $sinalVital->created_at->format('d/m/Y H:i:s'),
|
|
];
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function getAvaliacaoAntropometrica($atendimento)
|
|
{
|
|
$avaliacaoAntropometrica = $atendimento->avaliacoesAntropometricas()->orderByDesc('created_at')->first();
|
|
|
|
return array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($avaliacaoAntropometrica, $atendimento),
|
|
[
|
|
'massa' => $avaliacaoAntropometrica->massa ?? null,
|
|
'massa_unidade_medida_id' => $avaliacaoAntropometrica->massa_unidade_medida_id ?? UnidadeMedidaEnum::QUILOGRAMAS,
|
|
'altura_tipo_medida_id' => $avaliacaoAntropometrica->altura_tipo_medida_id ?? TipoMedidaAlturaEnum::ESTATURA,
|
|
'altura' => $avaliacaoAntropometrica->altura ?? null,
|
|
'altura_unidade_medida_id' => $avaliacaoAntropometrica->altura_unidade_medida_id ?? UnidadeMedidaEnum::METROS,
|
|
'imc' => [
|
|
'imc' => $avaliacaoAntropometrica->imc['imc'] ?? null,
|
|
'classificacao' => $avaliacaoAntropometrica->imc['classificacao'] ?? null,
|
|
],
|
|
]
|
|
);
|
|
}
|
|
|
|
private function getAnotacoes($atendimento)
|
|
{
|
|
return Anotacao::where(function ($query) use ($atendimento) {
|
|
|
|
$query
|
|
->whereHas('atendimentoEnfermagem', function ($query) use ($atendimento) {
|
|
|
|
$query->where('atendimento_id', $atendimento->id);
|
|
})
|
|
->orWhereHas('pacienteObservacao', function ($query) use ($atendimento) {
|
|
|
|
$query->where('atendimento_id', $atendimento->id);
|
|
});
|
|
})
|
|
->get()
|
|
->map(function ($anotacao) {
|
|
|
|
$atendimentoAnotacao = $anotacao->pacienteObservacao ?? $anotacao->atendimentoEnfermagem;
|
|
|
|
return array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($atendimentoAnotacao, $atendimentoAnotacao->atendimento),
|
|
[
|
|
'id' => $anotacao->id,
|
|
'data_hora_anotacao' => $anotacao->anotado_em->format('d/m/Y H:i'),
|
|
'anotacao' => $anotacao->descricao,
|
|
]
|
|
);
|
|
})
|
|
->sortBy('created_at');
|
|
}
|
|
|
|
private function getEscalasComaGlasgow($atendimento)
|
|
{
|
|
return EscalaComaGlasgow::whereHas('pacienteObservacao', function($query) use ($atendimento) {
|
|
|
|
$query->where('atendimento_id', $atendimento->id);
|
|
})->orWhereHas('atendimentoTriagem', function($query) use ($atendimento) {
|
|
|
|
$query->where('atendimento_id', $atendimento->id);
|
|
})
|
|
->get()
|
|
->map(function ($escalaComaGlasgow) use ($atendimento) {
|
|
|
|
return array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($escalaComaGlasgow, $atendimento),
|
|
[
|
|
'id' => $escalaComaGlasgow->id,
|
|
'pontuacao' => $this->getEscalaComaGlasgowPontuacao($escalaComaGlasgow),
|
|
'abertura_ocular' => $escalaComaGlasgow->aberturaOcular,
|
|
'resposta_verbal' => $escalaComaGlasgow->respostaVerbal,
|
|
'resposta_motora' => $escalaComaGlasgow->respostaMotora,
|
|
'reatividade_pupilar' => $escalaComaGlasgow->reatividadePupilar,
|
|
'observacoes' => $escalaComaGlasgow->observacao,
|
|
'resultado' => $this->getEscalaComaGlasgowResultado($escalaComaGlasgow),
|
|
]
|
|
);
|
|
});
|
|
}
|
|
|
|
private function getProcedimentos($atendimento, $tipoAtendimento)
|
|
{
|
|
$procedimentos = $atendimento->procedimentos()
|
|
->with('procedimento', 'cidPrincipal')
|
|
->whereNotNull($tipoAtendimento . '_id')
|
|
->orderBy('created_at')
|
|
->get();
|
|
|
|
$result = [];
|
|
|
|
foreach ($procedimentos as $procedimento) {
|
|
|
|
$result[] = array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($procedimento, $atendimento),
|
|
[
|
|
'id' => $procedimento->id,
|
|
'cbo' => $procedimento->createdLotacao->ocupacao->codigo,
|
|
'procedimento' => [
|
|
'nome' => $procedimento->procedimento->nome ?? null,
|
|
'codigo' => $procedimento->procedimento->codigo ?? null,
|
|
],
|
|
'codigo' => $procedimento->procedimento->codigo ?? null,
|
|
'cid_principal' => [
|
|
'id' => $procedimento->cidPrincipal->id ?? null,
|
|
'codigo' => $procedimento->cidPrincipal->codigo ?? null,
|
|
'nome' => $procedimento->cidPrincipal->nome ?? null,
|
|
],
|
|
'quantidade' => $procedimento->quantidade ?? null,
|
|
]
|
|
);
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function getPedidosExames($atendimento, $isForm = false)
|
|
{
|
|
$result = [];
|
|
|
|
foreach ($atendimento->pedidosExames as $pedidoExames) {
|
|
|
|
$exames = $this->getExamesPedidoExames($pedidoExames);
|
|
|
|
$usuarioUnidade = $this->handleUsuarioUnidade($pedidoExames);
|
|
$usuarioLaboratorio = $this->handleUsuarioLaboratorio($pedidoExames);
|
|
|
|
$dataPedido = [
|
|
'id' => $pedidoExames->id,
|
|
'urgente' => $pedidoExames->urgente,
|
|
"dataSolicitacao" => $pedidoExames->created_at->format('d/m/Y H:i'),
|
|
"centro_custo" => [
|
|
"infraestrutura" => $pedidoExames->createdLotacao->infraestrutura->unidade->nome_fantasia,
|
|
"setor" => $pedidoExames->createdCentroCusto->setor->nome
|
|
],
|
|
'lotacao' => [
|
|
'ocupacao' => [
|
|
'codigo' => $pedidoExames->createdLotacao->ocupacao->codigo,
|
|
'nome' => $pedidoExames->createdLotacao->ocupacao->nome
|
|
],
|
|
'profissional' => [
|
|
'nome' => $pedidoExames->createdLotacao->usuario->cidadao->nome,
|
|
]
|
|
],
|
|
'justificativa' => $pedidoExames->justificativa,
|
|
'usuario_id' => $usuarioUnidade ? $usuarioUnidade['id'] : null,
|
|
'ocupacao_id' => $usuarioUnidade ? $usuarioUnidade['ocupacao_id'] : null,
|
|
'usuario_infraestrutura_id' => $usuarioUnidade ? $usuarioUnidade['infraestrutura_id'] : null,
|
|
'laboratorio_usuario_id' => $usuarioLaboratorio ? $usuarioLaboratorio['id'] : null,
|
|
'laboratorio_ocupacao_id' => $usuarioLaboratorio ? $usuarioLaboratorio['ocupacao_id'] : null,
|
|
'laboratorio_infraestrutura_id' => $usuarioLaboratorio ? $usuarioLaboratorio['infraestrutura_id'] : null,
|
|
'exames' => $exames,
|
|
'files' => $pedidoExames->laudos
|
|
->where('created_at', '>=', $pedidoExames->created_at)
|
|
->map(fn($laudo) => [
|
|
'id' => $laudo->id,
|
|
'name' => $laudo->nome,
|
|
'hash' => $laudo->hash
|
|
])
|
|
];
|
|
|
|
if($isForm && !$this->hasExamesLaboratorialSolicitadosOrAguardandoResultado($pedidoExames)) {
|
|
$result[] = $dataPedido;
|
|
}
|
|
|
|
if(!$isForm && $this->hasExamesLaboratorialSolicitadosOrAguardandoResultado($pedidoExames)) {
|
|
$result[] = $dataPedido;
|
|
}
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function getExamesPedidoExames($pedidoExames)
|
|
{
|
|
$itens = $pedidoExames->exames();
|
|
|
|
return $itens->get()
|
|
->map(function ($item) {
|
|
|
|
$disabled =
|
|
$item->status_id === ExameStatusEnum::REALIZADO
|
|
|| $item->status_id === ExameStatusEnum::NAO_REALIZADO
|
|
|| $item->exame->tipo_id === ExameTipo::IMAGEM;
|
|
|
|
$disabled_horario =
|
|
$item->status_id === ExameStatusEnum::REALIZADO && $item->horario_realizacao != null
|
|
|| $item->status_id === ExameStatusEnum::NAO_REALIZADO
|
|
|| $item->exame->tipo_id === ExameTipo::IMAGEM;
|
|
|
|
return [
|
|
'id' => $item->id,
|
|
'data_solicitacao' => $item->data_solicitacao ?? $item->created_at->format('d/m/Y H:i'),
|
|
'unidade_solicitante' =>
|
|
$item->unidade_solicitante ??
|
|
$item->createdLotacao->infraestrutura->unidade->nome_fantasia,
|
|
'medico_solicitante' => $item->medico_solicitante ?? $item->createdLotacao->usuario->cidadao->nome,
|
|
'observacoes' => $this->getObservacoes($item),
|
|
'disabled' => $disabled,
|
|
'disabled_horario' => $disabled_horario,
|
|
'horario_realizacao' => $item->horario_realizacao,
|
|
'exame' => [
|
|
'id' => $item->exame->id,
|
|
'nome' => $item->exame->nome,
|
|
'tipo' => [
|
|
'id' => $item->exame->tipo->id,
|
|
'nome' => $item->exame->tipo->nome,
|
|
],
|
|
'procedimento' => [
|
|
'codigo' => $item->exame->procedimento->codigo ?? null,
|
|
'nome' => $item->exame->procedimento->nome ?? null,
|
|
],
|
|
'observacao' => $item->exame->observacao
|
|
],
|
|
'status' => [
|
|
'id' => $item->status->id,
|
|
'nome' => $item->status->nome,
|
|
],
|
|
];
|
|
});
|
|
}
|
|
|
|
private function hasExamesLaboratorialSolicitadosOrAguardandoResultado($pedidoExames)
|
|
{
|
|
foreach($pedidoExames->exames as $item) {
|
|
|
|
if($item->exame->tipo_id === ExameTipo::LABORATORIAL) {
|
|
|
|
if($item->status_id === ExameStatusEnum::SOLICITADO) {
|
|
return true;
|
|
} else if ($item->status_id === ExameStatusEnum::AGUARDANDO_RESULTADO) {
|
|
return true;
|
|
} else if ($item->status_id === ExameStatusEnum::REALIZADO && $item->horario_realizacao == null) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private function getObservacoes($item)
|
|
{
|
|
return Observacao::where('item_id', $item->id)->get()
|
|
->map(function ($observacao) use ($item) {
|
|
return array_merge (
|
|
$this->getBaseHistoricoAreaAtendimento($observacao, $item->pedidoExame->atendimento),
|
|
[
|
|
'observacao' => $observacao->observacao
|
|
]
|
|
);
|
|
});
|
|
}
|
|
|
|
private function getEscalaComaGlasgowResultado($escalaComaGlasgow)
|
|
{
|
|
$pontuacao = $this->getEscalaComaGlasgowPontuacao($escalaComaGlasgow);
|
|
|
|
if ($escalaComaGlasgow->aberturaOcular->pontos === 0
|
|
|| $escalaComaGlasgow->respostaVerbal->pontos === 0
|
|
|| $escalaComaGlasgow->respostaMotora->pontos === 0) {
|
|
|
|
return 'A pontuação não pode ser calculada. Um ou mais itens não foram testados';
|
|
}
|
|
|
|
$glasgowInterpretacaoResultado = GlasgowInterpretacaoResultado::all();
|
|
|
|
$result = $glasgowInterpretacaoResultado->filter(function ($glasgowInterpretacaoResultado, $key) use ($pontuacao) {
|
|
|
|
return $pontuacao >= $glasgowInterpretacaoResultado->min
|
|
&& $pontuacao <= ($glasgowInterpretacaoResultado->max ?? PHP_INT_MAX);
|
|
})->first();
|
|
|
|
return $result->descricao;
|
|
}
|
|
|
|
private function getEscalaComaGlasgowPontuacao($escalaComaGlasgow)
|
|
{
|
|
$result = $escalaComaGlasgow->aberturaOcular->pontos
|
|
+ $escalaComaGlasgow->respostaVerbal->pontos
|
|
+ $escalaComaGlasgow->respostaMotora->pontos
|
|
- $escalaComaGlasgow->reatividadePupilar->pontos;
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function getModelData($atendimento)
|
|
{
|
|
$classificacaoRisco = $this->getClassificacaoRisco($atendimento);
|
|
$pacienteObservacoes = $atendimento->pacienteObservacoes()->orderBy('created_at')->get();
|
|
$firstPacienteObservacao = $pacienteObservacoes->first();
|
|
$lastPacienteObservacao = $pacienteObservacoes->last();
|
|
|
|
$faa = $atendimento->faa;
|
|
$parecerMedico = $faa->raat && $faa->raat->pareceresMedico ? $faa->raat->pareceresMedico()->orderByDesc('created_at')->first() : [];
|
|
|
|
if ($atendimento->dor_toracica == true) {
|
|
|
|
$formulario = FormularioDorToracica::where('atendimento_id', $atendimento->id)->get();
|
|
|
|
foreach ($formulario as $registro) {
|
|
|
|
$formulario_id = $registro->id;
|
|
$data_sintoma = $registro->data_sintoma;
|
|
$hora_sintoma = $registro->hora_sintoma;
|
|
$data_ecg_admissao = $registro->data_ecg_admissao;
|
|
$hora_ecg_admissao = $registro->hora_ecg_admissao;
|
|
$dispneia = $registro->dispneia;
|
|
}
|
|
|
|
$formularioRelacionadoDor = RelacionadoFormularioDorToracica::where('formulario_id', $formulario_id)->get();
|
|
|
|
$dorToracicaRelacionada = [];
|
|
|
|
foreach ($formularioRelacionadoDor as $registroRelacionado) {
|
|
|
|
$dorToracicaRelacionada[] = $registroRelacionado->dor_toracica_id;
|
|
}
|
|
}
|
|
|
|
if($atendimento->faa->paciente->cidadao->sexo_id === Sexo::FEMININO && $atendimento->faa->paciente->cidadao->idade
|
|
&& $atendimento->faa->paciente->cidadao->idade['anos'] >= 9
|
|
&& $atendimento->faa->paciente->cidadao->idade['anos'] <= 60){
|
|
|
|
$exibirFatorRiscoGestante = true;
|
|
} else {
|
|
$exibirFatorRiscoGestante = false;
|
|
}
|
|
|
|
return [
|
|
'atendimento_id' => $atendimento->id,
|
|
'dor_toracica' => $atendimento->dor_toracica,
|
|
'quarto' => $lastPacienteObservacao->quarto ?? null,
|
|
'leito' => $lastPacienteObservacao->leito ?? null,
|
|
'aguardando_vaga_hospitalar' => $lastPacienteObservacao->aguardando_vaga_hospitalar ?? null,
|
|
'hemorragia_externa_grave_trauma_status_id' => $lastPacienteObservacao->hemorragia_externa_grave_trauma_status_id ?? null,
|
|
'hemorragia_externa_grave_local' => $lastPacienteObservacao->hemorragia_externa_grave_local ?? null,
|
|
'vias_aerias_trauma_status_id' => $lastPacienteObservacao->vias_aerias_trauma_status_id ?? null,
|
|
'vias_aerias_obstrucao_por' => $lastPacienteObservacao->vias_aerias_obstrucao_por ?? null,
|
|
'oxigenacao_respiracao_ventilacao_trauma_status_id' => $lastPacienteObservacao->oxigenacao_respiracao_ventilacao_trauma_status_id ?? null,
|
|
'pulso_trauma_status_id' => $lastPacienteObservacao->pulso_trauma_status_id ?? null,
|
|
'pele_trauma_status_id' => $lastPacienteObservacao->pele_trauma_status_id ?? null,
|
|
'pele_alteracao' => $lastPacienteObservacao->pele_alteracao ?? null,
|
|
'perfuracao_trauma_status_id' => $lastPacienteObservacao->perfuracao_trauma_status_id ?? null,
|
|
'perfuracao_lentificada' => $lastPacienteObservacao->perfuracao_lentificada ?? null,
|
|
'sangramento_trauma_status_id' => $lastPacienteObservacao->sangramento_trauma_status_id ?? null,
|
|
'sangramento_local' => $lastPacienteObservacao->sangramento_local ?? null,
|
|
'pupilas_trauma_status_id' => $lastPacienteObservacao->pupilas_trauma_status_id ?? null,
|
|
'paresias_trauma_status_id' => $lastPacienteObservacao->paresias_trauma_status_id ?? null,
|
|
'plegia_trauma_status_id' => $lastPacienteObservacao->plegia_trauma_status_id ?? null,
|
|
'exposicao_hipotermia_trauma_status_id' => $lastPacienteObservacao->exposicao_hipotermia_trauma_status_id ?? null,
|
|
'exposicao_hipotermia_observacao' => $lastPacienteObservacao->exposicao_hipotermia_observacao ?? null,
|
|
'avaliacao_cabeca_pescoco' => $this->getAvaliacaoCabecaPescoco($lastPacienteObservacao) ?? null,
|
|
'avaliacao_torax' => $lastPacienteObservacao->avaliacao_torax ?? null,
|
|
'avaliacao_abdome' => $lastPacienteObservacao->avaliacao_abdome ?? null,
|
|
'avaliacao_mmss_mmii' => $lastPacienteObservacao->avaliacao_mmss_mmii ?? null,
|
|
'observacao' => $lastPacienteObservacao->observacao ?? null,
|
|
|
|
'classificacao_risco_id' => $classificacaoRisco['classificacao_risco_id'] ?? null,
|
|
'gestacao' => $this->getGestacao($atendimento),
|
|
'medicamentos_uso' => null,
|
|
'sinais_vitais' => [],
|
|
'acidente_trabalho' => AcidenteTrabalhoService::getAcidenteTrabalho($atendimento->faa),
|
|
'alergias' => $this->getAlergias($atendimento),
|
|
'medicamentos_uso_continuo' => $this->getMedicamentosUsoContinuo($atendimento, Carbon::now()),
|
|
'fatores_risco' => $this->getCidadaoFatoresRisco($atendimento),
|
|
'fator_risco_outro' => $atendimento->faa->paciente->cidadao->fator_risco_outro,
|
|
'servicos_enfermagem' => $this->getServicosEnfermagem($atendimento, false),
|
|
'prescricoes_interna' => $this->getPrescricoesInterna($atendimento, false),
|
|
'avaliacao_antropometrica' => $this->getAvaliacaoAntropometrica($atendimento),
|
|
'escalas_coma_glasgow' => [],
|
|
'anotacoes' => [],
|
|
'historico' => null,
|
|
'diagnostico' => null,
|
|
'planejamento' => null,
|
|
'implementacao' => null,
|
|
'avaliacao' => null,
|
|
'procedimentos' => [],
|
|
'pedidos_exames' => $this->getPedidosExames($atendimento),
|
|
'finalizacao' => $this->getDesfecho($atendimento),
|
|
'dor_toracica_data_sintoma' => $data_sintoma ?? null,
|
|
'dor_toracica_hora_sintoma' => $hora_sintoma ?? null,
|
|
'dor_toracica_data_ecg_admissao' => $data_ecg_admissao ?? null,
|
|
'dor_toracica_hora_ecg_admissao' => $hora_ecg_admissao ?? null,
|
|
'dor_toracica_caracteristica_dor' => $dorToracicaRelacionada ?? null,
|
|
'dor_toracica_localizacao_dor' => $dorToracicaRelacionada ?? null,
|
|
'dor_toracica_fator_descadeante' => $dorToracicaRelacionada ?? null,
|
|
'dor_toracica_duracao_dor' => $dorToracicaRelacionada ?? null,
|
|
'dor_toracica_fatores_riscos' => $dorToracicaRelacionada ?? null,
|
|
'dor_toracica_dispneia' => $dispneia ?? null,
|
|
'cancelamento_desfecho' => false,
|
|
'exibir_fator_risco_gestante' => $exibirFatorRiscoGestante,
|
|
];
|
|
}
|
|
|
|
private function getAvaliacaoCabecaPescoco($pacienteObservacao)
|
|
{
|
|
if (is_null($pacienteObservacao)) {
|
|
|
|
return [
|
|
'avaliacao_cabeca_pescoco' => null
|
|
];
|
|
}
|
|
|
|
return array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($pacienteObservacao, null),
|
|
[
|
|
'avaliacao_cabeca_pescoco' => $pacienteObservacao->avaliacao_cabeca_pescoco ?? null,
|
|
]
|
|
);
|
|
}
|
|
|
|
private function getGestacao($atendimento)
|
|
{
|
|
$gestacao = $atendimento->gestacoes()->orderByDesc('created_at')->first();
|
|
$gestacaoPaciente = $atendimento->faa->paciente->dum;
|
|
|
|
return [
|
|
'dpp' => $gestacaoPaciente && $gestacaoPaciente->data_possivel_parto
|
|
? Carbon::create($gestacaoPaciente->data_possivel_parto)->format('d/m/Y')
|
|
: $gestacao->dpp ?? null,
|
|
'dum_min_date' => $atendimento->created_at->subDays(308)->format('d/m/Y'),
|
|
'dum_max_date' => $atendimento->created_at->format('d/m/Y'),
|
|
'dum' => $gestacaoPaciente && $gestacaoPaciente->data_ultima_menstruacao
|
|
? $gestacaoPaciente->data_ultima_menstruacao
|
|
: $gestacao->dum ?? null,
|
|
'gestante' => $atendimento->faa->paciente->cidadao->fatoresRisco->contains(FatorRiscoEnum::GESTANTE)
|
|
?? $gestacao->gestante ?? false,
|
|
'idade_gestacional' => [
|
|
'dias' => $gestacaoPaciente && $gestacaoPaciente->idade_gestacional_dias
|
|
? $gestacaoPaciente->idade_gestacional_dias
|
|
: $gestacao->idade_gestacional['dias'] ?? null,
|
|
'semanas' => $gestacaoPaciente && $gestacaoPaciente->idade_gestacional_semanas
|
|
? $gestacaoPaciente->idade_gestacional_semanas
|
|
: $gestacao->idade_gestacional['semanas'] ?? null,
|
|
],
|
|
];
|
|
}
|
|
|
|
private function getAlergias($atendimento)
|
|
{
|
|
$alergias = $atendimento->faa->paciente->cidadao->alergias;
|
|
$result = [];
|
|
|
|
foreach ($alergias as $i => $alergia) {
|
|
$result[] = array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($alergia->cidadaoAlergia, null),
|
|
[
|
|
'index' => $i,
|
|
'alergia' => [
|
|
'agente_substancia_especifica' => $alergia->agente_substancia_especifica,
|
|
'criticidade' => [
|
|
'id' => $alergia->cidadaoAlergia->criticidade->id,
|
|
'nome' => $alergia->cidadaoAlergia->criticidade->nome,
|
|
],
|
|
'id' => $alergia->cidadaoAlergia->alergia_id,
|
|
'reacoes_observacoes' => $alergia->cidadaoAlergia->reacoes_observacoes,
|
|
'tipo' => [
|
|
'id' => $alergia->tipo->id,
|
|
'descricao' => $alergia->tipo->descricao,
|
|
]
|
|
],
|
|
]);
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function getMedicamentosUsoContinuo($atendimento, $datetime)
|
|
{
|
|
$medicamentos = $atendimento->faa->paciente->cidadao->medicamentosUsoContinuo()->wherePivot('created_at', '<=', $datetime)->get();
|
|
$result = [];
|
|
|
|
foreach ($medicamentos as $medicamento) {
|
|
$result[] = [
|
|
'medicamento' => [
|
|
'nome' => $medicamento->nome,
|
|
'id' => $medicamento->CidadaoMedicamentoUsoContinuo->medicamento_id,
|
|
],
|
|
'lotacao' => [
|
|
'ocupacao' => [
|
|
'id' => $medicamento->CidadaoMedicamentoUsoContinuo->createdLotacao->ocupacao->id ?? null,
|
|
'codigo' => $medicamento->CidadaoMedicamentoUsoContinuo->createdLotacao->ocupacao->codigo ?? null,
|
|
'nome' => $medicamento->CidadaoMedicamentoUsoContinuo->createdLotacao->ocupacao->nome ?? null,
|
|
],
|
|
'profissional' => [
|
|
'nome' => $medicamento->CidadaoMedicamentoUsoContinuo->createdLotacao->usuario->cidadao->nome ?? null,
|
|
],
|
|
],
|
|
'centro_custo' => [
|
|
'setor' => [
|
|
'nome' => $medicamento->CidadaoMedicamentoUsoContinuo->createdCentroCusto->setor->nome ?? null,
|
|
],
|
|
],
|
|
'data_hora' => $medicamento->CidadaoMedicamentoUsoContinuo->created_at->format('d/m/Y H:i:s') ?? null,
|
|
];
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function getCidadaoFatoresRisco($atendimento)
|
|
{
|
|
$cidadao = $atendimento->faa->paciente->cidadao;
|
|
|
|
return $cidadao->fatoresRisco->pluck('id');
|
|
}
|
|
|
|
private function getClassificacaoRisco($atendimento)
|
|
{
|
|
if (is_null($atendimento)) {
|
|
|
|
return null;
|
|
}
|
|
|
|
$classificacaoRisco = $atendimento->classificacoesRisco()
|
|
->get()
|
|
->sortByDesc('created_at')
|
|
->first();
|
|
|
|
if ($classificacaoRisco == null)
|
|
return null;
|
|
|
|
return [
|
|
'id' => $classificacaoRisco->id,
|
|
'classificacao_risco_id' => $classificacaoRisco->classificacao_risco_id,
|
|
'nome' => $classificacaoRisco->classificacaoRisco->nome,
|
|
];
|
|
}
|
|
|
|
public function store(ObservacaoRequest $request)
|
|
{
|
|
$this->auth(__FUNCTION__);
|
|
|
|
$pacienteObservacao = new PacienteObservacao();
|
|
|
|
DB::transaction(function() use ($pacienteObservacao, $request) {
|
|
|
|
$atendimento = Atendimento::findOrFail($request['atendimento_id']);
|
|
$params = $request->all();
|
|
|
|
PlantaoService::setStatusComAtendimento($request->plantao_id);
|
|
|
|
$pacienteObservacao->fill($this->preparePacienteObservacaoData($params));
|
|
$pacienteObservacao->plantao_id = $request->plantao_id;
|
|
$atendimento->pacienteObservacoes()->save($pacienteObservacao);
|
|
|
|
$pacienteObservacao->refresh();
|
|
|
|
$gestacaoData = $this->prepareGestacaoData($params, $pacienteObservacao);
|
|
if (!is_null($gestacaoData)) {
|
|
|
|
$atendimento->gestacoes()->create($gestacaoData);
|
|
|
|
if ($request['gestacao'] && $request['gestacao']['dum']) {
|
|
|
|
$atendimento->faa->paciente->dum()->updateOrCreate(
|
|
['paciente_id' => $atendimento->faa->paciente->id],
|
|
['data_ultima_menstruacao' =>$this->getCarbonDate($request['gestacao']['dum'])]
|
|
);
|
|
}
|
|
}
|
|
|
|
$classificacaoRiscoData = $this->prepareClassificacaoRiscoData($params, $pacienteObservacao);
|
|
$atendimento->classificacoesRisco()->create($classificacaoRiscoData);
|
|
|
|
$alergiasData = $this->prepareAlergiasData($params);
|
|
$atendimento->faa->paciente->cidadao->alergias()->sync($alergiasData);
|
|
$atendimento->faa->paciente->cidadao->fatoresRisco()->sync($params['fatores_risco'] ?? []);
|
|
|
|
if ($request['gestacao'] && $request['gestacao']['gestante']) {
|
|
|
|
if (!$atendimento->faa->paciente->cidadao->fatoresRisco->contains(FatorRiscoEnum::GESTANTE)) {
|
|
|
|
$atendimento->faa->paciente->cidadao->fatoresRisco()->attach(FatorRiscoEnum::GESTANTE);
|
|
}
|
|
}
|
|
|
|
$this->handleFatorRiscoOutro($atendimento, $params);
|
|
|
|
$atendimento->faa->paciente->cidadao->medicamentosUsoContinuo()->sync($this->prepareMedicamentosUsoContinuoData($params));
|
|
|
|
$medicamentosUsoData = $this->prepareMedicamentosUsoData($params, $pacienteObservacao);
|
|
if (!empty($medicamentosUsoData)) {
|
|
|
|
$atendimento->medicamentosUso()->create($medicamentosUsoData);
|
|
}
|
|
|
|
$sinaisVitaisData = $this->prepareSinaisVitaisData($params, $pacienteObservacao);
|
|
if (!empty($sinaisVitaisData)) {
|
|
|
|
$atendimento->sinaisVitais()->createMany($sinaisVitaisData);
|
|
}
|
|
|
|
$avaliacaoAntropometricaData = $this->prepareAvaliacaoAntropometricaData($params, $pacienteObservacao);
|
|
if (!is_null($avaliacaoAntropometricaData)) {
|
|
|
|
$ultimaAvaliacao = $pacienteObservacao->atendimento->avaliacoesAntropometricas()
|
|
->orderByDesc('created_at')
|
|
->first();
|
|
|
|
if (!(!is_null($ultimaAvaliacao)
|
|
&& $avaliacaoAntropometricaData['massa'] == $ultimaAvaliacao->massa
|
|
&& $avaliacaoAntropometricaData['massa_unidade_medida_id'] == $ultimaAvaliacao->massa_unidade_medida_id
|
|
&& $avaliacaoAntropometricaData['altura_tipo_medida_id'] == $ultimaAvaliacao->altura_tipo_medida_id
|
|
&& $avaliacaoAntropometricaData['altura'] == $ultimaAvaliacao->altura
|
|
&& $avaliacaoAntropometricaData['altura_unidade_medida_id'] == $ultimaAvaliacao->altura_unidade_medida_id)
|
|
) {
|
|
|
|
$atendimento->avaliacoesAntropometricas()->create($avaliacaoAntropometricaData);
|
|
}
|
|
}
|
|
|
|
$anotacaoData = $this->prepareAnotacaoData($params);
|
|
if (!empty($anotacaoData)) {
|
|
|
|
$pacienteObservacao->anotacoes()->createMany($anotacaoData);
|
|
}
|
|
|
|
$procedimentosData = $this->prepareProcedimentosData($params, $pacienteObservacao);
|
|
if (!empty($procedimentosData)) {
|
|
|
|
$atendimento->procedimentos()->createMany($procedimentosData);
|
|
}
|
|
|
|
if (isset($request->servicos_enfermagem)) {
|
|
|
|
$servicosEnfermagem = $this->prepareServicosEnfermagem($pacienteObservacao, $request->servicos_enfermagem);
|
|
$pacienteObservacao->servicosEnfermagem()->saveMany($servicosEnfermagem);
|
|
}
|
|
|
|
if (isset($request->prescricao_interna_aplicacoes)) {
|
|
|
|
$prescricaoInternaAplicacoes = $this->preparePrescricaoInternaAplicacoesData(
|
|
$pacienteObservacao,
|
|
$request->prescricao_interna_aplicacoes
|
|
);
|
|
|
|
$this->saveProcedimentosPrescricaoInterna($pacienteObservacao, $prescricaoInternaAplicacoes);
|
|
|
|
$pacienteObservacao->prescricaoInternaAplicacoes()->saveMany($prescricaoInternaAplicacoes);
|
|
}
|
|
|
|
if (isset($request->pedidos_exames)) {
|
|
|
|
$this->handlePedidosExames($pacienteObservacao, $request->pedidos_exames);
|
|
}
|
|
|
|
if (isset($request->escala_coma_glasgow)) {
|
|
|
|
$pacienteObservacao->escalasComaGlasgow()->createMany(
|
|
$request->escala_coma_glasgow
|
|
);
|
|
}
|
|
|
|
$historicoData = $this->prepareHistoricoData($pacienteObservacao, $params);
|
|
if (!empty($historicoData)) {
|
|
|
|
$pacienteObservacao->historico()->create($historicoData);
|
|
}
|
|
|
|
$diagnosticoData = $this->prepareDiagnosticoData($pacienteObservacao, $params);
|
|
if (!empty($diagnosticoData)) {
|
|
|
|
$pacienteObservacao->diagnostico()->create($diagnosticoData);
|
|
}
|
|
|
|
$planejamentoData = $this->preparePlanejamentoData($pacienteObservacao, $params);
|
|
if (!empty($planejamentoData)) {
|
|
|
|
$pacienteObservacao->planejamento()->create($planejamentoData);
|
|
}
|
|
|
|
$implementacaoData = $this->prepareImplementacaoData($pacienteObservacao, $params);
|
|
if (!empty($implementacaoData)) {
|
|
|
|
$pacienteObservacao->implementacao()->create($implementacaoData);
|
|
}
|
|
|
|
$avaliacaoData = $this->prepareAvaliacaoData($pacienteObservacao, $params);
|
|
if (!empty($avaliacaoData)) {
|
|
|
|
$pacienteObservacao->avaliacao()->create($avaliacaoData);
|
|
}
|
|
|
|
if (isset($params['finalizacao'])) {
|
|
|
|
$this->storeFinalizacao($params['finalizacao'], $pacienteObservacao);
|
|
}
|
|
});
|
|
|
|
$pacienteObservacao->fresh();
|
|
|
|
$excludeImpressoes = !$request->get('finalizacao')
|
|
? ['faa' => ['value' => 'eletronica']]
|
|
: [];
|
|
|
|
$pacienteObservacao->faa_id = $pacienteObservacao->atendimento->faa_id;
|
|
|
|
$pacienteObservacao->impressoes = ImpressaoService::getImpressoes(
|
|
$pacienteObservacao->atendimento_id,
|
|
[
|
|
'excluded' => $excludeImpressoes,
|
|
]
|
|
);
|
|
|
|
$hasClassificacaoRisco = false;
|
|
|
|
if ($pacienteObservacao->classificacaoRisco) {
|
|
|
|
$classificacaoRiscoAnterior = $pacienteObservacao->atendimento->classificacoesRisco()
|
|
->where('id', $pacienteObservacao->classificacaoRisco->id - 1)
|
|
->first();
|
|
|
|
$hasClassificacaoRisco = !is_null($classificacaoRiscoAnterior)
|
|
&& $classificacaoRiscoAnterior->classificacao_risco_id !=
|
|
$pacienteObservacao->classificacaoRisco->classificacao_risco_id;
|
|
}
|
|
|
|
$assinar = (Parametrizacao::first()->assinatura_eletronica ?? false) && (
|
|
$hasClassificacaoRisco
|
|
|| !is_null($pacienteObservacao->medicamentoUso)
|
|
|| !(FaaEletronicaController::getAtendimentosObservacaoData(collect([$pacienteObservacao]))[0]['nodata'])
|
|
);
|
|
|
|
$pacienteObservacao->assinar = $assinar;
|
|
|
|
return response()->json($pacienteObservacao, Response::HTTP_CREATED);
|
|
}
|
|
|
|
private function saveProcedimentosPrescricaoInterna($pacienteObservacao, $prescricaoInternaAplicacoes)
|
|
{
|
|
$quantidades = [];
|
|
|
|
foreach ($prescricaoInternaAplicacoes as $aplicacao) {
|
|
|
|
if ($aplicacao->status_id == ExameStatusEnum::REALIZADO) {
|
|
|
|
$hasAplicacaoRealizada = $aplicacao->prescricaoInternaMedicamento->prescricaoInterna()
|
|
->whereHas('medicamentos.aplicacoes', function ($query) {
|
|
|
|
$query->where('status_id', ExameStatusEnum::REALIZADO);
|
|
})
|
|
->get()
|
|
->isNotEmpty();
|
|
|
|
if (!$hasAplicacaoRealizada) {
|
|
|
|
$quantidades[$aplicacao->prescricaoInternaMedicamento->prescricao_interna_id] = 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
$quantidadeTotal = 0;
|
|
|
|
foreach ($quantidades as $quantidade) {
|
|
|
|
$quantidadeTotal += $quantidade;
|
|
}
|
|
|
|
if ($quantidadeTotal > 0) {
|
|
|
|
$procedimento = Procedimento::where(
|
|
'codigo',
|
|
ProcedimentoEnum::ADMINISTRACAO_DE_MEDICAMENTOS_NA_ATENCAO_ESPECIALIZADA
|
|
)
|
|
->orderByDesc('competencia_id')
|
|
->firstOrFail();
|
|
|
|
$validation = new ProcedimentoValidationService($procedimento);
|
|
|
|
if ($validation->isOcupacaoValid($this->getCurrentLotacao()->ocupacao)) {
|
|
|
|
$pacienteObservacao->atendimento->procedimentos()->create([
|
|
'lotacao_id' => auth()->payload()->get('lotacao_id'),
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'procedimento_id' => $procedimento->id,
|
|
'quantidade' => $quantidadeTotal,
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
|
|
private function preparePacienteObservacaoData($params)
|
|
{
|
|
return [
|
|
'quarto' => $params['quarto'] ?? null,
|
|
'leito' => $params['leito'] ?? null,
|
|
'aguardando_vaga_hospitalar' => $params['aguardando_vaga_hospitalar'] ?? false,
|
|
'hemorragia_externa_grave_trauma_status_id' => $params['hemorragia_externa_grave_trauma_status_id'] ?? null,
|
|
'hemorragia_externa_grave_local' => $params['hemorragia_externa_grave_local'] ?? null,
|
|
'vias_aerias_trauma_status_id' => $params['vias_aerias_trauma_status_id'] ?? null,
|
|
'vias_aerias_obstrucao_por' => $params['vias_aerias_obstrucao_por'] ?? null,
|
|
'oxigenacao_respiracao_ventilacao_trauma_status_id' => $params['oxigenacao_respiracao_ventilacao_trauma_status_id'] ?? null,
|
|
'pulso_trauma_status_id' => $params['pulso_trauma_status_id'] ?? null,
|
|
'pele_trauma_status_id' => $params['pele_trauma_status_id'] ?? null,
|
|
'pele_alteracao' => $params['pele_alteracao'] ?? null,
|
|
'perfuracao_trauma_status_id' => $params['perfuracao_trauma_status_id'] ?? null,
|
|
'perfuracao_lentificada' => $params['perfuracao_lentificada'] ?? null,
|
|
'sangramento_trauma_status_id' => $params['sangramento_trauma_status_id'] ?? null,
|
|
'sangramento_local' => $params['sangramento_local'] ?? null,
|
|
'pupilas_trauma_status_id' => $params['pupilas_trauma_status_id'] ?? null,
|
|
'paresias_trauma_status_id' => $params['paresias_trauma_status_id'] ?? null,
|
|
'plegia_trauma_status_id' => $params['plegia_trauma_status_id'] ?? null,
|
|
'exposicao_hipotermia_trauma_status_id' => $params['exposicao_hipotermia_trauma_status_id'] ?? null,
|
|
'exposicao_hipotermia_observacao' => $params['exposicao_hipotermia_observacao'] ?? null,
|
|
'avaliacao_cabeca_pescoco' => $params['avaliacao_cabeca_pescoco'] ?? null,
|
|
'avaliacao_torax' => $params['avaliacao_torax'] ?? null,
|
|
'avaliacao_abdome' => $params['avaliacao_abdome'] ?? null,
|
|
'avaliacao_mmss_mmii' => $params['avaliacao_mmss_mmii'] ?? null,
|
|
'observacao' => $params['observacao'] ?? null,
|
|
];
|
|
}
|
|
|
|
private function prepareMedicamentosUsoContinuoData(array $params) : array
|
|
{
|
|
$medicamentos = [];
|
|
|
|
foreach (($params['medicamentos_uso_continuo'] ?? []) as $medicamento) {
|
|
|
|
$medicamentos[] = $medicamento['medicamento_id'];
|
|
}
|
|
|
|
return $medicamentos;
|
|
}
|
|
|
|
private function prepareGestacaoData($params, $pacienteObservacao)
|
|
{
|
|
if (!isset($params['gestacao']) || $params['gestacao']['gestante'] == false) {
|
|
|
|
return null;
|
|
}
|
|
|
|
$cidadao = $pacienteObservacao->atendimento->faa->paciente->cidadao;
|
|
$sexoPermitido = $cidadao->sexo_id === Sexo::FEMININO;
|
|
|
|
$idadePermitida = $cidadao->data_nascimento
|
|
? $cidadao->idade['anos'] >= 9 && $cidadao->idade['anos'] <= 60
|
|
: true;
|
|
|
|
if (!$sexoPermitido || !$idadePermitida) {
|
|
|
|
return null;
|
|
}
|
|
|
|
$params = $params['gestacao'];
|
|
|
|
return [
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'gestante' => $params['gestante'],
|
|
'dum' => $params['dum'] ? ($this->getCarbonDate($params['dum']) ?? null) : null,
|
|
];
|
|
}
|
|
|
|
private function getCarbonDate($date)
|
|
{
|
|
return Carbon::createFromFormat('d/m/Y', $date);
|
|
}
|
|
|
|
private function prepareClassificacaoRiscoData($params, $pacienteObservacao)
|
|
{
|
|
return [
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'classificacao_risco_id' => $params['classificacao_risco_id'],
|
|
];
|
|
}
|
|
|
|
private function prepareAlergiasData($params)
|
|
{
|
|
$alergias = [];
|
|
|
|
foreach (($params['alergias'] ?? []) as $alergia) {
|
|
|
|
$alergias[$alergia['alergia_id']] = [
|
|
'criticidade_id' => $alergia['criticidade_id'],
|
|
'reacoes_observacoes' => $alergia['reacoes_observacoes'] ?? null,
|
|
];
|
|
}
|
|
|
|
return $alergias;
|
|
}
|
|
|
|
private function handleFatorRiscoOutro($atendimento, $params)
|
|
{
|
|
$atendimento->faa->paciente->cidadao->fator_risco_outro = null;
|
|
|
|
if (in_array(FatorRiscoEnum::OUTRO, $params['fatores_risco'] ?? [])) {
|
|
|
|
$atendimento->faa->paciente->cidadao->fator_risco_outro = $params['fator_risco_outro'] ?? null;
|
|
}
|
|
|
|
$atendimento->faa->paciente->cidadao->save();
|
|
}
|
|
|
|
private function prepareMedicamentosUsoData($params, $pacienteObservacao)
|
|
{
|
|
if (!isset($params['medicamentos_uso'])) {
|
|
|
|
return null;
|
|
}
|
|
|
|
return [
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'descricao' => $params['medicamentos_uso'],
|
|
];
|
|
}
|
|
|
|
private function prepareSinaisVitaisData($params, $pacienteObservacao)
|
|
{
|
|
$sinaisVitaisData = [];
|
|
|
|
foreach (($params['sinais_vitais'] ?? []) as $sinaisVitais) {
|
|
|
|
$sinaisVitaisData[] = [
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'pa' => $sinaisVitais['pa'] ?? null,
|
|
'pa_unidade_medida_id' => isset($sinaisVitais['pa'])
|
|
? $sinaisVitais['pa_unidade_medida_id']
|
|
: null,
|
|
'glicemia' => $sinaisVitais['glicemia'] ?? null,
|
|
'temperatura' => $sinaisVitais['temperatura'] ?? null,
|
|
'pulso' => $sinaisVitais['pulso'] ?? null,
|
|
'respiracao' => $sinaisVitais['respiracao'] ?? null,
|
|
'saturacao' => $sinaisVitais['saturacao'] ?? null,
|
|
'intensidade_dor' => $sinaisVitais['intensidade_dor'] ?? null,
|
|
'cintura' => $sinaisVitais['cintura'] ?? null,
|
|
];
|
|
}
|
|
|
|
return $sinaisVitaisData;
|
|
}
|
|
|
|
private function prepareAvaliacaoAntropometricaData($params, $pacienteObservacao)
|
|
{
|
|
if (!isset($params['avaliacao_antropometrica'])) {
|
|
|
|
return null;
|
|
}
|
|
|
|
$params = $params['avaliacao_antropometrica'];
|
|
|
|
return [
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'massa' => $params['massa'] ?? null,
|
|
'massa_unidade_medida_id' => isset($params['massa']) ? $params['massa_unidade_medida_id'] : null,
|
|
'altura' => $params['altura'] ?? null,
|
|
'altura_unidade_medida_id' => isset($params['altura']) ? $params['altura_unidade_medida_id'] : null,
|
|
'altura_tipo_medida_id' => isset($params['altura']) ? $params['altura_tipo_medida_id'] : null,
|
|
];
|
|
}
|
|
|
|
private function prepareAnotacaoData($params)
|
|
{
|
|
$result = [];
|
|
|
|
foreach ($params['anotacoes'] ?? [] as $anotacao) {
|
|
|
|
$result[] = [
|
|
'anotado_em' => Carbon::createFromFormat('d/m/Y H:i', $anotacao['anotado_em']),
|
|
'descricao' => $anotacao['descricao'],
|
|
];
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function prepareProcedimentosData($params, $pacienteObservacao)
|
|
{
|
|
$procedimentos = [];
|
|
|
|
foreach (($params['procedimentos'] ?? []) as $procedimento) {
|
|
|
|
$procedimentos[] = [
|
|
'lotacao_id' => auth()->payload()->get('lotacao_id'),
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'procedimento_id' => $procedimento['procedimento_id'],
|
|
'cid_principal_id' => $procedimento['cid_principal_id'] ?? null,
|
|
'quantidade' => $procedimento['quantidade'],
|
|
];
|
|
}
|
|
|
|
if (!is_null($pacienteObservacao->avaliacaoAntropometrica)) {
|
|
|
|
$this->addProcedimentoAvaliacaoAntropometricaData($procedimentos, $pacienteObservacao);
|
|
}
|
|
|
|
$sinaisVitais = $pacienteObservacao->sinaisVitais()->get();
|
|
|
|
if ($sinaisVitais->isNotEmpty()) {
|
|
|
|
$this->addProcedimentosSinaisVitaisData($sinaisVitais, $procedimentos, $pacienteObservacao->id);
|
|
}
|
|
|
|
if (!is_null($params['servicos_enfermagem'] ?? null)) {
|
|
|
|
$this->handleServicoEnfermagemRealizado($procedimentos, $pacienteObservacao, $params['servicos_enfermagem']);
|
|
}
|
|
|
|
if (isset($params['finalizacao']) && !is_null($params['finalizacao']['desfecho_id'] ?? null)) {
|
|
|
|
if ($params['finalizacao']['desfecho_id'] === DesfechoEnum::EVASAO) {
|
|
|
|
$this->addProcedimentoPadraoData($procedimentos, $pacienteObservacao);
|
|
}
|
|
}
|
|
|
|
return $procedimentos;
|
|
}
|
|
|
|
private function addProcedimentoAvaliacaoAntropometricaData(&$procedimentos, $pacienteObservacao)
|
|
{
|
|
$proc = Procedimento::where('codigo', ProcedimentoEnum::AVALIACAO_ANTROPOMETRICA)
|
|
->orderByDesc('competencia_id')
|
|
->firstOrFail();
|
|
|
|
$validation = new ProcedimentoValidationService($proc);
|
|
|
|
if ($validation->isOcupacaoValid($this->getCurrentLotacao()->ocupacao)) {
|
|
|
|
if (!$pacienteObservacao->atendimento->procedimentos->contains('procedimento_id', $proc->id)) {
|
|
|
|
$procedimentos[] = [
|
|
'lotacao_id' => auth()->payload()->get('lotacao_id'),
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'procedimento_id' => $proc->id,
|
|
'quantidade' => 1,
|
|
];
|
|
}
|
|
}
|
|
}
|
|
|
|
private function addProcedimentosSinaisVitaisData($sinaisVitais, &$procedimentos, $pacienteObservacaoId)
|
|
{
|
|
$quantidadeMedicoesPa = 0;
|
|
$quantidadeMedicoesGlicemia = 0;
|
|
|
|
foreach ($sinaisVitais as $sinaisVitaisItem) {
|
|
|
|
if (!is_null($sinaisVitaisItem->pa)) {
|
|
|
|
$quantidadeMedicoesPa++;
|
|
}
|
|
|
|
if (!is_null($sinaisVitaisItem->glicemia)) {
|
|
|
|
$quantidadeMedicoesGlicemia++;
|
|
}
|
|
}
|
|
|
|
if ($quantidadeMedicoesPa > 0) {
|
|
|
|
$this->addProcedimentoPaData($quantidadeMedicoesPa, $procedimentos, $pacienteObservacaoId);
|
|
}
|
|
|
|
if ($quantidadeMedicoesGlicemia > 0) {
|
|
|
|
$this->addProcedimentoGlicemiaData($quantidadeMedicoesGlicemia, $procedimentos, $pacienteObservacaoId);
|
|
}
|
|
}
|
|
|
|
private function addProcedimentoPaData($quantidade, &$procedimentos, $pacienteObservacaoId)
|
|
{
|
|
$proc = Procedimento::where('codigo', ProcedimentoEnum::AFERICAO_PRESSAO_ARTERIAL)
|
|
->orderByDesc('competencia_id')
|
|
->firstOrFail();
|
|
|
|
$validation = new ProcedimentoValidationService($proc);
|
|
|
|
if ($validation->isOcupacaoValid($this->getCurrentLotacao()->ocupacao)) {
|
|
|
|
if (collect($procedimentos)->contains('procedimento_id', $proc->id)) {
|
|
|
|
foreach ($procedimentos as $i => $procedimento) {
|
|
|
|
if ($procedimento['procedimento_id'] === $proc->id) {
|
|
|
|
$procedimentos[$i]['quantidade'] += $quantidade;
|
|
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
else {
|
|
|
|
$procedimentos[] = [
|
|
'lotacao_id' => auth()->payload()->get('lotacao_id'),
|
|
'paciente_observacao_id' => $pacienteObservacaoId,
|
|
'procedimento_id' => $proc->id,
|
|
'quantidade' => $quantidade,
|
|
];
|
|
}
|
|
}
|
|
}
|
|
|
|
private function addProcedimentoGlicemiaData($quantidade, &$procedimentos, $pacienteObservacaoId)
|
|
{
|
|
$proc = Procedimento::where('codigo', ProcedimentoEnum::GLICEMIA_CAPILAR)
|
|
->orderByDesc('competencia_id')
|
|
->firstOrFail();
|
|
|
|
$validation = new ProcedimentoValidationService($proc);
|
|
|
|
if ($validation->isOcupacaoValid($this->getCurrentLotacao()->ocupacao)) {
|
|
|
|
if (collect($procedimentos)->contains('procedimento_id', $proc->id)) {
|
|
|
|
foreach ($procedimentos as $i => $procedimento) {
|
|
|
|
if ($procedimento['procedimento_id'] === $proc->id) {
|
|
|
|
$procedimentos[$i]['quantidade'] += $quantidade;
|
|
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
else {
|
|
|
|
$procedimentos[] = [
|
|
'lotacao_id' => auth()->payload()->get('lotacao_id'),
|
|
'paciente_observacao_id' => $pacienteObservacaoId,
|
|
'procedimento_id' => $proc->id,
|
|
'quantidade' => $quantidade,
|
|
];
|
|
}
|
|
}
|
|
}
|
|
|
|
private function handleServicoEnfermagemRealizado(&$procedimentos, $pacienteObservacao, $servicosEnfermagemRequested)
|
|
{
|
|
$servicosEnfermagem = collect($this->getServicosEnfermagemAll($pacienteObservacao->atendimento));
|
|
$procedimentoIds = $servicosEnfermagem->pluck('procedimento.id');
|
|
|
|
foreach ($servicosEnfermagemRequested as $servicoEnfermagem) {
|
|
|
|
if (!is_null($servicoEnfermagem['id'] ?? null)) {
|
|
|
|
$servico = $servicosEnfermagem->firstWhere('id', $servicoEnfermagem['id']);
|
|
|
|
if (!$procedimentoIds->contains($servicoEnfermagem['procedimento_id'])
|
|
|| ($procedimentoIds->contains($servicoEnfermagem['procedimento_id']
|
|
&& $servico['status']['id'] == ExameStatusEnum::REALIZADO))) {
|
|
|
|
throw new ServicoEnfermagemCannotChangeStatusException;
|
|
}
|
|
}
|
|
|
|
if (($servicoEnfermagem['status_id'] ?? null) == ExameStatusEnum::REALIZADO) {
|
|
|
|
$this->addProcedimentoServicoEnfermagemData(
|
|
$servicoEnfermagem['procedimento_id'],
|
|
$servicoEnfermagem['cid_id'] ?? null,
|
|
$procedimentos,
|
|
$pacienteObservacao->id,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
private function getServicosEnfermagem($atendimento, $isForm)
|
|
{
|
|
$result = [];
|
|
|
|
$servicosEnfermagem = $this->getBuilderServicoEnfermagem($atendimento)
|
|
->orderBy('created_at')
|
|
->get();
|
|
|
|
foreach ($servicosEnfermagem as $servico) {
|
|
|
|
$data = array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($servico, $atendimento),
|
|
[
|
|
'id' => $servico->id,
|
|
'procedimento' => [
|
|
'id' => $servico->procedimento->id,
|
|
'codigo' => $servico->procedimento->codigo,
|
|
'nome' => $servico->procedimento->nome,
|
|
'has_cid_principal' => $servico->procedimento->has_cid_principal
|
|
],
|
|
'status' => [
|
|
'id' => $servico->status->id,
|
|
],
|
|
'horario_realizacao' => $servico->horario_realizacao,
|
|
'profissional' => [
|
|
'nome' => $servico->updatedLotacao->usuario->cidadao->nome,
|
|
],
|
|
'cid' => $servico->cid,
|
|
'disabled' => $this->isServicoEnfermagemDisabled($servico),
|
|
]
|
|
);
|
|
|
|
if ($isForm && $this->isServicoEnfermagemDisabled($servico)) {
|
|
|
|
$result[] = $data;
|
|
|
|
} else if (!$isForm && !$this->isServicoEnfermagemDisabled($servico)) {
|
|
|
|
$result[] = $data;
|
|
}
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function getServicosEnfermagemAll($atendimento)
|
|
{
|
|
$result = [];
|
|
|
|
$servicosEnfermagem = $this->getBuilderServicoEnfermagem($atendimento)
|
|
->orderBy('created_at')
|
|
->get();
|
|
|
|
foreach ($servicosEnfermagem as $servico) {
|
|
|
|
$result[] = array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($servico, $atendimento),
|
|
[
|
|
'id' => $servico->id,
|
|
'procedimento' => [
|
|
'id' => $servico->procedimento->id,
|
|
'codigo' => $servico->procedimento->codigo,
|
|
'nome' => $servico->procedimento->nome,
|
|
],
|
|
'status' => [
|
|
'id' => $servico->status->id,
|
|
'nome' => $servico->status->nome,
|
|
],
|
|
'disabled' => $this->isServicoEnfermagemDisabled($servico),
|
|
]
|
|
);
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function getBuilderServicoEnfermagem($atendimento)
|
|
{
|
|
return ServicoEnfermagem::whereHas('atendimentoMedico', function ($query) use ($atendimento) {
|
|
|
|
$query->where('atendimento_id', $atendimento->id);
|
|
})
|
|
->orWhereHas('atendimentoEnfermagem', function ($query) use ($atendimento) {
|
|
|
|
$query->where('atendimento_id', $atendimento->id);
|
|
})
|
|
->orWhereHas('pacienteObservacao', function ($query) use ($atendimento) {
|
|
|
|
$query->where('atendimento_id', $atendimento->id);
|
|
});
|
|
}
|
|
|
|
private function addProcedimentoPadraoData(&$procedimentos, $pacienteObservacao)
|
|
{
|
|
$procedimentoPadrao = $this->getProcedimentoPadrao();
|
|
|
|
if (is_null($procedimentoPadrao)) {
|
|
|
|
return null;
|
|
}
|
|
|
|
$quantidade = 1;
|
|
|
|
if (collect($procedimentos)->contains('procedimento_id', $procedimentoPadrao['id'])) {
|
|
|
|
foreach ($procedimentos as $i => $procedimento) {
|
|
|
|
if ($procedimento['paciente_observacao_id'] !== $pacienteObservacao->id) {
|
|
|
|
continue;
|
|
}
|
|
|
|
if ($procedimento['procedimento_id'] === $procedimentoPadrao['id']) {
|
|
|
|
$procedimentos[$i]['quantidade'] += $quantidade;
|
|
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
else {
|
|
|
|
$procedimentos[] = [
|
|
'lotacao_id' => auth()->payload()->get('lotacao_id'),
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'procedimento_id' => $procedimentoPadrao['id'],
|
|
'quantidade' => $quantidade,
|
|
];
|
|
}
|
|
}
|
|
|
|
private function getProcedimentoPadrao()
|
|
{
|
|
$parametrizacaoProcedimento = ParametrizacaoProcedimento::select('procedimento_codigo')
|
|
->where('pronto_atendimento_procedimento_padrao', true)
|
|
->get()
|
|
->first();
|
|
|
|
if (is_null($parametrizacaoProcedimento)) {
|
|
|
|
return null;
|
|
}
|
|
|
|
return [
|
|
'id' => $parametrizacaoProcedimento->procedimento->id,
|
|
'codigo' => $parametrizacaoProcedimento->procedimento->codigo,
|
|
];
|
|
}
|
|
|
|
private function getBaseHistoricoAreaAtendimento($model, $atendimento)
|
|
{
|
|
$result = [
|
|
'centro_custo' => [
|
|
'setor' => [
|
|
'nome' => $model->createdCentroCusto->setor->nome ?? null,
|
|
],
|
|
],
|
|
'lotacao' => [
|
|
'ocupacao' => [
|
|
'codigo' => $model->createdLotacao->ocupacao->codigo ?? null,
|
|
'nome' => $model->createdLotacao->ocupacao->nome ?? null
|
|
],
|
|
'profissional' => [
|
|
'nome' => $model->createdLotacao->usuario->cidadao->nome ?? null,
|
|
],
|
|
],
|
|
'classificacao_risco' => [
|
|
'nome' => $this->getClassificacaoRisco($atendimento)['nome'] ?? null
|
|
],
|
|
'data_hora' => $model ? $model->created_at->format('d/m/Y H:i:s') : null,
|
|
];
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function isServicoEnfermagemDisabled($servicoEnfermagem)
|
|
{
|
|
return $servicoEnfermagem->status->id !== ExameStatusEnum::SOLICITADO
|
|
&& $servicoEnfermagem->status->id !== ExameStatusEnum::AGUARDANDO_RESULTADO;
|
|
}
|
|
|
|
private function addProcedimentoServicoEnfermagemData($procedimentoId, $cidId, &$procedimentos, $pacienteObservacaoId)
|
|
{
|
|
$procedimentos[] = [
|
|
'lotacao_id' => auth()->payload()->get('lotacao_id'),
|
|
'paciente_observacao_id' => $pacienteObservacaoId,
|
|
'procedimento_id' => $procedimentoId,
|
|
'cid_principal_id' => $cidId,
|
|
'quantidade' => 1,
|
|
];
|
|
}
|
|
|
|
private function prepareServicosEnfermagem($pacienteObservacao, $params)
|
|
{
|
|
$servicosEnfermagem = [];
|
|
|
|
foreach ($params as $param) {
|
|
|
|
$servicoEnfermagem = new ServicoEnfermagem();
|
|
|
|
if (isset($param['id']) && is_numeric($param['id'])) {
|
|
|
|
$servicoEnfermagem = ServicoEnfermagem::findOrFail($param['id']);
|
|
}
|
|
|
|
$servicoEnfermagem->status_id = $param['status_id'] ?? ExameStatusEnum::SOLICITADO;
|
|
$servicoEnfermagem->paciente_observacao_id = $pacienteObservacao->id;
|
|
$servicoEnfermagem->procedimento_id = $param['procedimento_id'];
|
|
$servicoEnfermagem->cid_id = $param['cid_id'] ?? null;
|
|
$servicoEnfermagem->horario_realizacao = $param['horario_realizacao'] ?? null;
|
|
$servicoEnfermagem->observacoes = $param['observacao'] ?? null;
|
|
|
|
$servicosEnfermagem[] = $servicoEnfermagem;
|
|
}
|
|
|
|
return $servicosEnfermagem;
|
|
}
|
|
|
|
private function preparePrescricaoInternaAplicacoesData($pacienteObservacao, $prescricaoInternaAplicacoes)
|
|
{
|
|
$result = [];
|
|
|
|
$prescricoesInterna = $this->getPrescricoesInterna($pacienteObservacao->atendimento, false);
|
|
|
|
foreach ($prescricaoInternaAplicacoes as $prescricaoInternaMedicamentoAplicacao) {
|
|
|
|
$aplicacao = PrescricaoInternaMedicamentoAplicacao::findOrFail(
|
|
$prescricaoInternaMedicamentoAplicacao['id']
|
|
);
|
|
|
|
if (!$this->isAplicacaoAllowChangeStatus($aplicacao, $prescricoesInterna)) {
|
|
|
|
throw new PrescricaoInternaAplicacaoCannotChangeStatusException;
|
|
}
|
|
|
|
$aplicacao->paciente_observacao_id = $pacienteObservacao->id;
|
|
$aplicacao->status_id = $prescricaoInternaMedicamentoAplicacao['status_id'];
|
|
$aplicacao->horario_aplicacao = $prescricaoInternaMedicamentoAplicacao['horario_aplicacao'];
|
|
$aplicacao->local_aplicacao_id = $prescricaoInternaMedicamentoAplicacao['local_aplicacao_id'];
|
|
|
|
$result[] = $aplicacao;
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function getPrescricoesInterna($atendimento, $isForm)
|
|
{
|
|
$result = [];
|
|
|
|
$prescricoes = PrescricaoInterna::whereHas('atendimentoMedico', function ($query) use ($atendimento) {
|
|
|
|
$query->where('atendimento_id', $atendimento->id);
|
|
})->get();
|
|
|
|
foreach ($prescricoes as $prescricaoInterna) {
|
|
|
|
$data = [
|
|
'id' => $prescricaoInterna->id,
|
|
'frequencia' => $prescricaoInterna->frequencia,
|
|
'observacao' => $prescricaoInterna->observacoes,
|
|
'medicamentos' => $this->getMedicamentosPrescricaoInterna($prescricaoInterna),
|
|
];
|
|
|
|
if ($isForm && !$this->hasAplicacoesSolicitado($prescricaoInterna)) {
|
|
|
|
$result[] = array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($prescricaoInterna, $prescricaoInterna->atendimentoMedico->atendimento),
|
|
$data
|
|
);
|
|
|
|
continue;
|
|
}
|
|
|
|
if (!$isForm && $this->hasAplicacoesSolicitado($prescricaoInterna)) {
|
|
|
|
$result[] = array_merge(
|
|
$this->getBaseHistoricoAreaAtendimento($prescricaoInterna, $prescricaoInterna->atendimentoMedico->atendimento),
|
|
$data
|
|
);
|
|
}
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function getMedicamentosPrescricaoInterna($prescricaoInterna)
|
|
{
|
|
$result = [];
|
|
|
|
foreach ($prescricaoInterna->medicamentos as $item) {
|
|
|
|
$result[] = [
|
|
'id' => $item->id,
|
|
'medicamento' => [
|
|
'nome' => $item->medicamento->nome,
|
|
'forma_farmaceutica' => [
|
|
'nome' => $item->medicamento->formaFarmaceutica->nome
|
|
]
|
|
],
|
|
'unidade_medida' => [
|
|
'sigla' => $item->unidadeMedida->sigla ?? null,
|
|
],
|
|
'quantidade' => $item->quantidade,
|
|
'administracao' => $item->administracao,
|
|
'aplicacoes' => $this->getAplicacoesMedicamentoPrescricaoInterna($item),
|
|
];
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function getAplicacoesMedicamentoPrescricaoInterna($medicamento)
|
|
{
|
|
return $medicamento->aplicacoes->map(function ($aplicacao) {
|
|
|
|
return [
|
|
'id' => $aplicacao->id,
|
|
'status' => [
|
|
'id' => $aplicacao->status->id,
|
|
'nome' => $aplicacao->status->nome,
|
|
],
|
|
'disabled' => $this->isDisabled($aplicacao->status->id),
|
|
'profissional' => [
|
|
'nome' => $aplicacao->updatedLotacao->usuario->cidadao->nome,
|
|
],
|
|
'horario_aplicacao' => $aplicacao->horario_aplicacao,
|
|
'local_aplicacao_id' => $aplicacao->local_aplicacao_id,
|
|
];
|
|
});
|
|
}
|
|
|
|
private function isDisabled($statusId)
|
|
{
|
|
return $statusId === ExameStatusEnum::REALIZADO
|
|
|| $statusId === ExameStatusEnum::NAO_REALIZADO;
|
|
}
|
|
|
|
private function hasAplicacoesSolicitado($prescricaoInterna)
|
|
{
|
|
foreach ($prescricaoInterna->medicamentos as $medicamento) {
|
|
|
|
$aplicacoesSolicitadas = $medicamento->aplicacoes->where('status_id', ExameStatusEnum::SOLICITADO);
|
|
|
|
if ($aplicacoesSolicitadas->count() > 0) {
|
|
|
|
return true;
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private function isAplicacaoAllowChangeStatus($aplicacao, $prescricoesInterna)
|
|
{
|
|
$prescricoesInterna = collect($prescricoesInterna);
|
|
|
|
$prescricao = $prescricoesInterna->firstWhere(
|
|
'id',
|
|
$aplicacao->prescricaoInternaMedicamento->prescricaoInterna->id
|
|
);
|
|
|
|
if (is_null($prescricao) || $aplicacao->status_id !== ExameStatusEnum::SOLICITADO) {
|
|
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
private function handlePedidosExames($pacienteObservacao, $pedidosExamesRequested)
|
|
{
|
|
$pedidoExamesAllowedChange = collect(
|
|
$this->getPedidosExames($pacienteObservacao->atendimento)
|
|
);
|
|
|
|
$quantidadesProcedimento = [];
|
|
|
|
foreach ($pedidosExamesRequested as $pedidoExamesRequested) {
|
|
|
|
$isForm = $pedidoExamesRequested['is_form'];
|
|
$pedidoExameRequestedId = $pedidoExamesRequested['id'] ?? null;
|
|
|
|
if (is_null($pedidoExameRequestedId)) {
|
|
|
|
$pedidoExamesData = $this->preparePedidoExamesData($pacienteObservacao, $pedidoExamesRequested);
|
|
if (!empty($pedidoExamesData)) {
|
|
|
|
$pedidoExames = $pacienteObservacao->pedidosExames()->create($pedidoExamesData);
|
|
$itensSaved = $this->storePedidoExamesItens($pedidoExames, $pedidoExamesData['exames']);
|
|
|
|
foreach ($itensSaved as $itemSaved) {
|
|
|
|
if ($itemSaved->exame->tipo_id === ExameTipo::LABORATORIAL
|
|
&& $itemSaved->status_id == ExameStatusEnum::REALIZADO
|
|
) {
|
|
|
|
$quantidadesProcedimento[$itemSaved->pedido_exame_id] = 1;
|
|
|
|
$lotacaoLaboratorio = Lotacao::where('usuario_id', $pedidoExamesRequested['laboratorio_usuario_id'])
|
|
->where('infraestrutura_id', $pedidoExamesRequested['laboratorio_infraestrutura_id'])
|
|
->where('ocupacao_id', $pedidoExamesRequested['laboratorio_ocupacao_id'])
|
|
->first();
|
|
|
|
$pacienteObservacao->atendimento->procedimentos()->create([
|
|
'lotacao_id' => $lotacaoLaboratorio->id ?? null,
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'procedimento_id' => $itemSaved->exame->procedimento->id,
|
|
'quantidade' => 1,
|
|
]);
|
|
}
|
|
}
|
|
|
|
if(count($pedidoExamesData['files'] ?? []) > 0) {
|
|
|
|
$this->storeFiles($pedidoExames, $pedidoExamesData['files'], $pacienteObservacao);
|
|
}
|
|
}
|
|
|
|
continue;
|
|
}
|
|
|
|
if (!is_numeric($pedidoExameRequestedId)) {
|
|
|
|
continue;
|
|
}
|
|
|
|
if (!$isForm && !$pedidoExamesAllowedChange->pluck('id')->contains($pedidoExameRequestedId)) {
|
|
|
|
throw new PedidoExameCannotChangeStatusException;
|
|
}
|
|
|
|
if (!$isForm) {
|
|
|
|
$this->requestedPedidoExamesAllowChangeStatus($pedidoExamesRequested, $pedidoExamesAllowedChange);
|
|
}
|
|
|
|
$pedidoExames = PedidoExame::findOrFail($pedidoExameRequestedId);
|
|
|
|
if (!$isForm) {
|
|
|
|
foreach ($pedidoExamesRequested['exames'] as $item) {
|
|
|
|
$pedidoItem = $pedidoExames->exames->firstWhere('id', $item['id']);
|
|
|
|
if ($item['status_id'] == ExameStatusEnum::REALIZADO && $pedidoItem->horario_realizacao == null) {
|
|
|
|
$pedidoItem->horario_realizacao = $item['horario_realizacao'] ?? null;
|
|
$pedidoItem->save();
|
|
}
|
|
|
|
if ($pedidoItem->status_id != ($item['status_id'] ?? ExameStatusEnum::SOLICITADO)) {
|
|
|
|
$pedidoItem->paciente_observacao_id = $pacienteObservacao->id;
|
|
$pedidoItem->status_id = $item['status_id'] ?? ExameStatusEnum::SOLICITADO;
|
|
$pedidoItem->horario_realizacao = $item['horario_realizacao'];
|
|
|
|
if ($pedidoItem->exame->tipo_id === ExameTipo::LABORATORIAL
|
|
&& $pedidoItem->status_id == ExameStatusEnum::REALIZADO
|
|
) {
|
|
|
|
$hasExameRealizado = $pedidoItem->pedidoExame()
|
|
->whereHas('exames', function ($query) {
|
|
|
|
$query->where('status_id', ExameStatusEnum::REALIZADO);
|
|
})
|
|
->get()
|
|
->isNotEmpty();
|
|
|
|
if (!$hasExameRealizado) {
|
|
|
|
$quantidadesProcedimento[$pedidoItem->pedido_exame_id] = 1;
|
|
}
|
|
|
|
$lotacaoLaboratorio = Lotacao::where('usuario_id', $pedidoExamesRequested['laboratorio_usuario_id'])
|
|
->where('infraestrutura_id', $pedidoExamesRequested['laboratorio_infraestrutura_id'])
|
|
->where('ocupacao_id', $pedidoExamesRequested['laboratorio_ocupacao_id'])
|
|
->first();
|
|
|
|
$pacienteObservacao->atendimento->procedimentos()->create([
|
|
'lotacao_id' => $lotacaoLaboratorio->id ?? null,
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'procedimento_id' => $pedidoItem->exame->procedimento->id,
|
|
'quantidade' => 1,
|
|
]);
|
|
}
|
|
|
|
$pedidoItem->save();
|
|
|
|
$this->storeItemObservacao($pedidoItem, $item['observacao'] ?? null);
|
|
}
|
|
}
|
|
}
|
|
|
|
if(count($pedidoExamesRequested['files'] ?? []) > 0) {
|
|
|
|
$this->storeFiles($pedidoExames, $pedidoExamesRequested['files'], $pacienteObservacao);
|
|
}
|
|
|
|
$usuarioId = $pedidoExamesRequested['usuario_id'] ?? null;
|
|
$infraestruturaId = $pedidoExamesRequested['usuario_infraestrutura_id'] ?? null;
|
|
$ocupacaoId = $pedidoExamesRequested['ocupacao_id'] ?? null;
|
|
|
|
$lotacao = Lotacao::where('usuario_id', $usuarioId)
|
|
->where('infraestrutura_id', $infraestruturaId)
|
|
->where('ocupacao_id', $ocupacaoId)
|
|
->first();
|
|
|
|
$laboratorioUsuarioId = $pedidoExamesRequested['laboratorio_usuario_id'] ?? null;
|
|
$laboratorioInfraestruturaId = $pedidoExamesRequested['laboratorio_infraestrutura_id'] ?? null;
|
|
$laboratorioOcupacaoId = $pedidoExamesRequested['laboratorio_ocupacao_id'] ?? null;
|
|
|
|
$lotacaoLaboratorio = Lotacao::where('usuario_id', $laboratorioUsuarioId)
|
|
->where('infraestrutura_id', $laboratorioInfraestruturaId)
|
|
->where('ocupacao_id', $laboratorioOcupacaoId)
|
|
->first();
|
|
|
|
$pedidoExames->usuario_id = $pedidoExamesRequested['usuario_id'] ?? null;
|
|
$pedidoExames->ocupacao_id = $pedidoExamesRequested['ocupacao_id'] ?? null;
|
|
$pedidoExames->lotacao_id = $lotacao->id ?? null;
|
|
$pedidoExames->laboratorio_usuario_id = $pedidoExamesRequested['laboratorio_usuario_id'] ?? null;
|
|
$pedidoExames->laboratorio_ocupacao_id = $pedidoExamesRequested['laboratorio_ocupacao_id'] ?? null;
|
|
$pedidoExames->laboratorio_lotacao_id = $lotacaoLaboratorio->id ?? null;
|
|
|
|
$pedidoExames->save();
|
|
}
|
|
|
|
$lotacaoPedidos = [];
|
|
|
|
foreach ($quantidadesProcedimento as $index => $quantidade) {
|
|
|
|
$lotacaoExame = PedidoExame::findOrFail($index)->lotacao_id;
|
|
|
|
if (isset($lotacaoPedidos[$lotacaoExame])) {
|
|
$lotacaoPedidos[$lotacaoExame]['quantidade'] += $quantidade;
|
|
} else {
|
|
$lotacaoPedidos[$lotacaoExame] = [
|
|
'lotacao_id' => $lotacaoExame,
|
|
'quantidade' => $quantidade,
|
|
];
|
|
}
|
|
}
|
|
|
|
foreach ($lotacaoPedidos as $lotacaoPedido) {
|
|
|
|
$procedimento = Procedimento::where(
|
|
'codigo',
|
|
ProcedimentoEnum::COLETA_DE_MATERIAL_PARA_EXAME_LABORATORIAL
|
|
)
|
|
->orderByDesc('competencia_id')
|
|
->firstOrFail();
|
|
|
|
$lotacao = Lotacao::where('id', $lotacaoPedido['lotacao_id'])->first();
|
|
|
|
if ($lotacao) {
|
|
|
|
$validation = new ProcedimentoValidationService($procedimento);
|
|
|
|
if ($validation->isOcupacaoValid($lotacao->ocupacao)) {
|
|
|
|
$pacienteObservacao->atendimento->procedimentos()->create([
|
|
'lotacao_id' => $lotacao->id,
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'procedimento_id' => $procedimento->id,
|
|
'quantidade' => $lotacaoPedido['quantidade'],
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private function preparePedidoExamesData($pacienteObservacao, $pedidoExames)
|
|
{
|
|
|
|
$result = [
|
|
'atendimento_id' => $pacienteObservacao->atendimento->id,
|
|
'urgente' => $pedidoExames['urgente'],
|
|
'justificativa' => $pedidoExames['justificativa'],
|
|
'exames' => [],
|
|
];
|
|
|
|
foreach ($pedidoExames['exames'] as $item) {
|
|
|
|
$result['exames'][] = [
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'exame_id' => $item['exame_id'],
|
|
'status_id' => $item['status_id'] ?? ExameStatusEnum::SOLICITADO,
|
|
'data_solicitacao' => Carbon::createFromFormat('d/m/Y', $item['data_solicitacao']) ?? null,
|
|
'unidade_solicitante' => $item['unidade_solicitante'] ?? null,
|
|
'medico_solicitante' => $item['medico_solicitante'] ?? null,
|
|
'observacao' => $item['observacao'] ?? null,
|
|
'horario_realizacao' => $item['horario_realizacao'] ?? null,
|
|
'files' => $item['files'] ?? [],
|
|
];
|
|
}
|
|
|
|
return $result;
|
|
}
|
|
|
|
private function storePedidoExamesItens($pedidoExames, $itens)
|
|
{
|
|
$itensSaved = [];
|
|
|
|
foreach ($itens as $item) {
|
|
|
|
$pedidoItem = $pedidoExames->exames()->create($item);
|
|
|
|
$itensSaved[] = $pedidoItem;
|
|
|
|
$this->storeItemObservacao($pedidoItem, $item['observacao'] ?? null);
|
|
}
|
|
|
|
return $itensSaved;
|
|
}
|
|
|
|
private function storeFiles($pedidoExame, $files, $pacienteObservacao)
|
|
{
|
|
$laudoService = new LaudoService();
|
|
$laudoService->storeFile($pedidoExame, $files, ['paciente_observacao_id' => $pacienteObservacao->id]);
|
|
}
|
|
|
|
private function storeItemObservacao($item, $observacao)
|
|
{
|
|
if (!is_null($observacao ?? null)) {
|
|
|
|
$item->observacoes()->create([
|
|
'observacao' => $observacao
|
|
]);
|
|
}
|
|
}
|
|
|
|
private function requestedPedidoExamesAllowChangeStatus($pedidoExamesRequested, $pedidoExamesAllowedChange)
|
|
{
|
|
$pedidoExamesAllowedIds = $pedidoExamesAllowedChange
|
|
->firstWhere('id', $pedidoExamesRequested['id'])['exames']->pluck('exame.id', 'id');
|
|
|
|
foreach ($pedidoExamesRequested['exames'] as $item) {
|
|
|
|
$exameIdAllowed = $pedidoExamesAllowedIds[$item['id']];
|
|
|
|
if ($exameIdAllowed != $item['exame_id']) {
|
|
|
|
throw new PedidoExameItemCannotChangeStatusException;
|
|
}
|
|
}
|
|
}
|
|
|
|
private function prepareHistoricoData($pacienteObservacao, $params)
|
|
{
|
|
if (!isset($params['historico'])) {
|
|
|
|
return [];
|
|
}
|
|
|
|
return [
|
|
'atendimento_id' => $pacienteObservacao->atendimento->id,
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'descricao' => $params['historico'],
|
|
];
|
|
}
|
|
|
|
private function prepareDiagnosticoData($pacienteObservacao, $params)
|
|
{
|
|
if (!isset($params['diagnostico'])) {
|
|
|
|
return [];
|
|
}
|
|
|
|
return [
|
|
'atendimento_id' => $pacienteObservacao->atendimento->id,
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'descricao' => $params['diagnostico'],
|
|
];
|
|
}
|
|
|
|
private function preparePlanejamentoData($pacienteObservacao, $params)
|
|
{
|
|
if (!isset($params['planejamento'])) {
|
|
|
|
return [];
|
|
}
|
|
|
|
return [
|
|
'atendimento_id' => $pacienteObservacao->atendimento->id,
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'descricao' => $params['planejamento'],
|
|
];
|
|
}
|
|
|
|
private function prepareImplementacaoData($pacienteObservacao, $params)
|
|
{
|
|
if (!isset($params['implementacao'])) {
|
|
|
|
return [];
|
|
}
|
|
|
|
return [
|
|
'atendimento_id' => $pacienteObservacao->atendimento->id,
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'descricao' => $params['implementacao'],
|
|
];
|
|
}
|
|
|
|
private function prepareAvaliacaoData($pacienteObservacao, $params)
|
|
{
|
|
if (!isset($params['avaliacao'])) {
|
|
|
|
return [];
|
|
}
|
|
|
|
return [
|
|
'atendimento_id' => $pacienteObservacao->atendimento->id,
|
|
'paciente_observacao_id' => $pacienteObservacao->id,
|
|
'descricao' => $params['avaliacao'],
|
|
];
|
|
}
|
|
|
|
private function storeFinalizacao($params, $pacienteObservacao)
|
|
{
|
|
$atendimentoMedicoDesfecho = $pacienteObservacao->atendimento->atendimentosMedico()
|
|
->whereNotNull('desfecho_id')
|
|
->orderByDesc('created_at')
|
|
->first();
|
|
|
|
$faaParams = [
|
|
'desfecho_id' => $params['desfecho_id'],
|
|
'finalizado' => true,
|
|
'data_hora_desfecho' => $atendimentoMedicoDesfecho->created_at
|
|
];
|
|
|
|
switch ($params['desfecho_id']) {
|
|
|
|
case DesfechoEnum::ALTA_MEDICA: {
|
|
|
|
$faaParams['usuario_id'] = Lotacao::findOrFail($params['alta_medica']['lotacao_id'])->usuario_id;
|
|
$faaParams['lotacao_id'] = $params['alta_medica']['lotacao_id'];
|
|
|
|
break;
|
|
}
|
|
case DesfechoEnum::EVASAO: {
|
|
|
|
$faaParams['usuario_id'] = $atendimentoMedicoDesfecho->createdLotacao->usuario_id;
|
|
$faaParams['lotacao_id'] = $atendimentoMedicoDesfecho->createdLotacao->id;
|
|
|
|
FilaService::evade([
|
|
'motivo_evasao' => $params['evasao']['motivo']
|
|
], $pacienteObservacao->atendimento->fila_id);
|
|
|
|
break;
|
|
}
|
|
case DesfechoEnum::ENCAMINHAMENTO_HOSPITALAR: {
|
|
|
|
$faaParams['usuario_id'] = Lotacao::findOrFail($params['encaminhamento_hospitalar']['lotacao_id'])->usuario_id;
|
|
$faaParams['lotacao_id'] = $params['encaminhamento_hospitalar']['lotacao_id'];
|
|
|
|
$pacienteObservacao->encaminhamentoHospitalar()->create([
|
|
'atendimento_id' => $pacienteObservacao->atendimento->id,
|
|
'usuario_id' => $faaParams['usuario_id'],
|
|
'unidade_id' => $params['encaminhamento_hospitalar']['unidade_id'] ?? null,
|
|
'unidade_nome' => $params['encaminhamento_hospitalar']['unidade_nome'] ?? null,
|
|
'quarto' => $params['encaminhamento_hospitalar']['quarto'] ?? null,
|
|
'leito' => $params['encaminhamento_hospitalar']['leito'] ?? null,
|
|
'cid_id' => $params['encaminhamento_hospitalar']['cid_id'] ?? null,
|
|
'medico_hospitalar' => $params['encaminhamento_hospitalar']['medico_hospitalar'] ?? null,
|
|
'observacoes' => $params['encaminhamento_hospitalar']['observacoes'] ?? null,
|
|
]);
|
|
|
|
break;
|
|
}
|
|
case DesfechoEnum::OBITO: {
|
|
|
|
$faaParams['usuario_id'] = $atendimentoMedicoDesfecho->createdLotacao->usuario_id;
|
|
$faaParams['lotacao_id'] = $atendimentoMedicoDesfecho->createdLotacao->id;
|
|
}
|
|
}
|
|
|
|
$pacienteObservacao->atendimento->faa->update($faaParams);
|
|
|
|
if ($params['desfecho_id'] != DesfechoEnum::EVASAO) {
|
|
|
|
FilaService::dispatch($pacienteObservacao->atendimento->fila->centroCusto);
|
|
}
|
|
}
|
|
|
|
private static function getCaracteristicaDor()
|
|
{
|
|
$caracteristicasEnum = [
|
|
DorToracicaEnum::CONTRICAO,
|
|
DorToracicaEnum::QUEIMACAO,
|
|
DorToracicaEnum::COMPRESSAO,
|
|
DorToracicaEnum::PESO,
|
|
DorToracicaEnum::DOR_SURDA
|
|
];
|
|
|
|
$result = OrigemDorToracica::whereIn('id', $caracteristicasEnum)
|
|
->orderBy('nome')
|
|
->get()
|
|
->map(fn ($dorToracica) => [
|
|
'id' => $dorToracica->id,
|
|
'nome' => $dorToracica->nome,
|
|
]);
|
|
|
|
return $result;
|
|
}
|
|
|
|
private static function getLocalizacaoDor()
|
|
{
|
|
$caracteristicasEnum = [
|
|
DorToracicaEnum::RETROESTERNAL,
|
|
DorToracicaEnum::MSE,
|
|
DorToracicaEnum::FACE,
|
|
DorToracicaEnum::PESCOCO,
|
|
DorToracicaEnum::DENTES,
|
|
DorToracicaEnum::INTER_ESCAPULAR,
|
|
DorToracicaEnum::EPIGASTRICA,
|
|
];
|
|
|
|
$result = OrigemDorToracica::whereIn('id', $caracteristicasEnum)
|
|
->orderBy('nome')
|
|
->get()
|
|
->map(fn ($dorToracica) => [
|
|
'id' => $dorToracica->id,
|
|
'nome' => $dorToracica->nome,
|
|
]);
|
|
|
|
return $result;
|
|
}
|
|
|
|
private static function getFatorDesencadeante()
|
|
{
|
|
$caracteristicasEnum = [
|
|
DorToracicaEnum::EXERCICIO,
|
|
DorToracicaEnum::EXCITACAO,
|
|
DorToracicaEnum::ESTRESSE,
|
|
DorToracicaEnum::FRIO,
|
|
DorToracicaEnum::REFEICOES_COPIOSAS,
|
|
];
|
|
|
|
$result = OrigemDorToracica::whereIn('id', $caracteristicasEnum)
|
|
->orderBy('nome')
|
|
->get()
|
|
->map(fn ($dorToracica) => [
|
|
'id' => $dorToracica->id,
|
|
'nome' => $dorToracica->nome,
|
|
]);
|
|
|
|
return $result;
|
|
}
|
|
|
|
private static function getFatoresRiscoToracica()
|
|
{
|
|
$caracteristicasEnum = [
|
|
DorToracicaEnum::HAS,
|
|
DorToracicaEnum::DM,
|
|
DorToracicaEnum::DISLIPIDEMIA,
|
|
DorToracicaEnum::HISTORIA_FAMILIAR,
|
|
DorToracicaEnum::IDADE_MAIOR_SESSENTA,
|
|
DorToracicaEnum::OBESIDADE,
|
|
DorToracicaEnum::TABAGISMO,
|
|
DorToracicaEnum::REVASCULARIZADO_PREVIO,
|
|
];
|
|
|
|
$result = OrigemDorToracica::whereIn('id', $caracteristicasEnum)
|
|
->orderBy('nome')
|
|
->get()
|
|
->map(fn ($dorToracica) => [
|
|
'id' => $dorToracica->id,
|
|
'nome' => $dorToracica->nome,
|
|
]);
|
|
|
|
return $result;
|
|
}
|
|
|
|
private static function getDuracaoDor()
|
|
{
|
|
$result = OrigemDorToracica::orderBy('id')
|
|
->where('id', '=', DorToracicaEnum::DURACAO_DA_DOR)
|
|
->get()
|
|
->map(fn ($duracao) => [
|
|
'id' => $duracao->id,
|
|
'nome' => $duracao->nome,
|
|
]);
|
|
|
|
return $result;
|
|
}
|
|
}
|