This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento;
|
||||
|
||||
use App\Models\ProntoAtendimento\Atendimento\Cat;
|
||||
|
||||
class AcidenteTrabalhoService
|
||||
{
|
||||
public static function getAcidenteTrabalho($faa)
|
||||
{
|
||||
$parecerMedico = [];
|
||||
|
||||
if(!$faa->raat) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parecerMedico = $faa->raat && $faa->raat->pareceresMedico ? $faa->raat->pareceresMedico()->orderByDesc('created_at')->first() : [];
|
||||
|
||||
$cat = null;
|
||||
|
||||
if($faa->raat->id){
|
||||
$cat = Cat::where('raat_id', $faa->raat->id)->first();
|
||||
}
|
||||
|
||||
return [
|
||||
'id' => $faa->raat->id ?? null,
|
||||
'tipo_formulario_acidente_trabalho' => $faa->raat->tipo_formulario_acidente_trabalho,
|
||||
'empresa_nome' => $faa->raat->empresa_nome ?? null,
|
||||
'empresa_ramo_atividade' => $faa->raat->empresa_ramo_atividade ?? null,
|
||||
'empresa_endereco' => $faa->raat->empresa_endereco ?? null,
|
||||
'empresa_telefone' => $faa->raat->empresa_telefone ?? null,
|
||||
'empresa_ocupacao_paciente' => $cat ? $cat->empresa_ocupacao_paciente : null,
|
||||
'acidente_data' => $faa->raat->acidente_data ?? null,
|
||||
'acidente_hora' => $faa->raat->acidente_hora ?? null,
|
||||
'acidente_tipo_id' => $faa->raat->acidente_tipo_id ?? null,
|
||||
'acidente_local' => $faa->raat->acidente_local ?? null,
|
||||
'acidente_descricao' => $faa->raat->acidente_descricao ?? null,
|
||||
'regime_trabalho_id' => $faa->raat->regime_trabalho_id ?? null,
|
||||
'regime_trabalho_outro' => $faa->raat->regime_trabalho_outro ?? null,
|
||||
'parecer_medico' => [
|
||||
'agenteId' => $parecerMedico ? $parecerMedico->agente_id : null,
|
||||
'partes_corpo_atingidas' => $parecerMedico ? $parecerMedico->partesCorpoAtingidas->pluck('id') : [],
|
||||
'parte_corpo_atingida_outras' => $parecerMedico ? $parecerMedico->parte_corpo_atingida_outras : null,
|
||||
'causas_acidente' => $parecerMedico ? $parecerMedico->causasAcidente->pluck('id') : [],
|
||||
'causa_acidente_outras' => $parecerMedico ? $parecerMedico->causa_acidente_outras : null,
|
||||
'diagnosticos' => $parecerMedico ? $parecerMedico->diagnosticos->pluck('id') : [],
|
||||
'diagnostico_outros' => $parecerMedico ? $parecerMedico->diagnostico_outros : null,
|
||||
'observacao' => $parecerMedico ? $parecerMedico->observacao : null,
|
||||
'classificacao_inicial_id' => $parecerMedico ? $parecerMedico->classificacao_inicial_id : null,
|
||||
'afastado' => $parecerMedico ? $parecerMedico->afastado : null,
|
||||
'lotacao' => [
|
||||
'profissional' => [
|
||||
'id' => $parecerMedico->createdLotacao->usuario->id ?? null,
|
||||
],
|
||||
],
|
||||
'cid' => [
|
||||
'codigo' => $parecerMedico->atendimentoMedico->cid->cid->codigo ?? null,
|
||||
'nome' => $parecerMedico->atendimentoMedico->cid->cid->nome ?? null,
|
||||
],
|
||||
'paciente_sofreu_acidente_trabalho' => $cat ? $cat->paciente_sofreu_acidente_trabalho : '',
|
||||
'paciente_portador_doenca_ocupacional' =>$cat ? $cat->paciente_portador_doenca_ocupacional : '',
|
||||
'paciente_precisa_internacao' => $cat ? $cat->paciente_precisa_internacao : '',
|
||||
'dias_afastamento' => $cat ? $cat->dias_afastamento : '',
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
507
api/app/Services/ProntoAtendimento/Aih/AihService.php
Normal file
507
api/app/Services/ProntoAtendimento/Aih/AihService.php
Normal file
@@ -0,0 +1,507 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento\Aih;
|
||||
|
||||
use App\Enums\Cadastro\SujeitoAtencao\Classificacao;
|
||||
use App\Enums\Cadastro\SujeitoAtencao\PreferenciaNome;
|
||||
use App\Enums\Geral\DocumentoTipo as DocumentoTipoEnum;
|
||||
use App\Models\Cadastro\Estabelecimento\Unidade;
|
||||
use App\Models\Cadastro\Parametrizacao\ParametrizacaoPermissaoUsuario;
|
||||
use App\Models\Cadastro\SujeitoAtencao\PacienteClassificacao;
|
||||
use App\Models\Cadastro\SujeitoAtencao\Sexo;
|
||||
use App\Models\Cns\TermoInvalido;
|
||||
use App\Models\Geral\DocumentoTipo;
|
||||
use App\Models\ProntoAtendimento\Aih\CaraterInternacao;
|
||||
use App\Models\ProntoAtendimento\Aih\CausaExterna;
|
||||
use App\Models\ProntoAtendimento\Aih\Clinica;
|
||||
use App\Models\ProntoAtendimento\Aih\Internacao;
|
||||
use App\Models\ProntoAtendimento\Aih\VinculoPrevidencia;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Faa;
|
||||
use App\Services\Cadastro\SujeitoAtencao\PacienteDesconhecidoSaveService;
|
||||
use App\Services\Service;
|
||||
use App\Utils\DataUtil;
|
||||
use App\Utils\MaskUtil;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class AihService extends Service
|
||||
{
|
||||
public static function datatable()
|
||||
{
|
||||
$builder = DB::table('pronto_atendimento_aih_internacao AS internacao')
|
||||
->join(
|
||||
'cadastro_lotacao AS lotacao',
|
||||
'lotacao.id',
|
||||
'internacao.created_lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_paciente AS paciente',
|
||||
'paciente.id',
|
||||
'internacao.paciente_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_cidadao AS cidadao',
|
||||
'cidadao.id',
|
||||
'paciente.cidadao_id'
|
||||
)
|
||||
->leftJoin(
|
||||
'cadastro_domicilio AS domicilio',
|
||||
'domicilio.id',
|
||||
'cidadao.domicilio_id'
|
||||
)
|
||||
->leftJoin(
|
||||
'cadastro_endereco AS endereco',
|
||||
'endereco.id',
|
||||
'domicilio.endereco_id'
|
||||
)
|
||||
->leftJoin(
|
||||
'cadastro_logradouro AS logradouro',
|
||||
'logradouro.id',
|
||||
'endereco.logradouro_id'
|
||||
)
|
||||
->leftJoin(
|
||||
'intranet.cadastro_municipio AS municipio',
|
||||
'municipio.id',
|
||||
'logradouro.municipio_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_aih_internacao_procedimento AS procedimento',
|
||||
'procedimento.internacao_id',
|
||||
'internacao.id'
|
||||
)
|
||||
->leftJoin(
|
||||
'pronto_atendimento_faa AS faa',
|
||||
'faa.id',
|
||||
'internacao.faa_id'
|
||||
)
|
||||
->whereNull('internacao.deleted_at')
|
||||
->where('lotacao.infraestrutura_id', self::getCurrentLotacao()->infraestrutura_id)
|
||||
->select(
|
||||
'internacao.id',
|
||||
'procedimento.data_solicitacao',
|
||||
'internacao.faa_id',
|
||||
'faa.numero AS faa_numero',
|
||||
'cidadao.nome AS paciente_nome',
|
||||
'cidadao.nome_social AS paciente_nome_social',
|
||||
'cidadao.preferencia_nome_id as paciente_preferencia_nome_id',
|
||||
'cidadao.data_nascimento AS paciente_data_nascimento',
|
||||
'cidadao.nome_mae AS paciente_nome_mae',
|
||||
'cidadao.caracteristicas_fisicas AS paciente_caracteristicas_fisicas',
|
||||
'paciente.prontuario AS paciente_prontuario',
|
||||
'paciente.sequencial_desconhecido_em AS paciente_sequencial_desconhecido_em',
|
||||
'municipio.nome AS municipio',
|
||||
);
|
||||
|
||||
return datatables()
|
||||
->of($builder)
|
||||
->setRowData([
|
||||
'paciente_prefere_nome_social' => function ($data) {
|
||||
|
||||
return $data->paciente_preferencia_nome_id === PreferenciaNome::NOME_SOCIAL;
|
||||
},
|
||||
'paciente_is_desconhecido' => function ($data) {
|
||||
|
||||
return !is_null($data->paciente_sequencial_desconhecido_em);
|
||||
}
|
||||
])
|
||||
->editColumn('paciente_data_nascimento', function ($data) {
|
||||
|
||||
return is_null($data->paciente_data_nascimento)
|
||||
? 'Não informada'
|
||||
: (new Carbon($data->paciente_data_nascimento))->format('d/m/Y');
|
||||
})
|
||||
->editColumn('paciente_nome_mae', function ($data) {
|
||||
|
||||
return $data->paciente_nome_mae ?? 'Não informado';
|
||||
})
|
||||
->editColumn('paciente_caracteristicas_fisicas', function ($data) {
|
||||
|
||||
return $data->paciente_caracteristicas_fisicas ?? 'Não informado';
|
||||
})
|
||||
->removeColumn([
|
||||
'paciente_preferencia_nome_id',
|
||||
'paciente_sequencial_desconhecido_em'
|
||||
])
|
||||
->addColumn('impressoes', self::getImpressoes())
|
||||
->filterColumn('procedimento.data_solicitacao', function ($query, $keyword) {
|
||||
|
||||
$query
|
||||
->whereRaw("DATE_FORMAT(procedimento.data_solicitacao, '%d/%m/%Y') like ?", ["%{$keyword}%"])
|
||||
->orWhereRaw(
|
||||
"CONCAT(
|
||||
SUBSTR(procedimento.data_solicitacao,9,2),
|
||||
SUBSTR(procedimento.data_solicitacao,6,2),
|
||||
SUBSTR(procedimento.data_solicitacao,1,4)
|
||||
) like ?",
|
||||
["%{$keyword}%"]
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
public static function index()
|
||||
{
|
||||
return Internacao::where(self::getWhereFromQueryString(['paciente_id', 'finalizada']))->get();
|
||||
}
|
||||
|
||||
public static function create($pacienteId = null)
|
||||
{
|
||||
$internacao = new Internacao;
|
||||
$internacao->paciente_id = $pacienteId;
|
||||
|
||||
return [
|
||||
'form' => self::getFormData($internacao->paciente),
|
||||
'model' => self::getModelData($internacao),
|
||||
'additionals' => self::getAdditionalsData()
|
||||
];
|
||||
}
|
||||
|
||||
public static function list()
|
||||
{
|
||||
|
||||
$lotacao = self::getCurrentLotacao();
|
||||
|
||||
$permissaoUsuario = ParametrizacaoPermissaoUsuario::where('usuario_id', $lotacao->usuario_id)
|
||||
->where('infraestrutura_id', $lotacao->infraestrutura_id)
|
||||
->first();
|
||||
|
||||
$countUsuario = ParametrizacaoPermissaoUsuario::count();
|
||||
|
||||
$classificacoes = $permissaoUsuario
|
||||
? PacienteClassificacao::orderBy('descricao')
|
||||
->get()
|
||||
->filter(function ($classificacao) use ($permissaoUsuario) {
|
||||
|
||||
$exibe = false;
|
||||
|
||||
switch ($classificacao->id) {
|
||||
case Classificacao::MUNICIPE:
|
||||
$exibe = $permissaoUsuario->municipe;
|
||||
break;
|
||||
case Classificacao::PROVISORIO:
|
||||
$exibe = $permissaoUsuario->provisorio;
|
||||
break;
|
||||
case Classificacao::OUTRO_MUNICIPIO:
|
||||
$exibe = $permissaoUsuario->outro_municipio;
|
||||
break;
|
||||
}
|
||||
|
||||
return $exibe ? [
|
||||
'id' => $classificacao->id,
|
||||
'descricao' => $classificacao->descricao
|
||||
] : null;
|
||||
})
|
||||
->values()
|
||||
: [];
|
||||
|
||||
return [
|
||||
'classificacoes' => $classificacoes,
|
||||
'is_permissao_cadastro' => $countUsuario === 0 ? true : false,
|
||||
];
|
||||
}
|
||||
|
||||
public static function store()
|
||||
{
|
||||
AihValidator::validateSave();
|
||||
|
||||
$internacao = new Internacao();
|
||||
|
||||
DB::transaction(function () use ($internacao) {
|
||||
|
||||
$params = self::getParams();
|
||||
|
||||
self::save($internacao, $params);
|
||||
});
|
||||
|
||||
$internacao->impressoes = self::getImpressoes();
|
||||
|
||||
return $internacao;
|
||||
}
|
||||
|
||||
private static function getImpressoes()
|
||||
{
|
||||
return [
|
||||
[
|
||||
'value' => 'laudo',
|
||||
'text' => 'Laudo',
|
||||
'disabled' => false,
|
||||
],
|
||||
[
|
||||
'value' => 'termoResponsabilidade',
|
||||
'text' => 'Termo de responsabilidade',
|
||||
'disabled' => false,
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
public static function edit($id)
|
||||
{
|
||||
$internacao = Internacao::findOrFail($id);
|
||||
|
||||
return [
|
||||
'form' => self::getFormData($internacao->paciente),
|
||||
'model' => self::getModelData($internacao),
|
||||
'additionals' => self::getAdditionalsData()
|
||||
];
|
||||
}
|
||||
|
||||
private static function getFormData($paciente = null)
|
||||
{
|
||||
$identificacao = null;
|
||||
$faas = [];
|
||||
|
||||
if ($paciente) {
|
||||
|
||||
$identificacao = [
|
||||
'nome_paciente' => $paciente->cidadao->nome,
|
||||
'nome_mae' => $paciente->cidadao->nome_mae ?? '',
|
||||
'data_nascimento' => $paciente && $paciente->cidadao->data_nascimento
|
||||
? $paciente->cidadao->data_nascimento->format('d/m/Y') : null,
|
||||
'cpf' => $paciente && $paciente->cidadao->cpf
|
||||
? MaskUtil::getCpfMasked($paciente->cidadao->cpf) : '',
|
||||
'cns' => $paciente && $paciente->cidadao->cns
|
||||
? MaskUtil::getCnsMasked($paciente->cidadao->cns) : '',
|
||||
'idade' => [
|
||||
'anos' => $paciente->cidadao->idade['anos'] ?? 'Não informada',
|
||||
'meses' => $paciente->cidadao->idade['meses'] ?? 'Não informada',
|
||||
'dias' => $paciente->cidadao->idade['dias'] ?? 'Não informada',
|
||||
],
|
||||
'sexo' => [
|
||||
'id' => $paciente->cidadao->sexo->id,
|
||||
'descricao' => $paciente->cidadao->sexo->descricao,
|
||||
],
|
||||
'nome_social' => $paciente->cidadao->nome_social,
|
||||
'preferencia_nome_id' => $paciente->cidadao->preferencia_nome_id ?? null,
|
||||
];
|
||||
|
||||
$faas = Faa::where('paciente_id', $paciente->id)
|
||||
->orderByDesc('id')
|
||||
->take(5)
|
||||
->get()
|
||||
->map(fn ($faa) => [
|
||||
'id' => $faa->id,
|
||||
'data' => (new Carbon($faa->atendimentos->first()->recepcao->atendido_em))->format('d/m/Y')
|
||||
]);
|
||||
}
|
||||
|
||||
return [
|
||||
'paciente' => [
|
||||
'identificacao' => $identificacao,
|
||||
'desconhecido' => [
|
||||
'sexos' => Sexo::orderBy('descricao')->get(['id', 'descricao'])
|
||||
]
|
||||
],
|
||||
'unidades' => Unidade::orderBy('nome_fantasia')->get(['id', 'nome_fantasia']),
|
||||
'unidade_internacao' => self::getCurrentCentroCusto()->infraestrutura->unidade->nome_fantasia,
|
||||
'faas' => $faas,
|
||||
'procedimento' => [
|
||||
'clinicas' => Clinica::orderBy('nome')->get(['id', 'nome']),
|
||||
'caraters_internacao' => CaraterInternacao::orderBy('nome')->get(['id', 'nome']),
|
||||
'documentos' => DocumentoTipo::orderBy('nome')->whereIn('id', [
|
||||
DocumentoTipoEnum::CPF, DocumentoTipoEnum::CNS
|
||||
])->get(['id', 'nome']),
|
||||
],
|
||||
'causa_externa' => [
|
||||
'causas_externas' => CausaExterna::orderBy('nome')->get(['id', 'nome'])
|
||||
->prepend(['id' => null, 'nome' => 'NÃO INFORMADO']),
|
||||
'vinculos_previdencia' => VinculoPrevidencia::orderBy('nome')->get(['id', 'nome'])
|
||||
->prepend(['id' => null, 'nome' => 'NÃO INFORMADO']),
|
||||
],
|
||||
'autorizacao' => [
|
||||
'documentos' => DocumentoTipo::orderBy('nome')->whereIn('id', [
|
||||
DocumentoTipoEnum::CPF, DocumentoTipoEnum::CNS
|
||||
])->get(['id', 'nome']),
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
private static function getModelData($internacao)
|
||||
{
|
||||
return [
|
||||
'id' => $internacao->id,
|
||||
'paciente' => [
|
||||
'sexo_id' => null,
|
||||
'caracteristicas_fisicas' => ''
|
||||
],
|
||||
'paciente_id' => $internacao->paciente_id,
|
||||
'unidade_solicitante_id' => $internacao->unidade_solicitante_id,
|
||||
'cid_principal' => $internacao->cidPrincipal,
|
||||
'cid_secundario' => $internacao->cidSecundario,
|
||||
'cid_causas_associadas' => $internacao->cidCausasAssociadas,
|
||||
'faa_id' => $internacao->faa_id,
|
||||
'principais_sinais_sintomas_clinicos' => $internacao->principais_sinais_sintomas_clinicos ?? '',
|
||||
'condicoes_que_justificam_internacao' => $internacao->condicoes_que_justificam_internacao ?? '',
|
||||
'principais_resultados_de_provas_diagnosticas' => $internacao->principais_resultados_de_provas_diagnosticas ?? '',
|
||||
'procedimento' => [
|
||||
'procedimento_solicitado' => $internacao->procedimento->procedimentoSolicitado ?? null,
|
||||
'data_solicitacao' => $internacao->procedimento && $internacao->procedimento->data_solicitacao
|
||||
? (new Carbon($internacao->procedimento->data_solicitacao))->format('d/m/Y') : null,
|
||||
'clinica_id' => $internacao->procedimento->clinica_id ?? null,
|
||||
'carater_internacao_id' => $internacao->procedimento->carater_internacao_id ?? null,
|
||||
'profissional_solicitante_assistente' => $internacao->procedimento ? [
|
||||
'id' => $internacao->procedimento->profissionalSolicitanteAssistente->id,
|
||||
'cidadao_nome' => $internacao->procedimento->profissionalSolicitanteAssistente->cidadao->nome,
|
||||
'cidadao_cns' => $internacao->procedimento->profissionalSolicitanteAssistente->cidadao->cns,
|
||||
'cidadao_cpf' => $internacao->procedimento->profissionalSolicitanteAssistente->cidadao->cpf,
|
||||
] : null,
|
||||
'documento_tipo_id' => $internacao->procedimento->documento_tipo_id ?? null,
|
||||
'documento_numero' => $internacao->procedimento->documento_numero ?? '',
|
||||
],
|
||||
'causa_externa' => [
|
||||
'causa_externa_id' => $internacao->causaExterna->causa_externa_id ?? null,
|
||||
'cnpj_seguradora' => $internacao->causaExterna && $internacao->causaExterna->cnpj_seguradora
|
||||
? MaskUtil::getCnpjMasked($internacao->causaExterna->cnpj_seguradora) : '',
|
||||
'numero_bilhete' => $internacao->causaExterna->numero_bilhete ?? '',
|
||||
'serie' => $internacao->causaExterna->serie ?? '',
|
||||
'cnpj_empresa' => $internacao->causaExterna && $internacao->causaExterna->cnpj_empresa
|
||||
? MaskUtil::getCnpjMasked($internacao->causaExterna->cnpj_empresa) : '',
|
||||
'cnae_empresa' => $internacao->causaExterna->cnae_empresa ?? '',
|
||||
'cbor' => $internacao->causaExterna->cbor ?? '',
|
||||
'vinculo_previdencia_id' => $internacao->causaExterna->vinculo_previdencia_id ?? null
|
||||
],
|
||||
'autorizacao' => [
|
||||
'profissional_autorizador' => $internacao->autorizacao ? [
|
||||
'id' => $internacao->autorizacao->profissionalAutorizador->id,
|
||||
'cidadao_nome' => $internacao->autorizacao->profissionalAutorizador->cidadao->nome,
|
||||
'cidadao_cns' => $internacao->autorizacao->profissionalAutorizador->cidadao->cns,
|
||||
'cidadao_cpf' => $internacao->autorizacao->profissionalAutorizador->cidadao->cpf,
|
||||
] : null,
|
||||
'documento_tipo_id' => $internacao->autorizacao->documento_tipo_id ?? null,
|
||||
'documento_numero' => $internacao->autorizacao->documento_numero ?? '',
|
||||
'data_autorizacao' => $internacao->autorizacao && $internacao->autorizacao->data_autorizacao
|
||||
? (new Carbon($internacao->autorizacao->data_autorizacao))->format('d/m/Y') : null,
|
||||
'codigo_orgao_emissor' => $internacao->autorizacao->codigo_orgao_emissor ?? ''
|
||||
],
|
||||
'finalizada' => $internacao->finalizada ?? false
|
||||
];
|
||||
}
|
||||
|
||||
private static function getAdditionalsData()
|
||||
{
|
||||
return [
|
||||
'data_atual' => Carbon::now()->format('d/m/Y'),
|
||||
'termos_invalidos' => TermoInvalido::pluck('descricao'),
|
||||
];
|
||||
}
|
||||
|
||||
public static function update($id)
|
||||
{
|
||||
AihValidator::validateSave();
|
||||
|
||||
$internacao = Internacao::findOrFail($id);
|
||||
|
||||
DB::transaction(function () use ($internacao) {
|
||||
|
||||
$params = self::getParams();
|
||||
|
||||
self::save($internacao, $params);
|
||||
});
|
||||
|
||||
return $internacao;
|
||||
}
|
||||
|
||||
private static function getParams()
|
||||
{
|
||||
$params = request()->except(['procedimento', 'causa_externa', 'autorizacao']);
|
||||
|
||||
$params['paciente'] = isset($params['paciente_id']) ? null : self::getParamsPaciente();
|
||||
$params['unidade_internacao_id'] = self::getCurrentCentroCusto()->infraestrutura->unidade_id;
|
||||
$params['procedimento'] = self::getParamsProcedimento();
|
||||
$params['causa_externa'] = self::getParamsCausaExterna();
|
||||
$params['autorizacao'] = self::getParamsAutorizacao();
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
private static function getParamsPaciente()
|
||||
{
|
||||
return request()->get('paciente');
|
||||
}
|
||||
|
||||
private static function getParamsProcedimento()
|
||||
{
|
||||
$params = request()->get('procedimento');
|
||||
|
||||
if (!DataUtil::hasData($params)) {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isset($params['data_solicitacao'])) {
|
||||
|
||||
$params['data_solicitacao'] = Carbon::createFromFormat('d/m/Y', $params['data_solicitacao']);
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
private static function getParamsCausaExterna()
|
||||
{
|
||||
$params = request()->get('causa_externa');
|
||||
|
||||
if (!DataUtil::hasData($params)) {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
private static function getParamsAutorizacao()
|
||||
{
|
||||
$params = request()->get('autorizacao');
|
||||
|
||||
if (!DataUtil::hasData($params) || !isset($params['profissional_autorizador_id'])) {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if (isset($params['data_autorizacao'])) {
|
||||
|
||||
$params['data_autorizacao'] = Carbon::createFromFormat('d/m/Y', $params['data_autorizacao']);
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
private static function save($internacao, $params)
|
||||
{
|
||||
$internacao->fill($params);
|
||||
|
||||
self::savePaciente($internacao, $params['paciente']);
|
||||
|
||||
$internacao->save();
|
||||
|
||||
self::saveChild($internacao, 'procedimento', $params['procedimento']);
|
||||
self::saveChild($internacao, 'causaExterna', $params['causa_externa']);
|
||||
self::saveChild($internacao, 'autorizacao', $params['autorizacao']);
|
||||
}
|
||||
|
||||
private static function savePaciente($internacao, $params)
|
||||
{
|
||||
if (is_null($params)) {
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$internacao->paciente_id = (new PacienteDesconhecidoSaveService(
|
||||
Carbon::now()->format('Y-m-d H:i:s'),
|
||||
$params['sexo_id'],
|
||||
$params['caracteristicas_fisicas']
|
||||
))->save()->id;
|
||||
}
|
||||
|
||||
private static function saveChild($internacao, $relationName, $params)
|
||||
{
|
||||
if (is_null($params)) {
|
||||
|
||||
if ($internacao->{$relationName}) {
|
||||
|
||||
$internacao->{$relationName}->delete();
|
||||
}
|
||||
}
|
||||
else {
|
||||
|
||||
$internacao->{$relationName}()->updateOrCreate(['internacao_id' => $internacao->id], $params);
|
||||
}
|
||||
}
|
||||
}
|
||||
224
api/app/Services/ProntoAtendimento/Aih/AihValidator.php
Normal file
224
api/app/Services/ProntoAtendimento/Aih/AihValidator.php
Normal file
@@ -0,0 +1,224 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento\Aih;
|
||||
|
||||
use App\Enums\Geral\DocumentoTipo;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Faa;
|
||||
use App\Rules\Cnpj;
|
||||
use App\Rules\Cns;
|
||||
use App\Rules\CnsTermoValido;
|
||||
use App\Rules\Cpf;
|
||||
use App\Rules\NomeCompleto;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class AihValidator
|
||||
{
|
||||
public static function validateSave()
|
||||
{
|
||||
$rules = [
|
||||
'paciente_id' => [
|
||||
'nullable',
|
||||
'integer'
|
||||
],
|
||||
'unidade_solicitante_id' => [
|
||||
'required',
|
||||
'integer'
|
||||
],
|
||||
'cid_principal_id' => [
|
||||
'required',
|
||||
'integer'
|
||||
],
|
||||
'cid_secundario_id' => [
|
||||
'nullable',
|
||||
'integer'
|
||||
],
|
||||
'cid_causas_associadas_id' => [
|
||||
'nullable',
|
||||
'integer'
|
||||
],
|
||||
'faa_id' => [
|
||||
'bail',
|
||||
'nullable',
|
||||
'integer',
|
||||
function ($attribute, $value, $fail) {
|
||||
|
||||
$faa = Faa::find($value);
|
||||
|
||||
if ($faa && $faa->paciente_id != request()->paciente_id) {
|
||||
|
||||
$fail('FAA não vinculada ao paciente.');
|
||||
}
|
||||
}
|
||||
],
|
||||
'principais_sinais_sintomas_clinicos' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:1000'
|
||||
],
|
||||
'condicoes_que_justificam_internacao' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:1000'
|
||||
],
|
||||
'principais_resultados_de_provas_diagnosticas' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:1000'
|
||||
],
|
||||
'finalizada' => [
|
||||
'required',
|
||||
'boolean'
|
||||
]
|
||||
];
|
||||
|
||||
return request()->validate(array_merge(
|
||||
$rules,
|
||||
self::getPacienteValidations(),
|
||||
self::getProcedimentoValidations(),
|
||||
self::getCausaExternaValidations(),
|
||||
self::getAutorizacaoValidations()
|
||||
));
|
||||
}
|
||||
|
||||
private static function getPacienteValidations()
|
||||
{
|
||||
return [
|
||||
'paciente.sexo_id' => [
|
||||
'nullable',
|
||||
'required_without:paciente_id',
|
||||
'integer'
|
||||
],
|
||||
'paciente.caracteristicas_fisicas' => [
|
||||
'nullable',
|
||||
'required_without:paciente_id',
|
||||
'string',
|
||||
'max:500'
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private static function getProcedimentoValidations()
|
||||
{
|
||||
return [
|
||||
'procedimento.procedimento_solicitado_id' => [
|
||||
'bail',
|
||||
'required',
|
||||
'integer',
|
||||
],
|
||||
'procedimento.data_solicitacao' => [
|
||||
'required',
|
||||
'date_format:d/m/Y',
|
||||
'before_or_equal:now'
|
||||
],
|
||||
'procedimento.clinica_id' => [
|
||||
'required',
|
||||
'integer'
|
||||
],
|
||||
'procedimento.carater_internacao_id' => [
|
||||
'required',
|
||||
'integer'
|
||||
],
|
||||
'procedimento.profissional_solicitante_assistente_id' => [
|
||||
'required',
|
||||
'integer'
|
||||
],
|
||||
'procedimento.documento_tipo_id' => [
|
||||
'required',
|
||||
'integer'
|
||||
],
|
||||
'procedimento.documento_numero' => [
|
||||
'required',
|
||||
self::getDocumentoNumeroValidation(request()->documento_tipo_id)
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private static function getCausaExternaValidations()
|
||||
{
|
||||
return [
|
||||
'causa_externa.causa_externa_id' => [
|
||||
'nullable',
|
||||
'integer'
|
||||
],
|
||||
'causa_externa.cnpj_seguradora' => [
|
||||
'nullable',
|
||||
new Cnpj
|
||||
],
|
||||
'causa_externa.numero_bilhete' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:10'
|
||||
],
|
||||
'causa_externa.serie' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:6'
|
||||
],
|
||||
'causa_externa.cnpj_empresa' => [
|
||||
'nullable',
|
||||
new Cnpj
|
||||
],
|
||||
'causa_externa.cnae_empresa' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:10'
|
||||
],
|
||||
'causa_externa.cbor' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:3'
|
||||
],
|
||||
'causa_externa.vinculo_previdencia_id' => [
|
||||
'nullable',
|
||||
'integer'
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private static function getAutorizacaoValidations()
|
||||
{
|
||||
return [
|
||||
'autorizacao.profissional_autorizador_id' => [
|
||||
'nullable',
|
||||
'integer'
|
||||
],
|
||||
'autorizacao.documento_tipo_id' => [
|
||||
'nullable',
|
||||
'integer'
|
||||
],
|
||||
'autorizacao.documento_numero' => [
|
||||
'nullable',
|
||||
self::getDocumentoNumeroValidation(request()->documento_tipo_id)
|
||||
],
|
||||
'autorizacao.data_autorizacao' => [
|
||||
'nullable',
|
||||
'date_format:d/m/Y',
|
||||
'before_or_equal:now'
|
||||
],
|
||||
'autorizacao.codigo_orgao_emissor' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:6'
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private static function getDocumentoNumeroValidation($documentoTipoId)
|
||||
{
|
||||
switch ($documentoTipoId) {
|
||||
|
||||
case DocumentoTipo::CPF: {
|
||||
|
||||
return new Cpf;
|
||||
}
|
||||
case DocumentoTipo::CNS: {
|
||||
|
||||
return new Cns;
|
||||
}
|
||||
default: {
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento;
|
||||
|
||||
use App\Enums\Cadastro\Medicamento\TipoReceita;
|
||||
use App\Enums\Cadastro\SujeitoAtencao\PreferenciaNome;
|
||||
use App\Models\Cadastro\SujeitoAtencao\Sexo;
|
||||
use App\Models\Cns\TermoInvalido;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Medico\Receita;
|
||||
use App\Services\Service;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class AssinaturaEletronicaService extends Service
|
||||
{
|
||||
public static function list()
|
||||
{
|
||||
$now = Carbon::now();
|
||||
$currentDate = $now->format('d/m/Y');
|
||||
$currentLotacao = self::getCurrentLotacao();
|
||||
|
||||
return [
|
||||
'form' => [
|
||||
'unidade' => $currentLotacao->infraestrutura->unidade->nome_fantasia,
|
||||
'infraestrutura' => $currentLotacao->infraestrutura->nome,
|
||||
'sexos' => Sexo::orderBy('descricao')->get(['id', 'descricao'])->makeHidden('identificador'),
|
||||
'tipos_documento' => [
|
||||
['value' => 'atendimento', 'text' => 'ATENDIMENTO'],
|
||||
['value' => 'receita_medica', 'text' => 'RECEITA MÉDICA'],
|
||||
],
|
||||
],
|
||||
'model' => [
|
||||
'periodo' => [
|
||||
'start' => $currentDate,
|
||||
'end' => $currentDate,
|
||||
],
|
||||
'sexo_id' => null,
|
||||
'paciente' => null,
|
||||
'data_nascimento' => null,
|
||||
'faa' => null,
|
||||
'tipo_documento' => null,
|
||||
],
|
||||
'additionals' => [
|
||||
'periodo_min_date' => $now->copy()->subYears(130)->format('d/m/Y'),
|
||||
'current_date' => $now->format('d/m/Y'),
|
||||
'termos_invalidos' => TermoInvalido::all()->map(fn ($termo) => $termo->descricao),
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
public static function datatable($request)
|
||||
{
|
||||
self::validateDatatableRequest($request);
|
||||
|
||||
$infraestruturaId = self::getCurrentCentroCusto()->infraestrutura_id;
|
||||
$usuarioId = self::getCurrentLotacao()->usuario_id;
|
||||
|
||||
$periodo = [
|
||||
Carbon::createFromFormat('d/m/Y', $request->periodo['start'])->setTime(0, 0, 0),
|
||||
Carbon::createFromFormat('d/m/Y', $request->periodo['end'])->setTime(23, 59, 59)
|
||||
];
|
||||
|
||||
$triagemQuery = DB::table('pronto_atendimento_atendimento_triagem as triagem')
|
||||
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'triagem.created_centro_custo_id')
|
||||
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'triagem.created_lotacao_id')
|
||||
->join('pronto_atendimento_atendimento as atendimento', 'atendimento.id', 'triagem.atendimento_id')
|
||||
->join('pronto_atendimento_faa as faa', 'faa.id', 'atendimento.faa_id')
|
||||
->join('cadastro_paciente as paciente', 'paciente.id', 'faa.paciente_id')
|
||||
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'paciente.cidadao_id')
|
||||
->leftJoin('cadastro_sexo as sexo', 'sexo.id', 'cidadao.sexo_id')
|
||||
->whereNull('triagem.deleted_at')
|
||||
->where('triagem.is_faa_assinada', false)
|
||||
->where('centro_custo.infraestrutura_id', $infraestruturaId)
|
||||
->where('lotacao.usuario_id', $usuarioId)
|
||||
->whereBetween('triagem.created_at', $periodo)
|
||||
->when($request->paciente, fn ($q, $value) => $q->where('cidadao.nome', 'like', "{$value}%"))
|
||||
->when($request->sexo_id, fn ($q, $id) => $q->where('cidadao.sexo_id', $id))
|
||||
->when($request->data_nascimento, fn ($q, $data) => $q
|
||||
->whereDate('cidadao.data_nascimento', Carbon::createFromFormat('d/m/Y', $data))
|
||||
)
|
||||
->when($request->faa, fn ($q, $id) => $q->where('faa.numero', $id))
|
||||
->select(DB::raw("
|
||||
atendimento.id as atendimento_id,
|
||||
triagem.id,
|
||||
'triagem' as tipo_identificador,
|
||||
'TRIAGEM' as tipo,
|
||||
triagem.created_at as data_hora,
|
||||
faa.id AS faa,
|
||||
faa.numero AS faa_numero,
|
||||
sexo.descricao AS sexo,
|
||||
paciente.prontuario AS paciente_prontuario,
|
||||
cidadao.data_nascimento AS paciente_data_nascimento,
|
||||
cidadao.nome_mae AS paciente_nome_mae,
|
||||
cidadao.nome AS paciente_nome,
|
||||
cidadao.nome_social AS paciente_nome_social,
|
||||
cidadao.preferencia_nome_id as paciente_preferencia_nome_id,
|
||||
cidadao.caracteristicas_fisicas AS paciente_caracteristicas_fisicas,
|
||||
paciente.sequencial_desconhecido_em AS paciente_sequencial_desconhecido_em,
|
||||
0 as tem_receita_medica_comum,
|
||||
0 as tem_receita_medica_especial
|
||||
"));
|
||||
|
||||
$medicoQuery = DB::table('pronto_atendimento_atendimento_medico as medico')
|
||||
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'medico.created_centro_custo_id')
|
||||
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'medico.created_lotacao_id')
|
||||
->join('pronto_atendimento_atendimento as atendimento', 'atendimento.id', 'medico.atendimento_id')
|
||||
->join('pronto_atendimento_faa as faa', 'faa.id', 'atendimento.faa_id')
|
||||
->join('cadastro_paciente as paciente', 'paciente.id', 'faa.paciente_id')
|
||||
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'paciente.cidadao_id')
|
||||
->leftJoin('cadastro_sexo as sexo', 'sexo.id', 'cidadao.sexo_id')
|
||||
->whereNull('medico.deleted_at')
|
||||
->where('medico.is_faa_assinada', false)
|
||||
->where('centro_custo.infraestrutura_id', $infraestruturaId)
|
||||
->where('lotacao.usuario_id', $usuarioId)
|
||||
->whereBetween('medico.created_at', $periodo)
|
||||
->when($request->paciente, fn ($q, $value) => $q->where('cidadao.nome', 'like', "{$value}%"))
|
||||
->when($request->sexo_id, fn ($q, $id) => $q->where('cidadao.sexo_id', $id))
|
||||
->when($request->data_nascimento, fn ($q, $data) => $q
|
||||
->whereDate('cidadao.data_nascimento', Carbon::createFromFormat('d/m/Y', $data))
|
||||
)
|
||||
->when($request->faa, fn ($q, $id) => $q->where('faa.numero', $id))
|
||||
->select(DB::raw("
|
||||
atendimento.id as atendimento_id,
|
||||
medico.id,
|
||||
'medico' as tipo_identificador,
|
||||
CONCAT('MÉDICO', IF(medico.is_observacao = 1,' (OBSERVAÇÃO)', '')) as tipo,
|
||||
medico.created_at as data_hora,
|
||||
faa.id AS faa,
|
||||
faa.numero AS faa_numero,
|
||||
sexo.descricao AS sexo,
|
||||
paciente.prontuario AS paciente_prontuario,
|
||||
cidadao.data_nascimento AS paciente_data_nascimento,
|
||||
cidadao.nome_mae AS paciente_nome_mae,
|
||||
cidadao.nome AS paciente_nome,
|
||||
cidadao.nome_social AS paciente_nome_social,
|
||||
cidadao.preferencia_nome_id as paciente_preferencia_nome_id,
|
||||
cidadao.caracteristicas_fisicas AS paciente_caracteristicas_fisicas,
|
||||
paciente.sequencial_desconhecido_em AS paciente_sequencial_desconhecido_em,
|
||||
0 as tem_receita_medica_comum,
|
||||
0 as tem_receita_medica_especial
|
||||
"));
|
||||
|
||||
$enfermagemQuery = DB::table('pronto_atendimento_atendimento_enfermagem as enfermagem')
|
||||
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'enfermagem.created_centro_custo_id')
|
||||
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'enfermagem.created_lotacao_id')
|
||||
->join('pronto_atendimento_atendimento as atendimento', 'atendimento.id', 'enfermagem.atendimento_id')
|
||||
->join('pronto_atendimento_faa as faa', 'faa.id', 'atendimento.faa_id')
|
||||
->join('cadastro_paciente as paciente', 'paciente.id', 'faa.paciente_id')
|
||||
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'paciente.cidadao_id')
|
||||
->leftJoin('cadastro_sexo as sexo', 'sexo.id', 'cidadao.sexo_id')
|
||||
->whereNull('enfermagem.deleted_at')
|
||||
->where('enfermagem.is_faa_assinada', false)
|
||||
->where('centro_custo.infraestrutura_id', $infraestruturaId)
|
||||
->where('lotacao.usuario_id', $usuarioId)
|
||||
->whereBetween('enfermagem.created_at', $periodo)
|
||||
->when($request->paciente, fn ($q, $value) => $q->where('cidadao.nome', 'like', "{$value}%"))
|
||||
->when($request->sexo_id, fn ($q, $id) => $q->where('cidadao.sexo_id', $id))
|
||||
->when($request->data_nascimento, fn ($q, $data) => $q
|
||||
->whereDate('cidadao.data_nascimento', Carbon::createFromFormat('d/m/Y', $data))
|
||||
)
|
||||
->when($request->faa, fn ($q, $id) => $q->where('faa.numero', $id))
|
||||
->select(DB::raw("
|
||||
atendimento.id as atendimento_id,
|
||||
enfermagem.id,
|
||||
'enfermagem' as tipo_identificador,
|
||||
'ENFERMAGEM' as tipo,
|
||||
enfermagem.created_at as data_hora,
|
||||
faa.id AS faa,
|
||||
faa.numero AS faa_numero,
|
||||
sexo.descricao AS sexo,
|
||||
paciente.prontuario AS paciente_prontuario,
|
||||
cidadao.data_nascimento AS paciente_data_nascimento,
|
||||
cidadao.nome_mae AS paciente_nome_mae,
|
||||
cidadao.nome AS paciente_nome,
|
||||
cidadao.nome_social AS paciente_nome_social,
|
||||
cidadao.preferencia_nome_id as paciente_preferencia_nome_id,
|
||||
cidadao.caracteristicas_fisicas AS paciente_caracteristicas_fisicas,
|
||||
paciente.sequencial_desconhecido_em AS paciente_sequencial_desconhecido_em,
|
||||
0 as tem_receita_medica_comum,
|
||||
0 as tem_receita_medica_especial
|
||||
"));
|
||||
|
||||
$observacaoQuery = DB::table('pronto_atendimento_paciente_observacao as observacao')
|
||||
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'observacao.created_centro_custo_id')
|
||||
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'observacao.created_lotacao_id')
|
||||
->join('pronto_atendimento_atendimento as atendimento', 'atendimento.id', 'observacao.atendimento_id')
|
||||
->join('pronto_atendimento_faa as faa', 'faa.id', 'atendimento.faa_id')
|
||||
->join('cadastro_paciente as paciente', 'paciente.id', 'faa.paciente_id')
|
||||
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'paciente.cidadao_id')
|
||||
->leftJoin('cadastro_sexo as sexo', 'sexo.id', 'cidadao.sexo_id')
|
||||
->whereNull('observacao.deleted_at')
|
||||
->where('observacao.is_faa_assinada', false)
|
||||
->where('centro_custo.infraestrutura_id', $infraestruturaId)
|
||||
->where('lotacao.usuario_id', $usuarioId)
|
||||
->whereBetween('observacao.created_at', $periodo)
|
||||
->when($request->paciente, fn ($q, $value) => $q->where('cidadao.nome', 'like', "{$value}%"))
|
||||
->when($request->sexo_id, fn ($q, $id) => $q->where('cidadao.sexo_id', $id))
|
||||
->when($request->data_nascimento, fn ($q, $data) => $q
|
||||
->whereDate('cidadao.data_nascimento', Carbon::createFromFormat('d/m/Y', $data))
|
||||
)
|
||||
->when($request->faa, fn ($q, $id) => $q->where('faa.numero', $id))
|
||||
->select(DB::raw("
|
||||
atendimento.id as atendimento_id,
|
||||
observacao.id,
|
||||
'observacao' as tipo_identificador,
|
||||
'ENFERMAGEM (OBSERVAÇÃO)' as tipo,
|
||||
observacao.created_at as data_hora,
|
||||
faa.id AS faa,
|
||||
faa.numero AS faa_numero,
|
||||
sexo.descricao AS sexo,
|
||||
paciente.prontuario AS paciente_prontuario,
|
||||
cidadao.data_nascimento AS paciente_data_nascimento,
|
||||
cidadao.nome_mae AS paciente_nome_mae,
|
||||
cidadao.nome AS paciente_nome,
|
||||
cidadao.nome_social AS paciente_nome_social,
|
||||
cidadao.preferencia_nome_id as paciente_preferencia_nome_id,
|
||||
cidadao.caracteristicas_fisicas AS paciente_caracteristicas_fisicas,
|
||||
paciente.sequencial_desconhecido_em AS paciente_sequencial_desconhecido_em,
|
||||
0 as tem_receita_medica_comum,
|
||||
0 as tem_receita_medica_especial
|
||||
"));
|
||||
|
||||
$receitaMedicaQuery = DB::table('pronto_atendimento_atendimento_medico_receita as receita')
|
||||
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'receita.created_centro_custo_id')
|
||||
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'receita.created_lotacao_id')
|
||||
->join('pronto_atendimento_atendimento_medico as medico', 'medico.id', 'receita.atendimento_medico_id')
|
||||
->join('pronto_atendimento_atendimento as atendimento', 'atendimento.id', 'medico.atendimento_id')
|
||||
->join('pronto_atendimento_faa as faa', 'faa.id', 'atendimento.faa_id')
|
||||
->join('cadastro_paciente as paciente', 'paciente.id', 'faa.paciente_id')
|
||||
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'paciente.cidadao_id')
|
||||
->leftJoin('cadastro_sexo as sexo', 'sexo.id', 'cidadao.sexo_id')
|
||||
->whereNull('receita.deleted_at')
|
||||
->where('receita.is_assinada', false)
|
||||
->where('centro_custo.infraestrutura_id', $infraestruturaId)
|
||||
->where('lotacao.usuario_id', $usuarioId)
|
||||
->whereBetween('receita.created_at', $periodo)
|
||||
->when($request->paciente, fn ($q, $value) => $q->where('cidadao.nome', 'like', "{$value}%"))
|
||||
->when($request->sexo_id, fn ($q, $id) => $q->where('cidadao.sexo_id', $id))
|
||||
->when($request->data_nascimento, fn ($q, $data) => $q
|
||||
->whereDate('cidadao.data_nascimento', Carbon::createFromFormat('d/m/Y', $data))
|
||||
)
|
||||
->when($request->faa, fn ($q, $id) => $q->where('faa.numero', $id))
|
||||
->select(DB::raw("
|
||||
atendimento.id as atendimento_id,
|
||||
receita.id,
|
||||
'receita_medica' as tipo_identificador,
|
||||
CONCAT('MÉDICO', IF(medico.is_observacao = 1,' (OBSERVAÇÃO)', ''), ' - RECEITA MÉDICA') as tipo,
|
||||
receita.created_at as data_hora,
|
||||
faa.id AS faa,
|
||||
faa.numero AS faa_numero,
|
||||
sexo.descricao AS sexo,
|
||||
paciente.prontuario AS paciente_prontuario,
|
||||
cidadao.data_nascimento AS paciente_data_nascimento,
|
||||
cidadao.nome_mae AS paciente_nome_mae,
|
||||
cidadao.nome AS paciente_nome,
|
||||
cidadao.nome_social AS paciente_nome_social,
|
||||
cidadao.preferencia_nome_id as paciente_preferencia_nome_id,
|
||||
cidadao.caracteristicas_fisicas AS paciente_caracteristicas_fisicas,
|
||||
paciente.sequencial_desconhecido_em AS paciente_sequencial_desconhecido_em
|
||||
"))
|
||||
->addSelect([
|
||||
'tem_receita_medica_comum' => function ($query) {
|
||||
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_atendimento_medico_receita_medicamento as receita_medicamento')
|
||||
->join('cadastro_medicamento as medicamento', 'medicamento.id', 'receita_medicamento.medicamento_id')
|
||||
->whereColumn('receita_medicamento.receita_id', 'receita.id')
|
||||
->whereNull('receita_medicamento.deleted_at')
|
||||
->where('medicamento.receita_tipo_id', TipoReceita::COMUM);
|
||||
},
|
||||
'tem_receita_medica_especial' => function ($query) {
|
||||
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_atendimento_medico_receita_medicamento as receita_medicamento')
|
||||
->join('cadastro_medicamento as medicamento', 'medicamento.id', 'receita_medicamento.medicamento_id')
|
||||
->whereColumn('receita_medicamento.receita_id', 'receita.id')
|
||||
->whereNull('receita_medicamento.deleted_at')
|
||||
->whereIn('medicamento.receita_tipo_id', [
|
||||
TipoReceita::ESPECIAL,
|
||||
TipoReceita::ESPECIAL_AMARELA,
|
||||
TipoReceita::ESPECIAL_AZUL,
|
||||
]);
|
||||
},
|
||||
]);
|
||||
|
||||
$documentos = null;
|
||||
|
||||
if ($request->tipo_documento == 'atendimento') {
|
||||
|
||||
$documentos = $triagemQuery
|
||||
->unionAll($medicoQuery)
|
||||
->unionAll($enfermagemQuery)
|
||||
->unionAll($observacaoQuery);
|
||||
}
|
||||
else if ($request->tipo_documento == 'receita_medica') {
|
||||
|
||||
$documentos = $receitaMedicaQuery;
|
||||
}
|
||||
else {
|
||||
|
||||
$documentos = $triagemQuery
|
||||
->unionAll($medicoQuery)
|
||||
->unionAll($enfermagemQuery)
|
||||
->unionAll($observacaoQuery)
|
||||
->unionAll($receitaMedicaQuery);
|
||||
}
|
||||
|
||||
$documentos = $documentos
|
||||
->orderBy('data_hora')
|
||||
->get()
|
||||
->map(function ($documento) {
|
||||
|
||||
if ($documento->tipo_identificador == 'receita_medica') {
|
||||
|
||||
$documento->tem_receita_medica_comum = (bool) $documento->tem_receita_medica_comum;
|
||||
$documento->tem_receita_medica_especial = (bool) $documento->tem_receita_medica_especial;
|
||||
}
|
||||
else {
|
||||
|
||||
unset($documento->tem_receita_medica_comum, $documento->tem_receita_medica_especial);
|
||||
}
|
||||
|
||||
if (is_null($documento->paciente_nome_mae)) {
|
||||
|
||||
$documento->paciente_nome_mae = 'Não informado';
|
||||
}
|
||||
|
||||
if (is_null($documento->paciente_caracteristicas_fisicas)) {
|
||||
|
||||
$documento->paciente_caracteristicas_fisicas = 'Não informado';
|
||||
}
|
||||
|
||||
$documento->paciente_is_desconhecido = !is_null($documento->paciente_sequencial_desconhecido_em);
|
||||
$documento->data_hora = (new Carbon($documento->data_hora))->format('d/m/Y H:i');
|
||||
|
||||
$documento->paciente_prefere_nome_social = $documento
|
||||
->paciente_preferencia_nome_id === PreferenciaNome::NOME_SOCIAL;
|
||||
|
||||
$documento->paciente_data_nascimento = is_null($documento->paciente_data_nascimento)
|
||||
? 'Não informada'
|
||||
: (new Carbon($documento->paciente_data_nascimento))->format('d/m/Y');
|
||||
|
||||
unset(
|
||||
$documento->paciente_preferencia_nome_id,
|
||||
$documento->paciente_sequencial_desconhecido_em
|
||||
);
|
||||
|
||||
return $documento;
|
||||
});
|
||||
|
||||
return $documentos;
|
||||
}
|
||||
|
||||
private static function validateDatatableRequest($request)
|
||||
{
|
||||
$minDate = Carbon::now()->subYears(130)->format('Y-m-d');
|
||||
|
||||
$request->validate([
|
||||
'periodo.start' => [
|
||||
'required',
|
||||
'date_format:d/m/Y',
|
||||
"after_or_equal:{$minDate}",
|
||||
'before_or_equal:periodo.end',
|
||||
],
|
||||
'periodo.end' => [
|
||||
'required',
|
||||
'date_format:d/m/Y',
|
||||
'after_or_equal:periodo.start',
|
||||
'before_or_equal:now',
|
||||
],
|
||||
'sexo_id' => [
|
||||
'nullable',
|
||||
'integer',
|
||||
],
|
||||
'paciente' => [
|
||||
'nullable',
|
||||
'string',
|
||||
],
|
||||
'data_nascimento' => [
|
||||
'nullable',
|
||||
'date_format:d/m/Y',
|
||||
],
|
||||
'faa' => [
|
||||
'nullable',
|
||||
'integer',
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento\AssistenciaSocial;
|
||||
|
||||
use App\Enums\Cadastro\SujeitoAtencao\PreferenciaNome;
|
||||
use App\Models\Cadastro\Estabelecimento\CentroCusto;
|
||||
use App\Models\Cadastro\SujeitoAtencao\Sexo;
|
||||
use App\Models\ProntoAtendimento\AssistenciaSocial\AssistenciaSocial;
|
||||
use App\Models\ProntoAtendimento\AssistenciaSocial\AssistenciaSocialHistorico;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Atendimento;
|
||||
use App\Models\Sigtap\Ocupacao;
|
||||
use App\Services\Service;
|
||||
use App\Utils\MaskUtil;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class AssistenciaSocialService extends Service
|
||||
{
|
||||
public static function list()
|
||||
{
|
||||
$now = Carbon::now();
|
||||
$currentDate = $now->format('d/m/Y');
|
||||
$currentLotacao = self::getCurrentLotacao();
|
||||
|
||||
return [
|
||||
'form' => [
|
||||
'unidade' => $currentLotacao->infraestrutura->unidade->nome_fantasia,
|
||||
'infraestrutura' => $currentLotacao->infraestrutura->nome,
|
||||
'sexos' => Sexo::orderBy('descricao')->get(['id', 'descricao'])->makeHidden('identificador')
|
||||
],
|
||||
'model' => [
|
||||
'periodo' => [
|
||||
'start' => $currentDate,
|
||||
'end' => $currentDate,
|
||||
],
|
||||
'sexo_id' => null,
|
||||
'paciente' => null,
|
||||
'data_nascimento' => null,
|
||||
'faa' => null,
|
||||
],
|
||||
'additionals' => [
|
||||
'periodo_min_date' => $now->copy()->subYears(130)->format('d/m/Y'),
|
||||
'current_date' => $now->format('d/m/Y')
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
public static function datatable($request)
|
||||
{
|
||||
self::validateDatatableRequest($request);
|
||||
|
||||
$atendimentos = DB::table('pronto_atendimento_atendimento AS atendimento')
|
||||
->leftJoin('painel_senha_fila AS fila', 'fila.id', 'atendimento.fila_id')
|
||||
->leftJoin('painel_senha_opcao_entrada AS opcao_entrada', 'opcao_entrada.id', 'fila.opcao_entrada_id')
|
||||
->join('pronto_atendimento_faa AS faa', 'faa.id', 'atendimento.faa_id')
|
||||
->join('cadastro_paciente AS paciente', 'paciente.id', 'faa.paciente_id')
|
||||
->join('cadastro_cidadao AS cidadao', 'cidadao.id', 'paciente.cidadao_id')
|
||||
->leftJoin('cadastro_sexo AS sexo', 'sexo.id', 'cidadao.sexo_id')
|
||||
->join('pronto_atendimento_atendimento_recepcao AS recepcao', 'recepcao.atendimento_id', 'atendimento.id')
|
||||
->join('cadastro_centro_custo AS centro_custo', 'centro_custo.id', 'atendimento.created_centro_custo_id')
|
||||
->join('cadastro_infraestrutura AS infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
|
||||
->select([
|
||||
'atendimento.id AS atendimento_id',
|
||||
'recepcao.atendido_em AS data',
|
||||
'recepcao.acompanhante AS acompanhante',
|
||||
'infraestrutura.nome as infraestrutura',
|
||||
'faa.id AS faa',
|
||||
'faa.numero AS faa_numero',
|
||||
DB::raw("CONCAT(opcao_entrada.sigla, fila.senha) AS senha"),
|
||||
'fila.created_at AS senha_data_hora_emissao',
|
||||
'sexo.descricao AS sexo',
|
||||
'paciente.prontuario AS paciente_prontuario',
|
||||
'faa.paciente_id AS paciente_id',
|
||||
'cidadao.data_nascimento AS paciente_data_nascimento',
|
||||
'cidadao.nome_mae AS paciente_nome_mae',
|
||||
'cidadao.nome AS paciente_nome',
|
||||
'cidadao.nome_social AS paciente_nome_social',
|
||||
'cidadao.preferencia_nome_id as paciente_preferencia_nome_id',
|
||||
'cidadao.caracteristicas_fisicas AS paciente_caracteristicas_fisicas',
|
||||
'paciente.sequencial_desconhecido_em AS paciente_sequencial_desconhecido_em',
|
||||
])
|
||||
->where('centro_custo.infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id)
|
||||
->whereBetween('recepcao.atendido_em', [
|
||||
Carbon::createFromFormat('d/m/Y', $request->periodo['start'])->setTime(0, 0, 0),
|
||||
Carbon::createFromFormat('d/m/Y', $request->periodo['end'])->setTime(23, 59, 59)
|
||||
])
|
||||
->when($request->sexo_id, function ($query, $value) {
|
||||
|
||||
$query->where('cidadao.sexo_id', $value);
|
||||
})
|
||||
->when($request->paciente, function ($query, $value) {
|
||||
|
||||
$query->where('cidadao.nome', 'like', "{$value}%");
|
||||
})
|
||||
->when($request->data_nascimento, function ($query, $value) {
|
||||
|
||||
$query->whereDate('cidadao.data_nascimento', Carbon::createFromFormat('d/m/Y', $value));
|
||||
})
|
||||
->when($request->faa, function ($query, $value) {
|
||||
|
||||
$query->where('faa.numero', $value);
|
||||
})
|
||||
->whereNull('faa.deleted_at')
|
||||
->get()
|
||||
->map(function ($atendimento) {
|
||||
|
||||
if (is_null($atendimento->paciente_nome_mae)) {
|
||||
|
||||
$atendimento->paciente_nome_mae = 'Não informado';
|
||||
}
|
||||
|
||||
if (is_null($atendimento->paciente_caracteristicas_fisicas)) {
|
||||
|
||||
$atendimento->paciente_caracteristicas_fisicas = 'Não informado';
|
||||
}
|
||||
|
||||
$atendimento->paciente_is_desconhecido = !is_null($atendimento->paciente_sequencial_desconhecido_em);
|
||||
$atendimento->data = (new Carbon($atendimento->data))->format('d/m/Y');
|
||||
|
||||
$atendimento->paciente_prefere_nome_social = $atendimento
|
||||
->paciente_preferencia_nome_id === PreferenciaNome::NOME_SOCIAL;
|
||||
|
||||
$atendimento->paciente_data_nascimento = is_null($atendimento->paciente_data_nascimento)
|
||||
? 'Não informada'
|
||||
: (new Carbon($atendimento->paciente_data_nascimento))->format('d/m/Y');
|
||||
|
||||
unset(
|
||||
$atendimento->acompanhante,
|
||||
$atendimento->infraestrutura,
|
||||
$atendimento->senha,
|
||||
$atendimento->senha_data_hora_emissao,
|
||||
$atendimento->paciente_preferencia_nome_id,
|
||||
$atendimento->paciente_sequencial_desconhecido_em
|
||||
);
|
||||
|
||||
return $atendimento;
|
||||
});
|
||||
|
||||
return $atendimentos;
|
||||
}
|
||||
|
||||
private static function validateDatatableRequest($request)
|
||||
{
|
||||
$minDate = Carbon::now()->subYears(130)->format('Y-m-d');
|
||||
|
||||
$request->validate([
|
||||
'periodo.start' => [
|
||||
'required',
|
||||
'date_format:d/m/Y',
|
||||
"after_or_equal:{$minDate}",
|
||||
'before_or_equal:periodo.end',
|
||||
],
|
||||
'periodo.end' => [
|
||||
'required',
|
||||
'date_format:d/m/Y',
|
||||
'after_or_equal:periodo.start',
|
||||
'before_or_equal:now',
|
||||
],
|
||||
'sexo_id' => [
|
||||
'nullable',
|
||||
'integer',
|
||||
],
|
||||
'paciente' => [
|
||||
'nullable',
|
||||
'string',
|
||||
],
|
||||
'data_nascimento' => [
|
||||
'nullable',
|
||||
'date_format:d/m/Y',
|
||||
],
|
||||
'faa' => [
|
||||
'nullable',
|
||||
'integer',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public static function edit($id)
|
||||
{
|
||||
|
||||
$assistencia = Atendimento::where('id', $id)
|
||||
->orderBy('created_at', 'desc')
|
||||
->firstOrFail();
|
||||
|
||||
$centroCustroLogado = self::getCentroCustoLogado();
|
||||
$currentLotacao = self::getCurrentLotacao();
|
||||
|
||||
return [
|
||||
'form' => [
|
||||
'unidade_logada' => $centroCustroLogado->infraestrutura->unidade->id,
|
||||
'local_atendimento_logado' => $centroCustroLogado->infraestrutura->id,
|
||||
'usuario' => $currentLotacao->usuario->cidadao->nome,
|
||||
'usuario_sistema_id' => $currentLotacao->usuario->id,
|
||||
'ocupacao_id' => $currentLotacao->ocupacao->id,
|
||||
'ocupacao_codigo' => $currentLotacao->ocupacao->codigo,
|
||||
'ocupacao_nome' => $currentLotacao->ocupacao->nome,
|
||||
'data_atual' => Carbon::now()->format('d/m/Y'),
|
||||
],
|
||||
'model' => [
|
||||
'anotacoes' => [
|
||||
'atendimento_id' => intval($assistencia->id),
|
||||
'usuario_id' => $assistencia->usuario_id,
|
||||
'paciente_id' => $assistencia->faa->paciente_id,
|
||||
'anotacao' => null,
|
||||
'data_anotacao' => $assistencia->data_anotacao,
|
||||
'prontuario' => $assistencia->faa->paciente->prontuario,
|
||||
'nome' => $assistencia->faa->paciente->cidadao->nome,
|
||||
'data_nascimento' => $assistencia->faa->paciente->cidadao->data_nascimento,
|
||||
'cns' => $assistencia->faa->paciente->cidadao->cns ? MaskUtil::getCnsMasked($assistencia->faa->paciente->cidadao->cns) : 'NÃO INFORMADO',
|
||||
'cpf' => $assistencia->faa->paciente->cidadao->cpf ? MaskUtil::getCpfMasked($assistencia->faa->paciente->cidadao->cpf) : 'NÃO INFORMADO',
|
||||
'sexo' => $assistencia->faa->paciente->cidadao->sexo->descricao,
|
||||
'data_nascimento' => $assistencia->faa->paciente->cidadao->data_nascimento
|
||||
? $assistencia->faa->paciente->cidadao->data_nascimento->format('d/m/Y')
|
||||
: 'NÃO INFORMADA',
|
||||
'idade' => $assistencia->faa->paciente->cidadao->data_nascimento
|
||||
? "{$assistencia->faa->paciente->cidadao->idade['anos']} ano(s), "
|
||||
. "{$assistencia->faa->paciente->cidadao->idade['meses']} mês(es) e "
|
||||
. "{$assistencia->faa->paciente->cidadao->idade['dias']} dia(s) "
|
||||
: 'NÃO INFORMADA',
|
||||
'idade_paciente' => $assistencia->faa->paciente->cidadao->data_nascimento ? [
|
||||
'anos' => $assistencia->faa->paciente->cidadao->idade['anos'] ?? 'Não informada',
|
||||
'meses' => $assistencia->faa->paciente->cidadao->idade['meses'] ?? 'Não informada',
|
||||
'dias' => $assistencia->faa->paciente->cidadao->idade['dias'] ?? 'Não informada',
|
||||
] : null,
|
||||
'nome_social' => $assistencia->faa->paciente->cidadao->nome_social,
|
||||
'preferencia_nome_id' => $assistencia->faa->paciente->cidadao->preferencia_nome_id ?? null,
|
||||
'nome_mae' => $assistencia->faa->paciente->cidadao->nome_mae ?? 'NÃO INFORMADO',
|
||||
'telefones' => $assistencia->faa->paciente->cidadao->telefones->map(fn ($t) => MaskUtil::getPhoneMasked($t->numero))->all(),
|
||||
'historico' => AssistenciaSocialHistorico::whereNotNull('anotacao')
|
||||
->where('atendimento_id', $assistencia->id)
|
||||
->orderBy('created_at', 'desc')
|
||||
->get()
|
||||
->map(function ($query){
|
||||
return [
|
||||
'data' => (new Carbon($query->created_at))->format('d/m/Y') ?? null,
|
||||
'horario' => (new Carbon($query->created_at))->format('H:i') ?? null,
|
||||
'anotacao' => $query->anotacao,
|
||||
'profissional' => [
|
||||
'nome' => $query->usuario->cidadao->nome,
|
||||
'usuario_id' => $query->usuario_id,
|
||||
'ocupacao_id' => $query->ocupacao_id,
|
||||
'cbo' => Ocupacao::findOrFail($query['ocupacao_id'])->nome,
|
||||
],
|
||||
];
|
||||
})
|
||||
->values(),
|
||||
]
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
private static function getCentroCustoLogado()
|
||||
{
|
||||
return CentroCusto::findOrFail(auth()->payload()->get('centro_custo_id'));
|
||||
}
|
||||
|
||||
public static function store(Request $request)
|
||||
{
|
||||
DB::transaction(function () use ($request) {
|
||||
|
||||
self::save($request);
|
||||
});
|
||||
}
|
||||
|
||||
private static function save($request)
|
||||
{
|
||||
$ids = [];
|
||||
|
||||
$atendimento_id = $request->anotacoes['atendimento_id'];
|
||||
$usuario_id = $request->anotacoes['usuario_id'];
|
||||
$paciente_id = $request->anotacoes['paciente_id'];
|
||||
$ocupacao_id = $request->anotacoes['ocupacao_id'];
|
||||
$anotacao = $request->anotacoes['anotacao'];
|
||||
$data_anotacao = $request->anotacoes['data_anotacao'];
|
||||
|
||||
$assistenciaSocial = AssistenciaSocial::where('atendimento_id', $atendimento_id)
|
||||
->first() ?? new AssistenciaSocial;
|
||||
|
||||
$assistenciaSocial->atendimento_id = $atendimento_id;
|
||||
$assistenciaSocial->paciente_id = $paciente_id;
|
||||
$assistenciaSocial->usuario_id = $usuario_id;
|
||||
$assistenciaSocial->ocupacao_id = $ocupacao_id;
|
||||
$assistenciaSocial->anotacao = $anotacao;
|
||||
$assistenciaSocial->data_anotacao = $data_anotacao;
|
||||
|
||||
$assistenciaSocial->save();
|
||||
|
||||
$ids[] = $assistenciaSocial->id;
|
||||
|
||||
$historico = new AssistenciaSocialHistorico();
|
||||
|
||||
$historico->assistencia_id = $assistenciaSocial['id'];
|
||||
$historico->atendimento_id = $assistenciaSocial['atendimento_id'];
|
||||
$historico->usuario_id = $assistenciaSocial['usuario_id'];
|
||||
$historico->paciente_id = $assistenciaSocial['paciente_id'];
|
||||
$historico->ocupacao_id = $assistenciaSocial['ocupacao_id'];
|
||||
$historico->anotacao = $assistenciaSocial['anotacao'];
|
||||
|
||||
$historico->save();
|
||||
$idsHistorico[] = $historico->id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento\Atendimento;
|
||||
|
||||
use App\Enums\ProntoAtendimento\ClassificacaoRisco;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Atendimento;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class AtendimentoService
|
||||
{
|
||||
public static function getTimelineItems($filaId)
|
||||
{
|
||||
$atendimento = Atendimento::where('fila_id', $filaId)->firstOrFail();
|
||||
$items = collect();
|
||||
|
||||
$items->push([
|
||||
'date_time' => new Carbon($atendimento->recepcao->atendido_em),
|
||||
'title' => 'Recepção',
|
||||
'label' => $atendimento->fila->senha,
|
||||
'disabled' => true,
|
||||
]);
|
||||
|
||||
$atendimento->atendimentosTriagem->each(fn ($atendimento) => $items->push([
|
||||
'date_time' => $atendimento->created_at,
|
||||
'title' => 'Triagem',
|
||||
'disabled' => false,
|
||||
'list_class' => self::getClassificacaoRiscoCssClass(
|
||||
$atendimento->classificacaoRisco->classificacao_risco_id ?? null
|
||||
),
|
||||
]));
|
||||
|
||||
$atendimento->atendimentosMedico->each(fn ($atendimento) => $items->push([
|
||||
'date_time' => $atendimento->created_at,
|
||||
'title' => 'Atendimento médico',
|
||||
'disabled' => false,
|
||||
'list_class' => self::getClassificacaoRiscoCssClass(
|
||||
$atendimento->classificacaoRisco->classificacao_risco_id ?? null
|
||||
),
|
||||
]));
|
||||
|
||||
$atendimento->atendimentosEnfermagem->each(fn ($atendimento) => $items->push([
|
||||
'date_time' => $atendimento->created_at,
|
||||
'title' => 'Enfermagem',
|
||||
'disabled' => false,
|
||||
'list_class' => self::getClassificacaoRiscoCssClass(
|
||||
$atendimento->classificacaoRisco->classificacao_risco_id ?? null
|
||||
),
|
||||
]));
|
||||
|
||||
$atendimento->atendimentosExameImagem->each(fn ($atendimento) => $items->push([
|
||||
'date_time' => $atendimento->created_at,
|
||||
'title' => 'Exames de imagem',
|
||||
'disabled' => false,
|
||||
]));
|
||||
|
||||
$atendimento->pacienteObservacoes->each(fn ($atendimento) => $items->push([
|
||||
'date_time' => $atendimento->created_at,
|
||||
'title' => 'Observação',
|
||||
'disabled' => false,
|
||||
'list_class' => self::getClassificacaoRiscoCssClass(
|
||||
$atendimento->classificacaoRisco->classificacao_risco_id ?? null
|
||||
),
|
||||
]));
|
||||
|
||||
return $items
|
||||
->sortBy('date_time')
|
||||
->map(function ($item) {
|
||||
|
||||
$item['date_time'] = $item['date_time']->format('d/m/Y H:i');
|
||||
|
||||
return $item;
|
||||
})
|
||||
->values();
|
||||
}
|
||||
|
||||
private static function getClassificacaoRiscoCssClass($classificacaoRiscoId)
|
||||
{
|
||||
$class = 'pronto-atendimento-classificacao-risco-';
|
||||
|
||||
switch ($classificacaoRiscoId) {
|
||||
|
||||
case ClassificacaoRisco::NAO_URGENTE: {
|
||||
|
||||
return $class . 'NAO_URGENTE';
|
||||
}
|
||||
case ClassificacaoRisco::POUCO_URGENTE: {
|
||||
|
||||
return $class . 'POUCO_URGENTE';
|
||||
}
|
||||
case ClassificacaoRisco::URGENTE: {
|
||||
|
||||
return $class . 'URGENTE';
|
||||
}
|
||||
case ClassificacaoRisco::MUITO_URGENTE: {
|
||||
|
||||
return $class . 'MUITO_URGENTE';
|
||||
}
|
||||
case ClassificacaoRisco::EMERGENCIA: {
|
||||
|
||||
return $class . 'EMERGENCIA';
|
||||
}
|
||||
default: {
|
||||
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento\Atendimento;
|
||||
|
||||
use App\Enums\ProntoAtendimento\Raat\CausaAcidente as CausaAcidenteEnum;
|
||||
use App\Enums\ProntoAtendimento\Raat\Diagnostico as DiagnosticoEnum;
|
||||
use App\Enums\ProntoAtendimento\Raat\ParteCorpoAtingida as ParteCorpoAtingidaEnum;
|
||||
use App\Enums\ProntoAtendimento\Raat\RegimeTrabalho as RegimeTrabalhoEnum;
|
||||
use App\Models\ProntoAtendimento\Atendimento\RaatParecerMedico;
|
||||
use App\Models\ProntoAtendimento\Raat\Agente;
|
||||
use App\Models\ProntoAtendimento\Raat\CausaAcidente;
|
||||
use App\Models\ProntoAtendimento\Raat\ClassificacaoInicial;
|
||||
use App\Models\ProntoAtendimento\Raat\Diagnostico;
|
||||
use App\Models\ProntoAtendimento\Raat\ParteCorpoAtingida;
|
||||
use App\Models\ProntoAtendimento\Raat\RegimeTrabalho;
|
||||
use App\Models\ProntoAtendimento\Raat\TipoAcidente;
|
||||
|
||||
class RaatService
|
||||
{
|
||||
public static function get($atendimentoMedico)
|
||||
{
|
||||
return [
|
||||
'identificacao' => self::getRaatIdentificacao($atendimentoMedico->atendimento->faa->raat),
|
||||
'parecer_medico' => self::getParecerMedico($atendimentoMedico->raatParecerMedico),
|
||||
];
|
||||
}
|
||||
|
||||
public static function getOptionsParecerMedico()
|
||||
{
|
||||
return [
|
||||
'agente' => Agente::all(),
|
||||
'causa_acidente' => CausaAcidente::all(),
|
||||
'classificacao_inicial' => ClassificacaoInicial::all(),
|
||||
'diagnostico' => Diagnostico::all(),
|
||||
'parte_corpo_atingida' => ParteCorpoAtingida::all(),
|
||||
'regime_trabalho' => RegimeTrabalho::all(),
|
||||
'tipo_acidente' => TipoAcidente::all(),
|
||||
];
|
||||
}
|
||||
|
||||
private static function getRaatIdentificacao($raat)
|
||||
{
|
||||
if (is_null($raat)) {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$hiddenFields = [];
|
||||
|
||||
if ($raat->regime_trabalho_id !== RegimeTrabalhoEnum::OUTRO) {
|
||||
|
||||
$hiddenFields[] ='regime_trabalho_outro';
|
||||
}
|
||||
|
||||
return $raat->makeHidden($hiddenFields);
|
||||
}
|
||||
|
||||
private static function getParecerMedico($parecerMedico)
|
||||
{
|
||||
if (is_null($parecerMedico)) {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$hiddenFields = [];
|
||||
|
||||
if (!$parecerMedico->partesCorpoAtingidas->contains('id', ParteCorpoAtingidaEnum::OUTROS)) {
|
||||
|
||||
$hiddenFields[] = 'parte_corpo_atingida_outras';
|
||||
}
|
||||
|
||||
if (!$parecerMedico->diagnosticos->contains('id', DiagnosticoEnum::OUTROS)) {
|
||||
|
||||
$hiddenFields[] = 'diagnostico_outros';
|
||||
}
|
||||
|
||||
return $parecerMedico
|
||||
->with('causasAcidente', 'diagnosticos', 'partesCorpoAtingidas')
|
||||
->get()
|
||||
->makeHidden($hiddenFields);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento\Atendimento;
|
||||
|
||||
use App\Enums\Cadastro\SujeitoAtencao\Classificacao;
|
||||
use App\Enums\ProntoAtendimento\Atendimento\Desfecho;
|
||||
use App\Enums\ProntoAtendimento\Atendimento\OrigemEntrada as AtendimentoOrigemEntrada;
|
||||
use App\Models\Cadastro\Parametrizacao\ParametrizacaoPermissaoUsuario;
|
||||
use App\Models\Cadastro\SujeitoAtencao\Lotacao;
|
||||
use App\Models\Cadastro\SujeitoAtencao\Paciente;
|
||||
use App\Models\Cadastro\SujeitoAtencao\PacienteClassificacao;
|
||||
use App\Models\Cadastro\SujeitoAtencao\Sexo;
|
||||
use App\Models\Cns\TermoInvalido;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Faa;
|
||||
use App\Models\ProntoAtendimento\Atendimento\OrigemEntrada;
|
||||
use App\Rules\CnsTermoValido;
|
||||
use App\Rules\NomeCompleto;
|
||||
use App\Services\Cadastro\SujeitoAtencao\PacienteDesconhecidoSaveService;
|
||||
use App\Utils\MaskUtil;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class RetroativoService
|
||||
{
|
||||
public static function create()
|
||||
{
|
||||
$now = Carbon::now();
|
||||
$pacienteIdentificado = null;
|
||||
|
||||
if (is_numeric(request()->paciente_id)) {
|
||||
|
||||
$paciente = Paciente::findOrFail(request()->paciente_id);
|
||||
$endereco = '';
|
||||
|
||||
if ($paciente->cidadao->domicilio_id) {
|
||||
|
||||
$endereco = $paciente->cidadao->domicilio->endereco;
|
||||
$endereco = $endereco->completo . ' - ' . MaskUtil::getCepMasked($endereco->logradouro->cep);
|
||||
}
|
||||
|
||||
$pacienteIdentificado = [
|
||||
'prontuario' => $paciente->prontuario,
|
||||
'classificacao_id' => $paciente->classificacao_id,
|
||||
'cns' => $paciente->cidadao->cns,
|
||||
'nome' => $paciente->cidadao->nome,
|
||||
'nome_social' => $paciente->cidadao->nome_social,
|
||||
'nome_mae' => $paciente->cidadao->nome_mae ?? '',
|
||||
'sexo' => [
|
||||
'id' => $paciente->cidadao->sexo->id,
|
||||
'descricao' => $paciente->cidadao->sexo->descricao,
|
||||
],
|
||||
'preferencia_nome_id' => $paciente->cidadao->preferencia_nome_id ?? null,
|
||||
'data_nascimento' => $paciente->cidadao->data_nascimento->format('d/m/Y'),
|
||||
'idade' => $paciente->cidadao->idade,
|
||||
'endereco' => $endereco,
|
||||
'telefones' => $paciente->cidadao->telefones->map(fn ($telefone) => [
|
||||
'id' => $telefone->id,
|
||||
'numero' => MaskUtil::getPhoneMasked($telefone->numero),
|
||||
'observacao' => $telefone->observacao ?? '',
|
||||
'autoriza_sms' => $telefone->autoriza_sms,
|
||||
'principal' => $telefone->principal,
|
||||
]),
|
||||
];
|
||||
}
|
||||
|
||||
$lotacao = Lotacao::findOrFail(auth()->payload()->get('lotacao_id'));
|
||||
|
||||
$permissaoUsuario = ParametrizacaoPermissaoUsuario::where('usuario_id', $lotacao->usuario_id)
|
||||
->where('infraestrutura_id', $lotacao->infraestrutura_id)
|
||||
->first();
|
||||
|
||||
$countUsuario = ParametrizacaoPermissaoUsuario::count();
|
||||
|
||||
$classificacoes = $permissaoUsuario
|
||||
? PacienteClassificacao::orderBy('descricao')
|
||||
->get()
|
||||
->filter(function ($classificacao) use ($permissaoUsuario) {
|
||||
|
||||
$exibe = false;
|
||||
|
||||
switch ($classificacao->id) {
|
||||
case Classificacao::MUNICIPE:
|
||||
$exibe = $permissaoUsuario->municipe;
|
||||
break;
|
||||
case Classificacao::PROVISORIO:
|
||||
$exibe = $permissaoUsuario->provisorio;
|
||||
break;
|
||||
case Classificacao::OUTRO_MUNICIPIO:
|
||||
$exibe = $permissaoUsuario->outro_municipio;
|
||||
break;
|
||||
}
|
||||
|
||||
return $exibe ? [
|
||||
'id' => $classificacao->id,
|
||||
'descricao' => $classificacao->descricao
|
||||
] : null;
|
||||
})
|
||||
->values()
|
||||
: [];
|
||||
|
||||
return [
|
||||
'form' => [
|
||||
'data_atual_menos_um_ano' => $now->copy()->subYear()->format('d/m/Y'),
|
||||
'data_atual' => $now->format('d/m/Y'),
|
||||
'data_registro' => $now->format('Y-m-d'),
|
||||
'isEncaminhamento' => false,
|
||||
'sem_acompanhante' => true,
|
||||
'paciente_identificado' => $pacienteIdentificado,
|
||||
'origem_unidade_value' => 'interna',
|
||||
'unidade_encaminhamento' => null,
|
||||
'paciente_desconhecido' => [
|
||||
'sexos' => Sexo::orderBy('descricao')
|
||||
->get()
|
||||
->map(fn ($sexo) => [
|
||||
'id' => $sexo->id,
|
||||
'descricao' => $sexo->descricao
|
||||
]),
|
||||
],
|
||||
'origens_entrada' => OrigemEntrada::orderBy('nome')
|
||||
->get()
|
||||
->map(fn ($origem) => [
|
||||
'id' => $origem->id,
|
||||
'nome' => $origem->nome,
|
||||
]),
|
||||
'origens_unidade' => [
|
||||
[ 'id' => 'interna', 'nome' => 'INTERNA' ],
|
||||
[ 'id' => 'externa', 'nome' => 'EXTERNA' ],
|
||||
],
|
||||
'faa_aberta' => self::getFaaAberta(request()->paciente_id),
|
||||
'classificacoes' => $classificacoes,
|
||||
'is_permissao_cadastro' => $countUsuario === 0 ? true : false,
|
||||
],
|
||||
'model' => [
|
||||
'acompanhante' => null,
|
||||
'atendido_em' => null,
|
||||
'atendido_hora' => null,
|
||||
'medico_samu' => null,
|
||||
'medico_solicitante_encaminhamento' => null,
|
||||
'motivo_atendimento' => null,
|
||||
'observacao' => null,
|
||||
'origem_entrada_id' => AtendimentoOrigemEntrada::ESPONTANEA,
|
||||
'unidade_encaminhamento_id' => null,
|
||||
'unidade_externa_encaminhamento_id' => null,
|
||||
'paciente_desconhecido' => [
|
||||
'sexo_id' => null,
|
||||
'caracteristicas_fisicas' => null,
|
||||
],
|
||||
],
|
||||
'adittional' => [
|
||||
'termos_invalidos' => TermoInvalido::all()->map(fn ($termo) => $termo->descricao),
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
public static function pacienteHasAtendimento($pacienteId)
|
||||
{
|
||||
if (is_numeric($pacienteId)) {
|
||||
|
||||
$faa = Faa::with('atendimentos.fila')
|
||||
->where('paciente_id', $pacienteId)
|
||||
->whereHas('atendimentos.fila', function($query) {
|
||||
|
||||
$query
|
||||
->whereHas('centroCusto', function($query) {
|
||||
$query->where(
|
||||
'infraestrutura_id',
|
||||
Lotacao::findOrFail(auth()->payload()->get('lotacao_id'))->infraestrutura_id
|
||||
);
|
||||
});
|
||||
})
|
||||
->where(function($query) {
|
||||
$query->whereNull('desfecho_id')
|
||||
->orWhere('desfecho_id', Desfecho::EVASAO);
|
||||
})
|
||||
->first();
|
||||
|
||||
if ($faa) {
|
||||
$setor = null;
|
||||
$emitidoEm = null;
|
||||
$procedimentos = 0;
|
||||
|
||||
$faa->atendimentos->map(function($atendimento) use (&$setor, &$procedimentos, &$emitidoEm) {
|
||||
$emitidoEm = $atendimento->fila->emitido_em;
|
||||
$setor = $atendimento->fila->centroCusto->setor;
|
||||
$procedimentos = $atendimento->procedimentos->count();
|
||||
});
|
||||
|
||||
$emitidoEm = Carbon::parse($emitidoEm)->format('Y-m-d');
|
||||
|
||||
if ($emitidoEm === Carbon::now()->format('Y-m-d')) {
|
||||
|
||||
if ($procedimentos > 0) {
|
||||
|
||||
return response()->json(['message' => 'Paciente já está em atendimento no setor de ' . $setor['nome']
|
||||
. '. Finalize o atendimento para iniciar um novo.'], Response::HTTP_BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (is_null($faa)) {
|
||||
|
||||
$faa = Faa::where('paciente_id', $pacienteId)
|
||||
->where('finalizado', false)
|
||||
->whereHas('createdCentroCusto', function ($query) {
|
||||
|
||||
$query->where(
|
||||
'infraestrutura_id',
|
||||
Lotacao::findOrFail(auth()->payload()->get('lotacao_id'))->infraestrutura_id
|
||||
);
|
||||
})
|
||||
->first();
|
||||
|
||||
if ($faa) {
|
||||
|
||||
return [
|
||||
'message' => 'Paciente já está em atendimento no setor de ' . $faa->createdCentroCusto->setor->nome . '. Finalize o atendimento para iniciar um novo.',
|
||||
'response' => Response::HTTP_BAD_REQUEST
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function getFaaAberta($pacienteId)
|
||||
{
|
||||
if (is_numeric($pacienteId)) {
|
||||
|
||||
$faa = Faa::with('atendimentos.fila')
|
||||
->where('paciente_id', $pacienteId)
|
||||
->whereHas('atendimentos.fila', function($query) {
|
||||
|
||||
$query
|
||||
->whereHas('centroCusto', function($query) {
|
||||
$query->where(
|
||||
'infraestrutura_id',
|
||||
Lotacao::findOrFail(auth()->payload()->get('lotacao_id'))->infraestrutura_id
|
||||
);
|
||||
});
|
||||
})
|
||||
->where(function($query) {
|
||||
$query->whereNull('desfecho_id')
|
||||
->orWhere('desfecho_id', Desfecho::EVASAO);
|
||||
})
|
||||
->first();
|
||||
|
||||
if ($faa) {
|
||||
$setor = null;
|
||||
$emitidoEm = null;
|
||||
$procedimentos = 0;
|
||||
|
||||
$faa->atendimentos->map(function($atendimento) use (&$setor, &$procedimentos, &$emitidoEm) {
|
||||
$emitidoEm = $atendimento->fila->emitido_em;
|
||||
$setor = $atendimento->fila->centroCusto->setor;
|
||||
$procedimentos = $atendimento->procedimentos->count();
|
||||
});
|
||||
|
||||
$emitidoEm = Carbon::parse($emitidoEm)->format('Y-m-d');
|
||||
|
||||
if ($emitidoEm === Carbon::now()->format('Y-m-d')) {
|
||||
|
||||
if ($procedimentos > 0) {
|
||||
|
||||
return response()->json(['message' => 'Paciente já está em atendimento no setor de ' . $setor['nome']
|
||||
. '. Finalize o atendimento para iniciar um novo.'], Response::HTTP_BAD_REQUEST);
|
||||
}
|
||||
|
||||
if ($faa->desfecho_id == null) {
|
||||
|
||||
return [
|
||||
'alert_faa_aberta' => true,
|
||||
'setor' => $setor['nome'],
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function store()
|
||||
{
|
||||
self::validations();
|
||||
|
||||
$recepcao = null;
|
||||
$params = self::getParams();
|
||||
|
||||
DB::transaction(function () use (&$recepcao, $params) {
|
||||
|
||||
$pacienteId = self::savePaciente($params['paciente'], $params['atendido_em']);
|
||||
|
||||
$faa = Faa::create(['paciente_id' => $pacienteId]);
|
||||
|
||||
$atendimento = $faa->atendimentos()->create();
|
||||
$recepcao = self::saveAtendimentoRecepcao($atendimento, $params);
|
||||
});
|
||||
|
||||
return $recepcao->refresh();
|
||||
}
|
||||
|
||||
private static function getParams()
|
||||
{
|
||||
$params = request()->all();
|
||||
|
||||
if (isset($params['medico_samu'])) {
|
||||
|
||||
$params['medico_samu'] = mb_strtoupper($params['medico_samu']);
|
||||
}
|
||||
|
||||
if (isset($params['acompanhante'])) {
|
||||
|
||||
$params['acompanhante'] = mb_strtoupper($params['acompanhante']);
|
||||
}
|
||||
|
||||
if (isset($params['medico_solicitante_encaminhamento'])) {
|
||||
|
||||
$params['medico_solicitante_encaminhamento'] = mb_strtoupper($params['medico_solicitante_encaminhamento']);
|
||||
}
|
||||
|
||||
return $params;
|
||||
}
|
||||
|
||||
private static function savePaciente($params, $atendidoEm)
|
||||
{
|
||||
if (isset($params['id'])) {
|
||||
|
||||
return $params['id'];
|
||||
}
|
||||
|
||||
return (new PacienteDesconhecidoSaveService(
|
||||
$atendidoEm,
|
||||
$params['sexo_id'],
|
||||
$params['caracteristicas_fisicas'] ?? null
|
||||
))->save()->id;
|
||||
}
|
||||
|
||||
private static function saveAtendimentoRecepcao($atendimento, $params)
|
||||
{
|
||||
return $atendimento->recepcao()->create([
|
||||
'atendido_em' => Carbon::createFromFormat('d-m-Y H:i', $params['atendido_em']),
|
||||
'urgente' => false,
|
||||
'origem_entrada_id' => $params['origem_entrada_id'] ?? null,
|
||||
'medico_samu' => $params['medico_samu'] ?? null,
|
||||
'motivo_atendimento' => $params['motivo_atendimento'] ?? null,
|
||||
'acompanhante' => $params['acompanhante'] ?? null,
|
||||
'unidade_encaminhamento_id' => $params['unidade_encaminhamento_id'] ?? null,
|
||||
'unidade_externa_encaminhamento_id' => $params['unidade_externa_encaminhamento_id'] ?? null,
|
||||
'medico_solicitante_encaminhamento' => $params['medico_solicitante_encaminhamento'] ?? null,
|
||||
'observacao' => $params['observacao'] ?? null,
|
||||
]);
|
||||
}
|
||||
|
||||
private static function validations()
|
||||
{
|
||||
return request()->validate([
|
||||
'paciente' => [
|
||||
'required',
|
||||
'array'
|
||||
],
|
||||
'paciente.id' => [
|
||||
'nullable',
|
||||
'integer'
|
||||
],
|
||||
'paciente.sexo_id' => [
|
||||
'required_without:paciente.id',
|
||||
'nullable',
|
||||
'integer'
|
||||
],
|
||||
'paciente.caracteristicas_fisicas' => [
|
||||
'required_without:paciente.id',
|
||||
'string',
|
||||
'max:500'
|
||||
],
|
||||
'atendido_em' => [
|
||||
'required',
|
||||
'date_format:d-m-Y H:i',
|
||||
'before_or_equal:now'
|
||||
],
|
||||
'origem_entrada_id' => ['nullable', 'integer'],
|
||||
'medico_samu' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:150'
|
||||
],
|
||||
"motivo_atendimento" => [
|
||||
'required',
|
||||
'nullable',
|
||||
'string',
|
||||
'max:3000'
|
||||
],
|
||||
"acompanhante" => [
|
||||
'nullable',
|
||||
'string',
|
||||
'between:6,150',
|
||||
new NomeCompleto,
|
||||
new CnsTermoValido(['attribute' => 'Acompanhante']),
|
||||
],
|
||||
"unidade_encaminhamento_id" => [
|
||||
'nullable',
|
||||
'integer'
|
||||
],
|
||||
"unidade_externa_encaminhamento_id" => [
|
||||
'nullable',
|
||||
'integer'
|
||||
],
|
||||
"medico_solicitante_encaminhamento" => [
|
||||
'nullable',
|
||||
'string',
|
||||
'between:6,150',
|
||||
new NomeCompleto,
|
||||
],
|
||||
"observacao" => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:500'
|
||||
],
|
||||
],
|
||||
[
|
||||
'atendido_em.before_or_equal' => 'O início do atendimento deve ser anterior ou igual hora atual.'
|
||||
]);
|
||||
}
|
||||
}
|
||||
322
api/app/Services/ProntoAtendimento/DesfechoService.php
Normal file
322
api/app/Services/ProntoAtendimento/DesfechoService.php
Normal file
@@ -0,0 +1,322 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento;
|
||||
|
||||
use App\Enums\ProntoAtendimento\Atendimento\Desfecho;
|
||||
use App\Models\Cadastro\SujeitoAtencao\Lotacao;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Atendimento;
|
||||
use App\Models\ProntoAtendimento\Atendimento\EncaminhamentoHospitalar;
|
||||
use App\Services\Cadastro\SujeitoAtencao\ObitoService;
|
||||
use App\Services\ProntoAtendimento\Fila\FilaService;
|
||||
use App\Services\Service;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class DesfechoService extends Service
|
||||
{
|
||||
public static function store($faa)
|
||||
{
|
||||
self::validations($faa);
|
||||
|
||||
$atendimento = self::getAtendimentoFaa($faa);
|
||||
$currentLotacao = self::getCurrentLotacao();
|
||||
|
||||
$lastAtendimentoMedico = $atendimento->atendimentosMedico->last() ?? null;
|
||||
$dataHoraDesfechoMedico = is_null($lastAtendimentoMedico->desfecho_id ?? null)
|
||||
? Carbon::now()
|
||||
: $lastAtendimentoMedico->created_at;
|
||||
|
||||
switch (request()->desfecho_id) {
|
||||
|
||||
case Desfecho::FAA_EXTRAVIADA: {
|
||||
|
||||
$faa->usuario_id = $currentLotacao->usuario_id;
|
||||
$faa->lotacao_id = $currentLotacao->id;
|
||||
$faa->data_hora_desfecho = Carbon::now();
|
||||
|
||||
break;
|
||||
}
|
||||
case Desfecho::PACIENTE_ATENDIDO: {
|
||||
|
||||
if (!is_null($faa->reaberto_em) && !is_null($faa->usuario_id)) {
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
$faa->usuario_id = Lotacao::findOrFail(request()->paciente_liberado['lotacao_id'])->usuario_id;
|
||||
$faa->lotacao_id = request()->paciente_liberado['lotacao_id'];
|
||||
$faa->data_hora_desfecho = $dataHoraDesfechoMedico;
|
||||
|
||||
break;
|
||||
}
|
||||
case Desfecho::ALTA_MEDICA: {
|
||||
|
||||
if (!is_null($faa->reaberto_em) && !is_null($faa->usuario_id)) {
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
$faa->usuario_id = Lotacao::findOrFail(request()->alta_medica['lotacao_id'])->usuario_id;
|
||||
$faa->lotacao_id = request()->alta_medica['lotacao_id'];
|
||||
$faa->data_hora_desfecho = $dataHoraDesfechoMedico;
|
||||
|
||||
break;
|
||||
}
|
||||
case Desfecho::EVASAO: {
|
||||
|
||||
if (!is_null($faa->reaberto_em) && !is_null($faa->usuario_id)) {
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
$faa->usuario_id = $currentLotacao->usuario_id;
|
||||
$faa->lotacao_id = $currentLotacao->id;
|
||||
$faa->data_hora_desfecho = $dataHoraDesfechoMedico;
|
||||
|
||||
if (!is_null($atendimento->fila)) {
|
||||
|
||||
FilaService::evade([
|
||||
'motivo_evasao' => request()->evasao['motivo']
|
||||
], $atendimento->fila_id);
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
case Desfecho::OBITO: {
|
||||
|
||||
$faa->usuario_id = Lotacao::findOrFail(request()->obito['lotacao_id'])->usuario_id;
|
||||
$faa->lotacao_id = request()->obito['lotacao_id'];
|
||||
$faa->data_hora_desfecho = $dataHoraDesfechoMedico;
|
||||
|
||||
$obitoService = new ObitoService($faa->paciente->cidadao);
|
||||
|
||||
if (!is_null($obitoService->get())) {
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
$obitoService->save(
|
||||
Carbon::createFromFormat('d/m/Y H:i', request()->obito['obito_em']),
|
||||
request()->obito['declaracao'],
|
||||
request()->obito['causa'],
|
||||
request()->obito['cid_id'],
|
||||
$faa->usuario_id,
|
||||
);
|
||||
|
||||
break;
|
||||
}
|
||||
case Desfecho::ENCAMINHAMENTO_HOSPITALAR: {
|
||||
|
||||
if ($atendimento->encaminhamentosHospitalar()->exists() && !is_null($faa->reaberto_em)) {
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
$faa->usuario_id = Lotacao::findOrFail(request()->encaminhamento_hospitalar['lotacao_id'])->usuario_id;
|
||||
$faa->lotacao_id = request()->encaminhamento_hospitalar['lotacao_id'];
|
||||
$faa->data_hora_desfecho = $dataHoraDesfechoMedico;
|
||||
|
||||
EncaminhamentoHospitalar::create([
|
||||
'atendimento_id' => $atendimento->id,
|
||||
'usuario_id' => $faa->usuario_id,
|
||||
'unidade_id' => request()->encaminhamento_hospitalar['unidade_id'] ?? null,
|
||||
'unidade_nome' => request()->encaminhamento_hospitalar['unidade_nome'] ?? null,
|
||||
'quarto' => request()->encaminhamento_hospitalar['quarto'] ?? null,
|
||||
'leito' => request()->encaminhamento_hospitalar['leito'] ?? null,
|
||||
'cid_id' => request()->encaminhamento_hospitalar['cid_id'] ?? null,
|
||||
'medico_hospitalar' => request()->encaminhamento_hospitalar['medico_hospitalar'] ?? null,
|
||||
'observacoes' => request()->encaminhamento_hospitalar['observacoes'] ?? null,
|
||||
]);
|
||||
|
||||
break;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static function validations($faa)
|
||||
{
|
||||
$rules = [
|
||||
'desfecho_id' => [
|
||||
'required',
|
||||
'integer',
|
||||
Rule::in(
|
||||
Desfecho::ALTA_MEDICA,
|
||||
Desfecho::EVASAO,
|
||||
Desfecho::ENCAMINHAMENTO_HOSPITALAR,
|
||||
Desfecho::OBITO,
|
||||
Desfecho::FAA_EXTRAVIADA,
|
||||
Desfecho::PACIENTE_ATENDIDO,
|
||||
),
|
||||
'exists:\App\Models\ProntoAtendimento\Atendimento\Desfecho,id',
|
||||
],
|
||||
'alta_medica' => [
|
||||
'nullable',
|
||||
'required_if:desfecho_id,' . Desfecho::ALTA_MEDICA,
|
||||
'array',
|
||||
],
|
||||
'evasao' => [
|
||||
'nullable',
|
||||
'required_if:desfecho_id,' . Desfecho::EVASAO,
|
||||
'array',
|
||||
],
|
||||
'evasao.motivo' => [
|
||||
'nullable',
|
||||
'required_if:desfecho_id,' . Desfecho::EVASAO,
|
||||
'string',
|
||||
'max:200'
|
||||
],
|
||||
'encaminhamento_hospitalar' => [
|
||||
'nullable',
|
||||
'required_if:desfecho_id,' . Desfecho::ENCAMINHAMENTO_HOSPITALAR,
|
||||
'array',
|
||||
],
|
||||
'obito' => [
|
||||
'required_if:desfecho_id,' . Desfecho::OBITO,
|
||||
'array',
|
||||
],
|
||||
];
|
||||
|
||||
if (!is_null(request()->alta_medica ?? null)) {
|
||||
|
||||
$rules = array_merge($rules, [
|
||||
'alta_medica.lotacao_id' => [
|
||||
'required',
|
||||
'integer',
|
||||
'exists:\App\Models\Cadastro\SujeitoAtencao\Lotacao,id',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
if (!is_null(request()->encaminhamento_hospitalar ?? null)) {
|
||||
|
||||
$rules = array_merge($rules,
|
||||
[
|
||||
'encaminhamento_hospitalar.unidade_id' => [
|
||||
'nullable',
|
||||
Rule::requiredIf(fn () =>
|
||||
request()->desfecho_id === Desfecho::ENCAMINHAMENTO_HOSPITALAR &&
|
||||
(request()->encaminhamento_hospitalar['unidade_nome'] ?? null) === null
|
||||
),
|
||||
'integer',
|
||||
'exists:\App\Models\Cadastro\Estabelecimento\Unidade,id',
|
||||
],
|
||||
'encaminhamento_hospitalar.unidade_nome' => [
|
||||
'nullable',
|
||||
Rule::requiredIf(fn () =>
|
||||
request()->desfecho_id === Desfecho::ENCAMINHAMENTO_HOSPITALAR &&
|
||||
(request()->encaminhamento_hospitalar['unidade_id'] ?? null) === null
|
||||
),
|
||||
'string',
|
||||
'max:100',
|
||||
],
|
||||
'encaminhamento_hospitalar.lotacao_id' => [
|
||||
'required',
|
||||
'integer',
|
||||
'exists:\App\Models\Cadastro\SujeitoAtencao\Lotacao,id',
|
||||
],
|
||||
'encaminhamento_hospitalar.quarto' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:3',
|
||||
],
|
||||
'encaminhamento_hospitalar.leito' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:3',
|
||||
],
|
||||
'encaminhamento_hospitalar.cid_id' => [
|
||||
'nullable',
|
||||
'integer',
|
||||
'exists:\App\Models\Sigtap\Cid,id',
|
||||
],
|
||||
'encaminhamento_hospitalar.medico_hospitalar' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:150',
|
||||
],
|
||||
'encaminhamento_hospitalar.observacoes' => [
|
||||
'nullable',
|
||||
'string',
|
||||
'max:3000',
|
||||
],
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
if (is_array(request()->obito ?? null)) {
|
||||
|
||||
$rules = array_merge($rules, [
|
||||
'obito.obito_em' => [
|
||||
'bail',
|
||||
'required',
|
||||
'date_format:d/m/Y H:i',
|
||||
self::getObitoEmValidator($faa),
|
||||
],
|
||||
'obito.declaracao' => [
|
||||
'required',
|
||||
'string',
|
||||
'min:8',
|
||||
'max:13'
|
||||
],
|
||||
'obito.causa' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:255'
|
||||
],
|
||||
'obito.cid_id' => [
|
||||
'required',
|
||||
'integer',
|
||||
'exists:\App\Models\Sigtap\Cid,id'
|
||||
],
|
||||
'obito.lotacao_id' => [
|
||||
'required',
|
||||
'integer',
|
||||
'exists:\App\Models\Cadastro\SujeitoAtencao\Lotacao,id',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
request()->validate($rules, [
|
||||
'encaminhamento_hospitalar.unidade_id.required' =>
|
||||
"O campo encaminhamento hospitalar.unidade id é obrigatório quando encaminhamento hospitalar.unidade nome não está presente.",
|
||||
'encaminhamento_hospitalar.unidade_nome.required' =>
|
||||
'O campo encaminhamento hospitalar.unidade nome é obrigatório quando encaminhamento hospitalar.unidade id não está presente.',
|
||||
]);
|
||||
}
|
||||
|
||||
private static function getObitoEmValidator($faa)
|
||||
{
|
||||
return function ($attribute, $value, $fail) use ($faa) {
|
||||
|
||||
$dataAtual = Carbon::now();
|
||||
$dataObito = Carbon::createFromFormat('d/m/Y H:i', $value);
|
||||
$diffObitoDataAtual = $dataAtual->diffInMinutes($dataObito, false);
|
||||
|
||||
if (!is_null($faa->paciente->cidadao->data_nascimento ?? null)) {
|
||||
|
||||
$dataNascimento = $faa->paciente->cidadao->data_nascimento;
|
||||
$diffObitoDataNascimento = $dataNascimento->diffInMinutes($dataObito, false);
|
||||
|
||||
if ($diffObitoDataNascimento < 0 || $diffObitoDataAtual > 0) {
|
||||
|
||||
$msg = "A data e hora inserida deve ser entre a data de nascimento ";
|
||||
$msg .= "{$dataNascimento->format('d/m/Y')} e a data e hora atual.";
|
||||
|
||||
$fail($msg);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($diffObitoDataAtual > 0) {
|
||||
|
||||
$fail("A data e hora inserida deve ser menor ou igual a data e hora atual.");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private static function getAtendimentoFaa($faa)
|
||||
{
|
||||
return Atendimento::where('faa_id', $faa->id)->get()->last();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento\Evasao;
|
||||
|
||||
use App\Enums\ProntoAtendimento\Atendimento\Desfecho;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Faa;
|
||||
use App\Services\Service;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class CancelamentoEvasaoService extends Service
|
||||
{
|
||||
public static function datatable($request)
|
||||
{
|
||||
$cancelamentoEvasao = DB::table('pronto_atendimento_atendimento')
|
||||
->leftJoin('painel_senha_fila_historico', function($leftJoin) {
|
||||
|
||||
$leftJoin->on('pronto_atendimento_atendimento.fila_id', '=', 'painel_senha_fila_historico.fila_id')
|
||||
->where('painel_senha_fila_historico.id', '=', function ($query) {
|
||||
|
||||
$query->select('painel_senha_fila_historico.id')
|
||||
->from('painel_senha_fila_historico')
|
||||
->whereColumn('painel_senha_fila_historico.fila_id', 'pronto_atendimento_atendimento.fila_id')
|
||||
->orderByDesc('painel_senha_fila_historico.created_at')
|
||||
->limit(1);
|
||||
});
|
||||
})
|
||||
->leftJoin('cadastro_centro_custo as fila_centro_custo', 'fila_centro_custo.id', 'painel_senha_fila_historico.created_centro_custo_id')
|
||||
->leftJoin('cadastro_setor', 'cadastro_setor.id', 'fila_centro_custo.setor_id')
|
||||
->join('pronto_atendimento_faa', 'pronto_atendimento_faa.id', 'pronto_atendimento_atendimento.faa_id')
|
||||
->join('cadastro_paciente', 'cadastro_paciente.id', 'pronto_atendimento_faa.paciente_id')
|
||||
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id')
|
||||
->join('cadastro_centro_custo', 'cadastro_centro_custo.id', 'pronto_atendimento_atendimento.created_centro_custo_id')
|
||||
->where('pronto_atendimento_faa.desfecho_id', Desfecho::EVASAO)
|
||||
->where('pronto_atendimento_faa.updated_at', '>=', Carbon::now()->subHours(24)->toDateTimeString())
|
||||
->where('cadastro_centro_custo.infraestrutura_id', '=', $request->infraestrutura_id);
|
||||
|
||||
return $cancelamentoEvasao
|
||||
->select([
|
||||
DB::raw('DATE_FORMAT(pronto_atendimento_faa.updated_at, "%d/%m/%Y") as data'),
|
||||
DB::raw('DATE_FORMAT(pronto_atendimento_faa.updated_at, "%H:%i") as hora'),
|
||||
'cadastro_cidadao.nome',
|
||||
DB::raw('(CASE
|
||||
WHEN cadastro_cidadao.nome_mae IS NULL
|
||||
THEN "Não informado"
|
||||
ELSE cadastro_cidadao.nome_mae
|
||||
END) as nome_mae'),
|
||||
DB::raw('(CASE
|
||||
WHEN DATE_FORMAT(cadastro_cidadao.data_nascimento, "%d/%m/%Y") IS NULL
|
||||
THEN "Não informada"
|
||||
ELSE DATE_FORMAT(cadastro_cidadao.data_nascimento, "%d/%m/%Y")
|
||||
END) as data_nascimento'),
|
||||
'cadastro_paciente.prontuario',
|
||||
'cadastro_paciente.sequencial_desconhecido',
|
||||
'cadastro_cidadao.caracteristicas_fisicas',
|
||||
'cadastro_cidadao.preferencia_nome_id AS preferencia_nome_id',
|
||||
'cadastro_cidadao.nome_social AS nome_social',
|
||||
'pronto_atendimento_faa.id as faa_id',
|
||||
'pronto_atendimento_faa.numero as faa_numero',
|
||||
DB::raw('(CASE
|
||||
WHEN painel_senha_fila_historico.motivo_evasao IS NULL
|
||||
THEN "Não informado"
|
||||
ELSE painel_senha_fila_historico.motivo_evasao
|
||||
END) as motivo_evasao'),
|
||||
'cadastro_setor.nome as setor'
|
||||
])
|
||||
->orderByDesc('pronto_atendimento_faa.updated_at')
|
||||
->get();
|
||||
}
|
||||
|
||||
public static function cancel($request, $faaId)
|
||||
{
|
||||
self::validations();
|
||||
|
||||
DB::transaction(function () use ($request, $faaId) {
|
||||
|
||||
$faa = Faa::findOrFail($faaId);
|
||||
|
||||
$faa->update([
|
||||
'desfecho_id' => null,
|
||||
'finalizado' => false,
|
||||
'motivo_cancelamento_evasao' => $request->motivo_cancelamento_evasao,
|
||||
]);
|
||||
|
||||
$fila = $faa->atendimentos->first()->fila;
|
||||
|
||||
if (!is_null($fila)) {
|
||||
|
||||
$fila->update([
|
||||
'evadido' => false,
|
||||
'motivo_cancelamento_evasao' => $request->motivo_cancelamento_evasao,
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static function validations()
|
||||
{
|
||||
return request()->validate([
|
||||
'motivo_cancelamento_evasao' => [
|
||||
'required',
|
||||
'string',
|
||||
'between:3,500',
|
||||
]
|
||||
]);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
155
api/app/Services/ProntoAtendimento/FechamentoFaa/Validations.php
Normal file
155
api/app/Services/ProntoAtendimento/FechamentoFaa/Validations.php
Normal file
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento\FechamentoFaa;
|
||||
|
||||
use App\Enums\ProntoAtendimento\Atendimento\Desfecho;
|
||||
use App\Models\Cadastro\SujeitoAtencao\Lotacao;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Atendimento;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Procedimento;
|
||||
use App\Models\Sigtap\Competencia;
|
||||
use App\Rules\Sigtap\CidBelongsToProcedimento;
|
||||
use App\Rules\Sigtap\CidIsRequiredForProcedimento;
|
||||
use App\Rules\Sigtap\ProcedimentoIsValidForCompetencia;
|
||||
use App\Rules\Sigtap\ProcedimentoIsValidForIdade;
|
||||
use App\Rules\Sigtap\ProcedimentoIsValidForOcupacao;
|
||||
use App\Rules\Sigtap\ProcedimentoIsValidForSexo;
|
||||
use App\Rules\Sigtap\QuantidadeIsValidForProcedimento;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Validation\Rule;
|
||||
|
||||
class Validations
|
||||
{
|
||||
public static function index()
|
||||
{
|
||||
return request()->validate([
|
||||
'start' => [
|
||||
'required',
|
||||
'date_format:d/m/Y',
|
||||
'before_or_equal:now'
|
||||
],
|
||||
'end' => [
|
||||
'required',
|
||||
'date_format:d/m/Y',
|
||||
'after_or_equal:start',
|
||||
'before_or_equal:now',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public static function update($faa)
|
||||
{
|
||||
$rules = [
|
||||
'usuario_responsavel_id' => [
|
||||
Rule::requiredIf(fn () => request()->desfecho_id !== Desfecho::FAA_EXTRAVIADA),
|
||||
'integer',
|
||||
'exists:\App\Models\Cadastro\SujeitoAtencao\Usuario,id',
|
||||
],
|
||||
'fatores_risco' => [
|
||||
'nullable',
|
||||
'array',
|
||||
],
|
||||
'fatores_risco.*' => [
|
||||
'required',
|
||||
'integer',
|
||||
'exists:\App\Models\Cadastro\SujeitoAtencao\FatorRisco,id',
|
||||
],
|
||||
];
|
||||
|
||||
$rules = array_merge(
|
||||
$rules,
|
||||
self::getPutProcedimentosRules($faa)
|
||||
);
|
||||
|
||||
return request()->validate($rules);
|
||||
}
|
||||
|
||||
private static function getPutProcedimentosRules($faa)
|
||||
{
|
||||
$rules = [
|
||||
'procedimentos' => [
|
||||
Rule::requiredIf(fn () =>
|
||||
request()->desfecho_id !== Desfecho::FAA_EXTRAVIADA
|
||||
&& !self::hasProcedimentoRegistered($faa)
|
||||
),
|
||||
'array',
|
||||
],
|
||||
'procedimentos.*.data' => [
|
||||
'required',
|
||||
'date_format:d/m/Y',
|
||||
],
|
||||
'procedimentos.*.lotacao_id' => [
|
||||
'bail',
|
||||
'required',
|
||||
'integer',
|
||||
'exists:\App\Models\Cadastro\SujeitoAtencao\Lotacao,id'
|
||||
],
|
||||
'procedimentos.*.is_parametrizado' => [
|
||||
'nullable',
|
||||
'boolean'
|
||||
],
|
||||
];
|
||||
|
||||
foreach ((request()->procedimentos ?? []) as $i => $params) {
|
||||
|
||||
$procedimentoIdAnterior = null;
|
||||
|
||||
if (isset($params['id']) && !is_null($params['id'])) {
|
||||
|
||||
$procedimentoIdAnterior = Procedimento::findOrFail($params['id'])->procedimento_id;
|
||||
}
|
||||
|
||||
$rules["procedimentos.{$i}.procedimento_id"] = [
|
||||
'required',
|
||||
'integer',
|
||||
'exists:\App\Models\Sigtap\Procedimento,id',
|
||||
];
|
||||
|
||||
$lotacao = Lotacao::find($params['lotacao_id']);
|
||||
|
||||
if (!is_null($lotacao) && $procedimentoIdAnterior != $params['procedimento_id']) {
|
||||
|
||||
$rules["procedimentos.{$i}.procedimento_id"] = array_merge(
|
||||
$rules["procedimentos.{$i}.procedimento_id"],
|
||||
[
|
||||
new ProcedimentoIsValidForOcupacao($lotacao->ocupacao_id),
|
||||
new ProcedimentoIsValidForSexo($faa->paciente->cidadao->sexo->identificador),
|
||||
(
|
||||
$faa->paciente->cidadao->idade
|
||||
? new ProcedimentoIsValidForIdade($faa->paciente->cidadao->idade['anos'])
|
||||
: null
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
$rules["procedimentos.{$i}.cid_id"] = [
|
||||
'nullable',
|
||||
'integer',
|
||||
'exists:\App\Models\Sigtap\Cid,id',
|
||||
new CidIsRequiredForProcedimento($params['procedimento_id']),
|
||||
new CidBelongsToProcedimento($params['procedimento_id']),
|
||||
];
|
||||
|
||||
$rules["procedimentos.{$i}.quantidade"] = [
|
||||
'required',
|
||||
'integer',
|
||||
'min:1',
|
||||
new QuantidadeIsValidForProcedimento($params['procedimento_id'])
|
||||
];
|
||||
}
|
||||
|
||||
return $rules;
|
||||
}
|
||||
|
||||
private static function hasProcedimentoRegistered($faa)
|
||||
{
|
||||
$atendimento = self::getAtendimentoFaa($faa);
|
||||
|
||||
return $atendimento->has('procedimentos')->exists();
|
||||
}
|
||||
|
||||
private static function getAtendimentoFaa($faa)
|
||||
{
|
||||
return Atendimento::where('faa_id', $faa->id)->get()->last();
|
||||
}
|
||||
}
|
||||
457
api/app/Services/ProntoAtendimento/FechamentoFaaMassaService.php
Normal file
457
api/app/Services/ProntoAtendimento/FechamentoFaaMassaService.php
Normal file
@@ -0,0 +1,457 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento;
|
||||
|
||||
use App\Enums\Cadastro\Estabelecimento\SetorTipo;
|
||||
use App\Enums\ProntoAtendimento\Atendimento\Desfecho;
|
||||
use App\Enums\Sigtap\Procedimento;
|
||||
use App\Models\Cadastro\Estabelecimento\CentroCusto;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Atendimento;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Faa;
|
||||
use App\Services\Service;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class FechamentoFaaMassaService extends Service
|
||||
{
|
||||
public static function create()
|
||||
{
|
||||
return [
|
||||
'additionals' => self::getAdditionals(),
|
||||
'form' => self::getForm(),
|
||||
'model' => self::getModel(),
|
||||
];
|
||||
}
|
||||
|
||||
public static function store($request)
|
||||
{
|
||||
self::validate($request);
|
||||
|
||||
DB::transaction(function() use ($request) {
|
||||
$centroCusto = CentroCusto::find($request->centro_custo_id);
|
||||
|
||||
if ($centroCusto->setor->tipo_id === SetorTipo::ENFERMAGEM) {
|
||||
self::criaAtendimentosEnfermagem($request);
|
||||
self::insereProcedimentosAdministracaoMedicamento($request);
|
||||
self::finalizaFaasEnfermagemAbertas($request);
|
||||
}
|
||||
else if ($centroCusto->setor->tipo_id === SetorTipo::OBSERVACAO) {
|
||||
self::finalizaFaasObservacaoAbertas($request);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static function datatable()
|
||||
{
|
||||
return DB::table('pronto_atendimento_atendimento')
|
||||
->select([
|
||||
'cadastro_unidade.nome_fantasia AS unidade_nome_fantasia',
|
||||
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia) AS infraestrutura_nome"),
|
||||
'cadastro_setor.nome AS setor_nome',
|
||||
'pronto_atendimento_faa.id AS faa_id',
|
||||
'pronto_atendimento_faa.numero AS faa_numero',
|
||||
DB::raw("DATE_FORMAT(pronto_atendimento_faa.created_at, '%d/%m/%Y') AS data_atendimento"),
|
||||
'cadastro_cidadao.nome AS paciente_nome',
|
||||
])
|
||||
->join('painel_senha_fila', 'painel_senha_fila.id', 'pronto_atendimento_atendimento.fila_id')
|
||||
->join('pronto_atendimento_faa', 'pronto_atendimento_faa.id', 'pronto_atendimento_atendimento.faa_id')
|
||||
->join('cadastro_centro_custo', 'cadastro_centro_custo.id', 'painel_senha_fila.centro_custo_id')
|
||||
->join('cadastro_setor', 'cadastro_setor.id', 'cadastro_centro_custo.setor_id')
|
||||
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_centro_custo.infraestrutura_id')
|
||||
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
|
||||
->join('cadastro_paciente', 'cadastro_paciente.id', 'pronto_atendimento_faa.paciente_id')
|
||||
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id')
|
||||
->whereNull('painel_senha_fila.deleted_at')
|
||||
->where('pronto_atendimento_faa.finalizado', false)
|
||||
->whereIn('cadastro_setor.tipo_id', [SetorTipo::ENFERMAGEM, SetorTipo::OBSERVACAO]);
|
||||
}
|
||||
|
||||
public static function list()
|
||||
{
|
||||
switch (request()->get('listar')) {
|
||||
case 'unidades':
|
||||
return self::getUnidades(request()->get('start_date'), request()->get('end_date'));
|
||||
break;
|
||||
|
||||
case 'infraestruturas':
|
||||
return self::getInfraestruturas(request()->get('start_date'), request()->get('end_date'), request()->get('unidade_id'));
|
||||
break;
|
||||
|
||||
case 'centros-custo':
|
||||
return self::getCentrosCusto(request()->get('start_date'), request()->get('end_date'), request()->get('infraestrutura_id'));
|
||||
break;
|
||||
|
||||
default:
|
||||
return [];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private static function validate($request)
|
||||
{
|
||||
return $request->validate([
|
||||
'start_date' => [
|
||||
'required',
|
||||
'date',
|
||||
],
|
||||
'end_date' => [
|
||||
'required',
|
||||
'date',
|
||||
],
|
||||
'centro_custo_id' => [
|
||||
'required',
|
||||
'integer',
|
||||
'exists:\App\Models\Cadastro\Estabelecimento\CentroCusto,id',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
private static function getAdditionals()
|
||||
{
|
||||
return [
|
||||
'data_atual' => Carbon::now()->format('d/m/Y'),
|
||||
];
|
||||
}
|
||||
|
||||
private static function getForm()
|
||||
{
|
||||
return [
|
||||
'unidades' => [],
|
||||
'infraestruturas' => [],
|
||||
'centros_custo' => [],
|
||||
];
|
||||
}
|
||||
|
||||
private static function getModel()
|
||||
{
|
||||
return [
|
||||
'periodo' => [
|
||||
'start' => null,
|
||||
'end' => null,
|
||||
],
|
||||
'unidade_id' => null,
|
||||
'infraestrutura_id' => null,
|
||||
'centro_custo_id' => null,
|
||||
];
|
||||
}
|
||||
|
||||
private static function getUnidades($startDate, $endDate)
|
||||
{
|
||||
return DB::table('cadastro_unidade')
|
||||
->select([
|
||||
'cadastro_unidade.id',
|
||||
'cadastro_unidade.nome_fantasia'
|
||||
])
|
||||
->whereExists(function ($query) use ($startDate, $endDate) {
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_atendimento')
|
||||
->join('painel_senha_fila', 'painel_senha_fila.id', 'pronto_atendimento_atendimento.fila_id')
|
||||
->join('pronto_atendimento_faa', 'pronto_atendimento_faa.id', 'pronto_atendimento_atendimento.faa_id')
|
||||
->join('cadastro_centro_custo', 'cadastro_centro_custo.id', 'painel_senha_fila.centro_custo_id')
|
||||
->join('cadastro_setor', 'cadastro_setor.id', 'cadastro_centro_custo.setor_id')
|
||||
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_centro_custo.infraestrutura_id')
|
||||
->whereRaw("CAST(pronto_atendimento_faa.created_at AS DATE) >= '" . $startDate . "'")
|
||||
->whereRaw("CAST(pronto_atendimento_faa.created_at AS DATE) <= '" . $endDate . "'")
|
||||
->whereNull('painel_senha_fila.deleted_at')
|
||||
->where('pronto_atendimento_faa.finalizado', false)
|
||||
->whereIn('cadastro_setor.tipo_id', [SetorTipo::ENFERMAGEM, SetorTipo::OBSERVACAO])
|
||||
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id');
|
||||
})
|
||||
->orderBy('cadastro_unidade.nome_fantasia')
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function getInfraestruturas($startDate, $endDate, $unidadeId)
|
||||
{
|
||||
return DB::table('cadastro_infraestrutura')
|
||||
->select([
|
||||
'cadastro_infraestrutura.id',
|
||||
DB::raw('COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia) AS nome'),
|
||||
])
|
||||
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
|
||||
->where('cadastro_unidade.id', $unidadeId)
|
||||
->whereExists(function ($query) use ($startDate, $endDate) {
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_atendimento')
|
||||
->join('painel_senha_fila', 'painel_senha_fila.id', 'pronto_atendimento_atendimento.fila_id')
|
||||
->join('pronto_atendimento_faa', 'pronto_atendimento_faa.id', 'pronto_atendimento_atendimento.faa_id')
|
||||
->join('cadastro_centro_custo', 'cadastro_centro_custo.id', 'painel_senha_fila.centro_custo_id')
|
||||
->join('cadastro_setor', 'cadastro_setor.id', 'cadastro_centro_custo.setor_id')
|
||||
->whereRaw("CAST(pronto_atendimento_faa.created_at AS DATE) >= '" . $startDate . "'")
|
||||
->whereRaw("CAST(pronto_atendimento_faa.created_at AS DATE) <= '" . $endDate . "'")
|
||||
->whereNull('painel_senha_fila.deleted_at')
|
||||
->where('pronto_atendimento_faa.finalizado', false)
|
||||
->whereIn('cadastro_setor.tipo_id', [SetorTipo::ENFERMAGEM, SetorTipo::OBSERVACAO])
|
||||
->whereColumn('cadastro_centro_custo.infraestrutura_id', 'cadastro_infraestrutura.id');
|
||||
})
|
||||
->orderByRaw('COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)')
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function getCentrosCusto($startDate, $endDate, $infraestruturaId)
|
||||
{
|
||||
return DB::table('cadastro_centro_custo')
|
||||
->select([
|
||||
'cadastro_centro_custo.id',
|
||||
'cadastro_setor.nome',
|
||||
])
|
||||
->join('cadastro_setor', 'cadastro_setor.id', 'cadastro_centro_custo.setor_id')
|
||||
->where('cadastro_centro_custo.infraestrutura_id', $infraestruturaId)
|
||||
->whereIn('cadastro_setor.tipo_id', [SetorTipo::ENFERMAGEM, SetorTipo::OBSERVACAO])
|
||||
->whereExists(function ($query) use ($startDate, $endDate) {
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_atendimento')
|
||||
->join('painel_senha_fila', 'painel_senha_fila.id', 'pronto_atendimento_atendimento.fila_id')
|
||||
->join('pronto_atendimento_faa', 'pronto_atendimento_faa.id', 'pronto_atendimento_atendimento.faa_id')
|
||||
->whereRaw("CAST(pronto_atendimento_faa.created_at AS DATE) >= '" . $startDate . "'")
|
||||
->whereRaw("CAST(pronto_atendimento_faa.created_at AS DATE) <= '" . $endDate . "'")
|
||||
->whereNull('painel_senha_fila.deleted_at')
|
||||
->where('pronto_atendimento_faa.finalizado', false)
|
||||
->whereColumn('painel_senha_fila.centro_custo_id', 'cadastro_centro_custo.id');
|
||||
})
|
||||
->orderBy('cadastro_setor.nome')
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function criaAtendimentosEnfermagem($request)
|
||||
{
|
||||
DB::table('pronto_atendimento_atendimento')
|
||||
->select([
|
||||
'pronto_atendimento_atendimento.id AS atendimento_id',
|
||||
DB::raw("
|
||||
(
|
||||
SELECT pronto_atendimento_plantao.id
|
||||
FROM pronto_atendimento_plantao
|
||||
WHERE pronto_atendimento_plantao.inicio <= pronto_atendimento_faa.created_at
|
||||
AND pronto_atendimento_plantao.fim >= pronto_atendimento_faa.created_at
|
||||
AND pronto_atendimento_plantao.servico_id = true
|
||||
LIMIT 1
|
||||
) AS plantao_id
|
||||
"),
|
||||
DB::raw("
|
||||
(
|
||||
SELECT pronto_atendimento_plantao.lotacao_id
|
||||
FROM pronto_atendimento_plantao
|
||||
WHERE pronto_atendimento_plantao.inicio <= pronto_atendimento_faa.created_at
|
||||
AND pronto_atendimento_plantao.fim >= pronto_atendimento_faa.created_at
|
||||
AND pronto_atendimento_plantao.servico_id = true
|
||||
LIMIT 1
|
||||
) AS lotacao_id
|
||||
"),
|
||||
DB::raw("
|
||||
(
|
||||
SELECT pronto_atendimento_plantao.created_centro_custo_id
|
||||
FROM pronto_atendimento_plantao
|
||||
WHERE pronto_atendimento_plantao.inicio <= pronto_atendimento_faa.created_at
|
||||
AND pronto_atendimento_plantao.fim >= pronto_atendimento_faa.created_at
|
||||
AND pronto_atendimento_plantao.servico_id = true
|
||||
LIMIT 1
|
||||
) AS created_centro_custo_id
|
||||
"),
|
||||
'pronto_atendimento_atendimento_prescricao_interna.created_at',
|
||||
'pronto_atendimento_atendimento_prescricao_interna.updated_at',
|
||||
])
|
||||
->join('pronto_atendimento_atendimento_medico', 'pronto_atendimento_atendimento_medico.atendimento_id', 'pronto_atendimento_atendimento.id')
|
||||
->join('pronto_atendimento_atendimento_prescricao_interna', 'pronto_atendimento_atendimento_prescricao_interna.atendimento_medico_id', 'pronto_atendimento_atendimento_medico.id')
|
||||
->join('pronto_atendimento_faa', 'pronto_atendimento_faa.id', 'pronto_atendimento_atendimento.faa_id')
|
||||
->join('painel_senha_fila', 'painel_senha_fila.id', 'pronto_atendimento_atendimento.fila_id')
|
||||
->whereRaw("CAST(pronto_atendimento_faa.created_at AS DATE) >= '" . $request->start_date . "'")
|
||||
->whereRaw("CAST(pronto_atendimento_faa.created_at AS DATE) <= '" . $request->end_date . "'")
|
||||
->where('painel_senha_fila.centro_custo_id', $request->centro_custo_id)
|
||||
->whereNull('painel_senha_fila.deleted_at')
|
||||
->where('pronto_atendimento_faa.finalizado', false)
|
||||
->whereNotExists(function ($query) {
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_atendimento_enfermagem')
|
||||
->whereColumn('pronto_atendimento_atendimento_enfermagem.atendimento_id', 'pronto_atendimento_atendimento.id');
|
||||
})
|
||||
->get()
|
||||
->each(function ($query) {
|
||||
|
||||
DB::table('pronto_atendimento_atendimento_enfermagem')
|
||||
->insert([
|
||||
'atendimento_id' => $query->atendimento_id,
|
||||
'plantao_id' => $query->plantao_id,
|
||||
'created_at' => $query->created_at,
|
||||
'updated_at' => $query->updated_at,
|
||||
'created_lotacao_id' => $query->lotacao_id,
|
||||
'created_centro_custo_id' => $query->created_centro_custo_id,
|
||||
'automatico' => true
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
private static function insereProcedimentosAdministracaoMedicamento($request)
|
||||
{
|
||||
DB::table('pronto_atendimento_atendimento_prescricao_interna_medicamento')
|
||||
->select([
|
||||
'pronto_atendimento_atendimento.id AS atendimento_id',
|
||||
DB::raw("
|
||||
(
|
||||
SELECT pronto_atendimento_atendimento_enfermagem.id
|
||||
FROM pronto_atendimento_atendimento_enfermagem
|
||||
WHERE pronto_atendimento_atendimento_enfermagem.atendimento_id = pronto_atendimento_atendimento.id
|
||||
ORDER BY pronto_atendimento_atendimento_enfermagem.id DESC
|
||||
LIMIT 1
|
||||
) AS atendimento_enfermagem_id
|
||||
"),
|
||||
DB::raw("
|
||||
(
|
||||
SELECT pronto_atendimento_atendimento_enfermagem.plantao_id
|
||||
FROM pronto_atendimento_atendimento_enfermagem
|
||||
WHERE pronto_atendimento_atendimento_enfermagem.atendimento_id = pronto_atendimento_atendimento.id
|
||||
ORDER BY pronto_atendimento_atendimento_enfermagem.id DESC
|
||||
LIMIT 1
|
||||
) AS plantao_id
|
||||
"),
|
||||
DB::raw("
|
||||
(
|
||||
SELECT pronto_atendimento_atendimento_enfermagem.created_lotacao_id
|
||||
FROM pronto_atendimento_atendimento_enfermagem
|
||||
WHERE pronto_atendimento_atendimento_enfermagem.atendimento_id = pronto_atendimento_atendimento.id
|
||||
ORDER BY pronto_atendimento_atendimento_enfermagem.id DESC
|
||||
LIMIT 1
|
||||
) AS created_lotacao_id
|
||||
"),
|
||||
DB::raw("
|
||||
(
|
||||
SELECT pronto_atendimento_atendimento_enfermagem.created_centro_custo_id
|
||||
FROM pronto_atendimento_atendimento_enfermagem
|
||||
WHERE pronto_atendimento_atendimento_enfermagem.atendimento_id = pronto_atendimento_atendimento.id
|
||||
ORDER BY pronto_atendimento_atendimento_enfermagem.id DESC
|
||||
LIMIT 1
|
||||
) AS created_centro_custo_id
|
||||
"),
|
||||
DB::raw("
|
||||
(
|
||||
SELECT procedimento.id
|
||||
FROM sigtap.procedimento
|
||||
WHERE procedimento.codigo = '" . Procedimento::ADMINISTRACAO_DE_MEDICAMENTOS_NA_ATENCAO_ESPECIALIZADA . "'
|
||||
ORDER BY procedimento.id DESC
|
||||
LIMIT 1
|
||||
) AS procedimento_id
|
||||
"),
|
||||
DB::raw("CAST(pronto_atendimento_atendimento_prescricao_interna.created_at AS DATE) AS realizado_em"),
|
||||
'pronto_atendimento_atendimento_prescricao_interna.created_at',
|
||||
'pronto_atendimento_atendimento_prescricao_interna.updated_at',
|
||||
])
|
||||
->join('pronto_atendimento_atendimento_prescricao_interna', 'pronto_atendimento_atendimento_prescricao_interna.id', 'pronto_atendimento_atendimento_prescricao_interna_medicamento.prescricao_interna_id')
|
||||
->join('pronto_atendimento_atendimento_medico', 'pronto_atendimento_atendimento_medico.id', 'pronto_atendimento_atendimento_prescricao_interna.atendimento_medico_id')
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_atendimento_medico.atendimento_id')
|
||||
->join('pronto_atendimento_faa', 'pronto_atendimento_faa.id', 'pronto_atendimento_atendimento.faa_id')
|
||||
->join('painel_senha_fila', 'painel_senha_fila.id', 'pronto_atendimento_atendimento.fila_id')
|
||||
->whereRaw("CAST(pronto_atendimento_faa.created_at AS DATE) >= '" . $request->start_date . "'")
|
||||
->whereRaw("CAST(pronto_atendimento_faa.created_at AS DATE) <= '" . $request->end_date . "'")
|
||||
->where('painel_senha_fila.centro_custo_id', $request->centro_custo_id)
|
||||
->whereNull('painel_senha_fila.deleted_at')
|
||||
->where('pronto_atendimento_faa.finalizado', false)
|
||||
->whereNotExists(function ($query) {
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_atendimento_procedimento')
|
||||
->join('sigtap.procedimento', 'procedimento.id', 'pronto_atendimento_atendimento_procedimento.procedimento_id')
|
||||
->where('procedimento.codigo', Procedimento::ADMINISTRACAO_DE_MEDICAMENTOS_NA_ATENCAO_ESPECIALIZADA)
|
||||
->whereColumn('pronto_atendimento_atendimento_procedimento.atendimento_id', 'pronto_atendimento_atendimento.id');
|
||||
})
|
||||
->groupBy('pronto_atendimento_atendimento.id')
|
||||
->get()
|
||||
->each(function ($query) {
|
||||
DB::table('pronto_atendimento_atendimento_procedimento')
|
||||
->insert([
|
||||
'atendimento_id' => $query->atendimento_id,
|
||||
'atendimento_enfermagem_id' => $query->atendimento_enfermagem_id,
|
||||
'procedimento_id' => $query->procedimento_id,
|
||||
'plantao_id' => $query->plantao_id,
|
||||
'lotacao_id' => $query->created_lotacao_id,
|
||||
'quantidade' => 1,
|
||||
'realizado_em' => $query->realizado_em,
|
||||
'created_at' => $query->created_at,
|
||||
'updated_at' => $query->updated_at,
|
||||
'created_lotacao_id' => $query->created_lotacao_id,
|
||||
'created_centro_custo_id' => $query->created_centro_custo_id,
|
||||
]);
|
||||
});
|
||||
}
|
||||
|
||||
private static function finalizaFaasEnfermagemAbertas($request)
|
||||
{
|
||||
DB::table('pronto_atendimento_faa')
|
||||
->whereIn('id', function ($query) use ($request) {
|
||||
$query->from('pronto_atendimento_atendimento')
|
||||
->select('pronto_atendimento_faa.id')
|
||||
->join('painel_senha_fila', 'painel_senha_fila.id', 'pronto_atendimento_atendimento.fila_id')
|
||||
->join('pronto_atendimento_faa', 'pronto_atendimento_faa.id', 'pronto_atendimento_atendimento.faa_id')
|
||||
->whereRaw("CAST(pronto_atendimento_faa.created_at AS DATE) >= '" . $request->start_date . "'")
|
||||
->whereRaw("CAST(pronto_atendimento_faa.created_at AS DATE) <= '" . $request->end_date . "'")
|
||||
->where('painel_senha_fila.centro_custo_id', $request->centro_custo_id)
|
||||
->whereNull('painel_senha_fila.deleted_at')
|
||||
->where('pronto_atendimento_faa.finalizado', false);
|
||||
})
|
||||
->get()
|
||||
->each(function ($faa) {
|
||||
$atendimento = Atendimento::where('faa_id', $faa->id)->first()->atendimentosMedico->first();
|
||||
|
||||
if($atendimento && $atendimento->desfecho_id == Desfecho::ALTA_MEDICA) {
|
||||
Faa::find($faa->id)->update([
|
||||
'finalizado' => true,
|
||||
'desfecho_id' => Desfecho::ALTA_MEDICA,
|
||||
'data_hora_desfecho' => Carbon::now(),
|
||||
'usuario_id' => $atendimento->plantao->lotacao->usuario_id,
|
||||
'lotacao_id' => $atendimento->plantao->lotacao_id
|
||||
]);
|
||||
}
|
||||
else {
|
||||
$currentLotacao = self::getCurrentLotacao();
|
||||
|
||||
Faa::find($faa->id)->update([
|
||||
'finalizado' => true,
|
||||
'desfecho_id' => Desfecho::ALTA_MEDICA,
|
||||
'data_hora_desfecho' => Carbon::now(),
|
||||
'usuario_id' => $currentLotacao->usuario_id,
|
||||
'lotacao_id' => $currentLotacao->id
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static function finalizaFaasObservacaoAbertas($request)
|
||||
{
|
||||
DB::table('pronto_atendimento_faa')
|
||||
->whereIn('pronto_atendimento_faa.id', function ($query) use ($request) {
|
||||
$query->from('pronto_atendimento_atendimento')
|
||||
->select('pronto_atendimento_faa.id')
|
||||
->join('painel_senha_fila', 'painel_senha_fila.id', 'pronto_atendimento_atendimento.fila_id')
|
||||
->join('pronto_atendimento_faa', 'pronto_atendimento_faa.id', 'pronto_atendimento_atendimento.faa_id')
|
||||
->whereRaw("CAST(pronto_atendimento_faa.created_at AS DATE) >= '" . $request->start_date . "'")
|
||||
->whereRaw("CAST(pronto_atendimento_faa.created_at AS DATE) <= '" . $request->end_date . "'")
|
||||
->where('painel_senha_fila.centro_custo_id', $request->centro_custo_id)
|
||||
->whereNull('painel_senha_fila.deleted_at')
|
||||
->where('pronto_atendimento_faa.finalizado', false);
|
||||
})
|
||||
->get()
|
||||
->each(function ($faa) {
|
||||
$atendimento = Atendimento::where('faa_id', $faa->id)->first()->atendimentosMedico->first();
|
||||
|
||||
if($atendimento && $atendimento->desfecho_id == Desfecho::ALTA_MEDICA) {
|
||||
Faa::find($faa->id)->update([
|
||||
'finalizado' => true,
|
||||
'desfecho_id' => Desfecho::ALTA_MEDICA,
|
||||
'data_hora_desfecho' => Carbon::now(),
|
||||
'usuario_id' => $atendimento->plantao->lotacao->usuario_id,
|
||||
'lotacao_id' => $atendimento->plantao->lotacao_id
|
||||
]);
|
||||
|
||||
}
|
||||
else{
|
||||
$currentLotacao = self::getCurrentLotacao();
|
||||
|
||||
Faa::find($faa->id)->update([
|
||||
'finalizado' => true,
|
||||
'desfecho_id' => Desfecho::ALTA_MEDICA,
|
||||
'data_hora_desfecho' => Carbon::now(),
|
||||
'usuario_id' => $currentLotacao->usuario_id,
|
||||
'lotacao_id' => $currentLotacao->id
|
||||
]);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
99
api/app/Services/ProntoAtendimento/Fila/ChamadaService.php
Normal file
99
api/app/Services/ProntoAtendimento/Fila/ChamadaService.php
Normal file
@@ -0,0 +1,99 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento\Fila;
|
||||
|
||||
use App\Events\PainelSenha\ChamadaEvent;
|
||||
use App\Models\Cadastro\Estabelecimento\CentroCusto;
|
||||
use App\Models\PainelSenha\Chamada;
|
||||
use App\Models\PainelSenha\ParametrizacaoInfraestrutura;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Atendimento;
|
||||
use App\Services\Service;
|
||||
use Exception;
|
||||
|
||||
class ChamadaService extends Service
|
||||
{
|
||||
public static function index($request)
|
||||
{
|
||||
return Chamada::where('tela_id', $request['tela_id'])
|
||||
->when($request['modulo_ids'] ?? null, fn ($q, $moduloIds) => $q
|
||||
->whereHas('fila', fn ($q) => $q
|
||||
->whereHas('opcaoEntrada', fn ($q) => $q
|
||||
->whereIn('modulo_id', $moduloIds)
|
||||
)
|
||||
)
|
||||
)
|
||||
->orderBy('created_at', 'desc')
|
||||
->take(4)
|
||||
->get()
|
||||
->map(function($query) {
|
||||
return [
|
||||
'id' => $query->id,
|
||||
'paciente' => [
|
||||
'cidadao' => [
|
||||
'preferencia_nome_id' => $query->paciente->cidadao->preferencia_nome_id ?? null,
|
||||
'nome' => $query->paciente->cidadao->nome ?? null,
|
||||
'nome_social' => $query->paciente->cidadao->nome_social ?? null,
|
||||
],
|
||||
],
|
||||
'sala' => [
|
||||
'nome' => $query->sala->nome ?? null,
|
||||
],
|
||||
'senha' => $query->fila->senha ?? null,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
public static function store($request)
|
||||
{
|
||||
$atendimento = Atendimento::where('fila_id', $request->fila_id)
|
||||
->orderBy('created_at', 'desc')
|
||||
->first();
|
||||
|
||||
$fila = FilaService::show($request->fila_id);
|
||||
|
||||
$chamada = Chamada::create([
|
||||
'fila_id' => $fila->id,
|
||||
'status_id' => $fila->status_id,
|
||||
'tela_id' => $request->tela_id,
|
||||
'sala_id' => $request->sala_id,
|
||||
'paciente_id' => $atendimento->faa->paciente_id ?? null,
|
||||
]);
|
||||
|
||||
$centroCusto = CentroCusto::findOrFail($fila->centro_custo_id);
|
||||
|
||||
FilaService::dispatch($centroCusto, $request->sala_id);
|
||||
|
||||
$parametrizacaoInfraestrutura = ParametrizacaoInfraestrutura::where(
|
||||
'infraestrutura_id',
|
||||
$centroCusto->infraestrutura_id
|
||||
)->first();
|
||||
|
||||
$moduloIds = is_null($parametrizacaoInfraestrutura)
|
||||
? collect()
|
||||
: $parametrizacaoInfraestrutura->modulos->pluck('id');
|
||||
|
||||
try {
|
||||
|
||||
$paramsChamada = [
|
||||
'tela_id' => $chamada->tela_id,
|
||||
'modulo_ids' => null,
|
||||
];
|
||||
|
||||
$moduloIds->each(function ($moduloId) use ($paramsChamada) {
|
||||
|
||||
$paramsChamada['modulo_ids'] = [$moduloId];
|
||||
|
||||
ChamadaEvent::dispatch(
|
||||
$paramsChamada['tela_id'],
|
||||
$moduloId,
|
||||
self::index($paramsChamada)
|
||||
);
|
||||
});
|
||||
} catch (Exception $error) {
|
||||
|
||||
// TODO: Gravar exception em um arquivo.
|
||||
}
|
||||
|
||||
return $chamada;
|
||||
}
|
||||
}
|
||||
1104
api/app/Services/ProntoAtendimento/Fila/FilaService.php
Normal file
1104
api/app/Services/ProntoAtendimento/Fila/FilaService.php
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento;
|
||||
|
||||
use App\Enums\PainelSenha\Status;
|
||||
use App\Models\Cadastro\Estabelecimento\Unidade;
|
||||
use App\Models\PainelSenha\Prioridade;
|
||||
use App\Services\ProntoAtendimento\Fila\FilaService;
|
||||
use App\Services\Service;
|
||||
use App\Models\PainelSenha\Status as StatusFila;
|
||||
|
||||
class FilaAtendimentoService extends Service
|
||||
{
|
||||
public static function list()
|
||||
{
|
||||
$centroCustoLogado = self::getCurrentCentroCusto();
|
||||
|
||||
return [
|
||||
'form' => [
|
||||
'unidades' => Unidade::orderBy('nome_fantasia')
|
||||
->get()
|
||||
->map(fn ($unidade) => [
|
||||
'id' => $unidade->id,
|
||||
'nome_fantasia' => $unidade->nome_fantasia,
|
||||
'infraestruturas' => $unidade->infraestruturas
|
||||
->map(fn ($infraestrutura) => [
|
||||
'id' => $infraestrutura->id,
|
||||
'nome' => $infraestrutura->nome,
|
||||
'centros_custo' => $infraestrutura->centrosCusto
|
||||
->map(fn ($centroCusto) => [
|
||||
'id' => $centroCusto->id,
|
||||
'setor_nome' => $centroCusto->setor->nome,
|
||||
'setor_tipo_id' => $centroCusto->setor->tipo_id,
|
||||
'status' => StatusFila::orderBy('nome')
|
||||
->get()
|
||||
->map(fn ($status) => [
|
||||
'id' => $status->id,
|
||||
'nome' => $status->nome,
|
||||
])
|
||||
])
|
||||
->sortBy('setor_nome')
|
||||
->values()
|
||||
])
|
||||
->sortBy('nome')
|
||||
->values()
|
||||
]),
|
||||
'prioridades' => Prioridade::orderBy('nome')
|
||||
->get()
|
||||
->map(function($query) {
|
||||
return [
|
||||
'id' => $query->id,
|
||||
'nome' => $query->nome,
|
||||
];
|
||||
}),
|
||||
],
|
||||
'model' => [
|
||||
'unidade_id' => $centroCustoLogado->infraestrutura->unidade_id,
|
||||
'infraestrutura_id' => $centroCustoLogado->infraestrutura_id,
|
||||
'centro_custo_id' => $centroCustoLogado->id,
|
||||
'status_id' => Status::EM_ESPERA,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public static function index()
|
||||
{
|
||||
$fila = FilaService::index([
|
||||
'centro_custo_id' => request()->centro_custo_id,
|
||||
'setor_tipo_id' => request()->setor_tipo_id,
|
||||
]);
|
||||
|
||||
return [
|
||||
'fila' => $fila->filter(fn ($f) => $f['status']['id'] == request()->status_id)->values(),
|
||||
'total_em_espera' => $fila
|
||||
->filter(fn ($f) => $f['status']['id'] == Status::EM_ESPERA)->count(),
|
||||
'total_em_atendimento' => $fila
|
||||
->filter(fn ($f) => $f['status']['id'] == Status::EM_ATENDIMENTO)->count(),
|
||||
];
|
||||
}
|
||||
}
|
||||
1379
api/app/Services/ProntoAtendimento/HistoricoService.php
Normal file
1379
api/app/Services/ProntoAtendimento/HistoricoService.php
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,326 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento\Impressao;
|
||||
|
||||
use App\Enums\Cadastro\SujeitoAtencao\PreferenciaNome;
|
||||
use App\Enums\Parametrizacao\Exame\Tipo;
|
||||
use App\Enums\ProntoAtendimento\Atendimento\Medico\DeclaracaoComparecimentoTipo;
|
||||
use App\Models\Cadastro\SujeitoAtencao\Sexo;
|
||||
use App\Models\ProntoAtendimento\AssistenciaSocial\AssistenciaSocial;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Atendimento;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Medico\AtendimentoMedico;
|
||||
use App\Models\ProntoAtendimento\Atendimento\ServicoEnfermagem;
|
||||
use App\Services\Service;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class ImpressaoFaaEletronicaService extends Service
|
||||
{
|
||||
public static function list()
|
||||
{
|
||||
$now = Carbon::now();
|
||||
$currentDate = $now->format('d/m/Y');
|
||||
$currentLotacao = self::getCurrentLotacao();
|
||||
|
||||
return [
|
||||
'form' => [
|
||||
'unidade' => $currentLotacao->infraestrutura->unidade->nome_fantasia,
|
||||
'infraestrutura' => $currentLotacao->infraestrutura->nome,
|
||||
'sexos' => Sexo::orderBy('descricao')->get(['id', 'descricao'])->makeHidden('identificador')
|
||||
],
|
||||
'model' => [
|
||||
'periodo' => [
|
||||
'start' => $currentDate,
|
||||
'end' => $currentDate,
|
||||
],
|
||||
'sexo_id' => null,
|
||||
'paciente' => null,
|
||||
'data_nascimento' => null,
|
||||
'faa' => null,
|
||||
],
|
||||
'additionals' => [
|
||||
'periodo_min_date' => $now->copy()->subYears(130)->format('d/m/Y'),
|
||||
'current_date' => $now->format('d/m/Y')
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
public static function datatable($request)
|
||||
{
|
||||
self::validateDatatableRequest($request);
|
||||
|
||||
$atendimentos = DB::table('pronto_atendimento_atendimento AS atendimento')
|
||||
->leftJoin('painel_senha_fila AS fila', 'fila.id', 'atendimento.fila_id')
|
||||
->leftJoin('painel_senha_opcao_entrada AS opcao_entrada', 'opcao_entrada.id', 'fila.opcao_entrada_id')
|
||||
->leftJoin('pronto_atendimento_assistencia_social AS assistencia', 'assistencia.atendimento_id', 'atendimento.id')
|
||||
->join('pronto_atendimento_faa AS faa', 'faa.id', 'atendimento.faa_id')
|
||||
->join('cadastro_paciente AS paciente', 'paciente.id', 'faa.paciente_id')
|
||||
->join('cadastro_cidadao AS cidadao', 'cidadao.id', 'paciente.cidadao_id')
|
||||
->leftJoin('cadastro_sexo AS sexo', 'sexo.id', 'cidadao.sexo_id')
|
||||
->join('pronto_atendimento_atendimento_recepcao AS recepcao', 'recepcao.atendimento_id', 'atendimento.id')
|
||||
->join('cadastro_centro_custo AS centro_custo', 'centro_custo.id', 'atendimento.created_centro_custo_id')
|
||||
->join('cadastro_infraestrutura AS infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
|
||||
->select([
|
||||
'atendimento.id AS atendimento_id',
|
||||
'recepcao.atendido_em AS data',
|
||||
'recepcao.acompanhante AS acompanhante',
|
||||
'infraestrutura.nome as infraestrutura',
|
||||
'faa.id AS faa',
|
||||
'faa.numero AS faa_numero',
|
||||
'assistencia.id AS assistencia_id',
|
||||
'assistencia.anotacao AS anotacao',
|
||||
DB::raw("CONCAT(opcao_entrada.sigla, fila.senha) AS senha"),
|
||||
'fila.created_at AS senha_data_hora_emissao',
|
||||
'sexo.descricao AS sexo',
|
||||
'paciente.prontuario AS paciente_prontuario',
|
||||
'cidadao.data_nascimento AS paciente_data_nascimento',
|
||||
'cidadao.nome_mae AS paciente_nome_mae',
|
||||
'cidadao.nome AS paciente_nome',
|
||||
'cidadao.nome_social AS paciente_nome_social',
|
||||
'cidadao.preferencia_nome_id as paciente_preferencia_nome_id',
|
||||
'cidadao.caracteristicas_fisicas AS paciente_caracteristicas_fisicas',
|
||||
'paciente.sequencial_desconhecido_em AS paciente_sequencial_desconhecido_em',
|
||||
])
|
||||
->where('centro_custo.infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id)
|
||||
->whereBetween('recepcao.atendido_em', [
|
||||
Carbon::createFromFormat('d/m/Y', $request->periodo['start'])->setTime(0, 0, 0),
|
||||
Carbon::createFromFormat('d/m/Y', $request->periodo['end'])->setTime(23, 59, 59)
|
||||
])
|
||||
->when($request->sexo_id, function ($query, $value) {
|
||||
|
||||
$query->where('cidadao.sexo_id', $value);
|
||||
})
|
||||
->when($request->paciente, function ($query, $value) {
|
||||
|
||||
$query->where('cidadao.nome', 'like', "{$value}%");
|
||||
})
|
||||
->when($request->data_nascimento, function ($query, $value) {
|
||||
|
||||
$query->whereDate('cidadao.data_nascimento', Carbon::createFromFormat('d/m/Y', $value));
|
||||
})
|
||||
->when($request->faa, function ($query, $value) {
|
||||
|
||||
$query->where('faa.numero', $value);
|
||||
})
|
||||
->get()
|
||||
->map(function ($atendimento) {
|
||||
|
||||
$atendimento->impressoes = self::getImpressoes($atendimento);
|
||||
|
||||
if (is_null($atendimento->paciente_nome_mae)) {
|
||||
|
||||
$atendimento->paciente_nome_mae = 'Não informado';
|
||||
}
|
||||
|
||||
if (is_null($atendimento->paciente_caracteristicas_fisicas)) {
|
||||
|
||||
$atendimento->paciente_caracteristicas_fisicas = 'Não informado';
|
||||
}
|
||||
|
||||
$atendimento->paciente_is_desconhecido = !is_null($atendimento->paciente_sequencial_desconhecido_em);
|
||||
$atendimento->data = (new Carbon($atendimento->data))->format('d/m/Y');
|
||||
|
||||
$atendimento->paciente_prefere_nome_social = $atendimento
|
||||
->paciente_preferencia_nome_id === PreferenciaNome::NOME_SOCIAL;
|
||||
|
||||
$atendimento->paciente_data_nascimento = is_null($atendimento->paciente_data_nascimento)
|
||||
? 'Não informada'
|
||||
: (new Carbon($atendimento->paciente_data_nascimento))->format('d/m/Y');
|
||||
|
||||
unset(
|
||||
$atendimento->acompanhante,
|
||||
$atendimento->infraestrutura,
|
||||
$atendimento->senha,
|
||||
$atendimento->senha_data_hora_emissao,
|
||||
$atendimento->paciente_preferencia_nome_id,
|
||||
$atendimento->paciente_sequencial_desconhecido_em
|
||||
);
|
||||
|
||||
return $atendimento;
|
||||
});
|
||||
|
||||
return $atendimentos;
|
||||
}
|
||||
|
||||
private static function getImpressoes($atendimento)
|
||||
{
|
||||
$atendimentoId = $atendimento->atendimento_id;
|
||||
|
||||
return [
|
||||
'recepcao' => [
|
||||
[
|
||||
'value' => 'etiqueta',
|
||||
'text' => 'Etiqueta',
|
||||
'disabled' => false,
|
||||
'data' => [
|
||||
'atendido_em' => (new Carbon($atendimento->data))->format('d/m/Y H:i'),
|
||||
'infraestrutura' => $atendimento->infraestrutura,
|
||||
'acompanhante' => $atendimento->acompanhante ?? '',
|
||||
'paciente' => $atendimento->paciente_nome,
|
||||
'data_nascimento' => is_null($atendimento->paciente_data_nascimento)
|
||||
? '' : (new Carbon($atendimento->paciente_data_nascimento))->format('d/m/Y'),
|
||||
'senha' => $atendimento->senha
|
||||
]
|
||||
],
|
||||
[
|
||||
'value' => 'raat',
|
||||
'text' => 'RAAT',
|
||||
'disabled' => Atendimento::where('id', $atendimentoId)
|
||||
->whereHas('faa.raat')->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'senha',
|
||||
'text' => 'Senha',
|
||||
'disabled' => Atendimento::where('id', $atendimentoId)
|
||||
->whereHas('fila')->get()->isEmpty(),
|
||||
'data' => [
|
||||
'data' => is_null($atendimento->senha_data_hora_emissao)
|
||||
? '' : (new Carbon($atendimento->senha_data_hora_emissao))->format('d/m/Y'),
|
||||
'hora' => is_null($atendimento->senha_data_hora_emissao)
|
||||
? '' : (new Carbon($atendimento->senha_data_hora_emissao))->format('H:i:s'),
|
||||
'senha' => $atendimento->senha,
|
||||
]
|
||||
],
|
||||
],
|
||||
'medicoEnfermagem' => [
|
||||
[
|
||||
'value' => 'atestado',
|
||||
'text' => 'Atestado',
|
||||
'disabled' => AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('atestado')->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'declaracaoAcompanhante',
|
||||
'text' => 'Declaração de Comparecimento - Acompanhante',
|
||||
'disabled' => AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('declaracoesComparecimento', function ($query) {
|
||||
|
||||
$query->where('tipo_id', DeclaracaoComparecimentoTipo::ACOMPANHANTE);
|
||||
})->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'declaracaoPaciente',
|
||||
'text' => 'Declaração de Comparecimento - Paciente',
|
||||
'disabled' => AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('declaracoesComparecimento', function ($query) {
|
||||
|
||||
$query->where('tipo_id', DeclaracaoComparecimentoTipo::PACIENTE);
|
||||
})->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'encaminhamentoHospitalar',
|
||||
'text' => 'Encaminhamento Hospitalar',
|
||||
'disabled' => AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('encaminhamentoHospitalar')->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'examesImagem',
|
||||
'text' => 'Exames - Imagem',
|
||||
'disabled' => Atendimento::where('id', $atendimentoId)
|
||||
->whereHas('pedidosExames.exames.exame', function ($query) {
|
||||
|
||||
$query->where('tipo_id', Tipo::IMAGEM);
|
||||
})->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'examesLaboratorial',
|
||||
'text' => 'Exames - Laboratorial',
|
||||
'disabled' => Atendimento::where('id', $atendimentoId)
|
||||
->whereHas('pedidosExames.exames.exame', function ($query) {
|
||||
|
||||
$query->where('tipo_id', Tipo::LABORATORIAL);
|
||||
})->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'guiaEncaminhamento',
|
||||
'text' => 'Guia de Encaminhamento',
|
||||
'disabled' => AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('encaminhamentos')->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'orientacoesPaciente',
|
||||
'text' => 'Orientação ao paciente',
|
||||
'disabled' => AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereNotNull('orientacoes')->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'prescricaoInterna',
|
||||
'text' => 'Prescrição Interna',
|
||||
'disabled' => AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('prescricoesInternas')->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'receitaMedica',
|
||||
'text' => 'Receita Médica',
|
||||
'disabled' => AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('receita')->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'servicoEnfermagem',
|
||||
'text' => 'Serviços Enfermagem',
|
||||
'disabled' => ServicoEnfermagem::whereHas('atendimentoMedico', function ($query) use ($atendimentoId) {
|
||||
|
||||
$query->where('atendimento_id', $atendimentoId);
|
||||
})
|
||||
->orWhereHas('atendimentoEnfermagem', function ($query) use ($atendimentoId) {
|
||||
|
||||
$query->where('atendimento_id', $atendimentoId);
|
||||
})
|
||||
->orWhereHas('pacienteObservacao', function ($query) use ($atendimentoId) {
|
||||
|
||||
$query->where('atendimento_id', $atendimentoId);
|
||||
})
|
||||
->get()
|
||||
->isEmpty()
|
||||
],
|
||||
],
|
||||
'assistenciaSocial' => [
|
||||
[
|
||||
'value' => 'assistencia',
|
||||
'text' => 'Assistencia',
|
||||
'disabled' => false,
|
||||
'data' => [
|
||||
'paciente' => $atendimento->paciente_nome,
|
||||
'anotacao' => $atendimento->anotacao
|
||||
]
|
||||
],
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
private static function validateDatatableRequest($request)
|
||||
{
|
||||
$minDate = Carbon::now()->subYears(130)->format('Y-m-d');
|
||||
|
||||
$request->validate([
|
||||
'periodo.start' => [
|
||||
'required',
|
||||
'date_format:d/m/Y',
|
||||
"after_or_equal:{$minDate}",
|
||||
'before_or_equal:periodo.end',
|
||||
],
|
||||
'periodo.end' => [
|
||||
'required',
|
||||
'date_format:d/m/Y',
|
||||
'after_or_equal:periodo.start',
|
||||
'before_or_equal:now',
|
||||
],
|
||||
'sexo_id' => [
|
||||
'nullable',
|
||||
'integer',
|
||||
],
|
||||
'paciente' => [
|
||||
'nullable',
|
||||
'string',
|
||||
],
|
||||
'data_nascimento' => [
|
||||
'nullable',
|
||||
'date_format:d/m/Y',
|
||||
],
|
||||
'faa' => [
|
||||
'nullable',
|
||||
'integer',
|
||||
],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,921 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento\Impressao;
|
||||
|
||||
use App\Enums\Cadastro\Medicamento\TipoReceita;
|
||||
use App\Enums\Cadastro\SujeitoAtencao\PreferenciaNome;
|
||||
use App\Enums\Parametrizacao\Exame\Tipo;
|
||||
use App\Enums\ProntoAtendimento\Atendimento\Medico\DeclaracaoComparecimentoTipo;
|
||||
use App\Enums\ProntoAtendimento\TipoFormularioAcidenteTrabalho;
|
||||
use App\Http\Controllers\ProntoAtendimento\Atendimento\Enfermagem\AtendimentoEnfermagemController;
|
||||
use App\Models\Cadastro\SujeitoAtencao\Sexo;
|
||||
use App\Models\Cns\TermoInvalido;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Atendimento;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Enfermagem\AtendimentoEnfermagem;
|
||||
use App\Models\ProntoAtendimento\Atendimento\ExameImagem\AtendimentoExameImagem;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Medico\AtendimentoMedico;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Medico\Atestado;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Medico\Receita;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Observacao\PacienteObservacao;
|
||||
use App\Models\ProntoAtendimento\Atendimento\PrescricaoInterna;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Recepcao;
|
||||
use App\Models\ProntoAtendimento\Atendimento\ServicoEnfermagem;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Triagem\AtendimentoTriagem;
|
||||
use App\Models\ProntoAtendimento\Parametrizacao\FaturamentoExameLaboratorial;
|
||||
use App\Services\Service;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class ImpressaoService extends Service
|
||||
{
|
||||
public static function list()
|
||||
{
|
||||
$now = Carbon::now();
|
||||
$currentDate = $now->format('d/m/Y');
|
||||
$currentLotacao = self::getCurrentLotacao();
|
||||
|
||||
return [
|
||||
'form' => [
|
||||
'unidade' => $currentLotacao->infraestrutura->unidade->nome_fantasia,
|
||||
'infraestrutura' => $currentLotacao->infraestrutura->nome,
|
||||
'sexos' => Sexo::orderBy('descricao')->get(['id', 'descricao'])->makeHidden('identificador')
|
||||
],
|
||||
'model' => [
|
||||
'periodo' => [
|
||||
'start' => $currentDate,
|
||||
'end' => $currentDate,
|
||||
],
|
||||
'sexo_id' => null,
|
||||
'paciente' => null,
|
||||
'data_nascimento' => null,
|
||||
'faa' => null,
|
||||
],
|
||||
'additionals' => [
|
||||
'periodo_min_date' => $now->copy()->subYears(130)->format('d/m/Y'),
|
||||
'current_date' => $now->format('d/m/Y'),
|
||||
'termos_invalidos' => TermoInvalido::all()->map(fn ($termo) => $termo->descricao),
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
public static function datatable($request)
|
||||
{
|
||||
self::validateDatatableRequest($request);
|
||||
|
||||
$atendimentos = DB::table('pronto_atendimento_atendimento AS atendimento')
|
||||
->leftJoin('painel_senha_fila AS fila', 'fila.id', 'atendimento.fila_id')
|
||||
->leftJoin('painel_senha_opcao_entrada AS opcao_entrada', 'opcao_entrada.id', 'fila.opcao_entrada_id')
|
||||
->join('pronto_atendimento_faa AS faa', 'faa.id', 'atendimento.faa_id')
|
||||
->join('cadastro_paciente AS paciente', 'paciente.id', 'faa.paciente_id')
|
||||
->join('cadastro_cidadao AS cidadao', 'cidadao.id', 'paciente.cidadao_id')
|
||||
->leftJoin('cadastro_sexo AS sexo', 'sexo.id', 'cidadao.sexo_id')
|
||||
->leftJoin('cadastro_carteira_identidade AS carteira_identidade', 'carteira_identidade.cidadao_id', 'cidadao.id')
|
||||
->leftJoin('cadastro_carteira_habilitacao AS carteira_habilitacao', 'carteira_habilitacao.cidadao_id', 'cidadao.id')
|
||||
->join('pronto_atendimento_atendimento_recepcao AS recepcao', 'recepcao.atendimento_id', 'atendimento.id')
|
||||
->join('cadastro_centro_custo AS centro_custo', 'centro_custo.id', 'atendimento.created_centro_custo_id')
|
||||
->join('cadastro_infraestrutura AS infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
|
||||
->join('cadastro_unidade AS unidade', 'unidade.id', 'infraestrutura.unidade_id')
|
||||
->select([
|
||||
'atendimento.id AS atendimento_id',
|
||||
'recepcao.atendido_em AS data',
|
||||
DB::raw("TIME_FORMAT(recepcao.atendido_em, '%H:%i') AS hora"),
|
||||
'recepcao.acompanhante AS acompanhante',
|
||||
'infraestrutura.nome as infraestrutura',
|
||||
'unidade.nome_fantasia as unidade',
|
||||
'faa.id AS faa',
|
||||
'faa.numero AS faa_numero',
|
||||
DB::raw("CONCAT(opcao_entrada.sigla, fila.senha) AS senha"),
|
||||
'fila.created_at AS senha_data_hora_emissao',
|
||||
'sexo.descricao AS sexo',
|
||||
'paciente.prontuario AS paciente_prontuario',
|
||||
'cidadao.data_nascimento AS paciente_data_nascimento',
|
||||
'cidadao.nome_mae AS paciente_nome_mae',
|
||||
'cidadao.nome AS paciente_nome',
|
||||
'cidadao.nome_social AS paciente_nome_social',
|
||||
'cidadao.preferencia_nome_id as paciente_preferencia_nome_id',
|
||||
'cidadao.caracteristicas_fisicas AS paciente_caracteristicas_fisicas',
|
||||
'cidadao.cpf AS paciente_cpf',
|
||||
'cidadao.cns AS paciente_cns',
|
||||
'carteira_identidade.numero AS paciente_rg',
|
||||
'carteira_habilitacao.numero AS paciente_cnh',
|
||||
'paciente.sequencial_desconhecido_em AS paciente_sequencial_desconhecido_em',
|
||||
DB::raw("DATE_FORMAT(IF(faa.data_hora_desfecho, faa.data_hora_desfecho, faa.updated_at), '%d/%m/%Y') AS data_desfecho"),
|
||||
DB::raw("TIME_FORMAT(IF(faa.data_hora_desfecho, faa.data_hora_desfecho, faa.updated_at), '%H:%i') AS hora_desfecho"),
|
||||
'faa.finalizado',
|
||||
])
|
||||
->where('centro_custo.infraestrutura_id', self::getCurrentCentroCusto()->infraestrutura_id)
|
||||
->whereBetween('recepcao.atendido_em', [
|
||||
Carbon::createFromFormat('d/m/Y', $request->periodo['start'])->setTime(0, 0, 0),
|
||||
Carbon::createFromFormat('d/m/Y', $request->periodo['end'])->setTime(23, 59, 59)
|
||||
])
|
||||
->when($request->sexo_id, function ($query, $value) {
|
||||
|
||||
$query->where('cidadao.sexo_id', $value);
|
||||
})
|
||||
->when($request->paciente, function ($query, $value) {
|
||||
|
||||
$query->where('cidadao.nome', 'like', "{$value}%");
|
||||
})
|
||||
->when($request->data_nascimento, function ($query, $value) {
|
||||
|
||||
$query->whereDate('cidadao.data_nascimento', Carbon::createFromFormat('d/m/Y', $value));
|
||||
})
|
||||
->when($request->faa, function ($query, $value) {
|
||||
|
||||
$query->where('faa.numero', $value);
|
||||
})
|
||||
->whereNull('faa.deleted_at')
|
||||
->get()
|
||||
->map(function ($atendimento) {
|
||||
|
||||
$atendimento->impressoes = self::getImpressoes(
|
||||
$atendimento->atendimento_id,
|
||||
[
|
||||
'recepcao' => [
|
||||
'etiqueta' => [
|
||||
'atendido_em' => (new Carbon($atendimento->data))->format('d/m/Y H:i'),
|
||||
'infraestrutura' => $atendimento->infraestrutura ?? $atendimento->unidade,
|
||||
'acompanhante' => $atendimento->acompanhante ?? '',
|
||||
'paciente' => $atendimento->paciente_nome,
|
||||
'data_nascimento' => is_null($atendimento->paciente_data_nascimento)
|
||||
? '' : (new Carbon($atendimento->paciente_data_nascimento))->format('d/m/Y'),
|
||||
'senha' => $atendimento->senha
|
||||
],
|
||||
'senha' => [
|
||||
'data' => is_null($atendimento->senha_data_hora_emissao)
|
||||
? '' : (new Carbon($atendimento->senha_data_hora_emissao))->format('d/m/Y'),
|
||||
'hora' => is_null($atendimento->senha_data_hora_emissao)
|
||||
? '' : (new Carbon($atendimento->senha_data_hora_emissao))->format('H:i:s'),
|
||||
'senha' => $atendimento->senha,
|
||||
]
|
||||
]
|
||||
]
|
||||
);
|
||||
|
||||
if (is_null($atendimento->paciente_nome_mae)) {
|
||||
|
||||
$atendimento->paciente_nome_mae = 'Não informado';
|
||||
}
|
||||
|
||||
if (is_null($atendimento->paciente_caracteristicas_fisicas)) {
|
||||
|
||||
$atendimento->paciente_caracteristicas_fisicas = 'Não informado';
|
||||
}
|
||||
|
||||
$atendimento->paciente_is_desconhecido = !is_null($atendimento->paciente_sequencial_desconhecido_em);
|
||||
$atendimento->data = (new Carbon($atendimento->data))->format('d/m/Y');
|
||||
|
||||
$atendimento->paciente_prefere_nome_social = $atendimento
|
||||
->paciente_preferencia_nome_id === PreferenciaNome::NOME_SOCIAL;
|
||||
|
||||
$atendimento->paciente_data_nascimento = is_null($atendimento->paciente_data_nascimento)
|
||||
? 'Não informada'
|
||||
: (new Carbon($atendimento->paciente_data_nascimento))->format('d/m/Y');
|
||||
|
||||
unset(
|
||||
$atendimento->infraestrutura,
|
||||
$atendimento->senha,
|
||||
$atendimento->senha_data_hora_emissao,
|
||||
$atendimento->paciente_preferencia_nome_id,
|
||||
$atendimento->paciente_sequencial_desconhecido_em
|
||||
);
|
||||
|
||||
return $atendimento;
|
||||
});
|
||||
|
||||
return $atendimentos;
|
||||
}
|
||||
|
||||
public static function getAtendimentosAssinados($atendimentoId)
|
||||
{
|
||||
$path = 'assinatura-eletronica' . DIRECTORY_SEPARATOR . app('config')->get('database.default') . DIRECTORY_SEPARATOR . 'pronto-atendimento';
|
||||
|
||||
$atendimentos = DB::table('pronto_atendimento_atendimento_triagem as triagem')
|
||||
->join('cadastro_lotacao as triagem_lotacao', 'triagem_lotacao.id', 'triagem.created_lotacao_id')
|
||||
->join('cadastro_usuario as triagem_usuario', 'triagem_usuario.id', 'triagem_lotacao.usuario_id')
|
||||
->join('cadastro_cidadao as triagem_cidadao', 'triagem_cidadao.id', 'triagem_usuario.cidadao_id')
|
||||
->join('sigtap.ocupacao as triagem_ocupacao', 'triagem_ocupacao.id', 'triagem_lotacao.ocupacao_id')
|
||||
->where('triagem.is_faa_assinada', true)
|
||||
->where('triagem.atendimento_id', $atendimentoId)
|
||||
->select(DB::raw("
|
||||
triagem.id,
|
||||
'triagem' as tipo_identificador,
|
||||
'TRIAGEM' as tipo,
|
||||
triagem.created_at as data_hora,
|
||||
triagem_cidadao.nome as profissional,
|
||||
CONCAT(triagem_ocupacao.codigo, ' - ', triagem_ocupacao.nome) as ocupacao
|
||||
"))
|
||||
->unionAll(
|
||||
DB::table('pronto_atendimento_atendimento_medico as medico')
|
||||
->join('cadastro_lotacao as medico_lotacao', 'medico_lotacao.id', 'medico.created_lotacao_id')
|
||||
->join('cadastro_usuario as medico_usuario', 'medico_usuario.id', 'medico_lotacao.usuario_id')
|
||||
->join('cadastro_cidadao as medico_cidadao', 'medico_cidadao.id', 'medico_usuario.cidadao_id')
|
||||
->join('sigtap.ocupacao as medico_ocupacao', 'medico_ocupacao.id', 'medico_lotacao.ocupacao_id')
|
||||
->where('medico.is_faa_assinada', true)
|
||||
->where('medico.atendimento_id', $atendimentoId)
|
||||
->select(DB::raw("
|
||||
medico.id,
|
||||
'medico' as tipo_identificador,
|
||||
CONCAT('MÉDICO', IF(medico.is_observacao = 1,' (OBSERVAÇÃO)', '')) as tipo,
|
||||
medico.created_at as data_hora,
|
||||
medico_cidadao.nome as profissional,
|
||||
CONCAT(medico_ocupacao.codigo, ' - ', medico_ocupacao.nome) as ocupacao
|
||||
"))
|
||||
)
|
||||
->unionAll(
|
||||
DB::table('pronto_atendimento_atendimento_enfermagem as enfermagem')
|
||||
->join('cadastro_lotacao as enfermagem_lotacao', 'enfermagem_lotacao.id', 'enfermagem.created_lotacao_id')
|
||||
->join('cadastro_usuario as enfermagem_usuario', 'enfermagem_usuario.id', 'enfermagem_lotacao.usuario_id')
|
||||
->join('cadastro_cidadao as enfermagem_cidadao', 'enfermagem_cidadao.id', 'enfermagem_usuario.cidadao_id')
|
||||
->join('sigtap.ocupacao as enfermagem_ocupacao', 'enfermagem_ocupacao.id', 'enfermagem_lotacao.ocupacao_id')
|
||||
->where('enfermagem.is_faa_assinada', true)
|
||||
->where('enfermagem.atendimento_id', $atendimentoId)
|
||||
->select(DB::raw("
|
||||
enfermagem.id,
|
||||
'enfermagem' as tipo_identificador,
|
||||
'ENFERMAGEM' as tipo,
|
||||
enfermagem.created_at as data_hora,
|
||||
enfermagem_cidadao.nome as profissional,
|
||||
CONCAT(enfermagem_ocupacao.codigo, ' - ', enfermagem_ocupacao.nome) as ocupacao
|
||||
"))
|
||||
)
|
||||
->unionAll(
|
||||
DB::table('pronto_atendimento_paciente_observacao as observacao')
|
||||
->join('cadastro_lotacao as observacao_lotacao', 'observacao_lotacao.id', 'observacao.created_lotacao_id')
|
||||
->join('cadastro_usuario as observacao_usuario', 'observacao_usuario.id', 'observacao_lotacao.usuario_id')
|
||||
->join('cadastro_cidadao as observacao_cidadao', 'observacao_cidadao.id', 'observacao_usuario.cidadao_id')
|
||||
->join('sigtap.ocupacao as observacao_ocupacao', 'observacao_ocupacao.id', 'observacao_lotacao.ocupacao_id')
|
||||
->where('observacao.is_faa_assinada', true)
|
||||
->where('observacao.atendimento_id', $atendimentoId)
|
||||
->select(DB::raw("
|
||||
observacao.id,
|
||||
'observacao' as tipo_identificador,
|
||||
'ENFERMAGEM (OBSERVAÇÃO)' as tipo,
|
||||
observacao.created_at as data_hora,
|
||||
observacao_cidadao.nome as profissional,
|
||||
CONCAT(observacao_ocupacao.codigo, ' - ', observacao_ocupacao.nome) as ocupacao
|
||||
"))
|
||||
)
|
||||
->get();
|
||||
|
||||
$atendimentos->each(function ($atendimento) use ($path) {
|
||||
|
||||
$atendimento->receitas_medicas_assinadas = collect();
|
||||
$atendimento->faa_assinada = null;
|
||||
|
||||
if ($atendimento->tipo_identificador == 'triagem') {
|
||||
$file = $path . DIRECTORY_SEPARATOR . "atendimento-triagem" . DIRECTORY_SEPARATOR . "{$atendimento->id}.PDF";
|
||||
|
||||
if (Storage::disk('local')->exists($file)) {
|
||||
$atendimento->faa_assinada = base64_encode(Storage::disk('local')->get($file));
|
||||
}
|
||||
}
|
||||
|
||||
else if ($atendimento->tipo_identificador == 'medico') {
|
||||
$file = $path . DIRECTORY_SEPARATOR . "atendimento-medico" . DIRECTORY_SEPARATOR . "{$atendimento->id}.PDF";
|
||||
|
||||
$receita = Receita::firstWhere('atendimento_medico_id', $atendimento->id);
|
||||
|
||||
if (!is_null($receita) && $receita->is_assinada) {
|
||||
|
||||
$receita->receitasAssinadas()
|
||||
->where('ordem', $receita->receitasAssinadas()->max('ordem'))
|
||||
->get('id')
|
||||
->each(function($receitaAssinada) use ($path, $atendimento) {
|
||||
$file = $path . DIRECTORY_SEPARATOR . "atendimento-medico-receita-medica" . DIRECTORY_SEPARATOR . "{$receitaAssinada->id}.PDF";
|
||||
|
||||
if (Storage::disk('local')->exists($file)) {
|
||||
$atendimento->receitas_medicas_assinadas->push(base64_encode(Storage::disk('local')->get($file)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (Storage::disk('local')->exists($file)) {
|
||||
$atendimento->faa_assinada = base64_encode(Storage::disk('local')->get($file));
|
||||
}
|
||||
}
|
||||
|
||||
else if ($atendimento->tipo_identificador == 'enfermagem') {
|
||||
$file = $path . DIRECTORY_SEPARATOR . "atendimento-enfermagem" . DIRECTORY_SEPARATOR . "{$atendimento->id}.PDF";
|
||||
|
||||
if (Storage::disk('local')->exists($file)) {
|
||||
$atendimento->faa_assinada = base64_encode(Storage::disk('local')->get($file));
|
||||
}
|
||||
}
|
||||
|
||||
else if ($atendimento->tipo_identificador == 'observacao') {
|
||||
$file = $path . DIRECTORY_SEPARATOR . "paciente-observacao" . DIRECTORY_SEPARATOR . "{$atendimento->id}.PDF";
|
||||
|
||||
if (Storage::disk('local')->exists($file)) {
|
||||
$atendimento->faa_assinada = base64_encode(Storage::disk('local')->get($file));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return $atendimentos;
|
||||
}
|
||||
|
||||
public static function getImpressoes($atendimentoId, $data = [])
|
||||
{
|
||||
$excluded = $data['excluded'] ?? [];
|
||||
$recepcaoData = $data['recepcao'] ?? [];
|
||||
$triagemData = $data['triagem'] ?? [];
|
||||
$faturarEnfermagem = $data['faturar_enfermagem'] ?? false;
|
||||
|
||||
$impressoes = [
|
||||
'additionals' => [
|
||||
'faturar_enfermagem' => $faturarEnfermagem,
|
||||
'usuarios_faturamento_exame_laboratorial' => $faturarEnfermagem
|
||||
? self::getUsuariosFaturamentoExameLaboratorial()
|
||||
: [],
|
||||
'has_exames_laboratoriais_pendente' => $faturarEnfermagem
|
||||
? (new AtendimentoEnfermagemController())->getPedidoExamesLaboratoriaisParaFaturamentoAutomatico(
|
||||
Atendimento::findOrFail($atendimentoId)
|
||||
)->isNotEmpty() : false,
|
||||
],
|
||||
'recepcao' => self::getImpressoesRecepcao($atendimentoId, $recepcaoData),
|
||||
'triagem' => self::getImpressoesTriagem($atendimentoId, $triagemData),
|
||||
'medicoEnfermagem' => self::getImpressoesMedicoEnfermagem($atendimentoId),
|
||||
'faa' => self::getImpressoesFaa($atendimentoId),
|
||||
];
|
||||
|
||||
foreach ($excluded as $key => $value) {
|
||||
|
||||
if (is_array($value)) {
|
||||
|
||||
foreach ($value as $col => $vl) {
|
||||
|
||||
$indice = array_search($vl, array_column($impressoes[$key], $col));
|
||||
if ($indice >= 0) {
|
||||
|
||||
unset($impressoes[$key][$indice]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
if (array_key_exists($value, $impressoes)) {
|
||||
|
||||
unset($impressoes[$value]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return $impressoes;
|
||||
}
|
||||
|
||||
private static function getUsuariosFaturamentoExameLaboratorial()
|
||||
{
|
||||
$usuariosFaturamentoExameLaboratorial = collect();
|
||||
|
||||
FaturamentoExameLaboratorial::whereHas('lotacao', function ($query) {
|
||||
|
||||
$query->where('infraestrutura_id', self::getCurrentLotacao()->infraestrutura_id);
|
||||
})->each(function ($parametrizacao) use ($usuariosFaturamentoExameLaboratorial) {
|
||||
|
||||
$lotacao = $parametrizacao->lotacao;
|
||||
|
||||
$usuario = $usuariosFaturamentoExameLaboratorial
|
||||
->where('id', $lotacao->usuario_id)
|
||||
->first();
|
||||
|
||||
if (is_null($usuario)) {
|
||||
|
||||
$usuario = (object) [
|
||||
'id' => $lotacao->usuario->id,
|
||||
'nome' => $lotacao->usuario->cidadao->nome,
|
||||
'lotacoes' => collect(),
|
||||
];
|
||||
|
||||
$usuariosFaturamentoExameLaboratorial->push($usuario);
|
||||
}
|
||||
|
||||
$usuario->lotacoes->push((object) [
|
||||
'id' => $lotacao->id,
|
||||
'ocupacao_descricao' => "{$lotacao->ocupacao->codigo} - {$lotacao->ocupacao->nome}",
|
||||
]);
|
||||
});
|
||||
|
||||
$usuariosFaturamentoExameLaboratorial
|
||||
->sortBy('nome')
|
||||
->values()
|
||||
->each(fn ($u) => $u->lotacoes->sortBy('ocupacao_descricao')->values());
|
||||
|
||||
return $usuariosFaturamentoExameLaboratorial;
|
||||
}
|
||||
|
||||
public static function getImpressoesRecepcao($atendimentoId, $data = [])
|
||||
{
|
||||
$impressoesRecepcao = [];
|
||||
|
||||
if (isset($data['etiqueta'])) {
|
||||
|
||||
$impressoesRecepcao[] = [
|
||||
'value' => 'etiqueta',
|
||||
'text' => 'Etiqueta',
|
||||
'disabled' => false,
|
||||
'data' => $data['etiqueta']
|
||||
];
|
||||
}
|
||||
|
||||
// $impressoesRecepcao[] = [
|
||||
// 'value' => 'raat',
|
||||
// 'text' => 'RAAT',
|
||||
// 'disabled' => Atendimento::where('id', $atendimentoId)
|
||||
// ->whereHas('faa.raat')->get()->isEmpty()
|
||||
// ];
|
||||
|
||||
if (isset($data['senha'])) {
|
||||
|
||||
$impressoesRecepcao[] = [
|
||||
'value' => 'senha',
|
||||
'text' => 'Senha',
|
||||
'disabled' => Atendimento::where('id', $atendimentoId)
|
||||
->whereHas('fila')->get()->isEmpty(),
|
||||
'data' => $data['senha']
|
||||
];
|
||||
}
|
||||
|
||||
$impressoesRecepcao[] = [
|
||||
'value' => 'termoCiencia',
|
||||
'text' => 'Termo de ciência',
|
||||
'disabled' => false,
|
||||
];
|
||||
|
||||
return $impressoesRecepcao;
|
||||
}
|
||||
|
||||
public static function getImpressoesTriagem($atendimentoId, $data = [])
|
||||
{
|
||||
$impressoesTriagem = [];
|
||||
|
||||
if (isset($data['etiqueta'])) {
|
||||
|
||||
$impressoesTriagem[] = [
|
||||
'value' => 'etiqueta',
|
||||
'text' => 'Etiqueta',
|
||||
'disabled' => false,
|
||||
'data' => $data['etiqueta']
|
||||
];
|
||||
}
|
||||
|
||||
$atendimento = Atendimento::where('id', $atendimentoId)
|
||||
->whereHas('faa.raat')
|
||||
->with(['faa.raat' => function ($query) {
|
||||
$query->latest('created_at')->limit(1);
|
||||
}])
|
||||
->first();
|
||||
|
||||
$tipoFormularioAcidenteTrabalho = TipoFormularioAcidenteTrabalho::AMBOS;
|
||||
|
||||
if ($atendimento) {
|
||||
$raat = $atendimento->faa->raat;
|
||||
$tipoFormularioAcidenteTrabalho = $raat->tipo_formulario_acidente_trabalho;
|
||||
}
|
||||
|
||||
$impressoesTriagem[] = [
|
||||
'value' => 'raat',
|
||||
'text' => 'RAAT',
|
||||
'disabled' => !$atendimento || ($tipoFormularioAcidenteTrabalho == TipoFormularioAcidenteTrabalho::CAT)
|
||||
];
|
||||
|
||||
$impressoesTriagem[] = [
|
||||
'value' => 'cat',
|
||||
'text' => 'CAT',
|
||||
'disabled' => !$atendimento || ($tipoFormularioAcidenteTrabalho == TipoFormularioAcidenteTrabalho::RAAT)
|
||||
];
|
||||
|
||||
$impressoesTriagem[] = [
|
||||
'value' => 'guiaEncaminhamento',
|
||||
'text' => 'Guia de Encaminhamento',
|
||||
'disabled' => AtendimentoTriagem::where('atendimento_id', $atendimentoId)->whereHas('encaminhamentos')->get()->isEmpty(),
|
||||
];
|
||||
|
||||
return $impressoesTriagem;
|
||||
}
|
||||
|
||||
public static function getImpressoesMedicoEnfermagem($atendimentoId)
|
||||
{
|
||||
|
||||
$atendimentosPrescricaoInterna = self::getAtendimentosPrescricaoInterna($atendimentoId);
|
||||
|
||||
return [
|
||||
[
|
||||
'value' => 'atestadoAcompanhante',
|
||||
'text' => 'Atestado - Acompanhante',
|
||||
'disabled' => self::getAtestadoAcompanhanteDisabled($atendimentoId)
|
||||
],
|
||||
[
|
||||
'value' => 'atestado',
|
||||
'text' => 'Atestado - Paciente',
|
||||
'disabled' => self::getAtestadoPacienteDisabled($atendimentoId)
|
||||
],
|
||||
[
|
||||
'value' => 'declaracaoAcompanhante',
|
||||
'text' => 'Declaração de Comparecimento - Acompanhante',
|
||||
'disabled' => self::getDeclaracaoAcompanhanteDisabled($atendimentoId)
|
||||
],
|
||||
[
|
||||
'value' => 'declaracaoPaciente',
|
||||
'text' => 'Declaração de Comparecimento - Paciente',
|
||||
'disabled' => self::getDeclaracaoPacienteDisabled($atendimentoId)
|
||||
],
|
||||
[
|
||||
'value' => 'encaminhamentoHospitalar',
|
||||
'text' => 'Encaminhamento Hospitalar',
|
||||
'disabled' => AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('encaminhamentoHospitalar')->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'examesImagem',
|
||||
'text' => 'Exames - Imagem',
|
||||
'disabled' => Atendimento::where('id', $atendimentoId)
|
||||
->whereHas('pedidosExames.exames.exame', function ($query) {
|
||||
|
||||
$query->where('tipo_id', Tipo::IMAGEM);
|
||||
})->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'examesLaboratorial',
|
||||
'text' => 'Exames - Laboratorial',
|
||||
'data' => [
|
||||
'atendimentos' => $atendimentosPrescricaoInterna,
|
||||
],
|
||||
'disabled' => Atendimento::where('id', $atendimentoId)
|
||||
->whereHas('pedidosExames.exames.exame', function ($query) {
|
||||
|
||||
$query->where('tipo_id', Tipo::LABORATORIAL);
|
||||
})->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'guiaEncaminhamento',
|
||||
'text' => 'Guia de Encaminhamento',
|
||||
'disabled' => AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('encaminhamentos')->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'orientacoesPaciente',
|
||||
'text' => 'Orientação ao paciente',
|
||||
'disabled' => AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereNotNull('orientacoes')->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'prescricaoInterna',
|
||||
'text' => 'Prescrição Interna',
|
||||
'data' => [
|
||||
'atendimentos' => $atendimentosPrescricaoInterna,
|
||||
],
|
||||
'disabled' => AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('prescricoesInternas')->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'receitaMedicaComum',
|
||||
'text' => 'Receita Médica - Comum',
|
||||
'disabled' => AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->where(function($query) {
|
||||
$query->whereHas('receita.medicamentos.medicamento', function ($query) {
|
||||
|
||||
$query->where('receita_tipo_id', TipoReceita::COMUM);
|
||||
})
|
||||
->orWhereHas('receita.medicamentos', function ($query) {
|
||||
|
||||
$query->whereNotNull('prescricao_manual');
|
||||
});
|
||||
})
|
||||
->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'receitaMedicaEspecial',
|
||||
'text' => 'Receita Médica - Especial',
|
||||
'disabled' => AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('receita.medicamentos.medicamento', function ($query) {
|
||||
|
||||
$query->whereIn('receita_tipo_id', [
|
||||
TipoReceita::ESPECIAL,
|
||||
TipoReceita::ESPECIAL_AMARELA,
|
||||
TipoReceita::ESPECIAL_AZUL
|
||||
]);
|
||||
})->get()->isEmpty()
|
||||
],
|
||||
[
|
||||
'value' => 'servicoEnfermagem',
|
||||
'text' => 'Serviços Enfermagem',
|
||||
'disabled' => ServicoEnfermagem::whereHas('atendimentoMedico', function ($query) use ($atendimentoId) {
|
||||
|
||||
$query->where('atendimento_id', $atendimentoId);
|
||||
})
|
||||
->orWhereHas('atendimentoEnfermagem', function ($query) use ($atendimentoId) {
|
||||
|
||||
$query->where('atendimento_id', $atendimentoId);
|
||||
})
|
||||
->orWhereHas('pacienteObservacao', function ($query) use ($atendimentoId) {
|
||||
|
||||
$query->where('atendimento_id', $atendimentoId);
|
||||
})
|
||||
->get()
|
||||
->isEmpty()
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public static function getAtendimentosPrescricaoInterna($atendimentoId)
|
||||
{
|
||||
|
||||
$atendimento = AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('prescricoesInternas')->get();
|
||||
|
||||
$resultados = $atendimento->map(function ($item) {
|
||||
$prescricoes = PrescricaoInterna::whereHas('atendimentoMedico', function ($query) use ($item) {
|
||||
$query->where('atendimento_medico_id', $item->id);
|
||||
})->get();
|
||||
|
||||
$dadosPrescricoes = $prescricoes->map(function ($prescricao) {
|
||||
|
||||
return [
|
||||
'id' => $prescricao->id,
|
||||
];
|
||||
});
|
||||
|
||||
return [
|
||||
'tipo' => 'prescricao',
|
||||
'value' => 'prescricao_' . $item->id,
|
||||
'id' => $item->id,
|
||||
'nome' => $item->plantao->lotacao->usuario->nome ?? null,
|
||||
'data_hora' => $item->created_at,
|
||||
'data' => $item->created_at->format('d/m/Y'),
|
||||
'hora' => $item->created_at->format('H:i'),
|
||||
'nova_prescricao' => $dadosPrescricoes,
|
||||
];
|
||||
})
|
||||
->sortBy('data_hora')
|
||||
->values()
|
||||
->map(function ($atendimento, $i) {
|
||||
|
||||
$atendimento['text'] = ++$i . 'º Atendimento - ' . $atendimento['nome'] . ' - ' . $atendimento['data'] . ' ás ' . $atendimento['hora'];
|
||||
|
||||
unset($atendimento['data_hora']);
|
||||
|
||||
return $atendimento;
|
||||
})
|
||||
->all();
|
||||
|
||||
return $resultados;
|
||||
}
|
||||
|
||||
public static function getDeclaracaoPacienteDisabled($atendimentoId) {
|
||||
|
||||
return
|
||||
AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('declaracoesComparecimento', function ($query) {
|
||||
|
||||
$query->where('tipo_id', DeclaracaoComparecimentoTipo::PACIENTE);
|
||||
})->get()->isEmpty()
|
||||
|
||||
&& AtendimentoEnfermagem::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('declaracoesComparecimento', function ($query) {
|
||||
|
||||
$query->where('tipo_id', DeclaracaoComparecimentoTipo::PACIENTE);
|
||||
})->get()->isEmpty()
|
||||
|
||||
&& AtendimentoTriagem::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('declaracoesComparecimento', function ($query) {
|
||||
|
||||
$query->where('tipo_id', DeclaracaoComparecimentoTipo::PACIENTE);
|
||||
})->get()->isEmpty()
|
||||
|
||||
&& PacienteObservacao::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('declaracoesComparecimento', function ($query) {
|
||||
|
||||
$query->where('tipo_id', DeclaracaoComparecimentoTipo::PACIENTE);
|
||||
})->get()->isEmpty()
|
||||
|
||||
&& AtendimentoExameImagem::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('declaracoesComparecimento', function ($query) {
|
||||
|
||||
$query->where('tipo_id', DeclaracaoComparecimentoTipo::PACIENTE);
|
||||
})->get()->isEmpty()
|
||||
|
||||
&& Recepcao::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('declaracoesComparecimento', function ($query) {
|
||||
|
||||
$query->where('tipo_id', DeclaracaoComparecimentoTipo::PACIENTE);
|
||||
})->get()->isEmpty() ? true : false;
|
||||
}
|
||||
|
||||
public static function getAtestadoAcompanhanteDisabled($atendimentoId)
|
||||
{
|
||||
return
|
||||
!Atestado::whereHas('atendimentoMedico', fn ($q) => $q->where('atendimento_id', $atendimentoId))
|
||||
->where('paciente', false)
|
||||
->exists();
|
||||
}
|
||||
|
||||
public static function getAtestadoPacienteDisabled($atendimentoId)
|
||||
{
|
||||
return
|
||||
!Atestado::whereHas('atendimentoMedico', fn ($q) => $q->where('atendimento_id', $atendimentoId))
|
||||
->where('paciente', true)
|
||||
->exists();
|
||||
}
|
||||
|
||||
public static function getDeclaracaoAcompanhanteDisabled($atendimentoId)
|
||||
{
|
||||
|
||||
return
|
||||
AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('declaracoesComparecimento', function ($query) {
|
||||
|
||||
$query->where('tipo_id', DeclaracaoComparecimentoTipo::ACOMPANHANTE);
|
||||
})->get()->isEmpty()
|
||||
|
||||
&& AtendimentoEnfermagem::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('declaracoesComparecimento', function ($query) {
|
||||
|
||||
$query->where('tipo_id', DeclaracaoComparecimentoTipo::ACOMPANHANTE);
|
||||
})->get()->isEmpty()
|
||||
|
||||
&& AtendimentoTriagem::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('declaracoesComparecimento', function ($query) {
|
||||
|
||||
$query->where('tipo_id', DeclaracaoComparecimentoTipo::ACOMPANHANTE);
|
||||
})->get()->isEmpty()
|
||||
|
||||
&& PacienteObservacao::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('declaracoesComparecimento', function ($query) {
|
||||
|
||||
$query->where('tipo_id', DeclaracaoComparecimentoTipo::ACOMPANHANTE);
|
||||
})->get()->isEmpty()
|
||||
|
||||
&& AtendimentoExameImagem::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('declaracoesComparecimento', function ($query) {
|
||||
|
||||
$query->where('tipo_id', DeclaracaoComparecimentoTipo::ACOMPANHANTE);
|
||||
})->get()->isEmpty()
|
||||
|
||||
&& Recepcao::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('declaracoesComparecimento', function ($query) {
|
||||
|
||||
$query->where('tipo_id', DeclaracaoComparecimentoTipo::ACOMPANHANTE);
|
||||
})->get()->isEmpty() ? true : false;
|
||||
}
|
||||
|
||||
public static function getImpressoesFaa($atendimentoId)
|
||||
{
|
||||
$atendimentosObservacao = self::getAtendimentosObservacao($atendimentoId);
|
||||
|
||||
return [
|
||||
[
|
||||
'value' => 'simplificada',
|
||||
'text' => 'Simplificada',
|
||||
'disabled' => false
|
||||
],
|
||||
[
|
||||
'value' => 'completa',
|
||||
'text' => 'Completa',
|
||||
'disabled' => false
|
||||
],
|
||||
[
|
||||
'value' => 'eletronica',
|
||||
'text' => 'Eletrônica',
|
||||
'disabled' => false
|
||||
],
|
||||
[
|
||||
'value' => 'eletronicaObservacao',
|
||||
'text' => 'Eletrônica (Paciente em observação)',
|
||||
'disabled' => empty($atendimentosObservacao),
|
||||
'data' => [
|
||||
'atendimentos' => $atendimentosObservacao,
|
||||
]
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
public static function getAtendimentosObservacao($atendimentoId)
|
||||
{
|
||||
$atendimento = Atendimento::findOrFail($atendimentoId);
|
||||
|
||||
return collect(array_merge(
|
||||
$atendimento->atendimentosMedico()
|
||||
->where('is_observacao', true)
|
||||
->get()
|
||||
->map(fn ($atendimento) => [
|
||||
'tipo' => 'medico',
|
||||
'value' => 'medico_' . $atendimento->id,
|
||||
'id' => $atendimento->id,
|
||||
'data_hora' => $atendimento->created_at,
|
||||
])->all(),
|
||||
$atendimento->atendimentosExameImagem()
|
||||
->where('is_observacao', true)
|
||||
->get()
|
||||
->map(fn ($atendimento) => [
|
||||
'tipo' => 'exame_imagem',
|
||||
'value' => 'exame_imagem_' . $atendimento->id,
|
||||
'id' => $atendimento->id,
|
||||
'data_hora' => $atendimento->created_at,
|
||||
])->all(),
|
||||
$atendimento->pacienteObservacoes
|
||||
->map(fn ($atendimento) => [
|
||||
'tipo' => 'observacao',
|
||||
'value' => 'observacao_' . $atendimento->id,
|
||||
'id' => $atendimento->id,
|
||||
'data_hora' => $atendimento->created_at,
|
||||
])->all(),
|
||||
))
|
||||
->sortBy('data_hora')
|
||||
->values()
|
||||
->map(function ($atendimento, $i) {
|
||||
|
||||
$atendimento['text'] = ++$i . 'º Atendimento';
|
||||
|
||||
unset($atendimento['data_hora']);
|
||||
|
||||
return $atendimento;
|
||||
})
|
||||
->all();
|
||||
}
|
||||
|
||||
private static function validateDatatableRequest($request)
|
||||
{
|
||||
$minDate = Carbon::now()->subYears(130)->format('Y-m-d');
|
||||
|
||||
$request->validate([
|
||||
'periodo.start' => [
|
||||
'required',
|
||||
'date_format:d/m/Y',
|
||||
"after_or_equal:{$minDate}",
|
||||
'before_or_equal:periodo.end',
|
||||
],
|
||||
'periodo.end' => [
|
||||
'required',
|
||||
'date_format:d/m/Y',
|
||||
'after_or_equal:periodo.start',
|
||||
'before_or_equal:now',
|
||||
],
|
||||
'sexo_id' => [
|
||||
'nullable',
|
||||
'integer',
|
||||
],
|
||||
'paciente' => [
|
||||
'nullable',
|
||||
'string',
|
||||
],
|
||||
'data_nascimento' => [
|
||||
'nullable',
|
||||
'date_format:d/m/Y',
|
||||
],
|
||||
'faa' => [
|
||||
'nullable',
|
||||
'integer',
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public static function faturarEnfermagem($request)
|
||||
{
|
||||
return (new AtendimentoEnfermagemController())->faturarProcedimentosAutomaticamente($request);
|
||||
}
|
||||
|
||||
public static function getAtendimentosExameLaboratorial($atendimentoId)
|
||||
{
|
||||
|
||||
$atendimento = AtendimentoMedico::where('atendimento_id', $atendimentoId)
|
||||
->whereHas('prescricoesInternas')->get();
|
||||
|
||||
$resultados = $atendimento->map(function ($item) {
|
||||
$prescricoes = PrescricaoInterna::whereHas('atendimentoMedico', function ($query) use ($item) {
|
||||
$query->where('atendimento_medico_id', $item->id);
|
||||
})->get();
|
||||
|
||||
$dadosPrescricoes = $prescricoes->map(function ($prescricao) {
|
||||
|
||||
return [
|
||||
'id' => $prescricao->id,
|
||||
];
|
||||
});
|
||||
|
||||
return [
|
||||
'tipo' => 'prescricao',
|
||||
'value' => 'prescricao_' . $item->id,
|
||||
'id' => $item->id,
|
||||
'nome' => $item->plantao->lotacao->usuario->nome,
|
||||
'data_hora' => $item->created_at,
|
||||
'data' => $item->created_at->format('d/m/Y'),
|
||||
'hora' => $item->created_at->format('H:i'),
|
||||
'nova_prescricao' => $dadosPrescricoes,
|
||||
];
|
||||
})
|
||||
->sortBy('data_hora')
|
||||
->values()
|
||||
->map(function ($atendimento, $i) {
|
||||
|
||||
$atendimento['text'] = ++$i . 'º Atendimento - ' . $atendimento['nome'] . ' - ' . $atendimento['data'] . ' ás ' . $atendimento['hora'];
|
||||
|
||||
unset($atendimento['data_hora']);
|
||||
|
||||
return $atendimento;
|
||||
})
|
||||
->all();
|
||||
|
||||
return $resultados;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento\PedidoExame;
|
||||
use App\Models\ProntoAtendimento\PedidoExame\Laudo;
|
||||
use App\Services\Service;
|
||||
|
||||
class LaudoService extends Service
|
||||
{
|
||||
public function storeFile($pedido, $files, $additionalsParams = [])
|
||||
{
|
||||
foreach (['pedido_exame_id', 'hash', 'nome'] as $field) {
|
||||
|
||||
if (array_key_exists($field, $additionalsParams)) {
|
||||
|
||||
unset($additionalsParams[$field]);
|
||||
}
|
||||
}
|
||||
|
||||
$path = storage_path( 'pronto-atendimento'
|
||||
. DIRECTORY_SEPARATOR
|
||||
. 'laudos'
|
||||
. DIRECTORY_SEPARATOR
|
||||
. app('config')->get('database.default')
|
||||
. DIRECTORY_SEPARATOR
|
||||
. $pedido->id
|
||||
);
|
||||
|
||||
if($files)
|
||||
{
|
||||
foreach($files as $file)
|
||||
{
|
||||
$data = (new \DateTime)->getTimestamp();
|
||||
$extensao = $file->extension();
|
||||
$arquivo = encrypt($data) . '.' . $extensao;
|
||||
$request['hash'] = $arquivo;
|
||||
$request['nome'] = mb_strtoupper($file->getClientOriginalName());
|
||||
$file->move($path, $arquivo);
|
||||
|
||||
Laudo::create(array_merge([
|
||||
'pedido_exame_id' => $pedido->id,
|
||||
'hash' => $request['hash'],
|
||||
'nome' => $request['nome']
|
||||
], $additionalsParams));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function destroy($id)
|
||||
{
|
||||
return Laudo::findOrFail($id)->delete();
|
||||
}
|
||||
|
||||
public function download($id, string $hash)
|
||||
{
|
||||
$laudo = Laudo::findOrFail($id);
|
||||
|
||||
$path = storage_path( 'pronto-atendimento'
|
||||
. DIRECTORY_SEPARATOR
|
||||
. 'laudos'
|
||||
. DIRECTORY_SEPARATOR
|
||||
. app('config')->get('database.default')
|
||||
. DIRECTORY_SEPARATOR
|
||||
. $laudo->pedido_exame_id
|
||||
. DIRECTORY_SEPARATOR
|
||||
) . $hash;
|
||||
|
||||
$headers = [
|
||||
'Content-Type' => 'application/pdf',
|
||||
];
|
||||
|
||||
return [
|
||||
'path' => $path,
|
||||
'nome' => $laudo->nome,
|
||||
'headers' => $headers
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,667 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento\Plantao;
|
||||
|
||||
use App\Enums\Cadastro\Estabelecimento\Servico;
|
||||
use App\Services\Service;
|
||||
use Carbon\Carbon;
|
||||
use DateInterval;
|
||||
use DateTime;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class RelatorioPlantaoService extends Service
|
||||
{
|
||||
public static function index()
|
||||
{
|
||||
$params = request()->all();
|
||||
|
||||
$plantoesBuilder = self::getPlantoesBuilder();
|
||||
|
||||
if (!$plantoesBuilder) {
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$plantoesBuilder = $plantoesBuilder
|
||||
->select(
|
||||
'pronto_atendimento_plantao.id',
|
||||
'pronto_atendimento_plantao.inicio',
|
||||
'pronto_atendimento_plantao.fim',
|
||||
'pronto_atendimento_plantao.servico_id',
|
||||
'pronto_atendimento_plantao.lotacao_id',
|
||||
'cadastro_unidade.nome_fantasia',
|
||||
'cadastro_infraestrutura.nome as local_atendimento',
|
||||
'cadastro_infraestrutura.principal as infra_principal',
|
||||
'sigtap.ocupacao.nome as especialidade',
|
||||
'cadastro_usuario.id as profissional_id',
|
||||
'cadastro_cidadao.nome as profissional',
|
||||
);
|
||||
|
||||
return $plantoesBuilder
|
||||
->orderBy('pronto_atendimento_plantao.inicio')
|
||||
->get()
|
||||
->map(function ($plantao) use ($plantoesBuilder, $params) {
|
||||
|
||||
$localAtendimento = $plantao->infra_principal ? $plantao->nome_fantasia : $plantao->local_atendimento;
|
||||
$start = Carbon::createFromFormat('Y-m-d H:i:s', $plantao->inicio);
|
||||
$end = Carbon::createFromFormat('Y-m-d H:i:s', $plantao->fim);
|
||||
|
||||
$plantoes = $plantoesBuilder->get();
|
||||
|
||||
$horasTrabalhadas = self::getHorasTrabalhadas($params, $plantoes, $plantao->id);
|
||||
$horasPeriodo = self::getStringHorasFromDiff($params, $start->diff($end));
|
||||
$horasTotal = self::getHorasTotal($params, $plantoes, $plantao->profissional_id);
|
||||
$primeiroAtendimento = self::getPrimeiroAtendimento($plantao);
|
||||
$ultimoAtendimento = self::getUltimoAtendimento($plantao);
|
||||
$ultimoAtendimento = self::getUltimoAtendimento($plantao);
|
||||
$quantidadeAtendimentos = self::getQuantidadeAtendimentos($plantao);
|
||||
$totalAtendimentos = self::getTotalAtendimentos($params, $plantao);
|
||||
|
||||
return [
|
||||
'start' => $start->format('d/m/Y H:i:s'),
|
||||
'end' => $end->format('d/m/Y H:i:s'),
|
||||
'nome_fantasia' => $plantao->nome_fantasia,
|
||||
'local_atendimento' => $localAtendimento,
|
||||
'especialidade' => $plantao->especialidade,
|
||||
'profissional' => $plantao->profissional,
|
||||
'horas_periodo' => $horasPeriodo,
|
||||
'horas_trabalhadas' => $horasTrabalhadas,
|
||||
'horas_total' => $horasTotal,
|
||||
'hora_primeiro_atendimento' => $primeiroAtendimento->horario ?? '-',
|
||||
'hora_ultimo_atendimento' => $ultimoAtendimento->horario ?? '-',
|
||||
'quantidade_atendimento' => $quantidadeAtendimentos,
|
||||
'total_atendimento' => $totalAtendimentos,
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
public static function getPrimeiroAtendimento($plantao) {
|
||||
|
||||
if ($plantao->servico_id == Servico::CONSULTA_MEDICA) {
|
||||
|
||||
return DB::table('pronto_atendimento_atendimento_medico')
|
||||
->select(DB::raw('DATE_FORMAT(painel_senha_fila_historico.created_at, "%d/%m/%Y %H:%i:%s") as horario'))
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_atendimento_medico.atendimento_id')
|
||||
->join('painel_senha_fila_historico', function ($join) {
|
||||
$join->on('painel_senha_fila_historico.fila_id', '=', 'pronto_atendimento_atendimento.fila_id')
|
||||
->on('painel_senha_fila_historico.created_lotacao_id', '=', 'pronto_atendimento_atendimento_medico.created_lotacao_id')
|
||||
->on('painel_senha_fila_historico.centro_custo_id', '=', 'pronto_atendimento_atendimento_medico.created_centro_custo_id');
|
||||
})
|
||||
->where('pronto_atendimento_atendimento_medico.plantao_id', $plantao->id)
|
||||
->orderBy('painel_senha_fila_historico.created_at', 'asc')
|
||||
->first();
|
||||
|
||||
} else if ($plantao->servico_id == Servico::ENFERMAGEM) {
|
||||
|
||||
$consultaEnfermagem = DB::table('pronto_atendimento_atendimento_enfermagem')
|
||||
->select(DB::raw('DATE_FORMAT(painel_senha_fila_historico.created_at, "%d/%m/%Y %H:%i:%s") as horario'))
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_atendimento_enfermagem.atendimento_id')
|
||||
->join('painel_senha_fila_historico', function ($join) {
|
||||
$join->on('painel_senha_fila_historico.fila_id', '=', 'pronto_atendimento_atendimento.fila_id')
|
||||
->on('painel_senha_fila_historico.created_lotacao_id', '=', 'pronto_atendimento_atendimento_enfermagem.created_lotacao_id')
|
||||
->on('painel_senha_fila_historico.centro_custo_id', '=', 'pronto_atendimento_atendimento_enfermagem.created_centro_custo_id');
|
||||
})
|
||||
->where('plantao_id', $plantao->id);
|
||||
|
||||
$consultaTriagem = DB::table('pronto_atendimento_atendimento_triagem')
|
||||
->select(DB::raw('DATE_FORMAT(painel_senha_fila_historico.created_at, "%d/%m/%Y %H:%i:%s") as horario'))
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_atendimento_triagem.atendimento_id')
|
||||
->join('painel_senha_fila_historico', function ($join) {
|
||||
$join->on('painel_senha_fila_historico.fila_id', '=', 'pronto_atendimento_atendimento.fila_id')
|
||||
->on('painel_senha_fila_historico.created_lotacao_id', '=', 'pronto_atendimento_atendimento_triagem.created_lotacao_id')
|
||||
->on('painel_senha_fila_historico.centro_custo_id', '=', 'pronto_atendimento_atendimento_triagem.created_centro_custo_id');
|
||||
})
|
||||
->where('plantao_id', $plantao->id);
|
||||
|
||||
$consultaObservacao = DB::table('pronto_atendimento_paciente_observacao')
|
||||
->select(DB::raw('DATE_FORMAT(painel_senha_fila_historico.created_at, "%d/%m/%Y %H:%i:%s") as horario'))
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_paciente_observacao.atendimento_id')
|
||||
->join('painel_senha_fila_historico', function ($join) {
|
||||
$join->on('painel_senha_fila_historico.fila_id', '=', 'pronto_atendimento_atendimento.fila_id')
|
||||
->on('painel_senha_fila_historico.created_lotacao_id', '=', 'pronto_atendimento_paciente_observacao.created_lotacao_id')
|
||||
->on('painel_senha_fila_historico.centro_custo_id', '=', 'pronto_atendimento_paciente_observacao.created_centro_custo_id');
|
||||
})
|
||||
->where('plantao_id', $plantao->id);
|
||||
|
||||
return $consultaEnfermagem
|
||||
->union($consultaTriagem)
|
||||
->union($consultaObservacao)
|
||||
->orderBy('horario', 'asc')
|
||||
->first();
|
||||
|
||||
} else if ($plantao->servico_id == Servico::EXAME_RAIO_X) {
|
||||
|
||||
return DB::table('pronto_atendimento_pedido_exame')
|
||||
->select(
|
||||
DB::raw('DATE_FORMAT(painel_senha_fila_historico.created_at, "%d/%m/%Y %H:%i:%s") as horario')
|
||||
)
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_pedido_exame.atendimento_id')
|
||||
->join('pronto_atendimento_plantao', 'pronto_atendimento_plantao.id', 'pronto_atendimento_pedido_exame.plantao_id')
|
||||
->join('painel_senha_fila_historico', function ($join) {
|
||||
$join->on('painel_senha_fila_historico.fila_id', '=', 'pronto_atendimento_atendimento.fila_id')
|
||||
->on('painel_senha_fila_historico.created_lotacao_id', '=', 'pronto_atendimento_plantao.lotacao_id');
|
||||
})
|
||||
->where('pronto_atendimento_pedido_exame.plantao_id', $plantao->id)
|
||||
->orderBy('painel_senha_fila_historico.created_at', 'asc')
|
||||
->first();
|
||||
} else if ($plantao->servico_id == Servico::NAO_SE_APLICA) {
|
||||
|
||||
return DB::table('pronto_atendimento_atendimento_recepcao')
|
||||
->select(DB::raw('DATE_FORMAT(painel_senha_fila_historico.created_at, "%d/%m/%Y %H:%i:%s") as horario'))
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_atendimento_recepcao.atendimento_id')
|
||||
->join('painel_senha_fila_historico', function ($join) {
|
||||
$join->on('painel_senha_fila_historico.fila_id', '=', 'pronto_atendimento_atendimento.fila_id')
|
||||
->on('painel_senha_fila_historico.created_lotacao_id', '=', 'pronto_atendimento_atendimento_recepcao.created_lotacao_id')
|
||||
->on('painel_senha_fila_historico.centro_custo_id', '=', 'pronto_atendimento_atendimento_recepcao.created_centro_custo_id');
|
||||
})
|
||||
->where('plantao_id', $plantao->id)
|
||||
->orderBy('painel_senha_fila_historico.created_at', 'asc')
|
||||
->first();
|
||||
}
|
||||
}
|
||||
|
||||
public static function getUltimoAtendimento($plantao) {
|
||||
|
||||
if ($plantao->servico_id == Servico::CONSULTA_MEDICA) {
|
||||
|
||||
return DB::table('pronto_atendimento_atendimento_medico')
|
||||
->select(DB::raw('DATE_FORMAT(painel_senha_fila_historico.created_at, "%d/%m/%Y %H:%i:%s") as horario'))
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_atendimento_medico.atendimento_id')
|
||||
->join('painel_senha_fila_historico', function ($join) {
|
||||
$join->on('painel_senha_fila_historico.fila_id', '=', 'pronto_atendimento_atendimento.fila_id')
|
||||
->on('painel_senha_fila_historico.created_lotacao_id', '=', 'pronto_atendimento_atendimento_medico.created_lotacao_id')
|
||||
->on('painel_senha_fila_historico.centro_custo_id', '=', 'pronto_atendimento_atendimento_medico.created_centro_custo_id');
|
||||
})
|
||||
->where('pronto_atendimento_atendimento_medico.plantao_id', $plantao->id)
|
||||
->orderBy('painel_senha_fila_historico.created_at', 'desc')
|
||||
->first();
|
||||
|
||||
} else if ($plantao->servico_id == Servico::ENFERMAGEM) {
|
||||
|
||||
$consultaEnfermagem = DB::table('pronto_atendimento_atendimento_enfermagem')
|
||||
->select(DB::raw('DATE_FORMAT(painel_senha_fila_historico.created_at, "%d/%m/%Y %H:%i:%s") as horario'))
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_atendimento_enfermagem.atendimento_id')
|
||||
->join('painel_senha_fila_historico', function ($join) {
|
||||
$join->on('painel_senha_fila_historico.fila_id', '=', 'pronto_atendimento_atendimento.fila_id')
|
||||
->on('painel_senha_fila_historico.created_lotacao_id', '=', 'pronto_atendimento_atendimento_enfermagem.created_lotacao_id')
|
||||
->on('painel_senha_fila_historico.centro_custo_id', '=', 'pronto_atendimento_atendimento_enfermagem.created_centro_custo_id');
|
||||
})
|
||||
->where('plantao_id', $plantao->id);
|
||||
|
||||
$consultaTriagem = DB::table('pronto_atendimento_atendimento_triagem')
|
||||
->select(DB::raw('DATE_FORMAT(painel_senha_fila_historico.created_at, "%d/%m/%Y %H:%i:%s") as horario'))
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_atendimento_triagem.atendimento_id')
|
||||
->join('painel_senha_fila_historico', function ($join) {
|
||||
$join->on('painel_senha_fila_historico.fila_id', '=', 'pronto_atendimento_atendimento.fila_id')
|
||||
->on('painel_senha_fila_historico.created_lotacao_id', '=', 'pronto_atendimento_atendimento_triagem.created_lotacao_id')
|
||||
->on('painel_senha_fila_historico.centro_custo_id', '=', 'pronto_atendimento_atendimento_triagem.created_centro_custo_id');
|
||||
})
|
||||
->where('plantao_id', $plantao->id);
|
||||
|
||||
$consultaObservacao = DB::table('pronto_atendimento_paciente_observacao')
|
||||
->select(DB::raw('DATE_FORMAT(painel_senha_fila_historico.created_at, "%d/%m/%Y %H:%i:%s") as horario'))
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_paciente_observacao.atendimento_id')
|
||||
->join('painel_senha_fila_historico', function ($join) {
|
||||
$join->on('painel_senha_fila_historico.fila_id', '=', 'pronto_atendimento_atendimento.fila_id')
|
||||
->on('painel_senha_fila_historico.created_lotacao_id', '=', 'pronto_atendimento_paciente_observacao.created_lotacao_id')
|
||||
->on('painel_senha_fila_historico.centro_custo_id', '=', 'pronto_atendimento_paciente_observacao.created_centro_custo_id');
|
||||
})
|
||||
->where('plantao_id', $plantao->id);
|
||||
|
||||
return $consultaEnfermagem
|
||||
->union($consultaTriagem)
|
||||
->union($consultaObservacao)
|
||||
->orderBy('horario', 'desc')
|
||||
->first();
|
||||
|
||||
} else if ($plantao->servico_id == Servico::EXAME_RAIO_X) {
|
||||
|
||||
return DB::table('pronto_atendimento_pedido_exame')
|
||||
->select(
|
||||
DB::raw('DATE_FORMAT(painel_senha_fila_historico.created_at, "%d/%m/%Y %H:%i:%s") as horario')
|
||||
)
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_pedido_exame.atendimento_id')
|
||||
->join('pronto_atendimento_plantao', 'pronto_atendimento_plantao.id', 'pronto_atendimento_pedido_exame.plantao_id')
|
||||
->join('painel_senha_fila_historico', function ($join) {
|
||||
$join->on('painel_senha_fila_historico.fila_id', '=', 'pronto_atendimento_atendimento.fila_id')
|
||||
->on('painel_senha_fila_historico.created_lotacao_id', '=', 'pronto_atendimento_plantao.lotacao_id');
|
||||
})
|
||||
->where('pronto_atendimento_pedido_exame.plantao_id', $plantao->id)
|
||||
->orderBy('painel_senha_fila_historico.created_at', 'desc')
|
||||
->first();
|
||||
} else if ($plantao->servico_id == Servico::NAO_SE_APLICA) {
|
||||
|
||||
return DB::table('pronto_atendimento_atendimento_recepcao')
|
||||
->select(DB::raw('DATE_FORMAT(painel_senha_fila_historico.created_at, "%d/%m/%Y %H:%i:%s") as horario'))
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_atendimento_recepcao.atendimento_id')
|
||||
->join('painel_senha_fila_historico', function ($join) {
|
||||
$join->on('painel_senha_fila_historico.fila_id', '=', 'pronto_atendimento_atendimento.fila_id')
|
||||
->on('painel_senha_fila_historico.created_lotacao_id', '=', 'pronto_atendimento_atendimento_recepcao.created_lotacao_id')
|
||||
->on('painel_senha_fila_historico.centro_custo_id', '=', 'pronto_atendimento_atendimento_recepcao.created_centro_custo_id');
|
||||
})
|
||||
->where('plantao_id', $plantao->id)
|
||||
->orderBy('painel_senha_fila_historico.created_at', 'desc')
|
||||
->first();
|
||||
}
|
||||
}
|
||||
|
||||
public static function getQuantidadeAtendimentos($plantao) {
|
||||
|
||||
if ($plantao->servico_id == Servico::CONSULTA_MEDICA) {
|
||||
|
||||
return DB::table('pronto_atendimento_atendimento_medico')
|
||||
->where('pronto_atendimento_atendimento_medico.plantao_id', $plantao->id)
|
||||
->count();
|
||||
} else if ($plantao->servico_id == Servico::ENFERMAGEM) {
|
||||
|
||||
$consultaEnfermagem = DB::table('pronto_atendimento_atendimento_enfermagem')
|
||||
->where('plantao_id', $plantao->id);
|
||||
|
||||
$consultaTriagem = DB::table('pronto_atendimento_atendimento_triagem')
|
||||
->where('plantao_id', $plantao->id);
|
||||
|
||||
$consultaObservacao = DB::table('pronto_atendimento_paciente_observacao')
|
||||
->where('plantao_id', $plantao->id);
|
||||
|
||||
return $consultaEnfermagem->count() + $consultaTriagem->count() + $consultaObservacao->count();
|
||||
} else if ($plantao->servico_id == Servico::EXAME_RAIO_X) {
|
||||
|
||||
return DB::table('pronto_atendimento_pedido_exame')
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_pedido_exame.atendimento_id')
|
||||
->join('pronto_atendimento_plantao', 'pronto_atendimento_plantao.id', 'pronto_atendimento_pedido_exame.plantao_id')
|
||||
->join('painel_senha_fila_historico', function ($join) {
|
||||
$join->on('painel_senha_fila_historico.fila_id', '=', 'pronto_atendimento_atendimento.fila_id')
|
||||
->on('painel_senha_fila_historico.created_lotacao_id', '=', 'pronto_atendimento_plantao.lotacao_id');
|
||||
})
|
||||
->where('pronto_atendimento_pedido_exame.plantao_id', $plantao->id)
|
||||
->count();
|
||||
} else if ($plantao->servico_id == Servico::NAO_SE_APLICA) {
|
||||
|
||||
return DB::table('pronto_atendimento_atendimento_recepcao')
|
||||
->where('plantao_id', $plantao->id)
|
||||
->count();
|
||||
}
|
||||
}
|
||||
|
||||
public static function getTotalAtendimentos($params, $plantao) {
|
||||
|
||||
$startEndDateTimeInCarbon = self::getStartEndDateTimeInCarbon($params);
|
||||
|
||||
$start = $startEndDateTimeInCarbon['start'];
|
||||
$end = $startEndDateTimeInCarbon['end'];
|
||||
|
||||
if ($plantao->servico_id == Servico::CONSULTA_MEDICA) {
|
||||
|
||||
return DB::table('pronto_atendimento_atendimento_medico')
|
||||
->whereBetween('pronto_atendimento_atendimento_medico.created_at', [$start, $end])
|
||||
->where('pronto_atendimento_atendimento_medico.created_lotacao_id', $plantao->lotacao_id)
|
||||
->count();
|
||||
} else if ($plantao->servico_id == Servico::ENFERMAGEM) {
|
||||
|
||||
$consultaEnfermagem = DB::table('pronto_atendimento_atendimento_enfermagem')
|
||||
->whereBetween('pronto_atendimento_atendimento_enfermagem.created_at', [$start, $end])
|
||||
->where('pronto_atendimento_atendimento_enfermagem.created_lotacao_id', $plantao->lotacao_id);
|
||||
|
||||
$consultaTriagem = DB::table('pronto_atendimento_atendimento_triagem')
|
||||
->whereBetween('pronto_atendimento_atendimento_triagem.created_at', [$start, $end])
|
||||
->where('pronto_atendimento_atendimento_triagem.created_lotacao_id', $plantao->lotacao_id);
|
||||
|
||||
$consultaObservacao = DB::table('pronto_atendimento_paciente_observacao')
|
||||
->whereBetween('pronto_atendimento_paciente_observacao.created_at', [$start, $end])
|
||||
->where('pronto_atendimento_paciente_observacao.created_lotacao_id', $plantao->lotacao_id);
|
||||
|
||||
return $consultaEnfermagem->count() + $consultaTriagem->count() + $consultaObservacao->count();
|
||||
} else if ($plantao->servico_id == Servico::EXAME_RAIO_X) {
|
||||
|
||||
return DB::table('pronto_atendimento_pedido_exame')
|
||||
->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_pedido_exame.atendimento_id')
|
||||
->join('pronto_atendimento_plantao', 'pronto_atendimento_plantao.id', 'pronto_atendimento_pedido_exame.plantao_id')
|
||||
->join('painel_senha_fila_historico', function ($join) {
|
||||
$join->on('painel_senha_fila_historico.fila_id', '=', 'pronto_atendimento_atendimento.fila_id')
|
||||
->on('painel_senha_fila_historico.created_lotacao_id', '=', 'pronto_atendimento_plantao.lotacao_id');
|
||||
})
|
||||
->whereBetween('painel_senha_fila_historico.created_at', [$start, $end])
|
||||
->where('painel_senha_fila_historico.created_lotacao_id', $plantao->lotacao_id)
|
||||
->count();
|
||||
} else if ($plantao->servico_id == Servico::NAO_SE_APLICA) {
|
||||
|
||||
return DB::table('pronto_atendimento_atendimento_recepcao')
|
||||
->whereBetween('pronto_atendimento_atendimento_recepcao.created_at', [$start, $end])
|
||||
->where('pronto_atendimento_atendimento_recepcao.created_lotacao_id', $plantao->lotacao_id)
|
||||
->count();
|
||||
}
|
||||
}
|
||||
|
||||
public static function getHorarioFim($plantao) {
|
||||
|
||||
return DB::table('pronto_atendimento_atendimento_recepcao')
|
||||
->select([
|
||||
'atendido_em',
|
||||
])
|
||||
->where('plantao_id', $plantao->id)
|
||||
->orderBy('atendido_em', 'desc')
|
||||
->first();
|
||||
}
|
||||
|
||||
public static function getHorasTrabalhadas($params, $plantoes, $plantaoId)
|
||||
{
|
||||
|
||||
$horasTrabalhadas = 0;
|
||||
|
||||
foreach($plantoes as $key => $plantao) {
|
||||
|
||||
if ($plantao->id !== $plantaoId) {
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$plantaoStart = Carbon::createFromFormat('Y-m-d H:i:s', $plantao->inicio);
|
||||
$plantaoEnd = Carbon::createFromFormat('Y-m-d H:i:s', $plantao->fim);
|
||||
|
||||
$totalMinutos = $plantaoStart->diffInMinutes($plantaoEnd);
|
||||
$horas = intdiv($totalMinutos, 60);
|
||||
$minutos = $totalMinutos % 60;
|
||||
|
||||
$horasTrabalhadas = sprintf('%02d:%02d', $horas, $minutos);
|
||||
}
|
||||
|
||||
return $horasTrabalhadas;
|
||||
}
|
||||
|
||||
public static function getHorasTotal($params, $plantoes, $profissionalId)
|
||||
{
|
||||
$startEndDateTimeInCarbon = self::getStartEndDateTimeInCarbon($params);
|
||||
$total = 0;
|
||||
$plantoes = $plantoes->sortBy('inicio');
|
||||
|
||||
$startToCalc = null;
|
||||
$endToCalc = null;
|
||||
|
||||
foreach($plantoes as $key => $plantao) {
|
||||
|
||||
if ($plantao->profissional_id != $profissionalId) {
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$plantaoStart = Carbon::createFromFormat('Y-m-d H:i:s', $plantao->inicio);
|
||||
$plantaoEnd = Carbon::createFromFormat('Y-m-d H:i:s', $plantao->fim);
|
||||
|
||||
$periodoStart = $startEndDateTimeInCarbon['start'];
|
||||
$periodoEnd = $startEndDateTimeInCarbon['end'];
|
||||
|
||||
$diffStart = round($periodoStart->floatDiffInMinutes($plantaoStart, false));
|
||||
$diffEnd = round($periodoEnd->floatDiffInMinutes($plantaoEnd, false));
|
||||
|
||||
if (is_null($startToCalc)) {
|
||||
|
||||
$startToCalc = $plantaoStart->copy();
|
||||
|
||||
if ($plantaoStart->format('d/m/Y') === $periodoStart->format('d/m/Y') && $diffStart < 0) {
|
||||
|
||||
$startToCalc = $periodoStart->copy();
|
||||
}
|
||||
}
|
||||
|
||||
if (is_null($endToCalc)) {
|
||||
|
||||
$endToCalc = $plantaoEnd->copy();
|
||||
|
||||
if ($plantaoEnd->format('d/m/Y') === $startEndDateTimeInCarbon['end']->format('d/m/Y') && $diffEnd > 0) {
|
||||
|
||||
$endToCalc = $startEndDateTimeInCarbon['end']->copy();
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
if ($plantaoEnd->format('d/m/Y') === $periodoEnd->format('d/m/Y') && $diffEnd > 0) {
|
||||
|
||||
$endToCalc->addMinutes($plantaoStart->floatDiffInMinutes($periodoEnd));
|
||||
|
||||
} else {
|
||||
|
||||
$endToCalc->addMinutes($plantaoStart->floatDiffInMinutes($plantaoEnd));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$horasTrabalhadas = $startToCalc->diff($endToCalc);
|
||||
|
||||
return self::getStringHorasFromDiff($params, $horasTrabalhadas);
|
||||
}
|
||||
|
||||
private static function getStringHorasFromDiff($params, $diff)
|
||||
{
|
||||
$startEndDateTimeInCarbon = self::getStartEndDateTimeInCarbon($params);
|
||||
|
||||
$daysOfYaer = $startEndDateTimeInCarbon['end']->isLeapYear() ? 366 : 365;
|
||||
$horas = ($diff->y * $daysOfYaer) + ($diff->m * 30) + ($diff->d * 24) + $diff->h;
|
||||
$minutos = $diff->i;
|
||||
|
||||
return str_pad($horas, 2, '0', STR_PAD_LEFT) . ':' . str_pad($minutos, 2, '0', STR_PAD_LEFT);
|
||||
}
|
||||
|
||||
public static function list()
|
||||
{
|
||||
return [
|
||||
'form' => self::getForm(),
|
||||
'model' => self::getModel(),
|
||||
'additionals' => [
|
||||
'data_atual' => Carbon::today()->format('d/m/Y'),
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
private static function getForm()
|
||||
{
|
||||
return [
|
||||
'unidades' => self::getUnidades(),
|
||||
'locais_atendimento' => self::getLocaisAtendimento(),
|
||||
'especialidades' => self::getEspecialidades(),
|
||||
'profissionais' => self::getProfissionais(),
|
||||
];
|
||||
}
|
||||
|
||||
private static function getUnidades()
|
||||
{
|
||||
$params = request()->all();
|
||||
$plantoesBuilder = self::getPlantoesBuilder();
|
||||
|
||||
if (!$plantoesBuilder) {
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
return $plantoesBuilder
|
||||
->select(
|
||||
'cadastro_unidade.id',
|
||||
'cadastro_unidade.nome_fantasia'
|
||||
)
|
||||
->distinct()
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function getLocaisAtendimento()
|
||||
{
|
||||
$params = request()->all();
|
||||
$plantoesBuilder = self::getPlantoesBuilder();
|
||||
|
||||
if (!$plantoesBuilder) {
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
$locaisAtendimento = $plantoesBuilder
|
||||
->select(
|
||||
'cadastro_unidade.id as unidade_id',
|
||||
'cadastro_unidade.nome_fantasia',
|
||||
'cadastro_infraestrutura.id',
|
||||
'cadastro_infraestrutura.nome',
|
||||
'cadastro_infraestrutura.principal'
|
||||
);
|
||||
|
||||
return $locaisAtendimento->distinct()
|
||||
->get()
|
||||
->map(function($query) {
|
||||
|
||||
$nome = $query->principal ? $query->nome_fantasia : $query->nome;
|
||||
|
||||
$collect = collect([
|
||||
'id' => $query->id,
|
||||
'unidade_id' => $query->unidade_id,
|
||||
'nome' => $nome,
|
||||
]);
|
||||
|
||||
return $collect->sortBy('nome');
|
||||
});
|
||||
}
|
||||
|
||||
private static function getEspecialidades()
|
||||
{
|
||||
$params = request()->all();
|
||||
$plantoesBuilder = self::getPlantoesBuilder();
|
||||
|
||||
if (!$plantoesBuilder) {
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
return $plantoesBuilder
|
||||
->select(
|
||||
'sigtap.ocupacao.id',
|
||||
'sigtap.ocupacao.nome'
|
||||
)
|
||||
->orderBy('nome')
|
||||
->distinct()
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function getProfissionais()
|
||||
{
|
||||
$params = request()->all();
|
||||
$plantoesBuilder = self::getPlantoesBuilder();
|
||||
|
||||
if (!$plantoesBuilder) {
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
return $plantoesBuilder
|
||||
->select(
|
||||
'cadastro_usuario.id',
|
||||
'cadastro_cidadao.nome'
|
||||
)
|
||||
->orderBy('nome')
|
||||
->distinct()
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function getPlantoesBuilder()
|
||||
{
|
||||
if (!request()->get('periodo')) {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$params = request()->all();
|
||||
|
||||
$startEndDateTimeInCarbon = self::getStartEndDateTimeInCarbon($params);
|
||||
|
||||
$inicio = $startEndDateTimeInCarbon['start'];
|
||||
$fim = $startEndDateTimeInCarbon['end'];
|
||||
|
||||
$unidadeId = $params['unidade_id'];
|
||||
$localAtendimentoId = $params['local_atendimento_id'];
|
||||
$especialidadeId = $params['especialidade_id'];
|
||||
$profissionalId = $params['profissional_id'];
|
||||
|
||||
$plantoes = DB::table('pronto_atendimento_plantao')
|
||||
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'pronto_atendimento_plantao.lotacao_id')
|
||||
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
|
||||
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
|
||||
->join('sigtap.ocupacao', 'sigtap.ocupacao.id', 'cadastro_lotacao.ocupacao_id')
|
||||
->join('cadastro_usuario', 'cadastro_usuario.id', 'cadastro_lotacao.usuario_id')
|
||||
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
|
||||
->whereNull('pronto_atendimento_plantao.deleted_at')
|
||||
->where(function ($query) use ($inicio, $fim) {
|
||||
|
||||
$query->whereBetween('inicio', [$inicio, $fim])
|
||||
->orWhereBetween('fim', [$inicio, $fim])
|
||||
->orWhere(function ($query) use ($inicio) {
|
||||
|
||||
$query->where('inicio', '<=', $inicio)
|
||||
->where('fim', '>=', $inicio);
|
||||
})
|
||||
->orWhere(function ($query) use ($fim) {
|
||||
|
||||
$query->where('inicio', '<=', $fim)
|
||||
->where('fim', '>=', $fim);
|
||||
});
|
||||
});
|
||||
|
||||
if (!is_null($unidadeId)) {
|
||||
|
||||
$plantoes->where('cadastro_unidade.id', $unidadeId);
|
||||
}
|
||||
|
||||
if (!is_null($localAtendimentoId)) {
|
||||
|
||||
$plantoes->where('cadastro_infraestrutura.id', $localAtendimentoId);
|
||||
}
|
||||
|
||||
if (!is_null($especialidadeId)) {
|
||||
|
||||
$plantoes->where('cadastro_lotacao.ocupacao_id', $especialidadeId);
|
||||
}
|
||||
|
||||
if (!is_null($profissionalId)) {
|
||||
|
||||
$plantoes->where('cadastro_lotacao.usuario_id', $profissionalId);
|
||||
}
|
||||
|
||||
return $plantoes;
|
||||
}
|
||||
|
||||
private static function getStartEndDateTimeInCarbon($params)
|
||||
{
|
||||
$startAt = $params['periodo']['time']['start'];
|
||||
if (empty($startAt)) {
|
||||
|
||||
$startAt = '00:00:00';
|
||||
}
|
||||
|
||||
$endsAt = $params['periodo']['time']['end'];
|
||||
if (empty($endsAt)) {
|
||||
|
||||
$endsAt = '23:59:00';
|
||||
}
|
||||
|
||||
$start = Carbon::createFromFormat('d/m/Y H:i:s', "{$params['periodo']['date']['start']} {$startAt}");
|
||||
$end = Carbon::createFromFormat('d/m/Y H:i:s', "{$params['periodo']['date']['end']} {$endsAt}");
|
||||
|
||||
return [
|
||||
'start' => $start,
|
||||
'end' => $end,
|
||||
];
|
||||
}
|
||||
|
||||
private static function getModel()
|
||||
{
|
||||
return [
|
||||
'periodo' => [
|
||||
'date' => [
|
||||
'start' => $params['periodo']['date']['start'] ?? null,
|
||||
'end' => $params['periodo']['date']['end'] ?? null,
|
||||
],
|
||||
'time' => [
|
||||
'start' => $params['periodo']['time']['start'] ?? null,
|
||||
'end' => $params['periodo']['time']['end'] ?? null,
|
||||
]
|
||||
],
|
||||
'unidade_id' => null,
|
||||
'localAtendimento_id' => null,
|
||||
'especialidade_id' => null,
|
||||
'profissional_id' => null,
|
||||
];
|
||||
}
|
||||
}
|
||||
74
api/app/Services/ProntoAtendimento/PlantaoService.php
Normal file
74
api/app/Services/ProntoAtendimento/PlantaoService.php
Normal file
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento;
|
||||
|
||||
use App\Enums\Cadastro\Estabelecimento\Servico;
|
||||
use App\Enums\ProntoAtendimento\Plantao\Status;
|
||||
use App\Models\ProntoAtendimento\Parametrizacao\Parametrizacao;
|
||||
use App\Models\ProntoAtendimento\Plantao\Plantao;
|
||||
use Carbon\Carbon;
|
||||
|
||||
class PlantaoService
|
||||
{
|
||||
public static function getCurrentPlantao($isObservacao = false)
|
||||
{
|
||||
$parametrizacao = Parametrizacao::first();
|
||||
|
||||
$now = Carbon::now();
|
||||
|
||||
$plantao = Plantao::whereIn('status_id', [Status::CONFIRMADO, Status::COM_ATENDIMENTO_AGENDADO])
|
||||
->where('lotacao_id', auth()->payload()->get('lotacao_id'))
|
||||
->when($isObservacao,
|
||||
function ($query) {
|
||||
|
||||
$query->whereIn('servico_id', [
|
||||
Servico::CONSULTA_MEDICA,
|
||||
Servico::ENFERMAGEM,
|
||||
Servico::EXAME_RAIO_X
|
||||
]);
|
||||
},
|
||||
function ($query) {
|
||||
|
||||
$query->whereHas('servico', function ($query) {
|
||||
|
||||
$query->whereHas('setores', function ($query) {
|
||||
|
||||
$query->whereHas('centrosCusto', function($query) {
|
||||
|
||||
$query->where('id', auth()->payload()->get('centro_custo_id'));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
)
|
||||
->where('inicio', '<=', $now->format('Y-m-d H:i:s'))
|
||||
->where('fim', '>', $now->subMinutes($parametrizacao->tempo_adicional_plantao ?? 0)->format('Y-m-d H:i:s'))
|
||||
->first();
|
||||
|
||||
return $plantao;
|
||||
}
|
||||
|
||||
public static function setStatusComAtendimento($plantaoId)
|
||||
{
|
||||
$plantao = Plantao::findOrFail($plantaoId);
|
||||
|
||||
if ($plantao->status_id !== Status::COM_ATENDIMENTO_AGENDADO) {
|
||||
|
||||
$plantao->status_id = Status::COM_ATENDIMENTO_AGENDADO;
|
||||
|
||||
$plantao->save();
|
||||
}
|
||||
}
|
||||
|
||||
public static function setStatusConfirmado($plantaoId)
|
||||
{
|
||||
$plantao = Plantao::findOrFail($plantaoId);
|
||||
|
||||
if ($plantao->status_id !== Status::CONFIRMADO) {
|
||||
|
||||
$plantao->status_id = Status::CONFIRMADO;
|
||||
|
||||
$plantao->save();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento;
|
||||
|
||||
use App\Enums\Sigtap\Procedimento as ProcedimentoEnum;
|
||||
use App\Models\Cadastro\SujeitoAtencao\Lotacao;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Medico\AtendimentoMedico;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Observacao\PacienteObservacao;
|
||||
use App\Models\ProntoAtendimento\Atendimento\Procedimento;
|
||||
use App\Models\Sigtap\Procedimento as SigtapProcedimento;
|
||||
use App\Services\Sigtap\ProcedimentoValidationService;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class ProcedimentoObservacaoService
|
||||
{
|
||||
private $lotacao;
|
||||
private $atendimentoMedico;
|
||||
|
||||
public function __construct(Lotacao $lotacao, AtendimentoMedico $atendimentoMedico)
|
||||
{
|
||||
$this->lotacao = clone $lotacao;
|
||||
$this->atendimentoMedico = clone $atendimentoMedico;
|
||||
}
|
||||
|
||||
public function save() : void
|
||||
{
|
||||
$primeiroAtendimentoObservacao = $this->getPrimeiroAtendimentoObservacao();
|
||||
|
||||
if (is_null($primeiroAtendimentoObservacao)) {
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$procedimentosLancados = $this->getProcedimentosLancados();
|
||||
$tempoAtendimento = $this->getTempoAtendimentoEmHoras($primeiroAtendimentoObservacao);
|
||||
$procedimentos = $this->getProcedimentos($primeiroAtendimentoObservacao->created_at, $tempoAtendimento);
|
||||
|
||||
for ($i = 0; $i < $procedimentos->count(); $i++) {
|
||||
|
||||
$procedimento = $procedimentos->slice($i, 1)->first();
|
||||
$procedimentoLancado = $procedimentosLancados->slice($i, 1)->first();
|
||||
|
||||
if (!is_null($procedimentoLancado)) {
|
||||
|
||||
if ($procedimento->procedimento->codigo == $procedimentoLancado->codigo) {
|
||||
|
||||
continue;
|
||||
}
|
||||
else {
|
||||
|
||||
Procedimento::destroy($procedimentoLancado->id);
|
||||
}
|
||||
}
|
||||
|
||||
$validation = new ProcedimentoValidationService($procedimento->procedimento);
|
||||
|
||||
if ($validation->isOcupacaoValid($this->lotacao->ocupacao)) {
|
||||
|
||||
$this->atendimentoMedico->procedimentos()->save($procedimento);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function getPrimeiroAtendimentoObservacao() : ?PacienteObservacao
|
||||
{
|
||||
return $this->atendimentoMedico->atendimento->pacienteObservacoes()
|
||||
->orderBy('created_at')
|
||||
->first();
|
||||
}
|
||||
|
||||
private function getProcedimentosLancados() : Collection
|
||||
{
|
||||
return DB::table('pronto_atendimento_atendimento_procedimento AS procedimento')
|
||||
->join(
|
||||
'sigtap.procedimento AS sigtap_procedimento',
|
||||
'sigtap_procedimento.id',
|
||||
'procedimento.procedimento_id'
|
||||
)
|
||||
->whereNull('procedimento.deleted_at')
|
||||
->where('procedimento.atendimento_id', $this->atendimentoMedico->atendimento->id)
|
||||
->whereIn('sigtap_procedimento.codigo', [
|
||||
ProcedimentoEnum::ATEND_URG_ATENCAO_PRIMARIA_OBS_ATE_8_HORAS,
|
||||
ProcedimentoEnum::ATEND_URG_OBS_ATE_24_HORAS_ATENCAO_ESPECIALIZADA
|
||||
])
|
||||
->select(
|
||||
'procedimento.id',
|
||||
'sigtap_procedimento.codigo',
|
||||
)
|
||||
->get();
|
||||
}
|
||||
|
||||
private function getTempoAtendimentoEmHoras(PacienteObservacao $primeiroAtendimentoObservacao) : float
|
||||
{
|
||||
return Carbon::now()->floatDiffInHours($primeiroAtendimentoObservacao->created_at);
|
||||
}
|
||||
|
||||
private function getProcedimentos(
|
||||
Carbon $dataAtendimento,
|
||||
float $tempoAtendimento,
|
||||
Collection $procedimentos = null
|
||||
) : Collection {
|
||||
|
||||
if (is_null($procedimentos)) {
|
||||
|
||||
$procedimentos = new Collection();
|
||||
}
|
||||
|
||||
if ($tempoAtendimento > 24) {
|
||||
|
||||
$procedimentos->push($this->getProcedimento(
|
||||
$this->getProcedimentoSigtapDeVinteQuatroHoras(),
|
||||
$dataAtendimento
|
||||
));
|
||||
|
||||
$tempoAtendimento -= 24;
|
||||
$dataAtendimento = $dataAtendimento->copy()->addHours(24);
|
||||
|
||||
return $this->getProcedimentos($dataAtendimento, $tempoAtendimento, $procedimentos);
|
||||
}
|
||||
|
||||
return $procedimentos;
|
||||
}
|
||||
|
||||
private function getProcedimento(SigtapProcedimento $procedimento, Carbon $dataAtendimento) : Procedimento
|
||||
{
|
||||
return new Procedimento([
|
||||
'atendimento_id' => $this->atendimentoMedico->atendimento->id,
|
||||
'lotacao_id' => $this->lotacao->id,
|
||||
'procedimento_id' => $procedimento->id,
|
||||
'realizado_em' => $dataAtendimento,
|
||||
'quantidade' => 1,
|
||||
]);
|
||||
}
|
||||
|
||||
private function getProcedimentoSigtapDeOitoHoras() : SigtapProcedimento
|
||||
{
|
||||
return SigtapProcedimento::where(
|
||||
'codigo',
|
||||
ProcedimentoEnum::ATEND_URG_ATENCAO_PRIMARIA_OBS_ATE_8_HORAS
|
||||
)->orderByDesc('competencia_id')->firstOrFail();
|
||||
}
|
||||
|
||||
private function getProcedimentoSigtapDeVinteQuatroHoras() : SigtapProcedimento
|
||||
{
|
||||
return SigtapProcedimento::where(
|
||||
'codigo',
|
||||
ProcedimentoEnum::ATEND_URG_OBS_ATE_24_HORAS_ATENCAO_ESPECIALIZADA
|
||||
)->orderByDesc('competencia_id')->firstOrFail();
|
||||
}
|
||||
}
|
||||
2973
api/app/Services/ProntoAtendimento/RelatorioAtendimentoService.php
Normal file
2973
api/app/Services/ProntoAtendimento/RelatorioAtendimentoService.php
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,447 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento;
|
||||
|
||||
use App\Models\ProntoAtendimento\ClassificacaoRisco\ClassificacaoRisco;
|
||||
use App\Models\Sigtap\Procedimento;
|
||||
use App\Services\Service;
|
||||
use App\Utils\Format;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class RelatorioClassificacaoRiscoService extends Service
|
||||
{
|
||||
public static function index()
|
||||
{
|
||||
$params = request()->all();
|
||||
|
||||
self::adjustPeriod($params);
|
||||
|
||||
$classificacoesRisco = DB::table('pronto_atendimento_atendimento_classificacao_risco')
|
||||
->select(
|
||||
DB::raw('count(pronto_atendimento_atendimento_classificacao_risco.classificacao_risco_id) totalClassificacoesRisco'),
|
||||
'pronto_atendimento_atendimento_classificacao_risco.classificacao_risco_id',
|
||||
'cadastro_infraestrutura.unidade_id',
|
||||
'cadastro_infraestrutura.id as infraestrutura_id',
|
||||
'cadastro_unidade.nome_fantasia as unidade',
|
||||
DB::raw("
|
||||
CASE WHEN cadastro_infraestrutura.nome IS NOT NULL
|
||||
THEN cadastro_infraestrutura.nome
|
||||
ELSE cadastro_unidade.nome_fantasia
|
||||
END AS infraestrutura"
|
||||
),
|
||||
)
|
||||
->groupBy('pronto_atendimento_atendimento_classificacao_risco.classificacao_risco_id')
|
||||
->groupBy('cadastro_infraestrutura.id')
|
||||
->groupBy('cadastro_infraestrutura.unidade_id')
|
||||
->join(
|
||||
'pronto_atendimento_atendimento',
|
||||
'pronto_atendimento_atendimento.id',
|
||||
'pronto_atendimento_atendimento_classificacao_risco.atendimento_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_faa',
|
||||
'pronto_atendimento_faa.id',
|
||||
'pronto_atendimento_atendimento.faa_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_faa.created_lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_infraestrutura',
|
||||
'cadastro_infraestrutura.id',
|
||||
'cadastro_lotacao.infraestrutura_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_unidade',
|
||||
'cadastro_unidade.id',
|
||||
'cadastro_infraestrutura.unidade_id'
|
||||
)
|
||||
->where('pronto_atendimento_atendimento_classificacao_risco.id', function ($query) {
|
||||
|
||||
$query->select(
|
||||
'pronto_atendimento_atendimento_classificacao_risco.id'
|
||||
)
|
||||
->from('pronto_atendimento_atendimento_classificacao_risco')
|
||||
->whereColumn(
|
||||
'pronto_atendimento_atendimento_classificacao_risco.atendimento_id',
|
||||
'pronto_atendimento_atendimento.id'
|
||||
)
|
||||
->orderByDesc('pronto_atendimento_atendimento_classificacao_risco.created_at')
|
||||
->limit(1);
|
||||
})
|
||||
->whereBetween(
|
||||
'pronto_atendimento_faa.created_at',
|
||||
[
|
||||
$params['periodo']['date']['start'] ?? null,
|
||||
$params['periodo']['date']['end'] ?? null
|
||||
]
|
||||
);
|
||||
|
||||
if (self::hasParamId($params, 'classificacao_risco_id')) {
|
||||
|
||||
$classificacoesRisco->where(
|
||||
'pronto_atendimento_atendimento_classificacao_risco.classificacao_risco_id',
|
||||
$params['classificacao_risco_id']
|
||||
);
|
||||
}
|
||||
|
||||
if (self::hasParamId($params, 'unidade_id')) {
|
||||
|
||||
$classificacoesRisco->where(
|
||||
'cadastro_infraestrutura.unidade_id',
|
||||
$params['unidade_id']
|
||||
);
|
||||
}
|
||||
|
||||
if (self::hasParamId($params, 'local_atendimento_id')) {
|
||||
|
||||
$classificacoesRisco->where(
|
||||
'cadastro_infraestrutura.id',
|
||||
$params['local_atendimento_id']
|
||||
);
|
||||
}
|
||||
|
||||
$results = [];
|
||||
$totalGeral = 0;
|
||||
|
||||
$classificacoesRisco->get()
|
||||
->map(function ($classRisco) use (&$results, &$totalGeral) {
|
||||
|
||||
$totalGeral += $classRisco->totalClassificacoesRisco;
|
||||
|
||||
if (!isset($results[$classRisco->unidade_id][$classRisco->infraestrutura_id]['total'])) {
|
||||
|
||||
$results[$classRisco->unidade_id][$classRisco->infraestrutura_id]['total'] = 0;
|
||||
}
|
||||
|
||||
$results[$classRisco->unidade_id][$classRisco->infraestrutura_id]['unidade'] = $classRisco->unidade;
|
||||
$results[$classRisco->unidade_id][$classRisco->infraestrutura_id]['infraestrutura'] = $classRisco->infraestrutura;
|
||||
$results[$classRisco->unidade_id][$classRisco->infraestrutura_id][$classRisco->classificacao_risco_id] = $classRisco->totalClassificacoesRisco;
|
||||
$results[$classRisco->unidade_id][$classRisco->infraestrutura_id]['total'] += $classRisco->totalClassificacoesRisco;
|
||||
});
|
||||
|
||||
$classificacoes = [];
|
||||
foreach ($results as $unidadeId => $infras) {
|
||||
|
||||
$columns = self::getColumns();
|
||||
|
||||
foreach ($infras as $infraId => $classRiscos) {
|
||||
|
||||
$columns['unidade'] = $classRiscos['unidade'];
|
||||
$columns['infraestrutura'] = $classRiscos['infraestrutura'];
|
||||
$columns['total'] = $classRiscos['total'];
|
||||
|
||||
unset($classRiscos['unidade']);
|
||||
unset($classRiscos['infraestrutura']);
|
||||
unset($classRiscos['total']);
|
||||
|
||||
$keys = array_keys($classRiscos);
|
||||
|
||||
foreach ($keys as $key) {
|
||||
|
||||
$columns["_{$key}"] = $classRiscos[$key];
|
||||
}
|
||||
|
||||
$classificacoes[] = $columns;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'classificacoes_risco' => $classificacoes,
|
||||
'total_geral' => $totalGeral,
|
||||
];
|
||||
}
|
||||
|
||||
private static function getColumns()
|
||||
{
|
||||
$classificacoesRiscoCadastradas = self::getClassificacoesRiscoCadastradas();
|
||||
|
||||
$columns = [];
|
||||
|
||||
$classificacoesRiscoCadastradas->map(function ($classificacoesRiscoCadastradas) use (&$columns) {
|
||||
|
||||
$columns["{$classificacoesRiscoCadastradas['value']}"] = 0;
|
||||
});
|
||||
|
||||
return $columns;
|
||||
}
|
||||
|
||||
public static function list()
|
||||
{
|
||||
return [
|
||||
'form' => self::getForm(),
|
||||
'model' => self::getModel(),
|
||||
'additionals' => [
|
||||
'data_atual' => Carbon::today()->format('d/m/Y'),
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
private static function getForm()
|
||||
{
|
||||
$params = request()->all();
|
||||
|
||||
self::adjustPeriod($params);
|
||||
|
||||
return [
|
||||
'columns' => array_merge(
|
||||
[['value' => 'infraestrutura', 'text' => 'Local de atendimento']],
|
||||
self::getClassificacoesRiscoCadastradas()->toArray()
|
||||
),
|
||||
'classificacoes_risco' => self::getClassificacoesRisco($params),
|
||||
'unidades' => self::getUnidades($params),
|
||||
'locais_atendimento' => self::getLocaisAtendimento($params),
|
||||
];
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
private static function adjustPeriod(&$params)
|
||||
{
|
||||
if (!is_null($params['periodo']['date']['start'] ?? null) && $params['periodo']['date']['end']) {
|
||||
|
||||
$params['periodo']['date']['start'] =
|
||||
(Carbon::createFromFormat('d/m/Y', "{$params['periodo']['date']['start']}"))->startOfDay();
|
||||
$params['periodo']['date']['end'] =
|
||||
(Carbon::createFromFormat('d/m/Y', "{$params['periodo']['date']['end']}"))->endOfDay();
|
||||
}
|
||||
}
|
||||
|
||||
private static function getClassificacoesRiscoCadastradas()
|
||||
{
|
||||
return ClassificacaoRisco::select('id', 'nome')->get()->map(function ($classificacaoRisco) {
|
||||
|
||||
return [
|
||||
'value' => "_{$classificacaoRisco->id}",
|
||||
'text' => $classificacaoRisco->nome
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
private static function getClassificacoesRisco($params)
|
||||
{
|
||||
return DB::table('pronto_atendimento_classificacao_risco')
|
||||
->select(
|
||||
'pronto_atendimento_classificacao_risco.id',
|
||||
'pronto_atendimento_classificacao_risco.nome',
|
||||
)
|
||||
->whereExists(function($query) use ($params) {
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_faa')
|
||||
->join(
|
||||
'pronto_atendimento_atendimento',
|
||||
'pronto_atendimento_atendimento.faa_id',
|
||||
'pronto_atendimento_faa.id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento_classificacao_risco',
|
||||
'pronto_atendimento_atendimento_classificacao_risco.atendimento_id',
|
||||
'pronto_atendimento_atendimento.id'
|
||||
)
|
||||
->whereBetween(
|
||||
'pronto_atendimento_faa.created_at',
|
||||
[
|
||||
$params['periodo']['date']['start'] ?? null,
|
||||
$params['periodo']['date']['end'] ?? null
|
||||
]
|
||||
)
|
||||
->where('pronto_atendimento_classificacao_risco.id', function ($query) {
|
||||
|
||||
$query->select(
|
||||
'pronto_atendimento_atendimento_classificacao_risco.classificacao_risco_id'
|
||||
)
|
||||
->from('pronto_atendimento_atendimento_classificacao_risco')
|
||||
->whereColumn(
|
||||
'pronto_atendimento_atendimento_classificacao_risco.atendimento_id',
|
||||
'pronto_atendimento_atendimento.id'
|
||||
)
|
||||
->orderByDesc('pronto_atendimento_atendimento_classificacao_risco.created_at')
|
||||
->limit(1);
|
||||
});
|
||||
})
|
||||
->orderBy('pronto_atendimento_classificacao_risco.nome')
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function getUnidades($params)
|
||||
{
|
||||
return DB::table('cadastro_unidade')
|
||||
->select(
|
||||
'cadastro_unidade.id',
|
||||
'cadastro_unidade.nome_fantasia',
|
||||
)
|
||||
->whereExists(function($query) use ($params) {
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_faa')
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_faa.created_lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_infraestrutura',
|
||||
'cadastro_infraestrutura.id',
|
||||
'cadastro_lotacao.infraestrutura_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento',
|
||||
'pronto_atendimento_atendimento.faa_id',
|
||||
'pronto_atendimento_faa.id'
|
||||
)
|
||||
->join('pronto_atendimento_atendimento_classificacao_risco', function ($join) {
|
||||
|
||||
$join->on(
|
||||
'pronto_atendimento_atendimento_classificacao_risco.atendimento_id',
|
||||
'=',
|
||||
'pronto_atendimento_atendimento.id'
|
||||
)
|
||||
->where('pronto_atendimento_atendimento_classificacao_risco.classificacao_risco_id', function ($query) {
|
||||
|
||||
$query->select(
|
||||
'pronto_atendimento_atendimento_classificacao_risco.classificacao_risco_id'
|
||||
)
|
||||
->from('pronto_atendimento_atendimento_classificacao_risco')
|
||||
->whereColumn(
|
||||
'pronto_atendimento_atendimento_classificacao_risco.atendimento_id',
|
||||
'pronto_atendimento_atendimento.id'
|
||||
)
|
||||
->orderByDesc('pronto_atendimento_atendimento_classificacao_risco.created_at')
|
||||
->limit(1);
|
||||
});
|
||||
})
|
||||
->whereColumn(
|
||||
'cadastro_infraestrutura.unidade_id',
|
||||
'cadastro_unidade.id'
|
||||
)
|
||||
->whereBetween(
|
||||
'pronto_atendimento_faa.created_at',
|
||||
[
|
||||
$params['periodo']['date']['start'] ?? null,
|
||||
$params['periodo']['date']['end'] ?? null
|
||||
]
|
||||
);
|
||||
|
||||
if (self::hasParamId($params, 'classificacao_risco_id')) {
|
||||
|
||||
$query->where(
|
||||
'pronto_atendimento_atendimento_classificacao_risco.classificacao_risco_id',
|
||||
$params['classificacao_risco_id']
|
||||
);
|
||||
}
|
||||
})
|
||||
->orderBy('cadastro_unidade.nome_fantasia')
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function getLocaisAtendimento($params)
|
||||
{
|
||||
$locaisAtendimento = DB::table('cadastro_infraestrutura')
|
||||
->select(
|
||||
'cadastro_infraestrutura.id',
|
||||
DB::raw(
|
||||
"CASE WHEN cadastro_infraestrutura.nome IS NOT NULL
|
||||
THEN cadastro_infraestrutura.nome
|
||||
ELSE cadastro_unidade.nome_fantasia END AS nome"
|
||||
),
|
||||
)
|
||||
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
|
||||
->whereExists(function($query) use ($params) {
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_faa')
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_faa.created_lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento',
|
||||
'pronto_atendimento_atendimento.faa_id',
|
||||
'pronto_atendimento_faa.id'
|
||||
)
|
||||
->join('pronto_atendimento_atendimento_classificacao_risco', function ($join) {
|
||||
|
||||
$join->on(
|
||||
'pronto_atendimento_atendimento_classificacao_risco.atendimento_id',
|
||||
'=',
|
||||
'pronto_atendimento_atendimento.id'
|
||||
)
|
||||
->where('pronto_atendimento_atendimento_classificacao_risco.classificacao_risco_id', function ($query) {
|
||||
|
||||
$query->select(
|
||||
'pronto_atendimento_atendimento_classificacao_risco.classificacao_risco_id'
|
||||
)
|
||||
->from('pronto_atendimento_atendimento_classificacao_risco')
|
||||
->whereColumn(
|
||||
'pronto_atendimento_atendimento_classificacao_risco.atendimento_id',
|
||||
'pronto_atendimento_atendimento.id'
|
||||
)
|
||||
->orderByDesc('pronto_atendimento_atendimento_classificacao_risco.created_at')
|
||||
->limit(1);
|
||||
});
|
||||
})
|
||||
->whereColumn(
|
||||
'cadastro_lotacao.infraestrutura_id',
|
||||
'cadastro_infraestrutura.id'
|
||||
)
|
||||
->whereBetween(
|
||||
'pronto_atendimento_faa.created_at',
|
||||
[
|
||||
$params['periodo']['date']['start'] ?? null,
|
||||
$params['periodo']['date']['end'] ?? null
|
||||
]
|
||||
);
|
||||
|
||||
if (self::hasParamId($params, 'classificacao_risco_id')) {
|
||||
|
||||
$query->where(
|
||||
'pronto_atendimento_atendimento_classificacao_risco.classificacao_risco_id',
|
||||
$params['classificacao_risco_id']
|
||||
);
|
||||
}
|
||||
|
||||
if (self::hasParamId($params, 'unidade_id')) {
|
||||
|
||||
$query->where(
|
||||
'cadastro_unidade.id',
|
||||
$params['unidade_id']
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
if (!is_null($params['unidade_id'] ?? null)) {
|
||||
|
||||
$locaisAtendimento->where('cadastro_unidade.id', $params['unidade_id']);
|
||||
}
|
||||
|
||||
return $locaisAtendimento->orderBy(
|
||||
DB::raw(
|
||||
"CASE WHEN cadastro_infraestrutura.nome IS NOT NULL
|
||||
THEN cadastro_infraestrutura.nome
|
||||
ELSE cadastro_unidade.nome_fantasia END"
|
||||
))
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function hasParamId($params, $param)
|
||||
{
|
||||
return isset($params[$param]) && $params[$param] > 0;
|
||||
}
|
||||
|
||||
private static function getModel()
|
||||
{
|
||||
return [
|
||||
'periodo' => [
|
||||
'date' => [
|
||||
'start' => $params['periodo']['date']['start'] ?? null,
|
||||
'end' => $params['periodo']['date']['end'] ?? null,
|
||||
],
|
||||
],
|
||||
'classificacao_risco_id' => null,
|
||||
'unidade_id' => null,
|
||||
'localAtendimento_id' => null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento;
|
||||
|
||||
use App\Models\Cadastro\Estabelecimento\Infraestrutura;
|
||||
use App\Models\Cadastro\Estabelecimento\Unidade;
|
||||
use App\Models\Cadastro\SujeitoAtencao\Usuario;
|
||||
use App\Services\Service;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class RelatorioDocumentoNaoAssinadoService extends Service
|
||||
{
|
||||
public static function index()
|
||||
{
|
||||
$periodo = [
|
||||
Carbon::createFromFormat('d/m/Y', request()->periodo['start'])->setTime(0, 0, 0),
|
||||
Carbon::createFromFormat('d/m/Y', request()->periodo['end'])->setTime(23, 59, 59)
|
||||
];
|
||||
|
||||
$triagemQuery = DB::table('pronto_atendimento_atendimento_triagem as triagem')
|
||||
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'triagem.created_centro_custo_id')
|
||||
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
|
||||
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
|
||||
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'triagem.created_lotacao_id')
|
||||
->join('cadastro_usuario as usuario', 'usuario.id', 'lotacao.usuario_id')
|
||||
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
|
||||
->join('pronto_atendimento_atendimento as atendimento', 'atendimento.id', 'triagem.atendimento_id')
|
||||
->join('pronto_atendimento_faa as faa', 'faa.id', 'atendimento.faa_id')
|
||||
->whereNull('triagem.deleted_at')
|
||||
->where('triagem.is_faa_assinada', false)
|
||||
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
|
||||
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
|
||||
->when(request()->profissional_id, fn ($q, $id) => $q->where('lotacao.usuario_id', $id))
|
||||
->whereBetween('triagem.created_at', $periodo)
|
||||
->select(DB::raw("
|
||||
'TRIAGEM' as tipo,
|
||||
triagem.created_at as data_hora,
|
||||
unidade.nome_fantasia as unidade,
|
||||
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura,
|
||||
cidadao.nome as profissional,
|
||||
atendimento.faa_id AS faa,
|
||||
faa.numero AS faa_numero
|
||||
"));
|
||||
|
||||
$medicoQuery = DB::table('pronto_atendimento_atendimento_medico as medico')
|
||||
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'medico.created_centro_custo_id')
|
||||
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
|
||||
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
|
||||
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'medico.created_lotacao_id')
|
||||
->join('cadastro_usuario as usuario', 'usuario.id', 'lotacao.usuario_id')
|
||||
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
|
||||
->join('pronto_atendimento_atendimento as atendimento', 'atendimento.id', 'medico.atendimento_id')
|
||||
->join('pronto_atendimento_faa as faa', 'faa.id', 'atendimento.faa_id')
|
||||
->whereNull('medico.deleted_at')
|
||||
->where('medico.is_faa_assinada', false)
|
||||
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
|
||||
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
|
||||
->when(request()->profissional_id, fn ($q, $id) => $q->where('lotacao.usuario_id', $id))
|
||||
->whereBetween('medico.created_at', $periodo)
|
||||
->select(DB::raw("
|
||||
CONCAT('MÉDICO', IF(medico.is_observacao = 1,' (OBSERVAÇÃO)', '')) as tipo,
|
||||
medico.created_at as data_hora,
|
||||
unidade.nome_fantasia as unidade,
|
||||
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura,
|
||||
cidadao.nome as profissional,
|
||||
atendimento.faa_id AS faa,
|
||||
faa.numero AS faa_numero
|
||||
"));
|
||||
|
||||
$enfermagemQuery = DB::table('pronto_atendimento_atendimento_enfermagem as enfermagem')
|
||||
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'enfermagem.created_centro_custo_id')
|
||||
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
|
||||
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
|
||||
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'enfermagem.created_lotacao_id')
|
||||
->join('cadastro_usuario as usuario', 'usuario.id', 'lotacao.usuario_id')
|
||||
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
|
||||
->join('pronto_atendimento_atendimento as atendimento', 'atendimento.id', 'enfermagem.atendimento_id')
|
||||
->join('pronto_atendimento_faa as faa', 'faa.id', 'atendimento.faa_id')
|
||||
->whereNull('enfermagem.deleted_at')
|
||||
->where('enfermagem.is_faa_assinada', false)
|
||||
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
|
||||
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
|
||||
->when(request()->profissional_id, fn ($q, $id) => $q->where('lotacao.usuario_id', $id))
|
||||
->whereBetween('enfermagem.created_at', $periodo)
|
||||
->select(DB::raw("
|
||||
'ENFERMAGEM' as tipo,
|
||||
enfermagem.created_at as data_hora,
|
||||
unidade.nome_fantasia as unidade,
|
||||
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura,
|
||||
cidadao.nome as profissional,
|
||||
atendimento.faa_id AS faa,
|
||||
faa.numero AS faa_numero
|
||||
"));
|
||||
|
||||
$observacaoQuery = DB::table('pronto_atendimento_paciente_observacao as observacao')
|
||||
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'observacao.created_centro_custo_id')
|
||||
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
|
||||
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
|
||||
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'observacao.created_lotacao_id')
|
||||
->join('cadastro_usuario as usuario', 'usuario.id', 'lotacao.usuario_id')
|
||||
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
|
||||
->join('pronto_atendimento_atendimento as atendimento', 'atendimento.id', 'observacao.atendimento_id')
|
||||
->join('pronto_atendimento_faa as faa', 'faa.id', 'atendimento.faa_id')
|
||||
->whereNull('observacao.deleted_at')
|
||||
->where('observacao.is_faa_assinada', false)
|
||||
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
|
||||
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
|
||||
->when(request()->profissional_id, fn ($q, $id) => $q->where('lotacao.usuario_id', $id))
|
||||
->whereBetween('observacao.created_at', $periodo)
|
||||
->select(DB::raw("
|
||||
'ENFERMAGEM (OBSERVAÇÃO)' as tipo,
|
||||
observacao.created_at as data_hora,
|
||||
unidade.nome_fantasia as unidade,
|
||||
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura,
|
||||
cidadao.nome as profissional,
|
||||
atendimento.faa_id AS faa,
|
||||
faa.numero AS faa_numero
|
||||
"));
|
||||
|
||||
$receitaMedicaQuery = DB::table('pronto_atendimento_atendimento_medico_receita as receita')
|
||||
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'receita.created_centro_custo_id')
|
||||
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
|
||||
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
|
||||
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'receita.created_lotacao_id')
|
||||
->join('cadastro_usuario as usuario', 'usuario.id', 'lotacao.usuario_id')
|
||||
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
|
||||
->join('pronto_atendimento_atendimento_medico as medico', 'medico.id', 'receita.atendimento_medico_id')
|
||||
->join('pronto_atendimento_atendimento as atendimento', 'atendimento.id', 'medico.atendimento_id')
|
||||
->join('pronto_atendimento_faa as faa', 'faa.id', 'atendimento.faa_id')
|
||||
->whereNull('receita.deleted_at')
|
||||
->where('receita.is_assinada', false)
|
||||
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
|
||||
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
|
||||
->when(request()->profissional_id, fn ($q, $id) => $q->where('lotacao.usuario_id', $id))
|
||||
->whereBetween('receita.created_at', $periodo)
|
||||
->select(DB::raw("
|
||||
CONCAT('MÉDICO', IF(medico.is_observacao = 1,' (OBSERVAÇÃO)', ''), ' - RECEITA MÉDICA') as tipo,
|
||||
receita.created_at as data_hora,
|
||||
unidade.nome_fantasia as unidade,
|
||||
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura,
|
||||
cidadao.nome as profissional,
|
||||
atendimento.faa_id AS faa,
|
||||
faa.numero AS faa_numero
|
||||
"));
|
||||
|
||||
$documentos = null;
|
||||
|
||||
if (request()->tipo_documento == 'atendimento') {
|
||||
|
||||
$documentos = $triagemQuery
|
||||
->unionAll($medicoQuery)
|
||||
->unionAll($enfermagemQuery)
|
||||
->unionAll($observacaoQuery);
|
||||
}
|
||||
else if (request()->tipo_documento == 'receita_medica') {
|
||||
|
||||
$documentos = $receitaMedicaQuery;
|
||||
}
|
||||
else {
|
||||
|
||||
$documentos = $triagemQuery
|
||||
->unionAll($medicoQuery)
|
||||
->unionAll($enfermagemQuery)
|
||||
->unionAll($observacaoQuery)
|
||||
->unionAll($receitaMedicaQuery);
|
||||
}
|
||||
|
||||
$documentos = $documentos
|
||||
->orderBy('data_hora')
|
||||
->get();
|
||||
|
||||
return compact('documentos');
|
||||
}
|
||||
|
||||
public static function list()
|
||||
{
|
||||
return [
|
||||
'additionals' => self::getAdditionalsData(),
|
||||
'form' => self::getFormData(),
|
||||
'model' => self::getModelData(),
|
||||
];
|
||||
}
|
||||
|
||||
public static function getAdditionalsData()
|
||||
{
|
||||
return [
|
||||
'data_atual' => Carbon::now()->format('d/m/Y'),
|
||||
];
|
||||
}
|
||||
|
||||
public static function getFormData()
|
||||
{
|
||||
$unidades = Unidade::orderBy('nome_fantasia')
|
||||
->get(['id', 'nome_fantasia'])
|
||||
->map(fn ($unidade) => [
|
||||
'id' => $unidade->id,
|
||||
'nome_fantasia' => $unidade->nome_fantasia,
|
||||
'infraestruturas' => $unidade->infraestruturas()
|
||||
->get(['id', 'nome', 'principal', 'unidade_id'])
|
||||
->map(fn ($infraestrutura) => [
|
||||
'id' => $infraestrutura->id,
|
||||
'nome' => $infraestrutura->nome,
|
||||
'profissionais' => $infraestrutura->lotacoes()
|
||||
->with([
|
||||
'usuario:id,cidadao_id',
|
||||
'usuario.cidadao:id,nome',
|
||||
])
|
||||
->distinct()
|
||||
->get(['usuario_id'])
|
||||
->map(fn ($lotacao) => [
|
||||
'id' => $lotacao->usuario_id,
|
||||
'nome' => $lotacao->usuario()->withTrashed()->first()->cidadao->nome
|
||||
])
|
||||
->sortBy('nome')
|
||||
->values()
|
||||
])
|
||||
->sortBy('nome')
|
||||
->values()
|
||||
]);
|
||||
|
||||
return [
|
||||
'unidades' => $unidades,
|
||||
'tipos_documento' => self::getTiposDocumento(),
|
||||
];
|
||||
}
|
||||
|
||||
private static function getTiposDocumento()
|
||||
{
|
||||
return collect([
|
||||
['value' => 'atendimento', 'text' => 'ATENDIMENTO'],
|
||||
['value' => 'receita_medica', 'text' => 'RECEITA MÉDICA'],
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getModelData()
|
||||
{
|
||||
$now = Carbon::now()->format('d/m/Y');
|
||||
|
||||
return [
|
||||
'periodo' => [
|
||||
'start' => $now,
|
||||
'end' => $now,
|
||||
],
|
||||
'unidade_id' => null,
|
||||
'infraestrutura_id' => null,
|
||||
'profissional_id' => null,
|
||||
'tipo_documento' => null,
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPrintExportData()
|
||||
{
|
||||
$resultado = self::index();
|
||||
$itens = $resultado['documentos'];
|
||||
|
||||
$itens->each(function ($item) {
|
||||
|
||||
$item->data_hora = (new Carbon($item->data_hora))->format('d/m/Y H:i');
|
||||
});
|
||||
|
||||
$unidade = Unidade::find(request()->unidade_id);
|
||||
$infraestrutura = Infraestrutura::find(request()->infraestrutura_id);
|
||||
$profissional = Usuario::find(request()->profissional_id);
|
||||
$tipo = self::getTiposDocumento()->firstWhere('value', request()->tipo_documento);
|
||||
|
||||
return [
|
||||
'inicio' => request()->periodo['start'],
|
||||
'fim' => request()->periodo['end'],
|
||||
'unidade' => $unidade->nome_fantasia ?? 'Todas',
|
||||
'infraestrutura' => $infraestrutura->nome ?? 'Todas',
|
||||
'profissional' => $profissional->cidadao->nome ?? 'Todos',
|
||||
'tipo' => $tipo['text'] ?? 'Todos',
|
||||
'colunas' => collect(request()->selectedCols),
|
||||
'itens' => $itens,
|
||||
];
|
||||
}
|
||||
}
|
||||
2428
api/app/Services/ProntoAtendimento/RelatorioExameImagemService.php
Normal file
2428
api/app/Services/ProntoAtendimento/RelatorioExameImagemService.php
Normal file
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,744 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento;
|
||||
|
||||
use App\Enums\ProntoAtendimento\Atendimento\MetodoProducao;
|
||||
use App\Services\Service;
|
||||
use App\Utils\Format;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class RelatorioProducaoMedicoService extends Service
|
||||
{
|
||||
public static function index()
|
||||
{
|
||||
$params = request()->all();
|
||||
|
||||
$metodoProducao = intval($params['metodo_producao']);
|
||||
|
||||
self::adjustPeriod($params);
|
||||
|
||||
if($metodoProducao === MetodoProducao::ATENDIMENTO) {
|
||||
return self::relatorioPorAtendimento($params);
|
||||
}
|
||||
|
||||
if($metodoProducao === MetodoProducao::FAA) {
|
||||
return self::relatorioPorFaa($params);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static function list()
|
||||
{
|
||||
return [
|
||||
'form' => self::getForm(),
|
||||
'model' => self::getModel(),
|
||||
'additionals' => [
|
||||
'data_atual' => Carbon::today()->format('d/m/Y'),
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
private static function relatorioPorAtendimento($params) {
|
||||
$atendimentos = DB::table('pronto_atendimento_plantao')
|
||||
->select(
|
||||
DB::raw("DATE_FORMAT(pronto_atendimento_plantao.inicio, '%d/%m/%Y %H:%i') AS inicio"),
|
||||
DB::raw("DATE_FORMAT(pronto_atendimento_plantao.fim, '%d/%m/%Y %H:%i') AS fim"),
|
||||
'cadastro_cidadao.nome AS nome_medico',
|
||||
'cadastro_unidade.nome_fantasia AS nome_unidade',
|
||||
DB::raw("
|
||||
CASE WHEN cadastro_infraestrutura.nome IS NOT NULL
|
||||
THEN cadastro_infraestrutura.nome
|
||||
ELSE cadastro_unidade.nome_fantasia END AS nome_infraestrutura
|
||||
"),
|
||||
DB::raw("COUNT(distinct pronto_atendimento_atendimento.id) AS quantidade")
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento_medico',
|
||||
'pronto_atendimento_atendimento_medico.plantao_id',
|
||||
'pronto_atendimento_plantao.id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento',
|
||||
'pronto_atendimento_atendimento.id',
|
||||
'pronto_atendimento_atendimento_medico.atendimento_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_faa',
|
||||
'pronto_atendimento_faa.id',
|
||||
'pronto_atendimento_atendimento.faa_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento_recepcao',
|
||||
'pronto_atendimento_atendimento_recepcao.atendimento_id',
|
||||
'pronto_atendimento_atendimento_medico.atendimento_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_plantao.lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_usuario',
|
||||
'cadastro_usuario.id',
|
||||
'cadastro_lotacao.usuario_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_cidadao',
|
||||
'cadastro_cidadao.id',
|
||||
'cadastro_usuario.cidadao_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_infraestrutura',
|
||||
'cadastro_infraestrutura.id',
|
||||
'cadastro_lotacao.infraestrutura_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_unidade',
|
||||
'cadastro_unidade.id',
|
||||
'cadastro_infraestrutura.unidade_id'
|
||||
)
|
||||
->where(function ($query) use ($params) {
|
||||
|
||||
$query->whereBetween(
|
||||
'inicio',
|
||||
[
|
||||
$params['periodo']['start'] ?? null,
|
||||
$params['periodo']['end'] ?? null
|
||||
]
|
||||
)
|
||||
->orWhereBetween(
|
||||
'fim',
|
||||
[
|
||||
$params['periodo']['start'] ?? null,
|
||||
$params['periodo']['end'] ?? null
|
||||
]
|
||||
);
|
||||
})
|
||||
->groupBy(
|
||||
DB::raw("DATE_FORMAT(pronto_atendimento_plantao.inicio, '%d/%m/%Y %H:%i')"),
|
||||
DB::raw("DATE_FORMAT(pronto_atendimento_plantao.fim, '%d/%m/%Y %H:%i')"),
|
||||
'cadastro_cidadao.nome',
|
||||
'cadastro_unidade.nome_fantasia',
|
||||
DB::raw("
|
||||
CASE WHEN cadastro_infraestrutura.nome IS NOT NULL
|
||||
THEN cadastro_infraestrutura.nome
|
||||
ELSE cadastro_unidade.nome_fantasia END
|
||||
")
|
||||
)
|
||||
->orderBy('pronto_atendimento_plantao.inicio');
|
||||
|
||||
|
||||
if (!is_null($params['unidade_id'] ?? null)) {
|
||||
|
||||
$atendimentos->where('cadastro_infraestrutura.unidade_id', $params['unidade_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['local_atendimento_id'] ?? null)) {
|
||||
|
||||
$atendimentos->where('cadastro_infraestrutura.id', $params['local_atendimento_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['usuario_id'] ?? null)) {
|
||||
|
||||
$atendimentos->where('cadastro_lotacao.usuario_id', $params['usuario_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['origem_entrada_id'] ?? null)) {
|
||||
|
||||
$atendimentos->where(
|
||||
'pronto_atendimento_atendimento_recepcao.origem_entrada_id',
|
||||
$params['origem_entrada_id']
|
||||
);
|
||||
}
|
||||
|
||||
if (!is_null($params['status'] ?? null)) {
|
||||
|
||||
$atendimentos->where(
|
||||
'pronto_atendimento_faa.finalizado',
|
||||
$params['status']
|
||||
);
|
||||
}
|
||||
|
||||
$atendimentos = $atendimentos->orderBy('pronto_atendimento_plantao.inicio')->get();
|
||||
|
||||
$quantidadeTotal = 0;
|
||||
|
||||
foreach($atendimentos as $atendimento) {
|
||||
|
||||
$quantidadeTotal += $atendimento->quantidade;
|
||||
}
|
||||
|
||||
return [
|
||||
'atendimentos' => $atendimentos,
|
||||
'quantidade_total' => $quantidadeTotal
|
||||
];
|
||||
}
|
||||
|
||||
private static function cbosMedicasPermitidas() {
|
||||
return [
|
||||
'221205', '2231A1', '2231F8', '2231F9', '2231G1', '223119', '223150', '223305', '225103', '225105',
|
||||
'225106', '225109', '225110', '225112', '225115', '225118', '225120', '225121', '225122', '225124',
|
||||
'225125', '225127', '225130', '225133', '225135', '225136', '225139', '225140', '225142', '225145',
|
||||
'225148', '225150', '225151', '225154', '225155', '225160', '225165', '225170', '225175', '225180',
|
||||
'225185', '225195', '225203', '225210', '225215', '225220', '225225', '225230', '225235', '225240',
|
||||
'225250', '225255', '225260', '225265', '225270', '225275', '225280', '225285', '225290', '225295',
|
||||
'225305', '225310', '225315', '225320', '225325', '225330', '225335', '225340', '225345', '225350',
|
||||
'225355'
|
||||
];
|
||||
}
|
||||
|
||||
private static function relatorioPorFaa($params) {
|
||||
$atendimentos = DB::table('pronto_atendimento_plantao')
|
||||
->select(
|
||||
DB::raw("DATE_FORMAT(pronto_atendimento_plantao.inicio, '%d/%m/%Y %H:%i') AS inicio"),
|
||||
DB::raw("DATE_FORMAT(pronto_atendimento_plantao.fim, '%d/%m/%Y %H:%i') AS fim"),
|
||||
'cadastro_cidadao.nome AS nome_medico',
|
||||
'cadastro_unidade.nome_fantasia AS nome_unidade',
|
||||
DB::raw("
|
||||
CASE WHEN cadastro_infraestrutura.nome IS NOT NULL
|
||||
THEN cadastro_infraestrutura.nome
|
||||
ELSE cadastro_unidade.nome_fantasia END AS nome_infraestrutura
|
||||
"),
|
||||
DB::raw("COUNT(distinct pronto_atendimento_atendimento.id) AS quantidade")
|
||||
)
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_plantao.lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'sigtap.ocupacao',
|
||||
'sigtap.ocupacao.id',
|
||||
'cadastro_lotacao.ocupacao_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento_procedimento',
|
||||
'pronto_atendimento_atendimento_procedimento.plantao_id',
|
||||
'pronto_atendimento_plantao.id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento',
|
||||
'pronto_atendimento_atendimento.id',
|
||||
'pronto_atendimento_atendimento_procedimento.atendimento_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_faa',
|
||||
'pronto_atendimento_faa.id',
|
||||
'pronto_atendimento_atendimento.faa_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_usuario',
|
||||
'cadastro_usuario.id',
|
||||
'cadastro_lotacao.usuario_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_cidadao',
|
||||
'cadastro_cidadao.id',
|
||||
'cadastro_usuario.cidadao_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_infraestrutura',
|
||||
'cadastro_infraestrutura.id',
|
||||
'cadastro_lotacao.infraestrutura_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_unidade',
|
||||
'cadastro_unidade.id',
|
||||
'cadastro_infraestrutura.unidade_id'
|
||||
)
|
||||
->where(function ($query) use ($params) {
|
||||
|
||||
$query->whereBetween(
|
||||
'inicio',
|
||||
[
|
||||
$params['periodo']['start'] ?? null,
|
||||
$params['periodo']['end'] ?? null
|
||||
]
|
||||
)
|
||||
->orWhereBetween(
|
||||
'fim',
|
||||
[
|
||||
$params['periodo']['start'] ?? null,
|
||||
$params['periodo']['end'] ?? null
|
||||
]
|
||||
);
|
||||
})
|
||||
->whereIn('sigtap.ocupacao.codigo', self::cbosMedicasPermitidas())
|
||||
->groupBy(
|
||||
DB::raw("DATE_FORMAT(pronto_atendimento_plantao.inicio, '%d/%m/%Y %H:%i')"),
|
||||
DB::raw("DATE_FORMAT(pronto_atendimento_plantao.fim, '%d/%m/%Y %H:%i')"),
|
||||
'cadastro_cidadao.nome',
|
||||
'cadastro_unidade.nome_fantasia',
|
||||
DB::raw("
|
||||
CASE WHEN cadastro_infraestrutura.nome IS NOT NULL
|
||||
THEN cadastro_infraestrutura.nome
|
||||
ELSE cadastro_unidade.nome_fantasia END
|
||||
")
|
||||
)
|
||||
->orderBy('pronto_atendimento_plantao.inicio');
|
||||
|
||||
if (!is_null($params['unidade_id'] ?? null)) {
|
||||
|
||||
$atendimentos->where('cadastro_infraestrutura.unidade_id', $params['unidade_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['local_atendimento_id'] ?? null)) {
|
||||
|
||||
$atendimentos->where('cadastro_infraestrutura.id', $params['local_atendimento_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['usuario_id'] ?? null)) {
|
||||
|
||||
$atendimentos->where('cadastro_lotacao.usuario_id', $params['usuario_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['status'] ?? null)) {
|
||||
|
||||
$atendimentos->where(
|
||||
'pronto_atendimento_faa.finalizado',
|
||||
$params['status']
|
||||
);
|
||||
}
|
||||
|
||||
$atendimentos = $atendimentos->orderBy('pronto_atendimento_plantao.inicio')->get();
|
||||
|
||||
$quantidadeTotal = 0;
|
||||
|
||||
foreach($atendimentos as $atendimento) {
|
||||
|
||||
$quantidadeTotal += $atendimento->quantidade;
|
||||
}
|
||||
|
||||
return [
|
||||
'atendimentos' => $atendimentos,
|
||||
'quantidade_total' => $quantidadeTotal
|
||||
];
|
||||
}
|
||||
|
||||
private static function getForm()
|
||||
{
|
||||
$params = request()->all();
|
||||
|
||||
self::adjustPeriod($params);
|
||||
|
||||
return [
|
||||
'unidades' => self::getUnidades($params),
|
||||
'locais_atendimento' => self::getLocaisAtendimento($params),
|
||||
'metodos_producao' => self::getMetodosProducao(),
|
||||
'usuarios' => self::getUsuarios($params),
|
||||
'origens_entrada' => self::getOrigensEntrada($params),
|
||||
'status' => self::getStatus($params),
|
||||
];
|
||||
}
|
||||
|
||||
private static function adjustPeriod(&$params)
|
||||
{
|
||||
if (!is_null($params['periodo']['start'] ?? null) && $params['periodo']['end']) {
|
||||
|
||||
$params['periodo']['start'] =
|
||||
(Carbon::createFromFormat('d/m/Y', "{$params['periodo']['start']}"))->startOfDay();
|
||||
$params['periodo']['end'] =
|
||||
(Carbon::createFromFormat('d/m/Y', "{$params['periodo']['end']}"))->endOfDay();
|
||||
}
|
||||
}
|
||||
|
||||
private static function getUnidades($params)
|
||||
{
|
||||
return DB::table('cadastro_unidade')
|
||||
->select(
|
||||
'cadastro_unidade.id',
|
||||
'cadastro_unidade.nome_fantasia',
|
||||
)
|
||||
->whereExists(function($query) use ($params) {
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_plantao')
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_plantao.lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_infraestrutura',
|
||||
'cadastro_infraestrutura.id',
|
||||
'cadastro_lotacao.infraestrutura_id'
|
||||
)
|
||||
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
|
||||
->where(function ($query) use ($params) {
|
||||
|
||||
$query->whereBetween(
|
||||
'inicio',
|
||||
[
|
||||
$params['periodo']['start'] ?? null,
|
||||
$params['periodo']['end'] ?? null
|
||||
]
|
||||
)
|
||||
->orWhereBetween(
|
||||
'fim',
|
||||
[
|
||||
$params['periodo']['start'] ?? null,
|
||||
$params['periodo']['end'] ?? null
|
||||
]
|
||||
);
|
||||
});
|
||||
})
|
||||
->orderBy('cadastro_unidade.nome_fantasia')
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function getLocaisAtendimento($params)
|
||||
{
|
||||
$infras = DB::table('cadastro_infraestrutura')
|
||||
->select(
|
||||
'cadastro_infraestrutura.id',
|
||||
DB::raw(
|
||||
"CASE WHEN cadastro_infraestrutura.nome IS NOT NULL
|
||||
THEN cadastro_infraestrutura.nome
|
||||
ELSE cadastro_unidade.nome_fantasia END AS nome"
|
||||
),
|
||||
)
|
||||
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
|
||||
->whereExists(function($query) use ($params) {
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_plantao')
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_plantao.lotacao_id'
|
||||
)
|
||||
->whereColumn('cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
|
||||
->where(function ($query) use ($params) {
|
||||
|
||||
$query->whereBetween(
|
||||
'inicio',
|
||||
[
|
||||
$params['periodo']['start'] ?? null,
|
||||
$params['periodo']['end'] ?? null
|
||||
]
|
||||
)
|
||||
->orWhereBetween(
|
||||
'fim',
|
||||
[
|
||||
$params['periodo']['start'] ?? null,
|
||||
$params['periodo']['end'] ?? null
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
if (!is_null($params['unidade_id'] ?? null)) {
|
||||
|
||||
$infras->where('cadastro_unidade.id', $params['unidade_id']);
|
||||
}
|
||||
|
||||
return $infras->orderBy(
|
||||
DB::raw(
|
||||
"CASE WHEN cadastro_infraestrutura.nome IS NOT NULL
|
||||
THEN cadastro_infraestrutura.nome
|
||||
ELSE cadastro_unidade.nome_fantasia END"
|
||||
))
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function getMetodosProducao()
|
||||
{
|
||||
$metodos = (new \ReflectionClass(MetodoProducao::class))->getConstants();
|
||||
|
||||
$metodosFormatados = [];
|
||||
foreach ($metodos as $nome => $valor) {
|
||||
$metodosFormatados[] = ['nome' => $nome, 'id' => $valor];
|
||||
}
|
||||
|
||||
return $metodosFormatados;
|
||||
}
|
||||
|
||||
private static function getUsuarios($params)
|
||||
{
|
||||
$joinReferenciaPlantao = 'pronto_atendimento_atendimento_medico';
|
||||
|
||||
if($params && $params['metodo_producao'] == MetodoProducao::FAA) {
|
||||
$joinReferenciaPlantao = 'pronto_atendimento_atendimento_procedimento';
|
||||
}
|
||||
|
||||
$usuarios = DB::table('cadastro_usuario')
|
||||
->select(
|
||||
'cadastro_usuario.id',
|
||||
'cadastro_cidadao.nome'
|
||||
)
|
||||
->join(
|
||||
'cadastro_cidadao',
|
||||
'cadastro_cidadao.id',
|
||||
'cadastro_usuario.cidadao_id'
|
||||
)
|
||||
->whereExists(function ($query) use ($params, $joinReferenciaPlantao) {
|
||||
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_plantao')
|
||||
->join(
|
||||
$joinReferenciaPlantao,
|
||||
"{$joinReferenciaPlantao}.plantao_id",
|
||||
'pronto_atendimento_plantao.id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_plantao.lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'sigtap.ocupacao',
|
||||
'sigtap.ocupacao.id',
|
||||
'cadastro_lotacao.ocupacao_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_infraestrutura',
|
||||
'cadastro_infraestrutura.id',
|
||||
'cadastro_lotacao.infraestrutura_id'
|
||||
)
|
||||
->whereColumn('cadastro_lotacao.usuario_id', 'cadastro_usuario.id')
|
||||
->where(function ($query) use ($params) {
|
||||
|
||||
$query->whereBetween(
|
||||
'inicio',
|
||||
[
|
||||
$params['periodo']['start'] ?? null,
|
||||
$params['periodo']['end'] ?? null
|
||||
]
|
||||
)
|
||||
->orWhereBetween(
|
||||
'fim',
|
||||
[
|
||||
$params['periodo']['start'] ?? null,
|
||||
$params['periodo']['end'] ?? null
|
||||
]
|
||||
);
|
||||
})
|
||||
->whereIn('sigtap.ocupacao.codigo', self::cbosMedicasPermitidas());
|
||||
|
||||
if (!is_null($params['unidade_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_infraestrutura.unidade_id', $params['unidade_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['local_atendimento_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_infraestrutura.id', $params['local_atendimento_id']);
|
||||
}
|
||||
});
|
||||
|
||||
return $usuarios
|
||||
->orderBy('cadastro_cidadao.nome')
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function getOrigensEntrada($params)
|
||||
{
|
||||
|
||||
$joinReferenciaPlantao = 'pronto_atendimento_atendimento_medico';
|
||||
|
||||
if($params && $params['metodo_producao'] == MetodoProducao::FAA) {
|
||||
$joinReferenciaPlantao = 'pronto_atendimento_atendimento_procedimento';
|
||||
}
|
||||
|
||||
$origensEntrada = DB::table('pronto_atendimento_origem_entrada')
|
||||
->select(
|
||||
'pronto_atendimento_origem_entrada.id',
|
||||
'pronto_atendimento_origem_entrada.nome'
|
||||
)
|
||||
->whereExists(function ($query) use ($params, $joinReferenciaPlantao) {
|
||||
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_plantao')
|
||||
->join(
|
||||
$joinReferenciaPlantao,
|
||||
"{$joinReferenciaPlantao}.plantao_id",
|
||||
'pronto_atendimento_plantao.id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento_recepcao',
|
||||
'pronto_atendimento_atendimento_recepcao.atendimento_id',
|
||||
"{$joinReferenciaPlantao}.atendimento_id"
|
||||
)
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_plantao.lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'sigtap.ocupacao',
|
||||
'sigtap.ocupacao.id',
|
||||
'cadastro_lotacao.ocupacao_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_infraestrutura',
|
||||
'cadastro_infraestrutura.id',
|
||||
'cadastro_lotacao.infraestrutura_id'
|
||||
)
|
||||
->whereColumn(
|
||||
'pronto_atendimento_atendimento_recepcao.origem_entrada_id',
|
||||
'pronto_atendimento_origem_entrada.id'
|
||||
)
|
||||
->where(function ($query) use ($params) {
|
||||
|
||||
$query->whereBetween(
|
||||
'inicio',
|
||||
[
|
||||
$params['periodo']['start'] ?? null,
|
||||
$params['periodo']['end'] ?? null
|
||||
]
|
||||
)
|
||||
->orWhereBetween(
|
||||
'fim',
|
||||
[
|
||||
$params['periodo']['start'] ?? null,
|
||||
$params['periodo']['end'] ?? null
|
||||
]
|
||||
);
|
||||
})
|
||||
->whereIn('sigtap.ocupacao.codigo', self::cbosMedicasPermitidas());
|
||||
|
||||
if (!is_null($params['unidade_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_infraestrutura.unidade_id', $params['unidade_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['local_atendimento_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_infraestrutura.id', $params['local_atendimento_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['usuario_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_lotacao.usuario_id', $params['usuario_id']);
|
||||
}
|
||||
});
|
||||
|
||||
return $origensEntrada
|
||||
->orderBy('pronto_atendimento_origem_entrada.nome')
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function getStatus($params)
|
||||
{
|
||||
$joinReferenciaPlantao = 'pronto_atendimento_atendimento_medico';
|
||||
|
||||
if($params && $params['metodo_producao'] == MetodoProducao::FAA) {
|
||||
$joinReferenciaPlantao = 'pronto_atendimento_atendimento_procedimento';
|
||||
}
|
||||
|
||||
$status = DB::table('pronto_atendimento_faa')
|
||||
->select(
|
||||
'pronto_atendimento_faa.finalizado',
|
||||
)
|
||||
->whereExists(function ($query) use ($params, $joinReferenciaPlantao) {
|
||||
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_plantao')
|
||||
->join(
|
||||
$joinReferenciaPlantao,
|
||||
"{$joinReferenciaPlantao}.plantao_id",
|
||||
'pronto_atendimento_plantao.id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento_recepcao',
|
||||
'pronto_atendimento_atendimento_recepcao.atendimento_id',
|
||||
"{$joinReferenciaPlantao}.atendimento_id"
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento',
|
||||
'pronto_atendimento_atendimento.id',
|
||||
"{$joinReferenciaPlantao}.atendimento_id"
|
||||
)
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_plantao.lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'sigtap.ocupacao',
|
||||
'sigtap.ocupacao.id',
|
||||
'cadastro_lotacao.ocupacao_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_infraestrutura',
|
||||
'cadastro_infraestrutura.id',
|
||||
'cadastro_lotacao.infraestrutura_id'
|
||||
)
|
||||
->whereColumn('pronto_atendimento_atendimento.faa_id', 'pronto_atendimento_faa.id')
|
||||
->where(function ($query) use ($params) {
|
||||
|
||||
$query->whereBetween(
|
||||
'inicio',
|
||||
[
|
||||
$params['periodo']['start'] ?? null,
|
||||
$params['periodo']['end'] ?? null
|
||||
]
|
||||
)
|
||||
->orWhereBetween(
|
||||
'fim',
|
||||
[
|
||||
$params['periodo']['start'] ?? null,
|
||||
$params['periodo']['end'] ?? null
|
||||
]
|
||||
);
|
||||
})
|
||||
->whereIn('sigtap.ocupacao.codigo', self::cbosMedicasPermitidas());
|
||||
|
||||
if (!is_null($params['unidade_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_infraestrutura.unidade_id', $params['unidade_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['local_atendimento_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_infraestrutura.id', $params['local_atendimento_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['usuario_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_lotacao.usuario_id', $params['usuario_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['origem_entrada_id'] ?? null)) {
|
||||
|
||||
$query->where(
|
||||
'pronto_atendimento_atendimento_recepcao.origem_entrada_id',
|
||||
$params['origem_entrada_id']
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return $status
|
||||
->distinct()
|
||||
->orderBy('pronto_atendimento_faa.finalizado')
|
||||
->get()
|
||||
->map(function($status) {
|
||||
return [
|
||||
'valor' => $status->finalizado ?? false,
|
||||
'nome' => $status->finalizado ? 'FINALIZADO' : 'EM ABERTO',
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
private static function hasParamId($params, $param)
|
||||
{
|
||||
return isset($params[$param]) && $params[$param] > 0;
|
||||
}
|
||||
|
||||
private static function getModel()
|
||||
{
|
||||
return [
|
||||
'periodo' => [
|
||||
'start' => null,
|
||||
'end' => null,
|
||||
],
|
||||
'unidade_id' => null,
|
||||
'localAtendimento_id' => null,
|
||||
'metodo_producao' => MetodoProducao::ATENDIMENTO,
|
||||
'usuario_id' => null,
|
||||
'origem_entrada_id' => null,
|
||||
'servico_id' => null,
|
||||
'status' => null,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,719 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\ProntoAtendimento;
|
||||
|
||||
use App\Models\Cadastro\SujeitoAtencao\Lotacao;
|
||||
use App\Models\Sigtap\Procedimento;
|
||||
use App\Services\Service;
|
||||
use App\Utils\Format;
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class RelatorioQuantitativoProducaoService extends Service
|
||||
{
|
||||
public static function index()
|
||||
{
|
||||
$params = request()->all();
|
||||
|
||||
self::adjustPeriod($params);
|
||||
|
||||
$idadeDe = $params['idade_de'] ?? null;
|
||||
$idadeAte = $params['idade_ate'] ?? null;
|
||||
|
||||
$procedimentosAtendimentos = DB::table('pronto_atendimento_atendimento_procedimento')
|
||||
->select(
|
||||
DB::raw(
|
||||
'SUM(pronto_atendimento_atendimento_procedimento.quantidade) as quantidade',
|
||||
),
|
||||
'sigtap_procedimento.nome as procedimento_nome',
|
||||
'sigtap_procedimento.codigo as procedimento_codigo',
|
||||
'sigtap_ocupacao.nome as ocupacao_nome',
|
||||
'sigtap_ocupacao.codigo as ocupacao_codigo',
|
||||
'profissional.nome as profissional_nome',
|
||||
DB::raw("CASE WHEN pronto_atendimento_faa.finalizado = 1 THEN 'FINALIZADO' ELSE 'EM ABERTO' END AS status"),
|
||||
)
|
||||
->join(
|
||||
'sigtap.procedimento as sigtap_procedimento',
|
||||
'sigtap_procedimento.id',
|
||||
'pronto_atendimento_atendimento_procedimento.procedimento_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_atendimento_procedimento.lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'sigtap.ocupacao as sigtap_ocupacao',
|
||||
'sigtap_ocupacao.id',
|
||||
'cadastro_lotacao.ocupacao_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento',
|
||||
'pronto_atendimento_atendimento.id',
|
||||
'pronto_atendimento_atendimento_procedimento.atendimento_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_faa',
|
||||
'pronto_atendimento_faa.id',
|
||||
'pronto_atendimento_atendimento.faa_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_centro_custo',
|
||||
'cadastro_centro_custo.id',
|
||||
'pronto_atendimento_atendimento.created_centro_custo_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_infraestrutura',
|
||||
'cadastro_infraestrutura.id',
|
||||
'cadastro_centro_custo.infraestrutura_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_paciente',
|
||||
'cadastro_paciente.id',
|
||||
'pronto_atendimento_faa.paciente_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_cidadao',
|
||||
'cadastro_cidadao.id',
|
||||
'cadastro_paciente.cidadao_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_usuario',
|
||||
'cadastro_usuario.id',
|
||||
'cadastro_lotacao.usuario_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_cidadao as profissional',
|
||||
'profissional.id',
|
||||
'cadastro_usuario.cidadao_id'
|
||||
)
|
||||
->whereBetween(
|
||||
'pronto_atendimento_faa.created_at',
|
||||
[
|
||||
$params['periodo']['date']['start'] ?? null,
|
||||
$params['periodo']['date']['end'] ?? null
|
||||
]
|
||||
)
|
||||
->where('pronto_atendimento_faa.cancelado', 0)
|
||||
->whereNull('pronto_atendimento_faa.deleted_at')
|
||||
->whereNull('pronto_atendimento_atendimento_procedimento.deleted_at')
|
||||
->groupBy(
|
||||
'sigtap_procedimento.codigo',
|
||||
'sigtap_ocupacao.codigo',
|
||||
DB::raw("CASE WHEN pronto_atendimento_faa.finalizado = 1 THEN 'FINALIZADO' ELSE 'EM ABERTO' END"),
|
||||
)
|
||||
->orderBy('sigtap_procedimento.nome');
|
||||
|
||||
if (!is_null($params['unidade_id'] ?? null)) {
|
||||
|
||||
$procedimentosAtendimentos->where('cadastro_infraestrutura.unidade_id', $params['unidade_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['local_atendimento_id'] ?? null)) {
|
||||
|
||||
$procedimentosAtendimentos->where('cadastro_infraestrutura.id', $params['local_atendimento_id']);
|
||||
}
|
||||
|
||||
if (!is_null($idadeDe)) {
|
||||
|
||||
$procedimentosAtendimentos->whereRaw("(TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, CURRENT_DATE)) >= $idadeDe");
|
||||
}
|
||||
|
||||
if (!is_null($idadeAte)) {
|
||||
|
||||
$procedimentosAtendimentos->whereRaw("(TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, CURRENT_DATE)) <= $idadeAte");
|
||||
}
|
||||
|
||||
if (!is_null($params['ocupacao_id'] ?? null)) {
|
||||
|
||||
$procedimentosAtendimentos->where('cadastro_lotacao.ocupacao_id', $params['ocupacao_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['usuario_id'] ?? null)) {
|
||||
|
||||
$procedimentosAtendimentos->where('cadastro_lotacao.usuario_id', $params['usuario_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['procedimento_id'] ?? null)) {
|
||||
|
||||
$procedimento = Procedimento::findOrFail($params['procedimento_id']);
|
||||
|
||||
$procedimentosAtendimentos->where('sigtap_procedimento.codigo', $procedimento->codigo);
|
||||
}
|
||||
|
||||
if (!is_null($params['status'] ?? null)) {
|
||||
|
||||
$procedimentosAtendimentos->where('pronto_atendimento_faa.finalizado', $params['status']);
|
||||
}
|
||||
|
||||
$procedimentosAtendimentos = $procedimentosAtendimentos->get();
|
||||
|
||||
$quantidadeTotal = 0;
|
||||
$result = [];
|
||||
$index = 1;
|
||||
|
||||
foreach ($procedimentosAtendimentos as $procedimentoAtendimento) {
|
||||
|
||||
$procedimentoAtendimento->index = $index;
|
||||
|
||||
$procedimentoCodigo = Format::getProcedimentoFormated($procedimentoAtendimento->procedimento_codigo);
|
||||
$procedimentoAtendimento->procedimento_codigo_nome =
|
||||
"{$procedimentoCodigo} - {$procedimentoAtendimento->procedimento_nome}";
|
||||
|
||||
$procedimentoAtendimento->ocupacao_codigo_nome =
|
||||
"{$procedimentoAtendimento->ocupacao_codigo} - {$procedimentoAtendimento->ocupacao_nome}";
|
||||
|
||||
$quantidadeTotal += $procedimentoAtendimento->quantidade;
|
||||
$index++;
|
||||
}
|
||||
|
||||
return [
|
||||
'procedimentos_atendimentos' => $procedimentosAtendimentos,
|
||||
'quantidade_total' => $quantidadeTotal,
|
||||
];
|
||||
}
|
||||
|
||||
public static function list()
|
||||
{
|
||||
return [
|
||||
'form' => self::getForm(),
|
||||
'model' => self::getModel(),
|
||||
'additionals' => [
|
||||
'data_atual' => Carbon::today()->format('d/m/Y'),
|
||||
]
|
||||
];
|
||||
}
|
||||
|
||||
private static function getForm()
|
||||
{
|
||||
$params = request()->all();
|
||||
$lotacao = Lotacao::findOrFail(auth()->payload()->get('lotacao_id'));
|
||||
|
||||
self::adjustPeriod($params);
|
||||
|
||||
return [
|
||||
'unidades' => self::getUnidades($params),
|
||||
'locais_atendimento' => self::getLocaisAtendimento($params),
|
||||
'ocupacoes' => self::getOcupacoes($params),
|
||||
'procedimentos' => self::getProcedimentos($params),
|
||||
'usuarios' => self::getUsuarios($params),
|
||||
'status' => self::getStatus($params),
|
||||
'unidade_logada' => [
|
||||
'unidade_id' => $lotacao->infraestrutura->unidade->id,
|
||||
'infraestrutura_id' => $lotacao->infraestrutura->id,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
private static function adjustPeriod(&$params)
|
||||
{
|
||||
if (!is_null($params['periodo']['date']['start'] ?? null) && $params['periodo']['date']['end']) {
|
||||
|
||||
$params['periodo']['date']['start'] =
|
||||
(Carbon::createFromFormat('d/m/Y', "{$params['periodo']['date']['start']}"))->startOfDay();
|
||||
$params['periodo']['date']['end'] =
|
||||
(Carbon::createFromFormat('d/m/Y', "{$params['periodo']['date']['end']}"))->endOfDay();
|
||||
}
|
||||
}
|
||||
|
||||
private static function getUnidades($params)
|
||||
{
|
||||
return DB::table('cadastro_unidade')
|
||||
->select(
|
||||
'cadastro_unidade.id',
|
||||
'cadastro_unidade.nome_fantasia'
|
||||
)
|
||||
->whereExists(function ($query) use ($params) {
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_faa')
|
||||
->join(
|
||||
'cadastro_centro_custo',
|
||||
'cadastro_centro_custo.id',
|
||||
'=',
|
||||
'pronto_atendimento_faa.created_centro_custo_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento',
|
||||
'pronto_atendimento_atendimento.faa_id',
|
||||
'=',
|
||||
'pronto_atendimento_faa.id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento_procedimento',
|
||||
'pronto_atendimento_atendimento_procedimento.atendimento_id',
|
||||
'=',
|
||||
'pronto_atendimento_atendimento.id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_infraestrutura',
|
||||
'cadastro_infraestrutura.id',
|
||||
'=',
|
||||
'cadastro_centro_custo.infraestrutura_id'
|
||||
)
|
||||
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
|
||||
->whereBetween(
|
||||
'pronto_atendimento_faa.created_at',
|
||||
[
|
||||
$params['periodo']['date']['start'] ?? null,
|
||||
$params['periodo']['date']['end'] ?? null
|
||||
]
|
||||
);
|
||||
})
|
||||
->orderBy('cadastro_unidade.nome_fantasia')
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function getLocaisAtendimento($params)
|
||||
{
|
||||
$locaisAtendimento = DB::table('cadastro_infraestrutura')
|
||||
->select(
|
||||
'cadastro_infraestrutura.id',
|
||||
DB::raw(
|
||||
"CASE WHEN cadastro_infraestrutura.nome IS NOT NULL
|
||||
THEN cadastro_infraestrutura.nome
|
||||
ELSE cadastro_unidade.nome_fantasia END AS nome"
|
||||
),
|
||||
)
|
||||
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
|
||||
->whereExists(function ($query) use ($params) {
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_faa')
|
||||
->join(
|
||||
'cadastro_centro_custo',
|
||||
'cadastro_centro_custo.id',
|
||||
'=',
|
||||
'pronto_atendimento_faa.created_centro_custo_id'
|
||||
)
|
||||
->whereColumn('cadastro_centro_custo.infraestrutura_id', 'cadastro_infraestrutura.id')
|
||||
->whereBetween(
|
||||
'pronto_atendimento_faa.created_at',
|
||||
[
|
||||
$params['periodo']['date']['start'] ?? null,
|
||||
$params['periodo']['date']['end'] ?? null
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
if (!is_null($params['unidade_id'] ?? null)) {
|
||||
|
||||
$locaisAtendimento->where('cadastro_unidade.id', $params['unidade_id']);
|
||||
}
|
||||
|
||||
return $locaisAtendimento->orderBy(
|
||||
DB::raw(
|
||||
"CASE WHEN cadastro_infraestrutura.nome IS NOT NULL
|
||||
THEN cadastro_infraestrutura.nome
|
||||
ELSE cadastro_unidade.nome_fantasia END"
|
||||
))
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function getOcupacoes($params)
|
||||
{
|
||||
$ocupacoes = DB::table('sigtap.ocupacao as ocupacao')
|
||||
->select(
|
||||
'ocupacao.id',
|
||||
'ocupacao.nome',
|
||||
'ocupacao.codigo',
|
||||
)
|
||||
->whereExists(function ($query) use ($params) {
|
||||
|
||||
$idadeDe = $params['idade_de'] ?? null;
|
||||
$idadeAte = $params['idade_ate'] ?? null;
|
||||
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_atendimento_procedimento')
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_atendimento_procedimento.lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento',
|
||||
'pronto_atendimento_atendimento.id',
|
||||
'pronto_atendimento_atendimento_procedimento.atendimento_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_faa',
|
||||
'pronto_atendimento_faa.id',
|
||||
'pronto_atendimento_atendimento.faa_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_centro_custo',
|
||||
'cadastro_centro_custo.id',
|
||||
'pronto_atendimento_atendimento.created_centro_custo_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_infraestrutura',
|
||||
'cadastro_infraestrutura.id',
|
||||
'cadastro_centro_custo.infraestrutura_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_paciente',
|
||||
'cadastro_paciente.id',
|
||||
'pronto_atendimento_faa.paciente_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_cidadao',
|
||||
'cadastro_cidadao.id',
|
||||
'cadastro_paciente.cidadao_id'
|
||||
)
|
||||
->whereBetween(
|
||||
'pronto_atendimento_faa.created_at',
|
||||
[
|
||||
$params['periodo']['date']['start'] ?? null,
|
||||
$params['periodo']['date']['end'] ?? null
|
||||
]
|
||||
)
|
||||
->whereColumn('cadastro_lotacao.ocupacao_id', 'ocupacao.id');
|
||||
|
||||
if (!is_null($params['unidade_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_infraestrutura.unidade_id', $params['unidade_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['local_atendimento_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_infraestrutura.id', $params['local_atendimento_id']);
|
||||
}
|
||||
|
||||
if (!is_null($idadeDe)) {
|
||||
|
||||
$query->whereRaw("(YEAR(CURDATE()) - YEAR(cadastro_cidadao.data_nascimento)) >= $idadeDe");
|
||||
}
|
||||
|
||||
if (!is_null($idadeAte)) {
|
||||
|
||||
$query->whereRaw("(YEAR(CURDATE()) - YEAR(cadastro_cidadao.data_nascimento)) <= $idadeAte");
|
||||
}
|
||||
});
|
||||
|
||||
$ocupacoes = $ocupacoes
|
||||
->orderBy('ocupacao.nome')
|
||||
->get();
|
||||
|
||||
foreach ($ocupacoes as $ocupacaoAtendimento) {
|
||||
|
||||
$ocupacaoCodigo = Format::getProcedimentoFormated($ocupacaoAtendimento->codigo);
|
||||
|
||||
$ocupacaoAtendimento->ocupacao_codigo_nome =
|
||||
"{$ocupacaoCodigo} - {$ocupacaoAtendimento->nome}";
|
||||
}
|
||||
|
||||
return $ocupacoes;
|
||||
}
|
||||
|
||||
private static function getUsuarios($params)
|
||||
{
|
||||
$usuarios = DB::table('cadastro_usuario')
|
||||
->select(
|
||||
'cadastro_usuario.id',
|
||||
'cadastro_cidadao.nome'
|
||||
)
|
||||
->join(
|
||||
'cadastro_cidadao',
|
||||
'cadastro_cidadao.id',
|
||||
'cadastro_usuario.cidadao_id'
|
||||
)
|
||||
->whereExists(function ($query) use ($params) {
|
||||
|
||||
$idadeDe = $params['idade_de'] ?? null;
|
||||
$idadeAte = $params['idade_ate'] ?? null;
|
||||
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_atendimento_procedimento')
|
||||
->join(
|
||||
'pronto_atendimento_atendimento',
|
||||
'pronto_atendimento_atendimento.id',
|
||||
'pronto_atendimento_atendimento_procedimento.atendimento_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_atendimento_procedimento.lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_faa',
|
||||
'pronto_atendimento_faa.id',
|
||||
'pronto_atendimento_atendimento.faa_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_centro_custo',
|
||||
'cadastro_centro_custo.id',
|
||||
'pronto_atendimento_atendimento.created_centro_custo_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_infraestrutura',
|
||||
'cadastro_infraestrutura.id',
|
||||
'cadastro_centro_custo.infraestrutura_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_paciente',
|
||||
'cadastro_paciente.id',
|
||||
'pronto_atendimento_faa.paciente_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_cidadao as paciente',
|
||||
'paciente.id',
|
||||
'cadastro_paciente.cidadao_id'
|
||||
)
|
||||
->whereBetween(
|
||||
'pronto_atendimento_faa.created_at',
|
||||
[
|
||||
$params['periodo']['date']['start'] ?? null,
|
||||
$params['periodo']['date']['end'] ?? null
|
||||
]
|
||||
)
|
||||
->whereColumn('cadastro_lotacao.usuario_id', 'cadastro_usuario.id');
|
||||
|
||||
if (!is_null($params['unidade_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_infraestrutura.unidade_id', $params['unidade_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['local_atendimento_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_infraestrutura.id', $params['local_atendimento_id']);
|
||||
}
|
||||
|
||||
if (!is_null($idadeDe)) {
|
||||
|
||||
$query->whereRaw("(YEAR(CURDATE()) - YEAR(paciente.data_nascimento)) >= $idadeDe");
|
||||
}
|
||||
|
||||
if (!is_null($idadeAte)) {
|
||||
|
||||
$query->whereRaw("(YEAR(CURDATE()) - YEAR(paciente.data_nascimento)) <= $idadeAte");
|
||||
}
|
||||
|
||||
if (!is_null($params['ocupacao_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_lotacao.ocupacao_id', $params['ocupacao_id']);
|
||||
}
|
||||
});
|
||||
|
||||
return $usuarios
|
||||
->orderBy('cadastro_cidadao.nome')
|
||||
->get();
|
||||
}
|
||||
|
||||
private static function getProcedimentos($params)
|
||||
{
|
||||
$procedimentos = DB::table('sigtap.procedimento as procedimento')
|
||||
->select(
|
||||
'procedimento.id',
|
||||
'procedimento.nome',
|
||||
'procedimento.codigo',
|
||||
)
|
||||
->whereExists(function ($query) use ($params) {
|
||||
|
||||
$idadeDe = $params['idade_de'] ?? null;
|
||||
$idadeAte = $params['idade_ate'] ?? null;
|
||||
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_atendimento_procedimento')
|
||||
->join(
|
||||
'pronto_atendimento_atendimento',
|
||||
'pronto_atendimento_atendimento.id',
|
||||
'pronto_atendimento_atendimento_procedimento.atendimento_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_atendimento_procedimento.lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_faa',
|
||||
'pronto_atendimento_faa.id',
|
||||
'pronto_atendimento_atendimento.faa_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_centro_custo',
|
||||
'cadastro_centro_custo.id',
|
||||
'pronto_atendimento_atendimento.created_centro_custo_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_infraestrutura',
|
||||
'cadastro_infraestrutura.id',
|
||||
'cadastro_centro_custo.infraestrutura_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_paciente',
|
||||
'cadastro_paciente.id',
|
||||
'pronto_atendimento_faa.paciente_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_cidadao',
|
||||
'cadastro_cidadao.id',
|
||||
'cadastro_paciente.cidadao_id'
|
||||
)
|
||||
->whereBetween(
|
||||
'pronto_atendimento_faa.created_at',
|
||||
[
|
||||
$params['periodo']['date']['start'] ?? null,
|
||||
$params['periodo']['date']['end'] ?? null
|
||||
]
|
||||
)
|
||||
->whereColumn('pronto_atendimento_atendimento_procedimento.procedimento_id', 'procedimento.id');
|
||||
|
||||
if (!is_null($params['unidade_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_infraestrutura.unidade_id', $params['unidade_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['local_atendimento_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_infraestrutura.id', $params['local_atendimento_id']);
|
||||
}
|
||||
|
||||
if (!is_null($idadeDe)) {
|
||||
|
||||
$query->whereRaw("(YEAR(CURDATE()) - YEAR(cadastro_cidadao.data_nascimento)) >= $idadeDe");
|
||||
}
|
||||
|
||||
if (!is_null($idadeAte)) {
|
||||
|
||||
$query->whereRaw("(YEAR(CURDATE()) - YEAR(cadastro_cidadao.data_nascimento)) <= $idadeAte");
|
||||
}
|
||||
|
||||
if (!is_null($params['ocupacao_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_lotacao.ocupacao_id', $params['ocupacao_id']);
|
||||
}
|
||||
});
|
||||
|
||||
$procedimentos = $procedimentos
|
||||
->groupBy('procedimento.codigo')
|
||||
->orderBy('procedimento.nome')
|
||||
->get();
|
||||
|
||||
foreach ($procedimentos as $procedimentoAtendimento) {
|
||||
|
||||
$procedimentoCodigo = Format::getProcedimentoFormated($procedimentoAtendimento->codigo);
|
||||
|
||||
$procedimentoAtendimento->procedimento_codigo_nome =
|
||||
"{$procedimentoCodigo} - {$procedimentoAtendimento->nome}";
|
||||
}
|
||||
|
||||
return $procedimentos;
|
||||
}
|
||||
|
||||
private static function getStatus($params)
|
||||
{
|
||||
return DB::table('pronto_atendimento_faa as paf')
|
||||
->select(
|
||||
'paf.finalizado',
|
||||
)
|
||||
->distinct()
|
||||
->whereExists(function($query) use ($params) {
|
||||
|
||||
$idadeDe = $params['idade_de'] ?? null;
|
||||
$idadeAte = $params['idade_ate'] ?? null;
|
||||
|
||||
$query->select(DB::raw(1))
|
||||
->from('pronto_atendimento_atendimento')
|
||||
->join(
|
||||
'pronto_atendimento_faa',
|
||||
'pronto_atendimento_faa.id',
|
||||
'pronto_atendimento_atendimento.faa_id'
|
||||
)
|
||||
->join(
|
||||
'pronto_atendimento_atendimento_procedimento',
|
||||
'pronto_atendimento_atendimento_procedimento.atendimento_id',
|
||||
'pronto_atendimento_atendimento.id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_lotacao',
|
||||
'cadastro_lotacao.id',
|
||||
'pronto_atendimento_atendimento_procedimento.lotacao_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_infraestrutura',
|
||||
'cadastro_infraestrutura.id',
|
||||
'cadastro_lotacao.infraestrutura_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_paciente',
|
||||
'cadastro_paciente.id',
|
||||
'pronto_atendimento_faa.paciente_id'
|
||||
)
|
||||
->join(
|
||||
'cadastro_cidadao',
|
||||
'cadastro_cidadao.id',
|
||||
'cadastro_paciente.cidadao_id'
|
||||
)
|
||||
->whereColumn(
|
||||
'pronto_atendimento_atendimento.faa_id',
|
||||
'paf.id'
|
||||
)
|
||||
->whereBetween(
|
||||
'paf.created_at',
|
||||
[
|
||||
$params['periodo']['date']['start'] ?? null,
|
||||
$params['periodo']['date']['end'] ?? null
|
||||
]
|
||||
);
|
||||
|
||||
if (!is_null($params['unidade_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_infraestrutura.unidade_id', $params['unidade_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['local_atendimento_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_infraestrutura.id', $params['local_atendimento_id']);
|
||||
}
|
||||
|
||||
if (!is_null($idadeDe)) {
|
||||
|
||||
$query->whereRaw("(YEAR(CURDATE()) - YEAR(cadastro_cidadao.data_nascimento)) >= $idadeDe");
|
||||
}
|
||||
|
||||
if (!is_null($idadeAte)) {
|
||||
|
||||
$query->whereRaw("(YEAR(CURDATE()) - YEAR(cadastro_cidadao.data_nascimento)) <= $idadeAte");
|
||||
}
|
||||
|
||||
if (!is_null($params['ocupacao_id'] ?? null)) {
|
||||
|
||||
$query->where('cadastro_lotacao.ocupacao_id', $params['ocupacao_id']);
|
||||
}
|
||||
|
||||
if (!is_null($params['procedimento_id'] ?? null)) {
|
||||
|
||||
$query->where('pronto_atendimento_atendimento_procedimento.procedimento_id', $params['procedimento_id']);
|
||||
}
|
||||
})
|
||||
->get()
|
||||
->map(function($status) {
|
||||
return [
|
||||
'valor' => $status->finalizado ?? false,
|
||||
'nome' => $status->finalizado ? 'FINALIZADO' : 'EM ABERTO',
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
private static function getModel()
|
||||
{
|
||||
return [
|
||||
'periodo' => [
|
||||
'date' => [
|
||||
'start' => $params['periodo']['date']['start'] ?? null,
|
||||
'end' => $params['periodo']['date']['end'] ?? null,
|
||||
],
|
||||
'time' => [
|
||||
'start' => $params['periodo']['time']['start'] ?? null,
|
||||
'end' => $params['periodo']['time']['end'] ?? null,
|
||||
]
|
||||
],
|
||||
'unidade_id' => null,
|
||||
'localAtendimento_id' => null,
|
||||
'ocupacao_id' => null,
|
||||
'usuario_id' => null,
|
||||
'procedimento_id' => null,
|
||||
'idade_de' => null,
|
||||
'idade_ate' => null,
|
||||
'status' => null,
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user