init commit
All checks were successful
build-api-image / build (push) Successful in 51s

This commit is contained in:
Antonio Lopes dos Santos
2026-08-04 16:52:02 -03:00
commit afec302c3e
11594 changed files with 1636728 additions and 0 deletions

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,198 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Ambulatorio\AgendamentoStatus;
use App\Models\Ambulatorio\Atendimento;
use Illuminate\Support\Facades\DB;
use App\Services\Service;
class AlteracaoConsultasFinalizadasService extends Service
{
private static function getStatus()
{
return [
AgendamentoStatus::FALTA_DO_PACIENTE,
AgendamentoStatus::FALTA_DO_MEDICO,
AgendamentoStatus::REALIZADO
];
}
public static function index()
{
return [
'model' => [
'data' => null,
'unidadeId' => null,
'especialidadeId' => null,
'usuarioId' => null
],
'form' => [
'unidades' => [],
'especialidades' => [],
'usuarios' => []
]
];
}
public static function getUnidades()
{
$data = request()->data;
$agendamentos = DB::table('ambulatorio_agendamento as agendamento')
->join('ambulatorio_jornada as jornada', 'agendamento.jornada_id', '=', 'jornada.id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', '=', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', '=', 'lotacao.infraestrutura_id')
->join('cadastro_unidade as unidade', 'unidade.id', '=', 'infraestrutura.unidade_id')
->whereIn('agendamento.status_id', self::getStatus())
->where('jornada.data', '=', $data)
->select('unidade.id', 'unidade.nome_fantasia');
$demandaEspontanea = DB::table('ambulatorio_demanda_espontanea as demanda_espontanea')
->join('ambulatorio_atendimento as atendimento', 'atendimento.demanda_espontanea_id', '=', 'demanda_espontanea.id')
->join('painel_senha_fila as fila', 'fila.id', '=', 'atendimento.fila_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', '=', 'fila.centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', '=', 'centro_custo.infraestrutura_id')
->join('cadastro_unidade as unidade', 'unidade.id', '=', 'infraestrutura.unidade_id')
->where('atendimento.finalizado_em', '=', $data)
->select('unidade.id', 'unidade.nome_fantasia');
return $agendamentos
->union($demandaEspontanea)
->orderBy('nome_fantasia')
->get();
}
public static function getEspecialidades()
{
$data = request()->data;
$unidade = request()->unidade_id;
return DB::table('cadastro_especialidade')
->select([
'cadastro_especialidade.id',
'cadastro_especialidade.nome',
])
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_jornada.especialidade_id', 'cadastro_especialidade.id')
->whereIn('ambulatorio_agendamento.status_id', self::getStatus())
->where('ambulatorio_jornada.data', $data)
->where('cadastro_infraestrutura.unidade_id', $unidade)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_demanda_espontanea.especialidade_id', 'cadastro_especialidade.id')
->whereNotNull('ambulatorio_atendimento.finalizado_em')
->where('ambulatorio_demanda_espontanea.data', $data)
->where('cadastro_infraestrutura.unidade_id', $unidade)
)
)
->orderBy('cadastro_especialidade.nome')
->get();
}
public static function getUsuarios()
{
$data = request()->data;
$unidade = request()->unidade_id;
$especialidade = request()->especialidade_id;
return DB::table('cadastro_usuario')
->select([
'cadastro_usuario.id',
'cadastro_cidadao.nome',
])
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->whereColumn('cadastro_lotacao.usuario_id', 'cadastro_usuario.id')
->when(request()->unidade_id, fn($q) => $q->where('cadastro_infraestrutura.unidade_id', request()->unidade_id))
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereColumn('ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->where('ambulatorio_jornada.data', $data)
->where('ambulatorio_jornada.especialidade_id', $especialidade)
->where('cadastro_infraestrutura.unidade_id', $unidade)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea')
->whereColumn('ambulatorio_demanda_espontanea.usuario_id', 'cadastro_usuario.id')
->where('ambulatorio_demanda_espontanea.data', $data)
->where('ambulatorio_demanda_espontanea.especialidade_id', $especialidade)
->where('cadastro_infraestrutura.unidade_id', $unidade)
)
)
)
->orderBy('cadastro_cidadao.nome')
->get();
}
public static function list()
{
return Atendimento::whereHas('agendamento', fn($q) => $q->whereIn('status_id', self::getStatus()))
->whereHas('agendamento.jornada.lotacao.infraestrutura', fn($q) => $q->where('unidade_id', request()->unidade_id))
->whereHas('agendamento.jornada', fn($q) => $q->where('especialidade_id', request()->especialidade_id))
->whereHas('agendamento.jornada.lotacao', fn($q) => $q->where('usuario_id', request()->usuario_id))
->whereHas('agendamento.jornada', fn($q) => $q->whereDate('data', request()->data))
->orHas('demandaEspontanea')
->whereHas('fila.centroCusto.infraestrutura', fn($q) => $q->where('unidade_id', request()->unidade_id))
->whereHas('demandaEspontanea', fn($q) => $q->where('especialidade_id', request()->especialidade_id))
->whereHas('demandaEspontanea', fn($q) => $q->where('usuario_id', request()->usuario_id))
->whereDate('finalizado_em', request()->data)
->get()
->map(function($atendimento) {
if($atendimento->agendamento_id) {
return [
'id' => $atendimento->id,
'nome' => $atendimento->agendamento->paciente->cidadao->nome,
'prontuario' => $atendimento->agendamento->paciente->prontuario,
'status' => $atendimento->agendamento->status->nome,
'selecionado' => false
];
} else if($atendimento->demanda_espontanea_id) {
return [
'id' => $atendimento->id,
'nome' => $atendimento->demandaEspontanea->paciente->cidadao->nome,
'prontuario' => $atendimento->demandaEspontanea->paciente->prontuario,
'status' => 'REALIZADO',
'selecionado' => false
];
}
});
}
public static function store()
{
DB::transaction(function() {
foreach(request()->all() as $id) {
$atendimento = Atendimento::find($id);
if($atendimento->agendamento_id) {
$atendimento->agendamento->update([ 'status_id' => AgendamentoStatus::AGENDADO ]);
}
$atendimento->finalizado_em = null;
$atendimento->finalizado_lotacao_id = null;
$atendimento->save();
}
});
}
}

View File

@@ -0,0 +1,254 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Cadastro\SujeitoAtencao\PreferenciaNome;
use App\Models\Ambulatorio\Atendimento;
use App\Models\Cadastro\SujeitoAtencao\Sexo;
use App\Models\Cns\TermoInvalido;
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'),
],
'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),
'permissao_assinatura' => self::getPermissaoAssinatura(),
]
];
}
public static function getPermissaoAssinatura()
{
$lotacaoLogada = self::getCurrentLotacao();
return DB::table('ambulatorio_parametrizacao_infraestrutura_assinatura_eletronica AS infraestrutura_assinatura_eletronica')
->join('ambulatorio_parametrizacao_infraestrutura AS parametrizacao_infraestrutura', 'parametrizacao_infraestrutura.id', 'infraestrutura_assinatura_eletronica.parametrizacao_infraestrutura_id')
->join('ambulatorio_parametrizacao_assinatura_eletronica as assinatura_eletronica', 'assinatura_eletronica.id', 'infraestrutura_assinatura_eletronica.parametrizacao_assinatura_eletronica_id')
->when($lotacaoLogada->infraestrutura_id, fn ($q, $id) => $q->where('parametrizacao_infraestrutura.infraestrutura_id', $id))
->select(
'assinatura_eletronica.id as id'
)
->get();
}
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)
];
$atendimentoQuery = DB::table('ambulatorio_atendimento_soap')
->select([
'ambulatorio_atendimento_soap.id',
'ambulatorio_atendimento_soap.atendimento_id',
'cadastro_sexo.descricao AS sexo',
'ambulatorio_atendimento_soap.created_at',
'ambulatorio_atendimento_soap.created_at as data_hora',
'ambulatorio_atendimento_soap.is_atendimento_enfermagem',
'ambulatorio_atendimento_soap.is_atendimento_soap_assinado',
'ocupacao.id AS ocupacao_id',
'ocupacao.codigo AS ocupacao_codigo',
'ocupacao.nome AS ocupacao_nome',
'cadastro_setor.nome AS setor_nome',
'cadastro_centro_custo.infraestrutura_id AS centro_custo_infraestrutura_id',
'cadastro_paciente.prontuario AS paciente_prontuario',
'cadastro_cidadao.data_nascimento AS paciente_data_nascimento',
'cadastro_cidadao.nome_mae AS paciente_nome_mae',
'cadastro_cidadao.nome AS paciente_nome',
'cadastro_cidadao.nome_social AS paciente_nome_social',
'cadastro_cidadao.preferencia_nome_id as paciente_preferencia_nome_id',
'cadastro_cidadao.caracteristicas_fisicas AS paciente_caracteristicas_fisicas',
'cadastro_paciente.sequencial_desconhecido_em AS paciente_sequencial_desconhecido_em',
DB::raw("'ATENDIMENTO' as tipo"),
])
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_atendimento_soap.created_lotacao_id')
->join('painel_senha_fila', 'painel_senha_fila.id', 'ambulatorio_atendimento.fila_id')
->join('cadastro_paciente', 'cadastro_paciente.id', 'painel_senha_fila.paciente_id')
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id')
->join('sigtap.ocupacao', 'ocupacao.id', 'cadastro_lotacao.ocupacao_id')
->join('cadastro_centro_custo', 'cadastro_centro_custo.id', 'ambulatorio_atendimento_soap.created_centro_custo_id')
->join('cadastro_setor', 'cadastro_setor.id', 'cadastro_centro_custo.setor_id')
->leftJoin('cadastro_sexo', 'cadastro_sexo.id', 'cadastro_cidadao.sexo_id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->where('cadastro_centro_custo.infraestrutura_id', $infraestruturaId)
->where('cadastro_lotacao.usuario_id', $usuarioId)
->whereBetween('ambulatorio_atendimento_soap.created_at', $periodo)
->when($request->paciente, fn ($q, $value) => $q->where('cadastro_cidadao.nome', 'like', "{$value}%"))
->when($request->sexo_id, fn ($q, $id) => $q->where('cadastro_cidadao.sexo_id', $id))
->when($request->data_nascimento, fn ($q, $data) => $q
->whereDate('cadastro_cidadao.data_nascimento', Carbon::createFromFormat('d/m/Y', $data))
)
->when($request->atendimento, fn ($q, $id) => $q->where('ambulatorio_atendimento_soap.atendimento_id', $id))
->unionAll(
DB::table('ambulatorio_atendimento_soap')
->select([
'ambulatorio_atendimento_soap.id',
'ambulatorio_atendimento_soap.atendimento_id',
'cadastro_sexo.descricao AS sexo',
'ambulatorio_atendimento_soap.created_at',
'ambulatorio_atendimento_soap.created_at as data_hora',
'ambulatorio_atendimento_soap.is_atendimento_enfermagem',
'ambulatorio_atendimento_soap.is_atendimento_soap_assinado',
'ocupacao.id AS ocupacao_id',
'ocupacao.codigo AS ocupacao_codigo',
'ocupacao.nome AS ocupacao_nome',
'cadastro_setor.nome AS setor_nome',
'cadastro_centro_custo.infraestrutura_id AS centro_custo_infraestrutura_id',
'cadastro_paciente.prontuario AS paciente_prontuario',
'cadastro_cidadao.data_nascimento AS paciente_data_nascimento',
'cadastro_cidadao.nome_mae AS paciente_nome_mae',
'cadastro_cidadao.nome AS paciente_nome',
'cadastro_cidadao.nome_social AS paciente_nome_social',
'cadastro_cidadao.preferencia_nome_id as paciente_preferencia_nome_id',
'cadastro_cidadao.caracteristicas_fisicas AS paciente_caracteristicas_fisicas',
'cadastro_paciente.sequencial_desconhecido_em AS paciente_sequencial_desconhecido_em',
DB::raw("'ATENDIMENTO' as tipo"),
])
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_atendimento_soap.created_lotacao_id')
->join('painel_senha_fila', 'painel_senha_fila.id', 'ambulatorio_atendimento.fila_id')
->join('cadastro_paciente', 'cadastro_paciente.id', 'painel_senha_fila.paciente_id')
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id')
->leftJoin('cadastro_sexo', 'cadastro_sexo.id', 'cadastro_cidadao.sexo_id')
->join('sigtap.ocupacao', 'ocupacao.id', 'cadastro_lotacao.ocupacao_id')
->join('cadastro_centro_custo', 'cadastro_centro_custo.id', 'ambulatorio_atendimento_soap.created_centro_custo_id')
->join('cadastro_setor', 'cadastro_setor.id', 'cadastro_centro_custo.setor_id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->where('cadastro_centro_custo.infraestrutura_id', $infraestruturaId)
->where('cadastro_lotacao.usuario_id', $usuarioId)
->whereBetween('ambulatorio_atendimento_soap.created_at', $periodo)
->when($request->paciente, fn ($q, $value) => $q->where('cadastro_cidadao.nome', 'like', "{$value}%"))
->when($request->sexo_id, fn ($q, $id) => $q->where('cadastro_cidadao.sexo_id', $id))
->when($request->data_nascimento, fn ($q, $data) => $q
->whereDate('cadastro_cidadao.data_nascimento', Carbon::createFromFormat('d/m/Y', $data))
)
->when($request->atendimento, fn ($q, $id) => $q->where('ambulatorio_atendimento_soap.atendimento_id', $id))
);
$documentos = null;
$documentos = $atendimentoQuery;
$documentos = $documentos
->orderBy('data_hora')
->get()
->filter(function ($documento) {
$assinados = ImpressaoService::getImpressoesAtendimentoAssinados($documento->id);
if ($assinados->isEmpty() || $assinados->count() === 0) {
return true;
}
$atendimento = Atendimento::where('id', $documento->atendimento_id)->first();
$impressoes = ImpressaoService::getImpressoesAtendimento($atendimento);
return $impressoes->count() !== $assinados->count();
})
->map(function ($documento) {
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;
})
->values()
->toArray();
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',
],
'atendimento' => [
'nullable',
'integer',
],
]);
}
}

View File

@@ -0,0 +1,726 @@
<?php
namespace App\Services\Ambulatorio\AtendimentoEnfermagem;
use App\Enums\Ambulatorio\ProblemaCondicaoSituacao;
use App\Enums\Ambulatorio\TesteRapido as AmbulatorioTesteRapido;
use App\Enums\AtencaoBasica\AtendimentoIndividual\CondicaoAvaliada;
use App\Enums\AtencaoBasica\AtendimentoIndividual\TipoAtendimento;
use App\Enums\AtencaoBasica\ProcedimentoPequenaCirurgia;
use App\Enums\AtencaoBasica\TesteRapido as AtencaoBasicaTesteRapido;
use App\Enums\Geral\Ciap;
use App\Enums\Sigtap\Procedimento;
use App\Models\Administracao\Funcionalidade;
use App\Models\Ambulatorio\AtendimentoSoap;
use App\Models\Ambulatorio\ParametrizacaoInfraestruturaOcupacao;
use App\Models\AtencaoBasica\AtendimentoIndividual\AtendimentoIndividual;
use App\Models\AtencaoBasica\AtendimentoIndividual\ExameSolicitadoAvaliado;
use App\Models\AtencaoBasica\AtendimentoIndividual\TriagemNeonatal;
use App\Models\AtencaoBasica\Avaliacao\Avaliacao;
use App\Models\AtencaoBasica\MarcadorConsumoAlimentar\MarcadorConsumoAlimentar;
use App\Services\AtencaoBasica\AtendimentoDomiciliar\AtendimentoDomiciliarService;
use App\Services\AtencaoBasica\AtendimentoIndividual\AtendimentoIndividualService;
use App\Services\AtencaoBasica\Avaliacao\AvaliacaoService;
use App\Services\AtencaoBasica\MarcadorConsumoAlimentar\MarcadorConsumoAlimentarService;
use App\Services\AtencaoBasica\Procedimento\ProcedimentoService;
use App\Services\Service;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class EnfermagemAtencaoBasicaFichaService extends Service
{
public static function store($soap, $data = [])
{
if (is_null($soap->equipe_id)) {
return;
}
self::storeAtendimentoIndividual($soap, $data);
self::storeProcedimento($soap);
self::storeMarcadorConsumoAlimentar($soap, $data['marcador_consumo_alimentar']);
self::storeAtendimentoDomiciliar($soap, $data);
self::storeAvaliacao($soap, $data);
}
public static function storeAtendimentoIndividual($soap, $data)
{
if (!self::criaFicha($soap, 'atendimento-individual')) {
return;
}
$getProcedimentos = function () use ($soap) {
$procedimentos = collect();
$soap->procedimentos()
->get()
->each(function ($atendimentoProcedimento) use ($procedimentos) {
for ($i = 1; $i <= $atendimentoProcedimento->quantidade; $i++) {
$procedimentos->push([
'procedimento_id' => $atendimentoProcedimento->procedimento->id,
]);
}
});
return $procedimentos->all();
};
$getDpp = function () use ($soap) {
$ultimaDum = EnfermagemService::getUltimaDum($soap->atendimento->paciente);
if (!is_null($ultimaDum)) {
$ultimaDum = Carbon::createFromFormat('d/m/Y', $ultimaDum);
return $ultimaDum->addMonths(9)->addDays(7)->format('Y-m-d');
}
return null;
};
$getCondicoesAvaliadas = function () use ($soap) {
$condicoes = $soap->condicoesAvaliadas->pluck('id');
if ($soap->is_atendimento_pre_natal) {
$condicoes->push(CondicaoAvaliada::PRE_NATAL);
}
if ($soap->is_atendimento_puericultura) {
$condicoes->push(CondicaoAvaliada::PUERICULTURA);
}
return $condicoes->all();
};
$getExamesAvaliados = function () use ($data, $soap) {
$exames = [];
foreach ($data['exame_avaliado'] as $avaliacao) {
$exames[] = 'a_'. $avaliacao['id'];
}
foreach ($data['exame_solicitado']['exames'] as $solicitado) {
$exames[] = 's_'. $solicitado['exame_id'];
}
foreach ($soap->solicitacoesExames as $solicitacao) {
foreach ($solicitacao->itens as $item) {
if ($item->exame->codigo) {
$exameSolicitado = ExameSolicitadoAvaliado::where('codigo_procedimento', $item->exame->codigo)->first();
if ($exameSolicitado) {
$exames[] = 's_'. $exameSolicitado->id;
} else {
$exameSolicitado = TriagemNeonatal::where('codigo_procedimento', $item->exame->codigo)->first();
if ($exameSolicitado) {
$exames[] = 's_'. $exameSolicitado->id;
}
}
}
}
}
foreach ($soap->resultadosExames as $solicitacao) {
if ($solicitacao->exame->codigo) {
$exameSolicitado = ExameSolicitadoAvaliado::where('codigo_procedimento', $solicitacao->exame->codigo)->first();
if ($exameSolicitado) {
$exames[] = 'a_'. $exameSolicitado->id;
} else {
$exameSolicitado = TriagemNeonatal::where('codigo_procedimento', $solicitacao->exame->codigo)->first();
if ($exameSolicitado) {
$exames[] = 'a_'. $exameSolicitado->id;
}
}
}
}
return $exames;
};
$getTriagensNeonatal = function () use ($data) {
$exames = [];
foreach ($data['triagem_neonatal'] as $avaliacao) {
$exames[] = 'a_'. $avaliacao['id'];
}
foreach ($data['triagem_neonatal_solicitado']['exames'] as $solicitado) {
$exames[] = 's_'. $solicitado['exame_id'];
}
return $exames;
};
$getOutrosExames = function () use ($soap) {
$exames = collect();
$soap->solicitacoesExames->each(function ($solicitacao) use ($exames) {
$solicitacao->itens->each(fn ($item) => $exames->push([
'exame_id' => $item->exame_id,
'avaliado' => false,
'solicitado' => true,
]));
});
$soap->resultadosExames->each(function ($resultado) use ($exames) {
if (is_null($resultado->exame->codigo)) {
return;
}
$exames->push([
'exame_id' => $resultado->exame_id,
'avaliado' => true,
'solicitado' => false,
]);
});
return $exames;
};
$idadeGestacional = ['semanas' => null, 'dias' => null];
$dataInicioGravidez = EnfermagemService::getDataInicioGravidezNaoResolvida($soap->atendimento->paciente);
if (!is_null($dataInicioGravidez)) {
$interval = Carbon::today()->diff(Carbon::createFromFormat('d/m/Y', $dataInicioGravidez));
$idadeGestacional['semanas'] = (int) floor($interval->days / 7);
$idadeGestacional['dias'] = $interval->days % 7;
}
$existeSoap = AtendimentoSoap::where('atendimento_id', $soap->atendimento_id)
->get(['id', 'turno_id'])
->toArray();
$atIndividual = AtendimentoIndividual::whereIn('soap_id', array_column($existeSoap, 'id'))
->get(['id', 'turno_id', 'data_usuario_responsavel']);
$atIndId = null;
foreach ($atIndividual as $individual) {
if ($individual->turno_id == $soap->turno_id &&
$individual->data_usuario_responsavel == $soap->created_at->format('Y-m-d')) {
$atIndId = $individual->id;
break;
}
}
$problemasCondicoes = $soap->problemasCondicoes()
->where(fn ($q) => $q
->doesntHave('ciap')
->orWhereHas('ciap', fn ($q) => $q
->whereNotIn('codigo', [Ciap::GRAVIDEZ, Ciap::MEDICINA_PREVENTIVA_MANUTENCAO_DA_SAUDE])
)
)
->get()
->map(function ($problemaCondicao) use ($atIndId) {
$problemaCondicaoAnteriorId = null;
if ($problemaCondicao->problema_condicao_anterior_id) {
$problemaCondicaoAnteriorId = self::getProblemaCondicaoAnteriorId($problemaCondicao->problema_condicao_anterior_id, $atIndId);
}
return [
'id' => null,
'automatico' => $problemaCondicao->automatico,
'soap_problema_condicao_id' => $problemaCondicao->id,
'problema_condicao_anterior_id' => $problemaCondicaoAnteriorId,
'ciap_id' => $problemaCondicao->ciap_id,
'cid_id' => $problemaCondicao->cid_id,
'situacao_id' => $problemaCondicao->situacao_id,
'inicio' => $problemaCondicao->inicio
? $problemaCondicao->inicio->format('d/m/Y')
: null,
'fim' => $problemaCondicao->fim
? $problemaCondicao->fim->format('d/m/Y')
: null,
'observacao' => $problemaCondicao->observacao,
];
})
->toArray();
AtendimentoIndividualService::saveStore([
'origem' => 'ambulatorio_atendimento_enfermagem',
'soap_id' => $soap->id,
'paciente_id' => $soap->atendimento->paciente->id,
'complemento' => null,
'procedimentos' => $getProcedimentos($soap),
'condicao' => [
'gestante' => EnfermagemService::isPacienteGestante($soap),
],
'cadastro' => [
'data_usuario_responsavel' => $soap->created_at->format('Y-m-d'),
'unidade_id' => $soap->equipe->unidade_id,
'usuario_id' => $soap->createdLotacao->usuario_id,
'equipe_id' => $soap->equipe_id,
'ocupacao_id' => $soap->createdLotacao->ocupacao_id,
'usuario_auxiliar_id' => null,
'equipe_auxiliar_id' => null,
'ocupacao_auxiliar_id' => null,
],
'atendimento' => [
'id' => $atIndId,
'turno_id' => $soap->turno_id,
'local_atendimento_id' => $soap->atencao_basica_local_atendimento_id,
'tipo_atendimento_id' => $soap->atendimento_tipo_id,
'perimetro_cefalico' => $soap->objetivoAntropometria->atendimentoAntropometria->perimetro_cefalico ?? null,
'circunferencia_abdominal' => $soap->objetivoAntropometria->atendimentoAntropometria->circunferencia_abdominal ?? null,
'perimetro_panturrilha' => $soap->objetivoAntropometria->atendimentoAntropometria->perimetro_panturrilha ?? null,
'peso' => $soap->objetivoAntropometria->atendimentoAntropometria->peso ?? null,
'altura' => $soap->objetivoAntropometria->atendimentoAntropometria->altura ?? null,
'temperatura' => $soap->objetivoSinalVital->atendimentoSinalVital->temperatura ?? null,
'pressao_arterial' => $soap->objetivoSinalVital->atendimentoSinalVital->pressao_arterial ?? null,
'frequencia_respiratoria' => $soap->objetivoSinalVital->atendimentoSinalVital->frequencia_respiratoria ?? null,
'frequencia_cardiaca' => $soap->objetivoSinalVital->atendimentoSinalVital->frequencia_cardiaca ?? null,
'saturacao_o2' => $soap->objetivoSinalVital->atendimentoSinalVital->saturacao_o2 ?? null,
'glicemia' => $soap->objetivoGlicemiaCapilar->atendimentoGlicemiaCapilar->valor ?? null,
'momento_coleta_id' => $soap->objetivoGlicemiaCapilar->atendimentoGlicemiaCapilar->momento_coleta_id ?? null,
'vacinacao' => $soap->vacinacao_em_dia,
'modalidade_atencao_domiciliar_id' => null,
'aleitamento_materno_id' => $soap->puericultura_aleitamento_tipo_id,
'racionalidade_saude_id' => $soap->racionalidade_saude_id,
'dum' => $soap->dum ? $soap->dum->format('Y-m-d') : null,
'idade_gestacional_semanas' => $idadeGestacional['semanas'],
'idade_gestacional_dias' => $idadeGestacional['dias'],
'data_possivel_parto' => $getDpp($soap),
'gravidez_planejada' => $soap->pre_natal_gravidez_planejada,
'gestacao_previa' => $soap->antecedente->gestas_previas ?? null,
'parto' => $soap->antecedente->partos_realizados ?? null,
'problemas_condicoes' => $problemasCondicoes,
'observacao' => null,
'condicao_avaliada' => $getCondicoesAvaliadas(),
'doenca_transmissivel' => $soap->doencasTransmissiveis->pluck('id')->all(),
'rastreamento' => $soap->rastreamentos->pluck('id')->all(),
'exame_solicitado_avaliado' => $getExamesAvaliados(),
'triagem_neonatal' => $getTriagensNeonatal(),
'outros_exames' => $getOutrosExames(),
'nasf' => [],
'conduta' => $soap->condutas->pluck('id')->all(),
'encaminhamento' => $soap->encaminhamentos->pluck('tipo_id')->all(),
'ivcf' => array_merge(
[
'deseja_preencher' => $soap->ivcf ? true : false,
],
$soap->ivcf ? $soap->ivcf->toArray() : [],
),
],
]);
}
private static function getProblemaCondicaoAnteriorId($soapProblemaCondicaoAnteriorId, $atendimentoIndividualId = null)
{
$problemaCondicaoAnteriorId = null;
$problemaCondicaoAnterior = self::getProblemaCondicaoAtendendimentoIndividual($soapProblemaCondicaoAnteriorId, $atendimentoIndividualId);
if (!is_null($problemaCondicaoAnterior)) {
$problemaCondicaoAnteriorId = self::getLastProblemaCondicaoId($problemaCondicaoAnterior->id, $problemaCondicaoAnterior->situacao_id, $atendimentoIndividualId);
}
return $problemaCondicaoAnteriorId;
}
private static function getProblemaCondicaoAtendendimentoIndividual($soapProblemaCondicaoId, $atendimentoIndividualId = null)
{
$problemaCondicaoAtendimentoIndividual = DB::table('atencao_basica_atendimento_individual_problema_condicao')
->when($atendimentoIndividualId, fn ($q) => $q->where('atendimento_individual_id', '<>', $atendimentoIndividualId))
->where('soap_problema_condicao_id', $soapProblemaCondicaoId)
->select('id', 'situacao_id')
->first();
if (is_null($problemaCondicaoAtendimentoIndividual)) {
$problemaCondicaoSoap = DB::table('ambulatorio_atendimento_soap_problema_condicao')
->where('id', $soapProblemaCondicaoId)
->select('problema_condicao_anterior_id')
->first();
if (isset($problemaCondicaoSoap->problema_condicao_anterior_id)) {
return self::getProblemaCondicaoAtendendimentoIndividual($problemaCondicaoSoap->problema_condicao_anterior_id, $atendimentoIndividualId);
}
return null;
}
return $problemaCondicaoAtendimentoIndividual;
}
private static function getLastProblemaCondicaoId($id, $situacaoId, $atendimentoIndividualId = null)
{
$proximo = DB::table('atencao_basica_atendimento_individual_problema_condicao')
->when($atendimentoIndividualId, fn ($q) => $q->where('atendimento_individual_id', '<>', $atendimentoIndividualId))
->where('problema_condicao_anterior_id', $id)
->select('id', 'situacao_id')
->first();
if (is_null($proximo)) {
if ($situacaoId == ProblemaCondicaoSituacao::RESOLVIDO) {
return null;
}
else {
return $id;
}
}
return self::getLastProblemaCondicaoId($proximo->id, $proximo->situacao_id, $atendimentoIndividualId);
}
public static function storeProcedimento($soap)
{
if (!self::criaFicha($soap, 'procedimento')) {
return;
}
$procedimentosParaIgnorar = collect();
$hasProcedimentoColetaMaterialExameLaboratoriao = false;
$procedimentosParaIgnorar->push(Procedimento::ESCUTA_INICIAL_ORIENTACAO_ACOLHIMENTO_A_DEMANDA_ESPONT_NEA);
$getPequenasCirurgias = function () use ($soap, $procedimentosParaIgnorar) {
$pequenasCirurgias = collect();
if ($soap->orientacao_individual_em_saude) {
$pequenasCirurgias->push(ProcedimentoPequenaCirurgia::ORIENTACAO_INDIVIDUAL_EM_SAUDE);
}
return $pequenasCirurgias;
};
$getTestesRapidos = function () use ($soap, $procedimentosParaIgnorar) {
$testesRapidos = collect();
$testesRapidosSoap = $soap->testesRapidos()->get(['id', 'codigo']);
if ($procedimento = $testesRapidosSoap->where('id', AmbulatorioTesteRapido::GRAVIDEZ)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::GRAVIDEZ);
}
if ($procedimento = $testesRapidosSoap->where('id', AmbulatorioTesteRapido::DETECCAO_DE_HEPATITE_C)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::HEPATITE_C);
}
if ($procedimento = $testesRapidosSoap->where('id', AmbulatorioTesteRapido::DETECCAO_DE_INFECCAO_PELO_HIV)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::HIV);
}
if ($procedimento = $testesRapidosSoap->where('id', AmbulatorioTesteRapido::SIFILIS)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::SIFILIS);
}
if ($procedimento = $testesRapidosSoap->where('id', AmbulatorioTesteRapido::DETECCAO_DE_INFECCAO_PELO_HBV)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::HEPATITE_B);
}
if ($procedimento = $testesRapidosSoap->where('id', AmbulatorioTesteRapido::PROTEINURIA)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::DOSAGEM_PROTEINURIA);
}
if ($procedimento = $testesRapidosSoap->where('id', AmbulatorioTesteRapido::TESTE_DO_OLHINHO_TRV)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::TESTE_OLHINHO_TRV);
}
return $testesRapidos;
};
$getProcedimentos = function () use ($soap, $procedimentosParaIgnorar, &$hasProcedimentoColetaMaterialExameLaboratoriao) {
$procedimentos = collect();
$soap->procedimentos()
->get()
->reject(fn ($p) => $procedimentosParaIgnorar->contains($p->procedimento->codigo))
->each(function ($atendimentoProcedimento) use ($soap, $procedimentos, &$hasProcedimentoColetaMaterialExameLaboratoriao) {
if ($atendimentoProcedimento->procedimento->codigo === Procedimento::COLETA_DE_MATERIAL_PARA_EXAME_LABORATORIAL) {
$hasProcedimentoColetaMaterialExameLaboratoriao = true;
}
for ($i = 1; $i <= $atendimentoProcedimento->quantidade; $i++) {
$procedimentos->push([
'soap_id' => $soap->id,
'procedimento_id' => $atendimentoProcedimento->procedimento->id
]);
}
});
return $procedimentos;
};
$pequenasCirurgias = $getPequenasCirurgias();
$testesRapidos = $getTestesRapidos();
$procedimentos = $getProcedimentos();
ProcedimentoService::saveFromAmbulatorioAtendimentoEnfermagem([
'cadastro' => [
'soap_id' => $soap->id,
'data_usuario_responsavel' => $soap->created_at->format('Y-m-d'),
'usuario_id' => $soap->createdLotacao->usuario_id,
'equipe_id' => $soap->equipe_id,
'ocupacao_id' => $soap->createdLotacao->ocupacao_id,
],
'atendimentos' => [
[
'soap_id' => $soap->id,
'paciente_id' => $soap->atendimento->paciente->id,
'turno_id' => $soap->turno_id,
'local_atendimento_id' => $soap->atencao_basica_local_atendimento_id,
'microarea_id' => is_null($soap->atendimento->paciente->cidadao->domicilio_id)
? null
: ProcedimentoService::getCadastroDomiciliar([
'domicilio_id' => $soap->atendimento->paciente->cidadao->domicilio_id,
'profissional_equipe_id' => $soap->equipe_id,
])['microarea_id'] ?? null,
'escuta_inicial' => $soap->atendimento_tipo_id === TipoAtendimento::ESCUTA_INICIAL_ORIENTACAO,
'peso' => $soap->objetivoAntropometria->atendimentoAntropometria->peso ?? null,
'altura' => $soap->objetivoAntropometria->atendimentoAntropometria->altura ?? null,
'temperatura' => $soap->objetivoSinalVital->atendimentoSinalVital->temperatura ?? null,
'afericao_pa' => $soap->objetivoSinalVital->atendimentoSinalVital->pressao_arterial ?? null,
'frequencia_respiratoria' => $soap->objetivoSinalVital->atendimentoSinalVital->frequencia_respiratoria ?? null,
'frequencia_cardiaca' => $soap->objetivoSinalVital->atendimentoSinalVital->frequencia_cardiaca ?? null,
'saturacao_o2' => $soap->objetivoSinalVital->atendimentoSinalVital->saturacao_o2 ?? null,
'glicemia' => $soap->objetivoGlicemiaCapilar->atendimentoGlicemiaCapilar->valor ?? null,
'momento_coleta_id' => $soap->objetivoGlicemiaCapilar->atendimentoGlicemiaCapilar->momento_coleta_id ?? null,
'perimetro_cefalico' => $soap->objetivoAntropometria->atendimentoAntropometria->perimetro_cefalico ?? null,
'circunferencia_abdominal' => $soap->objetivoAntropometria->atendimentoAntropometria->circunferencia_abdominal ?? null,
'perimetro_panturrilha' => $soap->objetivoAntropometria->atendimentoAntropometria->perimetro_panturrilha ?? null,
'exame_laboratorial' => $hasProcedimentoColetaMaterialExameLaboratoriao,
'teste_rapido' => $testesRapidos->all(),
'procedimento_pequena_cirurgia' => $pequenasCirurgias->all(),
'administracao_medicamento' => null,
'procedimentos' => $procedimentos->all(),
],
],
]);
}
public static function storeMarcadorConsumoAlimentar($soap, $data)
{
if (!self::criaFicha($soap, 'marcador-consumo-alimentar')) {
return;
}
$existeSoap = AtendimentoSoap::where('atendimento_id', $soap->atendimento_id)
->get(['id', 'turno_id'])
->toArray();
$mConsumo = MarcadorConsumoAlimentar::whereIn('soap_id', array_column($existeSoap, 'id'))
->get(['id', 'soap_id','data_atendimento'])
->map(function ($item) use ($existeSoap) {
$soap = collect($existeSoap)->firstWhere('id', $item->soap_id);
$item->turno_id = $soap['turno_id'] ?? null;
return $item;
});
$marCon = null;
foreach ($mConsumo as $marConsumo) {
if ($marConsumo->turno_id == $soap->turno_id
&& $marConsumo->data_atendimento == $soap->created_at->format('Y-m-d')) {
$marCon = $marConsumo->id;
break;
}
}
$respostaUnica = array_filter($data['pergunta_unica'], fn ($valor) => $valor !== null);
$respostaMultipla = array_filter($data['pergunta_multipla'], fn ($valor) => $valor !== null);
if ((!empty($respostaUnica) || !empty($respostaMultipla)) && empty($marCon)) {
MarcadorConsumoAlimentarService::saveStore([
'soap_id' => $soap->id,
'data_atendimento' => $soap->created_at->format('Y-m-d'),
'local_atendimento' => $soap->atencao_basica_local_atendimento_id,
'paciente' => $soap->atendimento->paciente->id,
'usuario' => $soap->createdLotacao->usuario_id,
'cbo_codigo' => $soap->createdLotacao->ocupacao_id,
'unidade' => $soap->createdLotacao->infraestrutura->unidade_id,
'equipe' => $soap->equipe_id,
'pergunta' => [
'resposta_unica' => $respostaUnica,
'resposta_multipla' => $respostaMultipla,
],
]);
}elseif((!empty($respostaUnica) || !empty($respostaMultipla)) && !empty($marCon)) {
MarcadorConsumoAlimentarService::update($marCon,[
'soap_id' => $soap->id,
'data_atendimento' => $soap->created_at->format('Y-m-d'),
'local_atendimento' => $soap->atencao_basica_local_atendimento_id,
'paciente' => $soap->atendimento->paciente->id,
'usuario' => $soap->createdLotacao->usuario_id,
'cbo_codigo' => $soap->createdLotacao->ocupacao_id,
'unidade' => $soap->createdLotacao->infraestrutura->unidade_id,
'equipe' => $soap->equipe_id,
'pergunta' => [
'resposta_unica' => $respostaUnica,
'resposta_multipla' => $respostaMultipla,
],
]);
}
}
public static function storeAtendimentoDomiciliar($soap, $data)
{
if (!self::criaFicha($soap, 'atendimento-domiciliar')) {
return;
}
$atendimentos = [];
$problemas_condicoes = [];
foreach ($data['problemas_condicoes'] as $problemaCondicao) {
$problemas_condicoes[] = [
'id' => $problemaCondicao['id'],
'ciap' => ['id' => $problemaCondicao['ciap_id']],
'cid' => ['id' => $problemaCondicao['cid_id']],
];
}
$atendimentos[] = [
'data' => $soap->created_at->format('Y-m-d'),
'paciente_id' => $soap->atendimento->paciente->id,
'local_atendimento_id' => $soap->atencao_basica_local_atendimento_id,
'tipo_atendimento_id' => $soap->emad_tipo_atendimento_id,
'modalidade_id' => $soap->emad_modalidade_id,
'turno_id' => $soap->turno_id,
'conduta_desfecho_id' => $soap->emad_conduta_desfecho_id,
'codigo_cid' => $soap->cid ?? null,
'codigo_ciap' => $soap->ciap ?? null,
'procedimentos' => $data['procedimentos_emad'],
'condicoes' => $data['condicoes_emad'],
'problemas_condicoes' => $problemas_condicoes,
'condicao_avaliada' => $data['condicoes_avaliadas'],
'doenca_transmissivel' => $data['doencas_transmissiveis'],
'rastreamento' => $data['rastreamentos'],
'observacao_perfil_epidemiologico' => $soap->observacao_perfil_epidemiologico,
'perfis_epidemiologicos' => $soap->perfisEpidemiologicos->pluck('id'),
'ivcf' => array_merge(
[
'deseja_preencher' => $soap->ivcf ? true : false,
],
$soap->ivcf ? $soap->ivcf->toArray() : [],
),
];
AtendimentoDomiciliarService::saveStore([
'soap_id' => $soap->id,
'data' => $soap->created_at->format('Y-m-d'),
'usuario_id' => $soap->createdLotacao->usuario_id,
'equipe_id' => $soap->equipe_id,
'ocupacao_id' => $soap->createdLotacao->ocupacao_id,
'usuario_auxiliar_id' => null,
'equipe_auxiliar_id' => null,
'ocupacao_auxiliar_id' => null,
'atendimentos' => $atendimentos,
]);
}
public static function storeAvaliacao($soap, $data)
{
$hasAvaliacao = Avaliacao::where('paciente_id', $soap->atendimento->paciente->id)->first() ? true : false;
if (!self::criaFicha($soap, 'avaliacao') || $hasAvaliacao || !$data['ficha_avaliacao']) {
return;
}
AvaliacaoService::saveStore([
'soap_id' => $soap->id,
'data' => $soap->created_at->format('Y-m-d'),
'usuario_id' => $soap->createdLotacao->usuario_id,
'equipe_id' => $soap->equipe_id,
'unidade_id' => $soap->createdLotacao->infraestrutura->unidade_id,
'infraestrutura_id' => $soap->createdLotacao->infraestrutura->id,
'ocupacao_id' => $soap->createdLotacao->ocupacao_id,
'usuario_auxiliar_id' => null,
'equipe_auxiliar_id' => null,
'ocupacao_auxiliar_id' => null,
'condicoes' => $data['condicoes_emad'],
'condicao_avaliada' => $data['condicoes_avaliadas'],
'data' => $soap->created_at->format('Y-m-d'),
'paciente_id' => $soap->atendimento->paciente->id,
'turno_id' => $soap->turno_id,
'cid_primario' => $soap->emad_cid_primario_id,
'conclusao_id' => $soap->emad_conclusao_id,
'procedencia_id' => $soap->emad_procedencia_id,
'cuidador_id' => $soap->emad_cuidador_id,
'cpf_cuidador' => $soap->emad_cpf_cuidador,
'cns_cuidador' => $soap->emad_cns_cuidador,
'justificativa' => $data['emad_conclusao_justificativa'],
]);
}
private static function criaFicha($soap, $funcionalidadeIdentificador)
{
return ParametrizacaoInfraestruturaOcupacao::whereHas('parametrizacaoInfraestrutura', fn ($q) => $q
->where('infraestrutura_id', $soap->createdLotacao->infraestrutura_id)
)
->where('ocupacao_id', $soap->createdLotacao->ocupacao_id)
->whereHas('fichasAtb', fn ($q) => $q
->where('funcionalidade_id', self::getAtencaoBasicaFuncionalidadeId($funcionalidadeIdentificador))
)
->exists();
}
private static function getAtencaoBasicaFuncionalidadeId($identificador)
{
return Funcionalidade::whereHas('modulo', fn ($q) => $q
->where('identificador', 'atencao-basica')
)
->where('identificador', $identificador)
->first('id')->id;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,229 @@
<?php
namespace App\Services\Ambulatorio\AtendimentoEnfermagem;
use App\Enums\Ambulatorio\OutroProcedimento;
use App\Enums\Ambulatorio\TesteRapido as AmbulatorioTesteRapido;
use App\Enums\AtencaoBasica\ProcedimentoPequenaCirurgia;
use App\Enums\AtencaoBasica\TesteRapido as AtencaoBasicaTesteRapido;
use App\Enums\Sigtap\Procedimento;
use App\Models\Administracao\Funcionalidade;
use App\Models\Ambulatorio\ParametrizacaoInfraestruturaOcupacao;
use App\Services\AtencaoBasica\Procedimento\ProcedimentoService;
use App\Services\Service;
class PosConsultaAtencaoBasicaFichaService extends Service
{
public static function store($posConsulta)
{
if (is_null($posConsulta->equipe_id)) {
return;
}
self::storeProcedimento($posConsulta);
}
public static function storeProcedimento($posConsulta)
{
if (!self::criaFicha($posConsulta, 'procedimento')) {
return;
}
$procedimentosParaIgnorar = collect();
$hasProcedimentoColetaMaterialExameLaboratoriao = false;
$procedimentosParaIgnorar->push(Procedimento::ESCUTA_INICIAL_ORIENTACAO_ACOLHIMENTO_A_DEMANDA_ESPONT_NEA);
$getPequenasCirurgias = function () use ($posConsulta, $procedimentosParaIgnorar) {
$pequenasCirurgias = collect();
if ($posConsulta->orientacao_individual_em_saude) {
$pequenasCirurgias->push(ProcedimentoPequenaCirurgia::ORIENTACAO_INDIVIDUAL_EM_SAUDE);
}
$outrosProcedimentos = $posConsulta->outrosProcedimentos()->get(['id', 'codigo']);
if ($procedimento = $outrosProcedimentos->where('id', OutroProcedimento::RETIRADA_DE_PONTOS)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$pequenasCirurgias->push(ProcedimentoPequenaCirurgia::RETIRADA_DE_PONTOS_DE_CIRURGIAS);
}
if ($procedimento = $outrosProcedimentos->where('id', OutroProcedimento::CURATIVO_SIMPLES)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$pequenasCirurgias->push(ProcedimentoPequenaCirurgia::CURATIVO_SIMPLES);
}
if ($procedimento = $outrosProcedimentos->where('id', OutroProcedimento::CURATIVO_ESPECIAL)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$pequenasCirurgias->push(ProcedimentoPequenaCirurgia::CURATIVO_ESPECIAL);
}
return $pequenasCirurgias;
};
$getTestesRapidos = function () use ($posConsulta, $procedimentosParaIgnorar) {
$testesRapidos = collect();
$testesRapidosPosConsulta = $posConsulta->testesRapidos()->get(['id', 'codigo']);
if ($procedimento = $testesRapidosPosConsulta->where('id', AmbulatorioTesteRapido::GRAVIDEZ)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::GRAVIDEZ);
}
if ($procedimento = $testesRapidosPosConsulta->where('id', AmbulatorioTesteRapido::DETECCAO_DE_HEPATITE_C)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::HEPATITE_C);
}
if ($procedimento = $testesRapidosPosConsulta->where('id', AmbulatorioTesteRapido::DETECCAO_DE_INFECCAO_PELO_HIV)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::HIV);
}
if ($procedimento = $testesRapidosPosConsulta->where('id', AmbulatorioTesteRapido::SIFILIS)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::SIFILIS);
}
if ($procedimento = $testesRapidosPosConsulta->where('id', AmbulatorioTesteRapido::DETECCAO_DE_INFECCAO_PELO_HBV)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::HEPATITE_B);
}
if ($procedimento = $testesRapidosPosConsulta->where('id', AmbulatorioTesteRapido::PROTEINURIA)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::DOSAGEM_PROTEINURIA);
}
if ($procedimento = $testesRapidosPosConsulta->where('id', AmbulatorioTesteRapido::TESTE_DO_OLHINHO_TRV)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::TESTE_OLHINHO_TRV);
}
return $testesRapidos;
};
$getAdministracoesMedicamento = function () use ($posConsulta, $procedimentosParaIgnorar) {
$administracoesMedicamentos = collect();
$posConsulta->administracoesMedicamentos()->get(['id', 'codigo_procedimento'])
->each(function ($administracaoMedicamento) use ($administracoesMedicamentos, $procedimentosParaIgnorar) {
$procedimentosParaIgnorar->push($administracaoMedicamento->codigo_procedimento);
$administracoesMedicamentos->push($administracaoMedicamento->id);
});
return $administracoesMedicamentos;
};
$getProcedimentos = function () use ($posConsulta, $procedimentosParaIgnorar, &$hasProcedimentoColetaMaterialExameLaboratoriao) {
$procedimentos = collect();
$posConsulta->procedimentos()
->get()
->reject(fn ($p) => $procedimentosParaIgnorar->contains($p->procedimento->codigo))
->each(function ($atendimentoProcedimento) use ($posConsulta, $procedimentos, &$hasProcedimentoColetaMaterialExameLaboratoriao) {
if ($atendimentoProcedimento->procedimento->codigo === Procedimento::COLETA_DE_MATERIAL_PARA_EXAME_LABORATORIAL) {
$hasProcedimentoColetaMaterialExameLaboratoriao = true;
}
for ($i = 1; $i <= $atendimentoProcedimento->quantidade; $i++) {
$procedimentos->push([
'pos_consulta_id' => $posConsulta->id,
'procedimento_id' => $atendimentoProcedimento->procedimento->id
]);
}
});
return $procedimentos;
};
$pequenasCirurgias = $getPequenasCirurgias();
$testesRapidos = $getTestesRapidos();
$administracoesMedicamentos = $getAdministracoesMedicamento();
$procedimentos = $getProcedimentos();
ProcedimentoService::saveFromAmbulatorioPosConsulta([
'cadastro' => [
'pos_consulta_id' => $posConsulta->id,
'data_usuario_responsavel' => $posConsulta->created_at->format('Y-m-d'),
'usuario_id' => $posConsulta->createdLotacao->usuario_id,
'equipe_id' => $posConsulta->equipe_id,
'ocupacao_id' => $posConsulta->createdLotacao->ocupacao_id,
],
'atendimentos' => [
[
'pos_consulta_id' => $posConsulta->id,
'paciente_id' => $posConsulta->atendimento->paciente->id,
'turno_id' => $posConsulta->turno_id,
'local_atendimento_id' => $posConsulta->atencao_basica_local_atendimento_id,
'microarea_id' => is_null($posConsulta->atendimento->paciente->cidadao->domicilio_id)
? null
: ProcedimentoService::getCadastroDomiciliar([
'domicilio_id' => $posConsulta->atendimento->paciente->cidadao->domicilio_id,
'profissional_equipe_id' => $posConsulta->equipe_id,
])['microarea_id'] ?? null,
'escuta_inicial' => false,
'peso' => $posConsulta->antropometria->peso ?? null,
'altura' => $posConsulta->antropometria->altura ?? null,
'temperatura' => $posConsulta->sinalVital->temperatura ?? null,
'afericao_pa' => $posConsulta->sinalVital->pressao_arterial ?? null,
'frequencia_respiratoria' => $posConsulta->sinalVital->frequencia_respiratoria ?? null,
'frequencia_cardiaca' => $posConsulta->sinalVital->frequencia_cardiaca ?? null,
'saturacao_o2' => $posConsulta->sinalVital->saturacao_o2 ?? null,
'glicemia' => $posConsulta->glicemiaCapilar->valor ?? null,
'momento_coleta_id' => $posConsulta->glicemiaCapilar->momento_coleta_id ?? null,
'perimetro_cefalico' => $posConsulta->antropometria->perimetro_cefalico ?? null,
'circunferencia_abdominal' => $posConsulta->antropometria->circunferencia_abdominal ?? null,
'perimetro_panturrilha' => $posConsulta->antropometria->perimetro_panturrilha ?? null,
'exame_laboratorial' => $hasProcedimentoColetaMaterialExameLaboratoriao,
'teste_rapido' => $testesRapidos->all(),
'procedimento_pequena_cirurgia' => $pequenasCirurgias->all(),
'administracao_medicamento' => $administracoesMedicamentos->all(),
'procedimentos' => $procedimentos->all(),
],
],
]);
}
private static function criaFicha($posConsulta, $funcionalidadeIdentificador)
{
return ParametrizacaoInfraestruturaOcupacao::whereHas('parametrizacaoInfraestrutura', fn ($q) => $q
->where('infraestrutura_id', $posConsulta->createdLotacao->infraestrutura_id)
)
->where('ocupacao_id', $posConsulta->createdLotacao->ocupacao_id)
->whereHas('fichasAtb', fn ($q) => $q
->where('funcionalidade_id', self::getAtencaoBasicaFuncionalidadeId($funcionalidadeIdentificador))
)
->exists();
}
private static function getAtencaoBasicaFuncionalidadeId($identificador)
{
return Funcionalidade::whereHas('modulo', fn ($q) => $q
->where('identificador', 'atencao-basica')
)
->where('identificador', $identificador)
->first('id')->id;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,230 @@
<?php
namespace App\Services\Ambulatorio\AtendimentoEnfermagem;
use App\Enums\Ambulatorio\OutroProcedimento;
use App\Enums\Ambulatorio\TesteRapido as AmbulatorioTesteRapido;
use App\Enums\AtencaoBasica\AtendimentoIndividual\TipoAtendimento;
use App\Enums\AtencaoBasica\ProcedimentoPequenaCirurgia;
use App\Enums\AtencaoBasica\TesteRapido as AtencaoBasicaTesteRapido;
use App\Enums\Sigtap\Procedimento;
use App\Models\Administracao\Funcionalidade;
use App\Models\Ambulatorio\ParametrizacaoInfraestruturaOcupacao;
use App\Services\AtencaoBasica\Procedimento\ProcedimentoService;
use App\Services\Service;
class PreAtendimentoAtencaoBasicaFichaService extends Service
{
public static function store($preAtendimento)
{
if (is_null($preAtendimento->equipe_id)) {
return;
}
self::storeProcedimento($preAtendimento);
}
public static function storeProcedimento($preAtendimento)
{
if (!self::criaFicha($preAtendimento, 'procedimento')) {
return;
}
$procedimentosParaIgnorar = collect();
$hasProcedimentoColetaMaterialExameLaboratoriao = false;
$procedimentosParaIgnorar->push(Procedimento::ESCUTA_INICIAL_ORIENTACAO_ACOLHIMENTO_A_DEMANDA_ESPONT_NEA);
$getPequenasCirurgias = function () use ($preAtendimento, $procedimentosParaIgnorar) {
$pequenasCirurgias = collect();
if ($preAtendimento->orientacao_individual_em_saude) {
$pequenasCirurgias->push(ProcedimentoPequenaCirurgia::ORIENTACAO_INDIVIDUAL_EM_SAUDE);
}
$outrosProcedimentos = $preAtendimento->outrosProcedimentos()->get(['id', 'codigo']);
if ($procedimento = $outrosProcedimentos->where('id', OutroProcedimento::RETIRADA_DE_PONTOS)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$pequenasCirurgias->push(ProcedimentoPequenaCirurgia::RETIRADA_DE_PONTOS_DE_CIRURGIAS);
}
if ($procedimento = $outrosProcedimentos->where('id', OutroProcedimento::CURATIVO_SIMPLES)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$pequenasCirurgias->push(ProcedimentoPequenaCirurgia::CURATIVO_SIMPLES);
}
if ($procedimento = $outrosProcedimentos->where('id', OutroProcedimento::CURATIVO_ESPECIAL)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$pequenasCirurgias->push(ProcedimentoPequenaCirurgia::CURATIVO_ESPECIAL);
}
return $pequenasCirurgias;
};
$getTestesRapidos = function () use ($preAtendimento, $procedimentosParaIgnorar) {
$testesRapidos = collect();
$testesRapidosPreAtendimento = $preAtendimento->testesRapidos()->get(['id', 'codigo']);
if ($procedimento = $testesRapidosPreAtendimento->where('id', AmbulatorioTesteRapido::GRAVIDEZ)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::GRAVIDEZ);
}
if ($procedimento = $testesRapidosPreAtendimento->where('id', AmbulatorioTesteRapido::DETECCAO_DE_HEPATITE_C)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::HEPATITE_C);
}
if ($procedimento = $testesRapidosPreAtendimento->where('id', AmbulatorioTesteRapido::DETECCAO_DE_INFECCAO_PELO_HIV)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::HIV);
}
if ($procedimento = $testesRapidosPreAtendimento->where('id', AmbulatorioTesteRapido::SIFILIS)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::SIFILIS);
}
if ($procedimento = $testesRapidosPreAtendimento->where('id', AmbulatorioTesteRapido::DETECCAO_DE_INFECCAO_PELO_HBV)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::HEPATITE_B);
}
if ($procedimento = $testesRapidosPreAtendimento->where('id', AmbulatorioTesteRapido::PROTEINURIA)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::DOSAGEM_PROTEINURIA);
}
if ($procedimento = $testesRapidosPreAtendimento->where('id', AmbulatorioTesteRapido::TESTE_DO_OLHINHO_TRV)->first()) {
$procedimentosParaIgnorar->push($procedimento->codigo);
$testesRapidos->push(AtencaoBasicaTesteRapido::TESTE_OLHINHO_TRV);
}
return $testesRapidos;
};
$getAdministracoesMedicamento = function () use ($preAtendimento, $procedimentosParaIgnorar) {
$administracoesMedicamentos = collect();
$preAtendimento->administracoesMedicamentos()->get(['id', 'codigo_procedimento'])
->each(function ($administracaoMedicamento) use ($administracoesMedicamentos, $procedimentosParaIgnorar) {
$procedimentosParaIgnorar->push($administracaoMedicamento->codigo_procedimento);
$administracoesMedicamentos->push($administracaoMedicamento->id);
});
return $administracoesMedicamentos;
};
$getProcedimentos = function () use ($preAtendimento, $procedimentosParaIgnorar, &$hasProcedimentoColetaMaterialExameLaboratoriao) {
$procedimentos = collect();
$preAtendimento->procedimentos()
->get()
->reject(fn ($p) => $procedimentosParaIgnorar->contains($p->procedimento->codigo))
->each(function ($atendimentoProcedimento) use ($preAtendimento, $procedimentos, &$hasProcedimentoColetaMaterialExameLaboratoriao) {
if ($atendimentoProcedimento->procedimento->codigo === Procedimento::COLETA_DE_MATERIAL_PARA_EXAME_LABORATORIAL) {
$hasProcedimentoColetaMaterialExameLaboratoriao = true;
}
for ($i = 1; $i <= $atendimentoProcedimento->quantidade; $i++) {
$procedimentos->push([
'pre_atendimento_id' => $preAtendimento->id,
'procedimento_id' => $atendimentoProcedimento->procedimento->id
]);
}
});
return $procedimentos;
};
$pequenasCirurgias = $getPequenasCirurgias();
$testesRapidos = $getTestesRapidos();
$administracoesMedicamentos = $getAdministracoesMedicamento();
$procedimentos = $getProcedimentos();
ProcedimentoService::saveFromAmbulatorioPreAtendimento([
'cadastro' => [
'pre_atendimento_id' => $preAtendimento->id,
'data_usuario_responsavel' => $preAtendimento->created_at->format('Y-m-d'),
'usuario_id' => $preAtendimento->createdLotacao->usuario_id,
'equipe_id' => $preAtendimento->equipe_id,
'ocupacao_id' => $preAtendimento->createdLotacao->ocupacao_id,
],
'atendimentos' => [
[
'pre_atendimento_id' => $preAtendimento->id,
'paciente_id' => $preAtendimento->atendimento->paciente->id,
'turno_id' => $preAtendimento->turno_id,
'local_atendimento_id' => $preAtendimento->atencao_basica_local_atendimento_id,
'microarea_id' => is_null($preAtendimento->atendimento->paciente->cidadao->domicilio_id)
? null
: ProcedimentoService::getCadastroDomiciliar([
'domicilio_id' => $preAtendimento->atendimento->paciente->cidadao->domicilio_id,
'profissional_equipe_id' => $preAtendimento->equipe_id,
])['microarea_id'] ?? null,
'escuta_inicial' => $preAtendimento->atendimento_tipo_id === TipoAtendimento::ESCUTA_INICIAL_ORIENTACAO,
'peso' => $preAtendimento->antropometria->peso ?? null,
'altura' => $preAtendimento->antropometria->altura ?? null,
'temperatura' => $preAtendimento->sinalVital->temperatura ?? null,
'afericao_pa' => $preAtendimento->sinalVital->pressao_arterial ?? null,
'frequencia_respiratoria' => $preAtendimento->sinalVital->frequencia_respiratoria ?? null,
'frequencia_cardiaca' => $preAtendimento->sinalVital->frequencia_cardiaca ?? null,
'saturacao_o2' => $preAtendimento->sinalVital->saturacao_o2 ?? null,
'glicemia' => $preAtendimento->glicemiaCapilar->valor ?? null,
'momento_coleta_id' => $preAtendimento->glicemiaCapilar->momento_coleta_id ?? null,
'perimetro_cefalico' => $preAtendimento->antropometria->perimetro_cefalico ?? null,
'circunferencia_abdominal' => $preAtendimento->antropometria->circunferencia_abdominal ?? null,
'perimetro_panturrilha' => $preAtendimento->antropometria->perimetro_panturrilha ?? null,
'exame_laboratorial' => $hasProcedimentoColetaMaterialExameLaboratoriao,
'teste_rapido' => $testesRapidos->all(),
'procedimento_pequena_cirurgia' => $pequenasCirurgias->all(),
'administracao_medicamento' => $administracoesMedicamentos->all(),
'procedimentos' => $procedimentos->all(),
],
],
]);
}
private static function criaFicha($preAtendimento, $funcionalidadeIdentificador)
{
return ParametrizacaoInfraestruturaOcupacao::whereHas('parametrizacaoInfraestrutura', fn ($q) => $q
->where('infraestrutura_id', $preAtendimento->createdLotacao->infraestrutura_id)
)
->where('ocupacao_id', $preAtendimento->createdLotacao->ocupacao_id)
->whereHas('fichasAtb', fn ($q) => $q
->where('funcionalidade_id', self::getAtencaoBasicaFuncionalidadeId($funcionalidadeIdentificador))
)
->exists();
}
private static function getAtencaoBasicaFuncionalidadeId($identificador)
{
return Funcionalidade::whereHas('modulo', fn ($q) => $q
->where('identificador', 'atencao-basica')
)
->where('identificador', $identificador)
->first('id')->id;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,105 @@
<?php
namespace App\Services\Ambulatorio;
use App\Services\Ambulatorio\AtendimentoEnfermagem\EnfermagemService;
use App\Services\Ambulatorio\AtendimentoEnfermagem\PosConsultaService;
use App\Services\Ambulatorio\AtendimentoEnfermagem\PreAtendimentoService;
use App\Services\Service;
class AtendimentoEnfermagemService extends Service
{
public static function list()
{
switch (request()->funcionalidade) {
case 'pre-atendimento': {
return PreAtendimentoService::list();
}
case 'enfermagem': {
return EnfermagemService::list();
}
case 'pos-consulta': {
return PosConsultaService::list();
}
}
}
public static function create()
{
switch (request()->funcionalidade) {
case 'pre-atendimento': {
return PreAtendimentoService::create();
}
case 'enfermagem': {
return EnfermagemService::create();
}
case 'pos-consulta': {
return PosConsultaService::create();
}
}
}
public static function store()
{
switch (request()->funcionalidade) {
case 'pre-atendimento': {
return PreAtendimentoService::store();
}
case 'enfermagem': {
return EnfermagemService::store();
}
case 'pos-consulta': {
return PosConsultaService::store();
}
}
}
public static function destroy($id)
{
switch (request()->funcionalidade) {
case 'enfermagem': {
return EnfermagemService::destroy($id);
}
}
}
public static function uploadImagem()
{
switch (request()->funcionalidade) {
case 'enfermagem': {
return EnfermagemService::uploadImagem();
}
}
}
public static function storeFeridaProcedimento()
{
return EnfermagemService::storeFeridaProcedimento();
}
public static function destroyFeridaProcedimento($id)
{
return EnfermagemService::destroyFeridaProcedimento($id);
}
public static function validarProcedimentosCbo()
{
return EnfermagemService::validarProcedimentosCbo();
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,116 @@
<?php
namespace App\Services\Ambulatorio;
use App\Events\PainelSenha\ChamadaEvent;
use App\Models\Cadastro\Estabelecimento\Sala;
use App\Models\PainelSenha\Chamada;
use App\Models\PainelSenha\Fila;
use App\Models\PainelSenha\ParametrizacaoInfraestrutura;
use App\Models\PainelSenha\Tela;
use App\Services\Service;
use Exception;
use Illuminate\Validation\Rule;
class ChamadaService extends Service
{
public static function index($params)
{
return Chamada::where('tela_id', $params['tela_id'])
->when($params['modulo_ids'] ?? null, fn ($q, $moduloIds) => $q
->whereHas('fila', fn ($q) => $q
->whereHas('opcaoEntrada', fn ($q) => $q
->whereIn('modulo_id', $moduloIds)
)
)
)
->orderByDesc('created_at')
->take(4)
->get()
->map(fn ($chamada) => [
'id' => $chamada->id,
'paciente' => [
'cidadao' => [
'preferencia_nome_id' => $chamada->paciente->cidadao->preferencia_nome_id ?? null,
'nome' => $chamada->paciente->cidadao->nome ?? null,
'nome_social' => $chamada->paciente->cidadao->nome_social ?? null,
],
],
'sala' => [
'nome' => $chamada->sala->nome ?? null,
],
'senha' => $chamada->fila->senha ?? null,
]);
}
public static function store()
{
self::validateStore();
$fila = Fila::findOrFail(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' => $fila->paciente_id ?? null,
]);
FilaService::dispatch($fila->centro_custo_id);
$parametrizacaoInfraestrutura = ParametrizacaoInfraestrutura::where(
'infraestrutura_id',
$fila->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;
}
private static function validateStore()
{
request()->validate([
'fila_id' => [
'required',
'integer',
Rule::exists(Fila::class, 'id'),
],
'tela_id' => [
'required',
'integer',
Rule::exists(Tela::class, 'id'),
],
'sala_id' => [
'nullable',
'integer',
Rule::exists(Sala::class, 'id'),
],
]);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,772 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Administracao\Modulo;
use App\Enums\Ambulatorio\AgendamentoStatus;
use App\Enums\Cadastro\Estabelecimento\SetorTipo;
use App\Enums\PainelSenha\Status;
use App\Events\PainelSenha\FilaEvent;
use App\Models\Administracao\Funcionalidade;
use App\Models\Ambulatorio\ClassificacaoRisco;
use App\Models\Ambulatorio\ParametrizacaoInfraestruturaOcupacao;
use App\Models\Cadastro\Estabelecimento\CentroCusto;
use App\Models\Cadastro\Estabelecimento\Sala;
use App\Models\Cadastro\Parametrizacao\Parametrizacao;
use App\Models\PainelSenha\Encaminhamento;
use App\Models\PainelSenha\Fila;
use App\Models\PainelSenha\OpcaoEntrada;
use App\Models\PainelSenha\Prioridade;
use App\Models\PainelSenha\Tela;
use App\Models\PainelSenha\TempoEspera;
use App\Services\Administracao\ModuloService;
use App\Services\Geral\AgeService;
use App\Services\Service;
use App\Utils\MaskUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class FilaService extends Service
{
public static function list()
{
$centroCusto = CentroCusto::findOrFail(request()->centro_custo_id);
$servicos = self::getFormServicos($centroCusto);
return [
'additionals' => [
'data_atual' => Carbon::today()->format('d/m/Y'),
'permite_atendimento_enfermagem' => self::permiteAtendimentoEnfermagem($centroCusto),
],
'form' => [
'classificacoes_risco' => ClassificacaoRisco::orderBy('nome')
->get(['id', 'nome'])
->map(fn ($classificacaoRisco) => [
'id' => $classificacaoRisco->id,
'nome' => Str::upper($classificacaoRisco->nome),
]),
'opcoes_entrada' => OpcaoEntrada::where('modulo_id', ModuloService::getId(Modulo::AMBULATORIO))
->whereHas('centroCusto', function($query) use ($centroCusto) {
$query->where('infraestrutura_id', $centroCusto->infraestrutura_id);
})
->whereExists(function($query) {
$query->select(DB::raw(1))
->from('ambulatorio_atendimento')
->join('painel_senha_fila', 'painel_senha_fila.id', 'ambulatorio_atendimento.fila_id')
->whereNull('ambulatorio_atendimento.finalizado_em')
->whereColumn('painel_senha_fila.opcao_entrada_id', 'painel_senha_opcao_entrada.id');
})
->orderBy('nome')
->get(['id', 'nome']),
'prioridades' => Prioridade::orderBy('nome')
->get(['id', 'nome']),
'salas' => Sala::orderBy('nome')
->where('centro_custo_id', request()->centro_custo_id)
->get(['id', 'nome']),
'status' => DB::table('painel_senha_status')
->select([
'id',
'nome',
])
->orderBy('nome')
->get(),
'telas' => Tela::orderBy('nome')
->whereHas('opcoesChamada', fn ($q) => $q
->where('centro_custo_id', request()->centro_custo_id)
)
->get(['id', 'nome']),
'tempos_espera' => TempoEspera::orderBy('tempo')
->whereHas('infraestrutura.centrosCusto', fn ($q) => $q
->where('id', request()->centro_custo_id)
)
->get(['id', 'tempo'])
->map(fn ($tempoEspera) => [
'id' => $tempoEspera->id,
'minutos' => $tempoEspera->minutos,
]),
'ordenacoes' => collect([
['value' => 'dataHoraAgendamento', 'text' => 'Data/hora de agendamento'],
['value' => 'dataHoraChegada', 'text' => 'Data/hora de chegada'],
]),
'servicos' => $servicos,
'cria_ficha_atencao_basica_atendimento_domiciliar' => self::criaFicha('atendimento-domiciliar'),
'centros_custo_encaminhamento' => self::getCentrosCustoEncaminhamento(),
],
'model' => [
'data' => Carbon::today()->format('d/m/Y'),
'classificacao_risco_id' => null,
'opcao_entrada_id' => null,
'prioridade_id' => null,
'status_id' => Status::EM_ESPERA,
'tempo_espera_id' => null,
'ordenacao' => 'dataHoraAgendamento',
'servicos' => $servicos->pluck('id'),
'fila' => self::index((object) request()->all()),
],
];
}
private static function permiteAtendimentoEnfermagem($centroCusto)
{
$parametrizacaoOcupacao = DB::table('ambulatorio_parametrizacao_infraestrutura_ocupacao as parametrizacao_infraestrutura_ocupacao')
->join(
'ambulatorio_parametrizacao_infraestrutura as parametrizacao_infraestrutura',
'parametrizacao_infraestrutura.id',
'parametrizacao_infraestrutura_ocupacao.parametrizacao_infraestrutura_id'
)
->where('parametrizacao_infraestrutura.infraestrutura_id', $centroCusto->infraestrutura_id)
->where('parametrizacao_infraestrutura_ocupacao.ocupacao_id', self::getCurrentLotacao()->ocupacao_id)
->select('parametrizacao_infraestrutura_ocupacao.permite_atendimento_enfermagem')
->first();
if ($parametrizacaoOcupacao) {
return (bool) $parametrizacaoOcupacao->permite_atendimento_enfermagem;
}
return false;
}
private static function getFormServicos($centroCusto)
{
return DB::table('ambulatorio_servico as servico')
->join(
'ambulatorio_parametrizacao_infraestrutura_servico as parametrizacao_servico',
'parametrizacao_servico.servico_id',
'servico.id'
)
->join(
'ambulatorio_parametrizacao_infraestrutura as parametrizacao_infraestrutura',
'parametrizacao_infraestrutura.id',
'parametrizacao_servico.parametrizacao_infraestrutura_id'
)
->where('parametrizacao_infraestrutura.infraestrutura_id', $centroCusto->infraestrutura_id)
->select(
'servico.id',
'servico.nome'
)
->orderBy('servico.nome')
->get();
}
public static function index($params)
{
$parametrizacao = Parametrizacao::first();
$quantidadeDias = $parametrizacao->cadastro_paciente_desatualizado_quantidade_dias ?? 0;
$filas = DB::table('painel_senha_fila as fila')
->join(
'cadastro_centro_custo AS centro_custo',
'centro_custo.id',
'fila.centro_custo_id'
)
->join(
'cadastro_setor AS setor',
'setor.id',
'centro_custo.setor_id'
)
->join(
'painel_senha_opcao_entrada as opcao_entrada',
'opcao_entrada.id',
'fila.opcao_entrada_id'
)
->join(
'painel_senha_status as fila_status',
'fila_status.id',
'fila.status_id'
)
->leftJoin(
'painel_senha_prioridade as prioridade',
'prioridade.id',
'fila.prioridade_id'
)
->leftJoin(
'ambulatorio_atendimento as atendimento',
'atendimento.fila_id',
'fila.id'
)
->leftJoin('ambulatorio_atendimento_soap as soap_rascunho', fn ($j) => $j
->on('soap_rascunho.atendimento_id', 'atendimento.id')
->where('soap_rascunho.is_rascunho', true)
)
->leftJoin(
'cadastro_lotacao as soap_rascunho_lotacao',
'soap_rascunho_lotacao.id',
'soap_rascunho.created_lotacao_id'
)
->leftJoin(
'ambulatorio_agendamento as agendamento',
'agendamento.id',
'atendimento.agendamento_id'
)
->leftJoin(
'ambulatorio_jornada as jornada',
'jornada.id',
'agendamento.jornada_id'
)
->leftJoin(
'cadastro_lotacao as jornada_lotacao',
'jornada_lotacao.id',
'jornada.lotacao_id'
)
->leftJoin(
'ambulatorio_demanda_espontanea as demanda_espontanea',
'demanda_espontanea.id',
'atendimento.demanda_espontanea_id'
)
->leftJoin(
'cadastro_paciente as paciente',
'paciente.id',
DB::raw("COALESCE(demanda_espontanea.paciente_id, agendamento.paciente_id)")
)
->leftJoin(
'cadastro_cidadao as paciente_cidadao',
'paciente_cidadao.id',
'paciente.cidadao_id'
)
->leftJoinSub(
DB::table('atencao_basica_avaliacao')
->select('paciente_id', DB::raw('MAX(id) as id'))
->groupBy('paciente_id'),
'avaliacao',
'avaliacao.paciente_id',
'paciente.id'
)
->leftJoin(
'cadastro_usuario as usuario',
'usuario.id',
DB::raw("COALESCE(atendimento.responsavel_atual_usuario_id, demanda_espontanea.usuario_id, jornada_lotacao.usuario_id)")
)
->leftJoin(
'cadastro_cidadao as usuario_cidadao',
'usuario_cidadao.id',
'usuario.cidadao_id'
)
->leftJoin(
'cadastro_especialidade as especialidade',
'especialidade.id',
DB::raw("COALESCE(atendimento.responsavel_atual_especialidade_id, demanda_espontanea.especialidade_id, jornada.especialidade_id)")
)
->leftJoin(
'sigtap.ocupacao as ocupacao',
'ocupacao.id',
DB::raw("COALESCE(atendimento.responsavel_atual_ocupacao_id, demanda_espontanea.ocupacao_id, jornada_lotacao.ocupacao_id)")
)
->leftJoin(
'cadastro_lotacao as responsavel_encaminhamento_atual_lotacao',
'responsavel_encaminhamento_atual_lotacao.id',
'atendimento.responsavel_encaminhamento_atual_lotacao_id'
)
->leftJoin(
'cadastro_usuario as responsavel_encaminhamento_atual_usuario',
'responsavel_encaminhamento_atual_usuario.id',
'responsavel_encaminhamento_atual_lotacao.usuario_id'
)
->leftJoin(
'cadastro_cidadao as responsavel_encaminhamento_atual_usuario_cidadao',
'responsavel_encaminhamento_atual_usuario_cidadao.id',
'responsavel_encaminhamento_atual_usuario.cidadao_id'
)
->leftJoin(
'ambulatorio_atendimento_pre_atendimento as pre_atendimento',
'pre_atendimento.atendimento_id',
'atendimento.id'
)
->leftJoin(
'ambulatorio_classificacao_risco as classificacao_risco',
'classificacao_risco.id',
'pre_atendimento.classificacao_risco_id'
)
->whereNull('fila.deleted_at')
->whereRaw("fila.created_at >= DATE_SUB(CURDATE(), INTERVAL 15 DAY)")
->where('fila.evadido', false)
->where('fila.finalizado', false)
->where('opcao_entrada.modulo_id', ModuloService::getId(Modulo::AMBULATORIO))
->where('setor.tipo_id', $params->setor_tipo_id)
->where('centro_custo.id', $params->centro_custo_id)
->whereNull('atendimento.finalizado_em')
->select(DB::raw("
fila.id,
avaliacao.id as avaliacao_id,
DATE_FORMAT(fila.emitido_em, '%d/%m/%Y') as emitido_em,
atendimento.id as atendimento_id,
fila.senha as numero_senha,
CONCAT(opcao_entrada.sigla, fila.senha) as senha,
paciente_cidadao.nome as paciente_nome,
paciente_cidadao.nome_social as paciente_nome_social,
paciente_cidadao.preferencia_nome_id as paciente_preferencia_nome_id,
DATE_FORMAT(paciente_cidadao.data_nascimento, '%d/%m/%Y') as paciente_data_nascimento,
paciente_cidadao.cpf as paciente_cpf,
paciente_cidadao.cns as paciente_cns,
paciente_cidadao.nome_mae as paciente_nome_mae,
LPAD(paciente.prontuario, 6, '0') as paciente_prontuario,
paciente.id as paciente_id,
usuario.id as usuario_id,
usuario_cidadao.nome as usuario_nome,
ocupacao.id as ocupacao_id,
ocupacao.codigo as ocupacao_descricao,
especialidade.nome as especialidade_nome,
agendamento.jornada_id,
TIMESTAMP(jornada.data, agendamento.horario) as data_hora_agendamento,
fila.created_at as data_hora_chegada,
DATE_FORMAT(agendamento.horario, '%H:%i') as horario_agendado,
DATE_FORMAT(fila.created_at, '%H:%i') as horario_chegada,
classificacao_risco.id as classificacao_risco_id,
classificacao_risco.nome as classificacao_risco_nome,
opcao_entrada.id as opcao_entrada_id,
opcao_entrada.nome as opcao_entrada_nome,
prioridade.id as prioridade_id,
prioridade.nome as prioridade_nome,
prioridade.grau as prioridade_grau,
fila_status.id as status_id,
CASE WHEN paciente.updated_at IS NULL AND paciente_cidadao.updated_at IS NULL THEN
1
WHEN paciente.updated_at IS NOT NULL AND (paciente_cidadao.updated_at IS NULL OR paciente.updated_at > paciente_cidadao.updated_at) THEN
CASE WHEN " . ($quantidadeDias > 0 ? "DATE_ADD(paciente.updated_at, INTERVAL " . $quantidadeDias . " DAY) < NOW()" : "false") . " THEN
DATEDIFF(NOW(), DATE_ADD(paciente.updated_at, INTERVAL " . $quantidadeDias . " DAY))
ELSE
0
END
WHEN paciente_cidadao.updated_at IS NOT NULL AND (paciente.updated_at IS NULL OR paciente_cidadao.updated_at > paciente.updated_at) THEN
CASE WHEN " . ($quantidadeDias > 0 ? "DATE_ADD(paciente_cidadao.updated_at, INTERVAL " . $quantidadeDias . " DAY) < NOW()" : "false") . " THEN
DATEDIFF(NOW(), DATE_ADD(paciente_cidadao.updated_at, INTERVAL " . $quantidadeDias . " DAY))
ELSE
0
END
ELSE
0
END as dias_cadastro_desatualizado,
soap_rascunho_lotacao.usuario_id as soap_rascunho_usuario_id,
soap_rascunho_lotacao.ocupacao_id as soap_rascunho_ocupacao_id,
IF(
pre_atendimento.id IS NOT NULL
OR EXISTS (
SELECT 1
FROM ambulatorio_atendimento_soap as soap
WHERE soap.atendimento_id = atendimento.id
),
0,
1
) as allow_pre_atendimento,
atendimento.pos_consulta,
responsavel_encaminhamento_atual_usuario_cidadao.nome as responsavel_encaminhamento_atual_nome
"))
->addSelect([
'chamadas' => function ($query) {
$query->select(DB::raw("COALESCE(COUNT(chamada.id), 0)"))
->from('painel_senha_chamada AS chamada')
->whereColumn('chamada.fila_id', 'fila.id')
->whereColumn('chamada.status_id', 'fila.status_id');
},
])
->get();
$filas->each(function ($fila) {
$fila->is_encaminhado = !is_null($fila->responsavel_encaminhamento_atual_nome);
$fila->paciente_cpf = MaskUtil::getCpfMasked($fila->paciente_cpf);
$fila->paciente_cns = MaskUtil::getCnsMasked($fila->paciente_cns);
$fila->paciente_idade = isset($fila->paciente_data_nascimento)
? AgeService::getFormattedAge(Carbon::createFromFormat('d/m/Y', $fila->paciente_data_nascimento))
: null;
$fila->tempo_espera = self::getTempoEspera($fila->id);
$fila->servicos = self::getServicos($fila->atendimento_id);
$fila->allow_pre_atendimento = (bool) $fila->allow_pre_atendimento;
$fila->pos_consulta = (bool) $fila->pos_consulta;
unset($fila->atendimento_id);
});
return $filas;
}
public static function getTempoEspera($filaId)
{
$tempoEsperaTotal = DB::table('painel_senha_fila_historico AS historico')
->where('historico.fila_id', $filaId)
->select(
'historico.created_at',
'historico.status_id'
)
->distinct()
->get()
->reduce(function ($count, $historico) use ($filaId) {
if ($historico->status_id === Status::EM_ESPERA) {
$proximo = DB::table('painel_senha_fila_historico')
->where('fila_id', $filaId)
->where('created_at', '>', $historico->created_at)
->select('created_at')
->first();
return $count + Carbon::create($historico->created_at)
->diffInMinutes($proximo->created_at ?? Carbon::now());
}
return $count;
}, 1);
$centroCustoLogado = self::getCurrentCentroCusto();
$tempoEspera = DB::table('painel_senha_tempo_espera')
->whereNull('deleted_at')
->where('tempo', '<=', $tempoEsperaTotal)
->where('infraestrutura_id', $centroCustoLogado->infraestrutura_id)
->select(
'id',
'cor'
)
->orderByDesc('tempo')
->first();
if (is_null($tempoEspera)) {
$tempoEspera = DB::table('painel_senha_tempo_espera')
->whereNull('deleted_at')
->where('tempo', '>=', $tempoEsperaTotal)
->where('infraestrutura_id', $centroCustoLogado->infraestrutura_id)
->select(
'id',
'cor'
)
->orderBy('tempo')
->first();
}
$tempoEsperaTotal = Carbon::now()
->subMinutes($tempoEsperaTotal)
->diff(Carbon::now());
return [
'id' => $tempoEspera->id ?? null,
'cor' => $tempoEspera->cor ?? null,
'total' => [
'dias' => (int) $tempoEsperaTotal->format('%d') > 0
? (int) $tempoEsperaTotal->format('%d') : null,
'horas' => (int) $tempoEsperaTotal->format('%h') ?? null,
'minutos' => (int) $tempoEsperaTotal->format('%i') ?? null,
],
];
}
private static function getServicos($atendimentoId)
{
return DB::table('ambulatorio_atendimento_servico as atendimento_servico')
->join(
'ambulatorio_servico as servico',
'servico.id',
'atendimento_servico.servico_id'
)
->where('atendimento_servico.atendimento_id', $atendimentoId)
->select(
'servico.id',
'servico.nome'
)
->orderBy('servico.nome')
->get();
}
public static function store($params)
{
$centroCusto = CentroCusto::findOrFail($params->centro_custo_id);
$senha = (
Fila::where('opcao_entrada_id', $params->opcao_entrada_id)
->whereRaw('emitido_em = CURRENT_DATE')
->max('senha') ?? 0
) + 1;
$emitidoEm = (isset($params->habilita_integracao_aplicativo_feridas) && $params->habilita_integracao_aplicativo_feridas)
? $params->data_jornada->format('Y-m-d')
: now();
return Fila::create([
'paciente_id' => $params->paciente_id,
'centro_custo_id' => $centroCusto->id,
'status_id' => Status::EM_ESPERA,
'opcao_entrada_id' => $params->opcao_entrada_id,
'prioridade_id' => $params->prioridade_id,
'senha' => $senha,
'emitido_em' => $emitidoEm
]);
self::dispatch($centroCusto->id);
}
public static function answer($id)
{
$fila = Fila::findOrFail($id);
$fila->update(['status_id' => Status::EM_ATENDIMENTO]);
self::dispatch($fila->centro_custo_id);
}
public static function forward($id, $centroCustoIdTo)
{
$fila = Fila::findOrFail($id);
$centroCustoIdFrom = $fila->centro_custo_id;
$fila->update([
'centro_custo_id' => $centroCustoIdTo,
'status_id' => Status::EM_ESPERA,
]);
self::dispatch($centroCustoIdFrom);
self::dispatch($centroCustoIdTo);
}
public static function sendBack($id)
{
$fila = Fila::findOrFail($id);
$fila->update(['status_id' => Status::EM_ESPERA]);
self::dispatch($fila->centro_custo_id);
}
public static function evade($id)
{
$fila = Fila::findOrFail($id);
self::validateEvade();
$fila->update([
'evadido' => true,
'motivo_evasao' => request()->motivo,
'motivo_cancelamento_evasao' => null,
'finalizado' => true,
]);
if ($fila->ambulatorioAtendimento) {
$atendimento = $fila->ambulatorioAtendimento;
if ($atendimento->agendamento_id) {
$atendimento->agendamento->update([
'status_id' => AgendamentoStatus::EVADIDO
]);
}
$atendimento->update([
'finalizado_em' => Carbon::now(),
'finalizado_lotacao_id' => self::getCurrentLotacao()->id,
]);
}
self::dispatch($fila->centro_custo_id);
}
private static function validateEvade()
{
request()->validate([
'motivo' => [
'required',
'string',
'max:500',
],
]);
}
public static function undoEvade($id)
{
$fila = Fila::findOrFail($id);
self::validateUndoEvade();
if ($fila->evadido) {
$fila->update([
'evadido' => false,
'motivo_evasao' => null,
'motivo_cancelamento_evasao' => request()->motivo,
'finalizado' => false,
]);
if ($fila->ambulatorioAtendimento) {
$fila->ambulatorioAtendimento->update([
'finalizado_em' => null,
'finalizado_lotacao_id' => null,
]);
if ($fila->ambulatorioAtendimento->agendamento_id) {
$fila->ambulatorioAtendimento->agendamento->update([
'status_id' => AgendamentoStatus::AGENDADO
]);
}
}
self::dispatch($fila->centro_custo_id);
}
}
private static function validateUndoEvade()
{
request()->validate([
'motivo' => [
'required',
'string',
'max:500',
],
]);
}
public static function destroy($id)
{
$fila = Fila::findOrFail($id);
$centroCustoId = $fila->centro_custo_id;
$fila->delete();
self::dispatch($centroCustoId);
}
public static function dispatch($centroCustoId)
{
$centroCusto = CentroCusto::findOrFail($centroCustoId);
$fila = self::index((object) [
'centro_custo_id' => $centroCusto->id,
'setor_tipo_id' => $centroCusto->setor->tipo_id,
]);
FilaEvent::dispatch(
$centroCusto->setor->tipo_id,
$centroCusto->id,
Modulo::AMBULATORIO,
$fila
);
}
public static function getAgendamentosRetroativos()
{
$agendamentos = DB::table('ambulatorio_agendamento as agendamento')
->join(
'cadastro_paciente as paciente',
'paciente.id',
'agendamento.paciente_id'
)
->join(
'cadastro_cidadao as paciente_cidadao',
'paciente_cidadao.id',
'paciente.cidadao_id'
)
->join(
'ambulatorio_jornada as jornada',
'jornada.id',
'agendamento.jornada_id'
)
->join(
'cadastro_lotacao as jornada_lotacao',
'jornada_lotacao.id',
'jornada.lotacao_id'
)
->join(
'cadastro_usuario as usuario',
'usuario.id',
'jornada_lotacao.usuario_id'
)
->join(
'cadastro_cidadao as usuario_cidadao',
'usuario_cidadao.id',
'usuario.cidadao_id'
)
->join(
'cadastro_especialidade as especialidade',
'especialidade.id',
'jornada.especialidade_id'
)
->where('agendamento.status_id', AgendamentoStatus::AGENDADO)
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento as atendimento')
->whereColumn('atendimento.agendamento_id', 'agendamento.id')
->whereNull('atendimento.finalizado_em')
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento as atendimento')
->whereColumn('atendimento.agendamento_id', 'agendamento.id')
)
)
->whereDate('jornada.data', Carbon::createFromFormat('d/m/Y', request()->data))
->where('jornada.lotacao_id', self::getCurrentLotacao()->id)
->selectRaw("
agendamento.id,
DATE_FORMAT(agendamento.horario, '%H:%i') as horario,
paciente_cidadao.nome as paciente_nome,
paciente_cidadao.nome_social as paciente_nome_social,
paciente_cidadao.preferencia_nome_id as paciente_preferencia_nome_id,
DATE_FORMAT(paciente_cidadao.data_nascimento, '%d/%m/%Y') as paciente_data_nascimento,
paciente_cidadao.cpf as paciente_cpf,
paciente_cidadao.cns as paciente_cns,
paciente_cidadao.nome_mae as paciente_nome_mae,
LPAD(paciente.prontuario, 6, '0') as paciente_prontuario,
especialidade.nome as especialidade_nome
")
->get();
$agendamentos->each(function ($agendamento) {
$agendamento->paciente_cpf = MaskUtil::getCpfMasked($agendamento->paciente_cpf);
$agendamento->paciente_cns = MaskUtil::getCnsMasked($agendamento->paciente_cns);
$agendamento->paciente_idade = isset($agendamento->paciente_data_nascimento)
? AgeService::getFormattedAge(Carbon::createFromFormat('d/m/Y', $agendamento->paciente_data_nascimento))
: null;
});
return $agendamentos;
}
public static function criaFicha($funcionalidadeIdentificador)
{
$lotacaoLogada = self::getCurrentLotacao();
return ParametrizacaoInfraestruturaOcupacao::whereHas('parametrizacaoInfraestrutura', fn ($q) => $q
->where('infraestrutura_id', $lotacaoLogada->infraestrutura_id)
)
->where('ocupacao_id', $lotacaoLogada->ocupacao_id)
->whereHas('fichasAtb', fn ($q) => $q
->where('funcionalidade_id', Funcionalidade::whereHas('modulo', fn ($q) => $q
->where('identificador', 'atencao-basica')
)
->where('identificador', $funcionalidadeIdentificador)
->first('id')->id
)
)
->exists();
}
private static function getCentrosCustoEncaminhamento($centroCustoId = null)
{
if (is_null($centroCustoId)) {
return Encaminhamento::where('centro_custo_id_de', self::getCurrentCentroCusto()->id)
->whereHas('centroCustoPara', fn ($q) => $q
->whereHas('setor', fn ($q) => $q
->whereIn('tipo_id', [
SetorTipo::ENFERMAGEM,
SetorTipo::CONSULTORIO,
])
)
)
->get()
->map(fn ($encaminhamento) => [
'id' => $encaminhamento->centroCustoPara->id,
'setor_nome' => $encaminhamento->centroCustoPara->setor->nome,
]);
}
return CentroCusto::where('id', $centroCustoId)
->get()
->map(fn ($centroCusto) => [
'id' => $centroCusto->id,
'setor_nome' => $centroCusto->setor->nome,
]);
}
}

View File

@@ -0,0 +1,302 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Sigtap\ClassificacaoServicoAtencaoPsicossocial;
use App\Enums\Sigtap\Procedimento as ProcedimentoEnum;
use App\Enums\Sigtap\Registro as RegistroEnum;
use App\Enums\Sigtap\Servico as ServicoEnum;
use App\Models\Ambulatorio\Atendimento;
use App\Models\Ambulatorio\AtendimentoRaas;
use App\Models\Raas\CaraterAtendimento;
use App\Models\Raas\DestinoPaciente;
use App\Models\Raas\LocalRealizacaoExame;
use App\Models\Raas\MotivoSaidaPermanencia;
use App\Models\Raas\OrigemPaciente;
use App\Models\Sigtap\Classificacao;
use App\Models\Sigtap\Competencia;
use App\Services\Service;
use App\Utils\MaskUtil;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
class FormularioRaasService extends Service
{
public static function datatable()
{
$infraestruturaId = self::getCurrentCentroCusto()->infraestrutura_id;
$atendimentosComRaasPendentes = DB::table('ambulatorio_atendimento_procedimento')
->join('sigtap.procedimento_registro', 'procedimento_registro.procedimento_id', 'ambulatorio_atendimento_procedimento.procedimento_id')
->join('sigtap.registro', 'registro.id', 'procedimento_registro.registro_id')
->whereNull('ambulatorio_atendimento_procedimento.raas_atendimento_procedimento_id')
->where('registro.codigo', RegistroEnum::RAAS_ATENCAO_PSICOSSOCIAL)
->where(fn ($q) => $q
->whereNull('ambulatorio_atendimento_procedimento.soap_id')
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap')
->whereColumn('ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
)
)
->select('ambulatorio_atendimento_procedimento.atendimento_id')
->distinct();
return DB::table('ambulatorio_atendimento as atendimento')
->joinSub($atendimentosComRaasPendentes, 'raas_sub',
fn ($join) => $join->on('raas_sub.atendimento_id', 'atendimento.id')
)
->leftJoin('painel_senha_fila as fila', 'fila.id', 'atendimento.fila_id')
->leftJoin('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->leftJoin('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->leftJoin('cadastro_lotacao as jornada_lotacao', 'jornada_lotacao.id', 'jornada.lotacao_id')
->leftJoin('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->leftJoin('cadastro_centro_custo as demanda_espontanea_centro_custo', 'demanda_espontanea_centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->leftJoin('cadastro_paciente as paciente', 'paciente.id', DB::raw("COALESCE(demanda_espontanea.paciente_id, agendamento.paciente_id)"))
->leftJoin('cadastro_cidadao as paciente_cidadao', 'paciente_cidadao.id', 'paciente.cidadao_id')
->leftJoin('cadastro_sexo as paciente_cidadao_sexo', 'paciente_cidadao_sexo.id', 'paciente_cidadao.sexo_id')
->leftJoin('cadastro_usuario as usuario', 'usuario.id', DB::raw("COALESCE(demanda_espontanea.usuario_id, jornada_lotacao.usuario_id)"))
->leftJoin('cadastro_cidadao as usuario_cidadao', 'usuario_cidadao.id', 'usuario.cidadao_id')
->leftJoin('cadastro_especialidade as especialidade', 'especialidade.id', DB::raw("COALESCE(demanda_espontanea.especialidade_id, jornada.especialidade_id)"))
->whereRaw('COALESCE(jornada_lotacao.infraestrutura_id, demanda_espontanea_centro_custo.infraestrutura_id) = ?', [$infraestruturaId])
->selectRaw("
atendimento.id,
DATE_FORMAT(COALESCE(jornada.data, CAST(demanda_espontanea.created_at AS DATE)), '%d/%m/%Y') as data,
paciente_cidadao.nome as paciente_nome,
paciente_cidadao.nome_social as paciente_nome_social,
paciente_cidadao.preferencia_nome_id as paciente_preferencia_nome_id,
DATE_FORMAT(paciente_cidadao.data_nascimento, '%d/%m/%Y') as paciente_data_nascimento,
paciente_cidadao.cpf as paciente_cpf,
paciente_cidadao.cns as paciente_cns,
paciente_cidadao.nome_mae as paciente_nome_mae,
LPAD(paciente.prontuario, 7, '0') as paciente_prontuario,
usuario_cidadao.nome as usuario_nome,
especialidade.nome as especialidade_nome,
DATE_FORMAT(agendamento.horario, '%H:%i') as horario_agendado,
DATE_FORMAT(fila.created_at, '%H:%i') as horario_chegada
");
}
public static function create()
{
$atendimento = Atendimento::findOrFail(request()->atendimento_id);
$hasProcedimentoRaasQuePrecisaDeClassificacao = self::hasProcedimentoRaasQuePrecisaDeClassificacao($atendimento->id);
$hasProcedimentoRaasQuePrecisaDeAutorizacao = self::hasProcedimentoRaasQuePrecisaDeAutorizacao($atendimento->id);
return [
'additionals' => [
'has_procedimento_raas_que_precisa_de_classificacao' => $hasProcedimentoRaasQuePrecisaDeClassificacao,
'has_procedimento_raas_que_precisa_de_autorizacao' => $hasProcedimentoRaasQuePrecisaDeAutorizacao,
],
'form' => [
'origens_paciente' => OrigemPaciente::orderBy('nome')->get(['id', 'nome']),
'destinos_paciente' => DestinoPaciente::orderBy('nome')->get(['id', 'nome']),
'motivos_saida_permanencia' => MotivoSaidaPermanencia::orderBy('nome')->get(['id', 'nome']),
'carateres_atendimento' => CaraterAtendimento::orderBy('nome')->get(['id', 'nome']),
'classificacoes' => Classificacao::where('competencia_id', Competencia::max('id'))
->whereHas('servico', fn ($q) => $q
->where('codigo', ServicoEnum::SERVICO_DE_ATENCAO_PSICOSSOCIAL)
)
->whereIn('codigo', [
ClassificacaoServicoAtencaoPsicossocial::RESIDENCIA_TERAPEUTICA_EM_SAUDE_MENTAL,
ClassificacaoServicoAtencaoPsicossocial::SERVICO_RESIDENCIAL_TERAPEUTICO_TIPO_I_SRT_TIPO_I,
ClassificacaoServicoAtencaoPsicossocial::SERVICO_RESIDENCIAL_TERAPEUTICO_TIPO_II_SRT_TIPO_II,
])
->orderBy('nome')
->get(['id', 'nome']),
'locais_realizacao_exame' => LocalRealizacaoExame::orderBy('nome')->get(['id', 'nome']),
'procedimentos' => self::getProcedimentos($atendimento),
],
'model' => [
'origem_paciente_id' => $atendimento->raas->origem_paciente_id ?? null,
'destino_paciente_id' => $atendimento->raas->destino_paciente_id ?? null,
'motivo_saida_permanencia_id' => $atendimento->raas->motivo_saida_permanencia_id
?? $atendimento->especialidade->atencao_basica_motivo_saida_permanencia_id
?? null,
'carater_atendimento_id' => $atendimento->raas->carater_atendimento_id ?? null,
'numero_autorizacao' => $hasProcedimentoRaasQuePrecisaDeAutorizacao
? ($atendimento->raas->numero_autorizacao
?? $atendimento->especialidade->atencao_basica_numero_autorizacao
?? null
) : null,
'classificacao_id' => $hasProcedimentoRaasQuePrecisaDeClassificacao
? ($atendimento->raas->classificacao_id
?? (is_null($atendimento->especialidade)
? null
: Classificacao::where('competencia_id', Competencia::max('id'))
->whereHas('servico', fn ($q) => $q
->where('codigo', ServicoEnum::SERVICO_DE_ATENCAO_PSICOSSOCIAL)
)
->where('codigo', $atendimento->especialidade->atencao_basica_classificacao_codigo)
->first()->id ?? null
)
) : null,
'local_realizacao_exame_id' => $atendimento->raas->local_realizacao_exame_id ?? null,
],
];
}
private static function getProcedimentos($atendimento)
{
$procedimentos = DB::table('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('sigtap.procedimento as procedimento', 'procedimento.id', 'atendimento_procedimento.procedimento_id')
->join('sigtap.procedimento_registro as procedimento_registro', 'procedimento_registro.procedimento_id', 'procedimento.id')
->join('sigtap.registro as registro', 'registro.id', 'procedimento_registro.registro_id')
->whereNull('atendimento_procedimento.raas_atendimento_procedimento_id')
->where('atendimento_procedimento.atendimento_id', $atendimento->id)
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->where('registro.codigo', RegistroEnum::RAAS_ATENCAO_PSICOSSOCIAL)
->selectRaw("
procedimento.id,
procedimento.codigo,
procedimento.nome
")
->distinct()
->get();
$procedimentos->each(function ($procedimento) {
$procedimento->codigo = MaskUtil::getProcedimentoMasked($procedimento->codigo);
});
return $procedimentos;
}
public static function store()
{
self::validate();
$atendimento = Atendimento::findOrFail(request()->atendimento_id);
AtendimentoRaas::updateOrCreate(
['atendimento_id' => $atendimento->id],
[
'origem_paciente_id' => request()->origem_paciente_id,
'destino_paciente_id' => request()->destino_paciente_id,
'motivo_saida_permanencia_id' => request()->motivo_saida_permanencia_id,
'carater_atendimento_id' => request()->carater_atendimento_id,
'numero_autorizacao' => self::hasProcedimentoRaasQuePrecisaDeAutorizacao($atendimento->id)
? request()->numero_autorizacao
: null,
'classificacao_id' => self::hasProcedimentoRaasQuePrecisaDeClassificacao($atendimento->id)
? request()->classificacao_id
: null,
'local_realizacao_exame_id' => request()->local_realizacao_exame_id,
]
);
return $atendimento->raas;
}
private static function validate()
{
request()->validate([
'atendimento_id' => [
'required',
'integer',
Rule::exists(Atendimento::class, 'id'),
],
'origem_paciente_id' => [
'required',
'integer',
Rule::exists(OrigemPaciente::class, 'id'),
],
'destino_paciente_id' => [
'required',
'integer',
Rule::exists(DestinoPaciente::class, 'id'),
],
'motivo_saida_permanencia_id' => [
'required',
'integer',
Rule::exists(MotivoSaidaPermanencia::class, 'id'),
],
'carater_atendimento_id' => [
'required',
'integer',
Rule::exists(CaraterAtendimento::class, 'id'),
],
'numero_autorizacao' => [
'nullable',
Rule::requiredIf(fn () => self::hasProcedimentoRaasQuePrecisaDeAutorizacao(request()->atendimento_id)),
'digits_between:1,13',
],
'classificacao_id' => [
'nullable',
Rule::requiredIf(fn () => self::hasProcedimentoRaasQuePrecisaDeClassificacao(request()->atendimento_id)),
'integer',
Rule::exists(Classificacao::class, 'id'),
],
'local_realizacao_exame_id' => [
'required',
'integer',
Rule::exists(LocalRealizacaoExame::class, 'id'),
],
]);
}
private static function hasProcedimentoRaasQuePrecisaDeClassificacao($atendimentoId)
{
return DB::table('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('sigtap.procedimento as procedimento', 'procedimento.id', 'atendimento_procedimento.procedimento_id')
->whereNull('atendimento_procedimento.raas_atendimento_procedimento_id')
->where('atendimento_procedimento.atendimento_id', $atendimentoId)
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->where('procedimento.codigo', ProcedimentoEnum::ACOMPANHAMENTO_DE_PACIENTE_EM_SAUDE_MENTAL)
->exists();
}
private static function hasProcedimentoRaasQuePrecisaDeAutorizacao($atendimentoId)
{
return DB::table('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('sigtap.procedimento as procedimento', 'procedimento.id', 'atendimento_procedimento.procedimento_id')
->whereNull('atendimento_procedimento.raas_atendimento_procedimento_id')
->where('atendimento_procedimento.atendimento_id', $atendimentoId)
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereIn('procedimento.codigo', [
ProcedimentoEnum::ACOMPANHAMENTO_DE_PACIENTE_EM_SAUDE_MENTAL,
ProcedimentoEnum::ACOMPANHAMENTO_DE_PESSOAS_COM_NECESSIDADES_DECORRENTES_DO_USO_DE_ALCOOL_CRACK_E_OUTRAS_DROGAS,
ProcedimentoEnum::ACOMPANHAMENTO_DE_PESSOAS_ADULTAS_COM_SOFRIMENTO_OU_TRANSTORNOS_MENTAIS_DECORRENTES_DO_USO_DE_CRACK_ALCOOL_E_OUTRAS_DROGAS,
ProcedimentoEnum::ACOMPANHAMENTO_DA_POPULACAO_INFANTO_JUVENIL_COM_SOFRIMENTO_OU_TRANSTORNOS_MENTAIS_DECORRENTES_DO_USO_DE_CRACK_ALCOOL_E_OUTRAS_DROGAS,
])
->exists();
}
}

View File

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

View File

@@ -0,0 +1,976 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Administracao\Modulo;
use App\Enums\Ambulatorio\AgendamentoStatus;
use App\Enums\Ambulatorio\AgendamentoTipo;
use App\Enums\Ambulatorio\JornadaTipo;
use App\Models\Ambulatorio\Agendamento;
use App\Models\Ambulatorio\Jornada;
use App\Models\Cadastro\Especialidade;
use App\Models\Cadastro\Estabelecimento\Infraestrutura;
use App\Models\Cadastro\Estabelecimento\Unidade;
use App\Models\Cadastro\Feriado\Feriado;
use App\Models\Cadastro\SujeitoAtencao\Usuario;
use App\Models\Geral\DiaSemana;
use App\Models\Sigtap\Procedimento;
use App\Services\Regulacao\SolicitacaoService as RegulacaoSolicitacaoService;
use App\Services\Service;
use App\Services\Sigtap\ProcedimentoValidationService;
use App\Utils\MaskUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
class GerenciamentoMedicoService extends Service
{
public static function datatable()
{
$usuarios = DB::table('cadastro_usuario')
->join(
'cadastro_cidadao',
'cadastro_cidadao.id',
'cadastro_usuario.cidadao_id'
)
->whereNull('cadastro_usuario.deleted_at')
->select(DB::raw("
cadastro_usuario.id,
cadastro_cidadao.nome,
DATE_FORMAT(cadastro_cidadao.data_nascimento, '%d/%m/%Y') as data_nascimento,
CONCAT(
SUBSTR(cadastro_cidadao.cpf,1,3),
'.',
SUBSTR(cadastro_cidadao.cpf,4,3),
'.',
SUBSTR(cadastro_cidadao.cpf,7,3),
'-',
SUBSTR(cadastro_cidadao.cpf,10,2)
) AS cpf,
cadastro_cidadao.cns
"));
return datatables()
->of($usuarios)
->filterColumn('cadastro_cidadao.data_nascimento', function ($query, $keyword) {
$query->whereRaw("DATE_FORMAT(cadastro_cidadao.data_nascimento, '%d/%m/%Y') LIKE ?", ["%{$keyword}%"])
->orWhereRaw(
"CONCAT(
SUBSTR(cadastro_cidadao.data_nascimento,9,2),
SUBSTR(cadastro_cidadao.data_nascimento,6,2),
SUBSTR(cadastro_cidadao.data_nascimento,1,4)
) like ?",
["%{$keyword}%"]
);
})
->filterColumn('cadastro_cidadao.cpf', function ($query, $keyword) {
$query->whereRaw("cadastro_cidadao.cpf LIKE ?", ["%{$keyword}%"])
->orWhereRaw(
"CONCAT(
SUBSTR(cadastro_cidadao.cpf,1,3),
'.',
SUBSTR(cadastro_cidadao.cpf,4,3),
'.',
SUBSTR(cadastro_cidadao.cpf,7,3),
'-',
SUBSTR(cadastro_cidadao.cpf,10,2)
) LIKE ?",
["%{$keyword}%"]
);
})
->skipTotalRecords()
->toJson();
}
public static function edit($usuarioId)
{
$usuario = Usuario::findOrFail($usuarioId);
return [
'form' => self::getFormData($usuario),
'model' => self::getModelData(),
];
}
private static function getFormData($usuario)
{
return [
'usuario' => self::getUsuarioData($usuario),
'origem' => [
'feriados' => self::getFeriados(),
'unidades' => self::getOrigemUnidades((object) ['usuario_id' => $usuario->id]),
'infraestruturas' => [],
'ocupacoes' => [],
'especialidades' => [],
'datas' => [],
'agendamentos' => [],
],
'destino' => [
'unidades' => [],
'infraestruturas' => [],
'ocupacoes' => [],
'especialidades' => [],
'usuarios' => [],
'jornadas' => [],
]
];
}
private static function getUsuarioData($usuario)
{
$cidadao = $usuario->cidadao()->setEagerLoads([])->first(['nome', 'data_nascimento', 'cns', 'cpf']);
return [
'nome' => $cidadao->nome,
'data_nascimento' => is_null($cidadao->data_nascimento)
? null : (new Carbon($cidadao->data_nascimento))->format('d/m/Y'),
'cns' => MaskUtil::getCnsMasked($cidadao->cns),
'cpf' => MaskUtil::getCpfMasked($cidadao->cpf),
];
}
private static function getModelData()
{
return [
'origem' => [
'unidade_id' => null,
'infraestrutura_id' => null,
'ocupacao_id' => null,
'especialidade_id' => null,
'data' => null,
],
'destino' => [
'unidade_id' => null,
'infraestrutura_id' => null,
'ocupacao_id' => null,
'especialidade_id' => null,
'usuario_id' => null,
'agendamentos' => [],
'jornada_id' => null,
'motivo_agendamento_excedente' => null,
],
'cancelamento' => [
'agendamentos' => [],
'motivo' => null,
]
];
}
public static function list()
{
$params = (object) request()->all();
switch (request()->origem) {
case 'origem': {
return self::getListOrigemData($params);
}
case 'destino': {
return self::getListDestinoData($params);
}
}
}
private static function getListOrigemData($params)
{
switch (request()->listar) {
case 'infraestruturas': {
return [
'infraestruturas' => self::getOrigemInfraestruturas($params),
'ocupacoes' => [],
'especialidades' => [],
'datas' => [],
'agendamentos' => [],
];
}
case 'ocupacoes': {
return [
'ocupacoes' => self::getOrigemOcupacoes($params),
'especialidades' => [],
'datas' => [],
'agendamentos' => [],
];
}
case 'especialidades': {
return [
'especialidades' => self::getOrigemEspecialidades($params),
'datas' => [],
'agendamentos' => [],
];
}
case 'datas': {
return [
'datas' => self::getOrigemDatas($params),
'agendamentos' => [],
];
}
case 'agendamentos': {
return [
'agendamentos' => self::getOrigemAgendamentos($params),
];
}
}
}
private static function getOrigemUnidades($params)
{
return Unidade::whereHas('infraestruturas', fn ($q) => $q
->whereHas('lotacoes', fn ($q) => $q
->where('usuario_id', $params->usuario_id)
->whereHas('ambulatorioJornadas', fn ($q) => $q
->whereDate('data', '>=', Carbon::today())
->whereHas('agendamentos', fn ($q) => $q
->where('status_id', AgendamentoStatus::AGENDADO)
)
)
)
)
->orderBy('nome_fantasia')
->get(['id', 'nome_fantasia']);
}
private static function getOrigemInfraestruturas($params)
{
return Infraestrutura::setEagerLoads([])
->where('unidade_id', $params->unidade_id)
->whereHas('lotacoes', fn ($q) => $q
->where('usuario_id', $params->usuario_id)
->whereHas('ambulatorioJornadas', fn ($q) => $q
->whereDate('data', '>=', Carbon::today())
->whereHas('agendamentos', fn ($q) => $q
->where('status_id', AgendamentoStatus::AGENDADO)
)
)
)
->get(['id', 'nome', 'principal', 'unidade_id'])
->map(fn ($infraestrutura) => [
'id' => $infraestrutura->id,
'nome' => $infraestrutura->nome,
])
->sortBy('nome')
->values();
}
private static function getOrigemOcupacoes($params)
{
return DB::table('sigtap.ocupacao as ocupacao')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao as lotacao')
->whereColumn('lotacao.ocupacao_id', 'ocupacao.id')
->where('lotacao.usuario_id', $params->usuario_id)
->where('lotacao.infraestrutura_id', $params->infraestrutura_id)
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_jornada as jornada')
->whereColumn('jornada.lotacao_id', 'lotacao.id')
->whereDate('jornada.data', '>=', Carbon::today())
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento as agendamento')
->whereColumn('agendamento.jornada_id', 'jornada.id')
->where('status_id', AgendamentoStatus::AGENDADO)
)
)
)
->orderByRaw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome)")
->select(
'ocupacao.id',
DB::raw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) as descricao")
)
->get();
}
private static function getOrigemEspecialidades($params)
{
return Especialidade::where('ocupacao_id', $params->ocupacao_id)
->whereHas('ambulatorioJornadas', fn ($q) => $q
->whereDate('data', '>=', Carbon::today())
->whereHas('lotacao', fn ($q) => $q
->where('usuario_id', $params->usuario_id)
->where('infraestrutura_id', $params->infraestrutura_id)
)
->whereHas('agendamentos', fn ($q) => $q
->where('status_id', AgendamentoStatus::AGENDADO)
)
)
->orderBy('nome')
->get(['id', 'nome']);
}
private static function getOrigemDatas($params)
{
$feriados = self::getFeriados()->map(fn ($f) => Carbon::createFromFormat('d/m/Y', $f->data)->setTime(0, 0));
$datas = Jornada::whereDate('data', '>=', Carbon::today())
->where('especialidade_id', $params->especialidade_id)
->whereHas('lotacao', fn ($q) => $q
->where('usuario_id', $params->usuario_id)
->where('infraestrutura_id', $params->infraestrutura_id)
)
->whereHas('agendamentos', fn ($q) => $q
->where('status_id', AgendamentoStatus::AGENDADO)
)
->groupBy('data')
->select(
'data',
DB::raw("(
SUM(COALESCE(quantidade_consulta, 0))
+
SUM(COALESCE(quantidade_retorno, 0))
) as quantidade_total")
)
->get()
->reject(fn ($d) => $feriados->contains($d->data))
->values();
$datas->each(function ($data) use ($params) {
$data->quantidade_total = (int) $data->quantidade_total;
$data->quantidade_agendada = Agendamento::whereNotIn('status_id', self::getStatusLiberamHorario())
->whereHas('jornada', fn ($q) => $q
->whereDate('data', $data->data)
->whereHas('lotacao', fn ($q) => $q
->where('usuario_id', $params->usuario_id)
->where('infraestrutura_id', $params->infraestrutura_id)
)
)
->count();
});
return $datas;
}
private static function getFeriados()
{
return Feriado::whereHas('modulos', fn ($q) => $q
->where('identificador', Modulo::AMBULATORIO)
)
->orderBy('data')
->get()
->map(fn ($feriado) => (object) [
'data' => (new Carbon($feriado->data))->format('d/m/Y'),
'tipo_descricao' => $feriado->tipo->descricao,
'observacao' => $feriado->observacao,
]);
}
private static function getOrigemAgendamentos($params)
{
return Agendamento::where('status_id', AgendamentoStatus::AGENDADO)
->whereHas('jornada', fn ($q) => $q
->whereDate('data', Carbon::createFromFormat('d/m/Y', $params->data))
->where('especialidade_id', $params->especialidade_id)
->whereHas('lotacao', fn ($q) => $q
->where('usuario_id', $params->usuario_id)
->where('infraestrutura_id', $params->infraestrutura_id)
)
)
->get(['id', 'jornada_id', 'horario', 'tipo_id', 'paciente_id', 'regulacao_solicitacao_id', 'created_lotacao_id'])
->map(function ($agendamento) {
$paciente = $agendamento->paciente()->setEagerLoads([])->first(['cidadao_id', 'prontuario']);
$cidadao = $paciente->cidadao()->setEagerLoads([])->first(['id', 'nome', 'data_nascimento']);
$tipo = $agendamento->tipo()->first(['id', 'nome']);
return (object) [
'id' => $agendamento->id,
'is_from_regulacao' => !is_null($agendamento->regulacao_solicitacao_id),
'horario' => $agendamento->horario->format('H:i'),
'tipo_id' => $tipo->id,
'tipo_nome' => $tipo->nome,
'paciente_nome' => $cidadao->nome,
'paciente_data_nascimento' => is_null($cidadao->data_nascimento)
? null : (new Carbon($cidadao->data_nascimento))->format('d/m/Y'),
'paciente_prontuario' => $paciente->prontuario,
'paciente_telefone' => MaskUtil::getPhoneMasked($paciente->cidadao->telefone_principal->numero ?? null),
'usuario_agendador_nome' => $agendamento->createdLotacao()
->first('usuario_id')
->usuario()
->setEagerLoads([])
->first('cidadao_id')
->cidadao()
->setEagerLoads([])
->first('nome')
->nome
];
})
->sortBy([
['horario', 'asc'],
['paciente_nome', 'asc'],
])
->values();
}
private static function getListDestinoData($params)
{
switch (request()->listar) {
case 'unidades': {
return [
'unidades' => self::getDestinoUnidades(),
'infraestruturas' => [],
'ocupacoes' => [],
'especialidades' => [],
'usuarios' => [],
'jornadas' => [],
];
}
case 'infraestruturas': {
return [
'infraestruturas' => self::getDestinoInfraestruturas($params),
'ocupacoes' => [],
'especialidades' => [],
'usuarios' => [],
'jornadas' => [],
];
}
case 'ocupacoes': {
return [
'ocupacoes' => self::getDestinoOcupacoes($params),
'especialidades' => [],
'usuarios' => [],
'jornadas' => [],
];
}
case 'especialidades': {
return [
'especialidades' => self::getDestinoEspecialidades($params),
'usuarios' => [],
'jornadas' => [],
];
}
case 'usuarios': {
return [
'usuarios' => self::getDestinoUsuarios($params),
'jornadas' => [],
];
}
case 'jornadas': {
return [
'jornadas' => self::getDestinoJornadas($params),
];
}
}
}
private static function getDestinoUnidades()
{
return Unidade::whereHas('infraestruturas', fn ($q) => $q
->whereHas('lotacoes', fn ($q) => $q
->whereHas('ambulatorioJornadas', fn ($q) => $q
->whereNull('situacao_id')
->whereDate('data', '>=', Carbon::today())
)
)
)
->orderBy('nome_fantasia')
->get(['id', 'nome_fantasia']);
}
private static function getDestinoInfraestruturas($params)
{
return Infraestrutura::setEagerLoads([])
->where('unidade_id', $params->unidade_id)
->whereHas('lotacoes', fn ($q) => $q
->whereHas('ambulatorioJornadas', fn ($q) => $q
->whereNull('situacao_id')
->whereDate('data', '>=', Carbon::today())
)
)
->get(['id', 'nome', 'principal', 'unidade_id'])
->map(fn ($infraestrutura) => [
'id' => $infraestrutura->id,
'nome' => $infraestrutura->nome
])
->sortBy('nome')
->values();
}
private static function getDestinoOcupacoes($params)
{
return DB::table('sigtap.ocupacao as ocupacao')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao as lotacao')
->whereColumn('lotacao.ocupacao_id', 'ocupacao.id')
->where('lotacao.infraestrutura_id', $params->infraestrutura_id)
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_jornada as jornada')
->whereColumn('jornada.lotacao_id', 'lotacao.id')
->whereNull('jornada.situacao_id')
->whereDate('jornada.data', '>=', Carbon::today())
)
)
->orderByRaw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome)")
->select(DB::raw("
ocupacao.id,
CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) as descricao
"))
->get();
}
private static function getDestinoEspecialidades($params)
{
return Especialidade::where('ocupacao_id', $params->ocupacao_id)
->whereHas('ambulatorioJornadas', fn ($q) => $q
->whereNull('situacao_id')
->whereDate('data', '>=', Carbon::today())
->whereHas('lotacao', fn ($q) => $q
->where('infraestrutura_id', $params->infraestrutura_id)
)
)
->orderBy('nome')
->get(['id', 'nome']);
}
private static function getDestinoUsuarios($params)
{
return Usuario::setEagerLoads([])
->whereHas('lotacoes', fn ($q) => $q
->where('infraestrutura_id', $params->infraestrutura_id)
->whereHas('ambulatorioJornadas', fn ($q) => $q
->whereNull('situacao_id')
->whereDate('data', '>=', Carbon::today())
->where('especialidade_id', $params->especialidade_id)
)
)
->get(['id', 'cidadao_id'])
->map(fn ($usuario) => [
'id' => $usuario->id,
'nome' => $usuario->cidadao()->setEagerLoads([])->first(['nome'])->nome,
])
->sortBy('nome')
->values();
}
private static function getDestinoJornadas($params)
{
return Jornada::whereNull('situacao_id')
->whereDate('data', '>=', Carbon::today())
->where('especialidade_id', $params->especialidade_id)
->whereHas('lotacao', fn ($q) => $q
->where('infraestrutura_id', $params->infraestrutura_id)
->where('usuario_id', $params->usuario_id)
)
->select(
'id',
'data',
'inicio',
'fim',
DB::raw("COALESCE(quantidade_consulta, 0) as quantidade_consulta_total"),
DB::raw("COALESCE(quantidade_retorno, 0) as quantidade_retorno_total")
)
->get()
->map(function ($jornada) {
return [
'id' => $jornada->id,
'data' => $jornada->data->format('d/m/Y'),
'dia_semana' => DiaSemana::findOrFail($jornada->dia_semana)->descricao,
'inicio' => $jornada->inicio->format('H:i'),
'fim' => $jornada->fim->format('H:i'),
'quantidade_consulta_agendada' => Agendamento::where('jornada_id', $jornada->id)
->where('tipo_id', AgendamentoTipo::CONSULTA)
->whereNotIn('status_id', self::getStatusLiberamHorario())
->count(),
'quantidade_consulta_total' => (int) $jornada->quantidade_consulta_total,
'quantidade_retorno_agendado' => Agendamento::where('jornada_id', $jornada->id)
->where('tipo_id', AgendamentoTipo::RETORNO)
->whereNotIn('status_id', self::getStatusLiberamHorario())
->count(),
'quantidade_retorno_total' => (int) $jornada->quantidade_retorno_total,
];
});
}
public static function reschedule()
{
self::validateReschedule();
$agendamentosNaoReagendados = (object) [
'status_nao_permite_alteracao' => collect(),
'incompativel_com_especialidade' => collect(),
];
DB::transaction(function () use ($agendamentosNaoReagendados) {
collect(request()->agendamentos)->each(function ($id) use ($agendamentosNaoReagendados) {
$agendamentoAnterior = Agendamento::findOrFail($id);
if ($agendamentoAnterior->status_id === AgendamentoStatus::AGENDADO) {
$jornada = Jornada::findOrFail(request()->jornada_id);
if (self::isPacienteValidForEspecialidade($agendamentoAnterior->paciente, $jornada->especialidade)) {
$agendamentoAnterior->update(['status_id' => AgendamentoStatus::REAGENDADO_PELO_MEDICO]);
$nextHorario = self::getNextHorario($jornada, $agendamentoAnterior->tipo_id);
$agendamentoNovo = Agendamento::create([
'agendamento_anterior_id' => $agendamentoAnterior->id,
'jornada_id' => $jornada->id,
'tipo_id' => $agendamentoAnterior->tipo_id,
'horario' => $nextHorario->horario,
'paciente_id' => $agendamentoAnterior->paciente_id,
'motivo_agendamento_excedente' => $nextHorario->is_excedente
? request()->motivo_agendamento_excedente : null,
'observacao' => $agendamentoAnterior->observacao,
'status_id' => AgendamentoStatus::AGENDADO,
]);
(new SmsService($agendamentoAnterior->id))->cancel();
(new SmsService($agendamentoNovo->id))->send();
}
else {
$agendamentosNaoReagendados->incompativel_com_especialidade->push($agendamentoAnterior->id);
}
}
else {
$agendamentosNaoReagendados->status_nao_permite_alteracao->push($agendamentoAnterior->id);
}
});
});
return (object) ['agendamentos_nao_reagendados' => $agendamentosNaoReagendados];
}
private static function validateReschedule()
{
request()->validate([
'agendamentos' => [
'required',
'array',
],
'agendamentos.*' => [
'required',
'integer',
Rule::exists(Agendamento::class, 'id'),
],
'jornada_id' => [
'required',
'integer',
Rule::exists(Jornada::class, 'id'),
function ($attribute, $value, $fail) {
$hasAgendamentoConsulta = false;
$hasAgendamentoRetorno = false;
collect(request()->agendamentos)
->each(function ($id) use (&$hasAgendamentoConsulta, &$hasAgendamentoRetorno) {
$agendamento = Agendamento::findOrFail($id);
if ($agendamento->tipo_id === AgendamentoTipo::CONSULTA) {
$hasAgendamentoConsulta = true;
}
else if ($agendamento->tipo_id === AgendamentoTipo::RETORNO) {
$hasAgendamentoRetorno = true;
}
});
$jornada = Jornada::findOrFail($value);
if (($hasAgendamentoConsulta && is_null($jornada->quantidade_consulta))
|| ($hasAgendamentoRetorno && is_null($jornada->quantidade_retorno))
) {
$fail("A jornada não é compatível com os agendamentos.");
}
}
],
'motivo_agendamento_excedente' => [
'nullable',
'string',
'max:500',
]
]);
}
private static function isPacienteValidForEspecialidade($paciente, $especialidade)
{
$idade = $paciente->cidadao->idade['anos'];
$sexo = $paciente->cidadao->sexo;
if (!is_null($especialidade->sexo_id) && $especialidade->sexo_id !== $sexo->id) {
return false;
}
if ((!is_null($especialidade->idade_minima) && $idade < $especialidade->idade_minima)
|| (!is_null($especialidade->idade_maxima) && $idade > $especialidade->idade_maxima)
) {
return false;
}
if (!is_null($especialidade->procedimento_grupo_codigo)) {
$procedimento = Procedimento::where('codigo', $especialidade->procedimento_grupo_codigo)
->orderByDesc('competencia_id')
->first();
$validator = new ProcedimentoValidationService($procedimento);
if (!$validator->isSexoValid($sexo) || !$validator->isIdadeValid($idade)) {
return false;
}
}
return true;
}
private static function getNextHorario($jornada, $agendamentoTipoId)
{
$nextHorario = (object) [
'horario' => null,
'is_excedente' => false,
];
if ($jornada->tipo_id === JornadaTipo::FIXA) {
$quantidadeAgendada = Agendamento::where('jornada_id', $jornada->id)
->where('tipo_id', $agendamentoTipoId)
->whereTime('horario', $jornada->inicio)
->whereNotIn('status_id', self::getStatusLiberamHorario())
->count();
$nextHorario->horario = $jornada->inicio->format('H:i');
$nextHorario->is_excedente = $quantidadeAgendada >= $jornada->{self::getCampoQuantidade($agendamentoTipoId)};
}
else if ($jornada->tipo_id === JornadaTipo::DINAMICA) {
$horarios = collect();
$agendamentos = self::getAgendamentos($jornada->id);
$agendamentos->each(fn ($a) => $a->horario = $jornada->inicio->copy()->setTimeFromTimeString($a->horario));
$agendamentos->where('tipo_id', $agendamentoTipoId)
->each(fn ($agendamento) => $horarios->push((object) [
'horario' => $agendamento->horario->format('H:i'),
'quantidade_agendada' => $agendamento->quantidade_agendada,
'quantidade_total' => 1,
]));
$quantidade = $agendamentos->where('tipo_id', $agendamentoTipoId)->count();
if ($quantidade < $jornada->{self::getCampoQuantidade($agendamentoTipoId)}) {
$data = $jornada->inicio->copy();
self::setHorarioJornadaDinamica(
$horarios,
$agendamentos,
$jornada,
$agendamentoTipoId,
$quantidade,
$data
);
}
$horarios = $horarios->sortBy('horario')->values();
$horario = $horarios->where('quantidade_agendada', 0)->first();
if (is_null($horario)) {
$horario = $horarios->last();
}
$nextHorario->horario = $horario->horario;
$nextHorario->is_excedente = $horario->quantidade_agendada >= $horario->quantidade_total;
}
return $nextHorario;
}
private static function getAgendamentos($jornadaId)
{
return Agendamento::where('jornada_id', $jornadaId)
->whereNotIn('status_id', self::getStatusLiberamHorario())
->groupBy([
'tipo_id',
'horario',
])
->orderBy('horario')
->select(
'tipo_id',
'horario',
DB::raw("COUNT(id) as quantidade_agendada")
)
->get();
}
private static function getStatusLiberamHorario()
{
return [
AgendamentoStatus::REAGENDADO_PELO_PACIENTE,
AgendamentoStatus::REAGENDADO_PELO_MEDICO,
AgendamentoStatus::CANCELADO_PELO_PACIENTE,
AgendamentoStatus::CANCELADO_PELO_MEDICO,
];
}
private static function setHorarioJornadaDinamica($horarios, $agendamentos, $jornada, $tipoId, $quantidade, $data)
{
$agendamento = $agendamentos->where('horario', $data)->first();
if (is_null($agendamento)) {
$final = $data->copy()->addMinutes($jornada->{self::getCampoTempo($tipoId)});
$agendamento = $agendamentos
->where('horario', '>', $data)
->where('horario', '<', $final)
->first();
if ($agendamento) {
self::setHorarioJornadaDinamica(
$horarios,
$agendamentos,
$jornada,
$tipoId,
$quantidade,
$agendamento->horario
);
}
else {
$horarios->push((object) [
'horario' => $data->format('H:i'),
'quantidade_agendada' => 0,
'quantidade_total' => 1,
]);
if (++$quantidade < $jornada->{self::getCampoQuantidade($tipoId)}) {
$data->addMinutes($jornada->{self::getCampoTempo($tipoId)});
self::setHorarioJornadaDinamica($horarios, $agendamentos, $jornada, $tipoId, $quantidade, $data);
}
}
}
else {
if ($agendamento->tipo_id == $tipoId) {
$data->addMinutes($jornada->{self::getCampoTempo($tipoId)});
self::setHorarioJornadaDinamica($horarios, $agendamentos, $jornada, $tipoId, $quantidade, $data);
}
else {
$data = $agendamento->horario->copy()->addMinutes($jornada->{self::getCampoTempo($tipoId, true)});
self::setHorarioJornadaDinamica($horarios, $agendamentos, $jornada, $tipoId, $quantidade, $data);
}
}
}
private static function getCampoQuantidade($tipoId)
{
if ($tipoId === AgendamentoTipo::CONSULTA) {
return 'quantidade_consulta';
}
else if ($tipoId === AgendamentoTipo::RETORNO) {
return 'quantidade_retorno';
}
}
private static function getCampoTempo($tipoId, $inverso = false)
{
if ($tipoId === AgendamentoTipo::CONSULTA) {
return $inverso ? 'tempo_retorno' : 'tempo_consulta';
}
else if ($tipoId === AgendamentoTipo::RETORNO) {
return $inverso ? 'tempo_consulta' : 'tempo_retorno';
}
}
public static function cancel()
{
self::validateCancel();
$agendamentosNaoCancelados = (object) [
'status_nao_permite_alteracao' => collect()
];
DB::transaction(function () use ($agendamentosNaoCancelados) {
collect(request()->agendamentos)->each(function ($id) use ($agendamentosNaoCancelados) {
$agendamento = Agendamento::findOrFail($id);
if ($agendamento->status_id === AgendamentoStatus::AGENDADO) {
$agendamento->update([
'status_id' => AgendamentoStatus::CANCELADO_PELO_MEDICO,
'motivo_cancelamento' => request()->motivo,
]);
(new SmsService($agendamento->id))->cancel();
if (!is_null($agendamento->regulacao_solicitacao_id)) {
RegulacaoSolicitacaoService::voltarParaStatusSolicitado($agendamento->regulacao_solicitacao_id);
}
}
else {
$agendamentosNaoCancelados->status_nao_permite_alteracao->push($id);
}
});
});
return (object) ['agendamentos_nao_cancelados' => $agendamentosNaoCancelados];
}
private static function validateCancel()
{
request()->validate([
'agendamentos' => [
'required',
'array',
],
'agendamentos.*' => [
'required',
'integer',
Rule::exists(Agendamento::class, 'id'),
],
'motivo' => [
'required',
'string',
'max:500',
],
]);
}
}

View File

@@ -0,0 +1,229 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Cadastro\SujeitoAtencao\Subclassificacao;
use App\Models\Cadastro\Parametrizacao\Parametrizacao;
use App\Models\Cadastro\SujeitoAtencao\Paciente;
use App\Models\Integracao\Erpsaude\Atendimento as ErpsaudeAtendimento;
use App\Services\Service;
use App\Utils\DataUtil;
use App\Utils\MaskUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class HistoricoAtendimentoService extends Service
{
public const IDADE_ANOS_INICIAL_IDOSO = 60;
public const IDADE_ANOS_FINAL_CRIANCA = 9;
public const IDADE_ANOS_FINAL_CRIANCA_ALEITAMENTO = 1;
public const IDADE_ANOS_FINAL_ADOLESCENTE = 18;
public static function datatable()
{
$parametrizacao = Parametrizacao::first();
$quantidadeDias = $parametrizacao->cadastro_paciente_desatualizado_quantidade_dias ?? 0;
$provisorioBloqueado = $parametrizacao->cadastro_paciente_provisorio_bloqueado ?? false;
$provisorioQuantidadeDias = $parametrizacao->cadastro_paciente_provisorio_quantidade_dias ?? 0;
$pacientes = DB::table('cadastro_paciente as paciente')
->join(
'cadastro_paciente_classificacao as classificacao',
'classificacao.id',
'paciente.classificacao_id'
)
->leftJoin(
'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'
)
->leftJoin(
'intranet.cadastro_estado as estado',
'estado.id',
'municipio.estado_id'
)
->whereNull('paciente.deleted_at')
->whereNull('paciente.sequencial_desconhecido_em')
->select(DB::raw("
paciente.id,
paciente.classificacao_id,
cidadao.nome,
cidadao.nome_social,
cidadao.preferencia_nome_id,
DATE_FORMAT(cidadao.data_nascimento, '%d/%m/%Y') as data_nascimento,
cidadao.nome_mae,
LPAD(paciente.prontuario, 7, '0') as prontuario,
CONCAT(
SUBSTR(cidadao.cpf, 1, 3),
'.',
SUBSTR(cidadao.cpf, 4, 3),
'.',
SUBSTR(cidadao.cpf, 7, 3),
'-',
SUBSTR(cidadao.cpf, 10, 2)
) as cpf,
CONCAT(
SUBSTR(cidadao.cns, 1, 3),
' ',
SUBSTR(cidadao.cns, 4, 4),
' ',
SUBSTR(cidadao.cns, 8, 4),
' ',
SUBSTR(cidadao.cns, 12, 4)
) as cns,
classificacao.descricao as classificacao_descricao,
IF(paciente.validade_fim IS NULL,
'INDETERMINADO',
DATE_FORMAT(paciente.validade_fim, '%d/%m/%Y')
) as validade_fim,
CASE
WHEN paciente.updated_at IS NULL THEN 1
WHEN " . ($quantidadeDias > 0 ? "DATE_ADD(paciente.updated_at, INTERVAL $quantidadeDias DAY) < NOW()" : "false") . "
THEN DATEDIFF(NOW(), DATE_ADD(paciente.updated_at, INTERVAL $quantidadeDias DAY))
ELSE 0
END as dias_cadastro_desatualizado
"));
if (!DataUtil::isStringTrue(request()->with_paciente_bloqueado)) {
$pacientes->where(function ($query) {
$query
->where('paciente.bloqueado', false)
->orWhereNull('paciente.bloqueado');
});
}
if (!DataUtil::isStringTrue(request()->with_paciente_provisorio) && $provisorioBloqueado) {
$pacientes->where(function ($query) use ($provisorioQuantidadeDias) {
$query->where('paciente.subclassificacao_id', '!=', Subclassificacao::TEMPORARIO)
->orWhere(function ($query) use ($provisorioQuantidadeDias) {
$query->where('paciente.subclassificacao_id', Subclassificacao::TEMPORARIO)
->where(function ($query) use ($provisorioQuantidadeDias) {
$query->where(function ($query) {
$query->whereNull('paciente.validade_inicio')
->orWhereDate('paciente.validade_inicio', '<=', Carbon::now()->format('Y-m-d'));
});
$query->where(function ($query) use ($provisorioQuantidadeDias) {
$query->whereNull('paciente.validade_fim')
->orWhere(function ($query) use ($provisorioQuantidadeDias) {
if (!is_null($provisorioQuantidadeDias) && $provisorioQuantidadeDias > 0) {
$query->whereDate('paciente.validade_fim', '>=', Carbon::now()->format('Y-m-d'))
->orWhereDate('paciente.validade_fim', '>=', Carbon::now()->subDays($provisorioQuantidadeDias)->format('Y-m-d'));
} else {
$query->whereDate('paciente.validade_fim', '>=', Carbon::now()->format('Y-m-d'));
}
});
});
});
})
->orWhereNull('paciente.subclassificacao_id');
});
}
return $pacientes;
}
public static function show($id)
{
$paciente = Paciente::findOrFail($id);
return [
'form' => self::getFormData($paciente),
];
}
private static function getFormData($paciente)
{
$exibeHistoricoErpsaude = app('config')->get('database.default') == 'santarita' ? true : false;
return [
'paciente' => self::getPacienteData($paciente),
'historico' => AtendimentoService::getHistorico($paciente->id),
'historico_erpsaude' => $exibeHistoricoErpsaude ? AtendimentoService::getHistoricoErpsaude($paciente) : null,
'exibe_historico_erpsaude' => $exibeHistoricoErpsaude,
];
}
private static function getPacienteData($paciente)
{
$municipioResidencia = $paciente->cidadao->domicilio->endereco->logradouro->municipio ?? null;
return [
'id' => $paciente->id,
'nome' => $paciente->cidadao->nome,
'nome_social' => $paciente->cidadao->nome_social,
'preferencia_nome_id' => $paciente->cidadao->preferencia_nome_id,
'sexo_id' => $paciente->cidadao->sexo_id,
'sexo_descricao' => $paciente->cidadao->sexo->descricao ?? null,
'sexo_identificador' => $paciente->cidadao->sexo->identificador ?? null,
'data_nascimento' => is_null($paciente->cidadao->data_nascimento)
? null
: (new Carbon($paciente->cidadao->data_nascimento))->format('d/m/Y'),
'idade_em_dias' => is_null($paciente->cidadao->data_nascimento)
? null
: Carbon::now()->diffInDays($paciente->cidadao->data_nascimento),
'idade_em_meses' => is_null($paciente->cidadao->data_nascimento)
? null
: ceil(Carbon::now()->diffInDays($paciente->cidadao->data_nascimento) / 31),
'idade_anos' => is_null($paciente->cidadao->data_nascimento)
? null
: $paciente->cidadao->idade['anos'],
'idade_meses' => is_null($paciente->cidadao->data_nascimento)
? null
: $paciente->cidadao->idade['meses'],
'is_idoso' => is_null($paciente->cidadao->data_nascimento)
? false
: $paciente->cidadao->idade['anos'] >= self::IDADE_ANOS_INICIAL_IDOSO,
'is_crianca' => is_null($paciente->cidadao->data_nascimento)
? false
: $paciente->cidadao->idade['anos'] <= self::IDADE_ANOS_FINAL_CRIANCA,
'is_crianca_aleitamento' => is_null($paciente->cidadao->data_nascimento)
? false
: $paciente->cidadao->idade['anos'] <= self::IDADE_ANOS_FINAL_CRIANCA_ALEITAMENTO,
'is_adolescente' => is_null($paciente->cidadao->data_nascimento)
? false
: $paciente->cidadao->idade['anos'] > self::IDADE_ANOS_FINAL_CRIANCA
&& $paciente->cidadao->idade['anos'] <= self::IDADE_ANOS_FINAL_ADOLESCENTE,
'nome_mae' => $paciente->cidadao->nome_mae,
'prontuario' => $paciente->prontuario,
'cpf' => MaskUtil::getCpfMasked($paciente->cidadao->cpf),
'cns' => MaskUtil::getCnsMasked($paciente->cidadao->cns),
'municipio_uf' => is_null($municipioResidencia)
? null
: "{$municipioResidencia->nome} / {$municipioResidencia->estado->uf}",
'telefone_id' => $paciente->cidadao->telefone_principal->id ?? null,
'telefone_numero' => MaskUtil::getPhoneMasked($paciente->cidadao->telefone_principal->numero ?? null),
'telefone_autoriza_sms' => $paciente->cidadao->telefone_principal->autoriza_sms ?? false,
'unidade_referencia' => $paciente->unidade->nome_fantasia ?? null,
'cep' => $paciente->cidadao->domicilio->endereco->logradouro->cep ?? null,
'ibge' => $paciente->cidadao->domicilio->endereco->logradouro->municipio->ibge ?? null,
'raca_cor_id' => $paciente->cidadao->racaCorId ?? null,
];
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,375 @@
<?php
namespace App\Services\Ambulatorio;
use App\Exceptions\Ambulatorio\ConflitoJornadaBloqueioException;
use App\Models\Ambulatorio\JornadaBloqueio;
use App\Models\Cadastro\Especialidade;
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;
use Illuminate\Validation\Rule;
class JornadaBloqueioService extends Service
{
public static function datatable()
{
$jornadas = DB::table('ambulatorio_jornada_bloqueio as jornada_bloqueio')
->join(
'cadastro_infraestrutura as infraestrutura',
'infraestrutura.id',
'jornada_bloqueio.infraestrutura_id'
)
->join(
'cadastro_unidade as unidade',
'unidade.id',
'infraestrutura.unidade_id'
)
->join(
'cadastro_especialidade as especialidade',
'especialidade.id',
'jornada_bloqueio.especialidade_id'
)
->join(
'sigtap.ocupacao as ocupacao',
'ocupacao.id',
'especialidade.ocupacao_id'
)
->leftJoin(
'cadastro_usuario as usuario',
'usuario.id',
'jornada_bloqueio.usuario_id'
)
->leftJoin(
'cadastro_cidadao as cidadao',
'cidadao.id',
'usuario.cidadao_id'
)
->select(DB::raw("
jornada_bloqueio.id,
unidade.nome_fantasia as unidade_nome_fantasia,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura_nome,
CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) as ocupacao_descricao,
especialidade.nome as especialidade_nome,
cidadao.nome as usuario_nome,
DATE_FORMAT(jornada_bloqueio.inicio, '%d/%m/%Y') as inicio,
DATE_FORMAT(jornada_bloqueio.fim, '%d/%m/%Y') as fim
"));
return datatables()
->of($jornadas)
->filterColumn('jornada_bloqueio.inicio', function ($query, $keyword) {
$query->whereRaw("DATE_FORMAT(jornada_bloqueio.inicio, '%d/%m/%Y') LIKE ?", ["%{$keyword}%"])
->orWhereRaw(
"CONCAT(
SUBSTR(jornada_bloqueio.inicio,9,2),
SUBSTR(jornada_bloqueio.inicio,6,2),
SUBSTR(jornada_bloqueio.inicio,1,4)
) like ?",
["%{$keyword}%"]
);
})
->filterColumn('jornada_bloqueio.fim', function ($query, $keyword) {
$query->whereRaw("DATE_FORMAT(jornada_bloqueio.fim, '%d/%m/%Y') LIKE ?", ["%{$keyword}%"])
->orWhereRaw(
"CONCAT(
SUBSTR(jornada_bloqueio.fim,9,2),
SUBSTR(jornada_bloqueio.fim,6,2),
SUBSTR(jornada_bloqueio.fim,1,4)
) like ?",
["%{$keyword}%"]
);
})
->skipTotalRecords()
->toJson();
}
public static function list()
{
$params = (object) request()->all();
switch (request()->listar) {
case 'infraestruturas': {
return self::getInfraestruturas($params);
}
case 'ocupacoes': {
return self::getOcupacoes($params);
}
case 'especialidades': {
return self::getEspecialidades($params);
}
case 'usuarios': {
return self::getUsuarios($params);
}
}
}
public static function create()
{
return [
'form' => [
'unidades' => self::getUnidades(),
'infraestruturas' => [],
'ocupacoes' => [],
'especialidades' => [],
'usuarios' => [],
],
'model' => [
'id' => null,
'unidade_id' => null,
'infraestrutura_id' => null,
'ocupacao_id' => null,
'especialidade_id' => null,
'usuario_id' => null,
'periodo' => [
'start' => null,
'end' => null,
],
]
];
}
public static function edit($id)
{
$bloqueio = JornadaBloqueio::findOrFail($id);
return [
'form' => [
'unidades' => self::getUnidades($bloqueio->infraestrutura->unidade_id),
'infraestruturas' => self::getInfraestruturas((object) [
'unidade_id' => $bloqueio->infraestrutura->unidade_id,
], $bloqueio->infraestrutura_id),
'ocupacoes' => self::getOcupacoes((object) [
'infraestrutura_id' => $bloqueio->infraestrutura_id,
], $bloqueio->especialidade->ocupacao_id),
'especialidades' => self::getEspecialidades((object) [
'ocupacao_id' => $bloqueio->ocupacao_id,
], $bloqueio->especialidade_id),
'usuarios' => self::getUsuarios((object) [
'infraestrutura_id' => $bloqueio->infraestrutura_id,
'ocupacao_id' => $bloqueio->especialidade->ocupacao_id,
], $bloqueio->usuario_id),
],
'model' => [
'id' => $bloqueio->id,
'unidade_id' => $bloqueio->infraestrutura->unidade_id,
'infraestrutura_id' => $bloqueio->infraestrutura_id,
'ocupacao_id' => $bloqueio->especialidade->ocupacao_id,
'especialidade_id' => $bloqueio->especialidade_id,
'usuario_id' => $bloqueio->usuario_id,
'periodo' => [
'start' => $bloqueio->inicio->format('d/m/Y'),
'end' => $bloqueio->fim->format('d/m/Y'),
],
],
];
}
private static function getUnidades($unidadeId = null)
{
return Unidade::orderBy('nome_fantasia')
->where('id', $unidadeId)
->orWhereHas('infraestruturas', fn ($q) => $q
->whereHas('ambulatorioParametrizacaoJornadaInfraestrutura')
)
->get(['id', 'nome_fantasia']);
}
private static function getInfraestruturas($params, $infraestruturaId = null)
{
return Infraestrutura::setEagerLoads([])
->where('id', $infraestruturaId)
->orWhere(fn ($q) => $q
->where('unidade_id', $params->unidade_id)
->whereHas('ambulatorioParametrizacaoJornadaInfraestrutura')
)
->get(['id', 'nome', 'principal', 'unidade_id'])
->map(fn ($infraestrutura) => [
'id' => $infraestrutura->id,
'nome' => $infraestrutura->nome,
])
->sortBy('nome')
->values();
}
private static function getOcupacoes($params, $ocupacaoId = null)
{
return DB::table('sigtap.ocupacao as ocupacao')
->where('ocupacao.id', $ocupacaoId)
->orWhere(function ($query) use ($params) {
$query->whereExists(function ($query) use ($params) {
$query->select(DB::raw(1))
->from('cadastro_lotacao as lotacao')
->whereColumn('lotacao.ocupacao_id', 'ocupacao.id')
->where('lotacao.infraestrutura_id', $params->infraestrutura_id);
})
->whereExists(function ($query) {
$query->select(DB::raw(1))
->from('cadastro_especialidade as especialidade')
->whereColumn('especialidade.ocupacao_id', 'ocupacao.id');
});
})
->orderBy('ocupacao.nome')
->select(
'ocupacao.id',
DB::raw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) as descricao")
)
->get();
}
private static function getEspecialidades($params, $especialidadeId = null)
{
return Especialidade::where('id', $especialidadeId)
->orWhere('ocupacao_id', $params->ocupacao_id)
->orderBy('nome')
->get(['id', 'nome']);
}
private static function getUsuarios($params, $usuarioId = null)
{
return DB::table('cadastro_usuario as usuario')
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
->where('usuario.id', $usuarioId)
->orWhere(function ($query) use ($params) {
$query->whereExists(function ($query) use ($params) {
$query->select(DB::raw(1))
->from('cadastro_lotacao as lotacao')
->whereColumn('lotacao.usuario_id', 'usuario.id')
->where('lotacao.infraestrutura_id', $params->infraestrutura_id)
->where('lotacao.ocupacao_id', $params->ocupacao_id);
});
})
->orderBy('cidadao.nome')
->select(
'usuario.id',
'cidadao.nome'
)
->get();
}
public static function store()
{
self::validate();
$params = self::getParams();
self::validateConflito($params);
return JornadaBloqueio::create($params)->fresh();
}
public static function update($id)
{
$bloqueio = JornadaBloqueio::findOrFail($id);
self::validate();
$params = self::getParams();
self::validateConflito($params, $bloqueio->id);
$bloqueio->update($params);
return $bloqueio->fresh();
}
private static function getParams()
{
$params = request()->all();
$params['inicio'] = Carbon::createFromFormat('d/m/Y', $params['inicio']);
$params['fim'] = Carbon::createFromFormat('d/m/Y', $params['fim']);
return $params;
}
public static function validate()
{
$rules = [
'infraestrutura_id' => [
'required',
'integer',
Rule::exists(Infraestrutura::class, 'id'),
],
'especialidade_id' => [
'required',
'integer',
Rule::exists(Especialidade::class, 'id'),
],
'usuario_id' => [
'nullable',
'integer',
Rule::exists(Usuario::class, 'id'),
],
'inicio' => [
'required',
'date_format:d/m/Y',
'before_or_equal:fim'
],
'fim' => [
'required',
'date_format:d/m/Y',
'after_or_equal:inicio'
],
];
$messages = [];
request()->validate($rules, $messages);
}
private static function validateConflito($params, $id = null)
{
$conflito = JornadaBloqueio::when($id, fn ($q) => $q->where('id', '<>', $id))
->where('infraestrutura_id', $params['infraestrutura_id'])
->where('especialidade_id', $params['especialidade_id'])
->when($params['usuario_id'],
fn ($q, $id) => $q->where('usuario_id', $id),
fn ($q) => $q->whereNull('usuario_id')
)
->where(fn ($q) => $q
->where(fn ($q) => $q
->whereDate('inicio', '<=', $params['inicio'])
->whereDate('fim', '>=', $params['inicio'])
)
->orWhere(fn ($q) => $q
->whereDate('inicio', '<=', $params['fim'])
->whereDate('fim', '>=', $params['fim'])
)
->orWhere(fn ($q) => $q
->whereDate('inicio', '>=', $params['inicio'])
->whereDate('inicio', '<=', $params['fim'])
)
->orWhere(fn ($q) => $q
->whereDate('fim', '>=', $params['inicio'])
->whereDate('fim', '<=', $params['fim'])
)
)
->exists();
if ($conflito) {
throw new ConflitoJornadaBloqueioException();
}
}
public static function destroy($id)
{
JornadaBloqueio::findOrFail($id)->delete();
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,81 @@
<?php
namespace App\Services\Ambulatorio;
use App\Models\Ambulatorio\JornadaSituacao;
use App\Services\Service;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
class JornadaSituacaoService extends Service
{
public static function datatable()
{
return DB::table('ambulatorio_jornada_situacao as situacao')
->select(DB::raw("
situacao.id,
situacao.nome
"));
}
public static function create()
{
return [
'model' => [
'id' => null,
'nome' => null,
]
];
}
public static function edit($id)
{
$situacao = JornadaSituacao::findOrFail($id);
return [
'model' => [
'id' => $situacao->id,
'nome' => $situacao->nome,
],
];
}
public static function store()
{
self::validate();
return JornadaSituacao::create(request()->all())->fresh();
}
public static function update($id)
{
self::validate();
return (tap(JornadaSituacao::findOrFail($id))->update(request()->all()))->fresh();
}
public static function validate()
{
$rules = [
'nome' => [
'string',
'required',
'between:3,100',
Rule::unique(JornadaSituacao::class, 'nome')->ignore(request()->route('jornada_situacao')),
]
];
$messages = [
'nome.unique' => 'O nome da Situação já foi inserido anteriormente.',
];
request()->validate($rules, $messages);
}
public static function destroy($id)
{
JornadaSituacao::findOrFail($id)->delete();
return null;
}
}

View File

@@ -0,0 +1,836 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Ambulatorio\AgendamentoStatus;
use App\Services\Geral\AgeService;
use App\Services\Service;
use App\Utils\DataUtil;
use App\Utils\MaskUtil;
use Carbon\Carbon;
use DateTime;
use Illuminate\Support\Facades\DB;
class ListagemConsultaAgendadaRealizadaService extends Service
{
public static function index()
{
$params = self::getParams();
$getDemandasEspontaneas = fn () => DB::table('ambulatorio_demanda_espontanea as demanda_espontanea')
->join('ambulatorio_atendimento as atendimento', 'atendimento.demanda_espontanea_id', 'demanda_espontanea.id')
->join('cadastro_lotacao as lotacao_registro', 'lotacao_registro.id', 'demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura as infraestrutura_registro', 'infraestrutura_registro.id', 'lotacao_registro.infraestrutura_id')
->join('cadastro_unidade as unidade_registro', 'unidade_registro.id', 'infraestrutura_registro.unidade_id')
->join('cadastro_usuario as usuario_registro', 'usuario_registro.id', 'lotacao_registro.usuario_id')
->join('cadastro_cidadao as cidadao_registro', 'cidadao_registro.id', 'usuario_registro.cidadao_id')
->join('cadastro_paciente as paciente', 'paciente.id', 'demanda_espontanea.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')
->leftJoin('cadastro_prontuario_unidade', function($leftJoin){
$leftJoin->on('cadastro_prontuario_unidade.unidade_id', 'infraestrutura_registro.unidade_id')
->on('cadastro_prontuario_unidade.paciente_id','paciente.id');
})
->leftJoin('cadastro_usuario as usuario_executante', 'usuario_executante.id', 'demanda_espontanea.usuario_id')
->leftJoin('cadastro_cidadao as cidadao_executante', 'cidadao_executante.id', 'usuario_executante.cidadao_id')
->whereBetween('demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('infraestrutura_registro.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('lotacao_registro.infraestrutura_id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('demanda_espontanea.especialidade_id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('demanda_espontanea.usuario_id', $usuarioId)
)
->when($params->status_id === 'em-aberto', fn ($q) => $q
->whereNull('atendimento.finalizado_em')
)
->when($params->status_id == AgendamentoStatus::REALIZADO, fn ($q) => $q
->whereNotNull('atendimento.finalizado_em')
)
->when($params->paciente_id, fn ($q, $pacienteId) => $q
->whereIn('paciente.id', $pacienteId)
)
->select(DB::raw("
'Demanda espontânea' AS origem,
CASE
WHEN cidadao.nome_social IS NOT NULL THEN
CONCAT(cidadao.nome, ' (', cidadao.nome_social, ')')
ELSE
cidadao.nome
END AS paciente_nome,
cidadao.data_nascimento as paciente_data_nascimento,
paciente.prontuario as paciente_prontuario,
paciente.id as paciente_id,
cadastro_prontuario_unidade.prontuario as paciente_prontuario_unidade,
cidadao.cns as paciente_cns,
demanda_espontanea.data as agendado_para_data,
NULL as agendado_para_horario,
NULL as agendamento_tipo_nome,
municipio.nome as paciente_municipio_nome,
CAST(demanda_espontanea.created_at AS DATE) as agendado_na_data,
DATE_FORMAT(demanda_espontanea.created_at, '%H:%i') as agendado_no_horario,
cidadao_registro.nome AS agendamento_usuario_nome,
unidade_registro.nome_fantasia AS agendamento_unidade_nome_fantasia,
COALESCE(infraestrutura_registro.nome, unidade_registro.nome_fantasia) AS agendamento_infraestrutura_nome,
NULL AS reagendamento_usuario_nome,
NULL AS reagendamento_unidade_nome_fantasia,
NULL AS reagendamento_infraestrutura_nome,
NULL as agendamento_observacao,
cidadao_executante.nome AS usuario_executante_nome
"))
->addSelect([
'procedimentos' => function ($query) {
$query->select(DB::raw("GROUP_CONCAT(DISTINCT(procedimento.codigo) SEPARATOR '#')"))
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('sigtap.procedimento as procedimento', 'procedimento.id', 'atendimento_procedimento.procedimento_id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereColumn('atendimento.demanda_espontanea_id', 'demanda_espontanea.id');
},
'telefones' => function ($query) {
$query->select(DB::raw("GROUP_CONCAT(DISTINCT(cidadao_telefone.numero) SEPARATOR '#')"))
->from('cadastro_cidadao_telefone as cidadao_telefone')
->whereColumn('cidadao_telefone.cidadao_id', 'cidadao.id');
}
])
->groupBy('demanda_espontanea.id');
$getAgendamentos = fn () => DB::table('ambulatorio_agendamento as agendamento')
->leftJoin('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->leftJoin('cadastro_lotacao as jornada_lotacao', 'jornada_lotacao.id', 'jornada.lotacao_id')
->leftJoin('cadastro_infraestrutura as jornada_lotacao_infraestrutura', 'jornada_lotacao_infraestrutura.id', 'jornada_lotacao.infraestrutura_id')
->leftJoin('ambulatorio_agendamento_tipo as agendamento_tipo', 'agendamento_tipo.id', 'agendamento.tipo_id')
->leftJoin('cadastro_paciente as paciente', 'paciente.id', 'agendamento.paciente_id')
->leftJoin('cadastro_cidadao as cidadao', 'cidadao.id', 'paciente.cidadao_id')
->leftJoin('cadastro_lotacao as lotacao_agendador', 'lotacao_agendador.id', 'agendamento.created_lotacao_id')
->leftJoin('cadastro_usuario as usuario_agendador', 'usuario_agendador.id', 'lotacao_agendador.usuario_id')
->leftJoin('cadastro_cidadao as cidadao_agendador', 'cidadao_agendador.id', 'usuario_agendador.cidadao_id')
->leftJoin('cadastro_infraestrutura as infraestrutura_agendador', 'infraestrutura_agendador.id', 'lotacao_agendador.infraestrutura_id')
->leftJoin('cadastro_unidade as unidade_agendador', 'unidade_agendador.id', 'infraestrutura_agendador.unidade_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')
->leftJoin('ambulatorio_agendamento as agendamento_anterior', 'agendamento_anterior.id', 'agendamento.agendamento_anterior_id')
->leftJoin('cadastro_lotacao as lotacao_agendador_anterior', 'lotacao_agendador_anterior.id', 'agendamento_anterior.created_lotacao_id')
->leftJoin('cadastro_usuario as usuario_agendador_anterior', 'usuario_agendador_anterior.id', 'lotacao_agendador_anterior.usuario_id')
->leftJoin('cadastro_cidadao as cidadao_agendador_anterior', 'cidadao_agendador_anterior.id', 'usuario_agendador_anterior.cidadao_id')
->leftJoin('cadastro_infraestrutura as infraestrutura_agendador_anterior', 'infraestrutura_agendador_anterior.id', 'lotacao_agendador_anterior.infraestrutura_id')
->leftJoin('cadastro_unidade as unidade_agendador_anterior', 'unidade_agendador_anterior.id', 'infraestrutura_agendador_anterior.unidade_id')
->leftJoin('cadastro_prontuario_unidade', function($leftJoin){
$leftJoin->on('cadastro_prontuario_unidade.unidade_id', 'jornada_lotacao_infraestrutura.unidade_id')
->on('cadastro_prontuario_unidade.paciente_id','paciente.id');
})
->leftJoin('cadastro_usuario as usuario_executante', 'usuario_executante.id', 'jornada_lotacao.usuario_id')
->leftJoin('cadastro_cidadao as cidadao_executante', 'cidadao_executante.id', 'usuario_executante.cidadao_id')
->whereBetween('jornada.data', $params->periodo)
->when($params->inicio, fn ($q, $inicio) => $q
->where('agendamento.horario', '>=', $inicio)
)
->when($params->fim, fn ($q, $fim) => $q
->where('agendamento.horario', '<=', $fim)
)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('jornada_lotacao_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('jornada_lotacao.infraestrutura_id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('jornada.especialidade_id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('jornada_lotacao.usuario_id', $usuarioId)
)
->when($params->status_id,
fn ($q, $statusId) => $q->where('agendamento.status_id', $statusId),
fn ($q) => $q->whereIn('agendamento.status_id', self::getStatusIds()),
)
->when($params->paciente_id, fn ($q, $pacienteId) => $q
->whereIn('paciente.id', $pacienteId)
)
->select(DB::raw("
'Consulta agendada' AS origem,
CASE
WHEN cidadao.nome_social IS NOT NULL THEN
CONCAT(cidadao.nome, ' (', cidadao.nome_social, ')')
ELSE
cidadao.nome
END AS paciente_nome,
cidadao.data_nascimento as paciente_data_nascimento,
paciente.prontuario as paciente_prontuario,
paciente.id as paciente_id,
cadastro_prontuario_unidade.prontuario as paciente_prontuario_unidade,
cidadao.cns as paciente_cns,
jornada.data as agendado_para_data,
DATE_FORMAT(agendamento.horario, '%H:%i') as agendado_para_horario,
agendamento_tipo.nome as agendamento_tipo_nome,
municipio.nome as paciente_municipio_nome,
IF(agendamento.agendamento_anterior_id IS NULL,
CAST(agendamento.created_at AS DATE),
CAST(agendamento_anterior.created_at AS DATE)
) as agendado_na_data,
IF(agendamento.agendamento_anterior_id IS NULL,
DATE_FORMAT(agendamento.created_at, '%H:%i'),
DATE_FORMAT(agendamento_anterior.created_at, '%H:%i')
) as agendado_no_horario,
IF(agendamento.agendamento_anterior_id IS NULL,
cidadao_agendador.nome,
cidadao_agendador_anterior.nome
) AS agendamento_usuario_nome,
IF(agendamento.agendamento_anterior_id IS NULL,
unidade_agendador.nome_fantasia,
unidade_agendador_anterior.nome_fantasia
) AS agendamento_unidade_nome_fantasia,
IF(agendamento.agendamento_anterior_id IS NULL,
COALESCE(infraestrutura_agendador.nome, unidade_agendador.nome_fantasia),
COALESCE(infraestrutura_agendador_anterior.nome, unidade_agendador_anterior.nome_fantasia)
) AS agendamento_infraestrutura_nome,
IF(agendamento.agendamento_anterior_id IS NULL,
NULL,
cidadao_agendador.nome
) AS reagendamento_usuario_nome,
IF(agendamento.agendamento_anterior_id IS NULL,
NULL,
unidade_agendador.nome_fantasia
) AS reagendamento_unidade_nome_fantasia,
IF(agendamento.agendamento_anterior_id IS NULL,
NULL,
COALESCE(infraestrutura_agendador.nome, unidade_agendador.nome_fantasia)
) AS reagendamento_infraestrutura_nome,
agendamento.observacao as agendamento_observacao,
cidadao_executante.nome AS usuario_executante_nome
"))
->addSelect([
'procedimentos' => function ($query) {
$query->select(DB::raw("GROUP_CONCAT(DISTINCT(procedimento.codigo) SEPARATOR '#')"))
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('sigtap.procedimento as procedimento', 'procedimento.id', 'atendimento_procedimento.procedimento_id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereColumn('atendimento.agendamento_id', 'agendamento.id');
},
'telefones' => function ($query) {
$query->select(DB::raw("GROUP_CONCAT(DISTINCT(cidadao_telefone.numero) SEPARATOR '#')"))
->from('cadastro_cidadao_telefone as cidadao_telefone')
->whereColumn('cidadao_telefone.cidadao_id', 'cidadao.id')
->whereNull('cidadao_telefone.deleted_at');
}
])
->groupBy('agendamento.id');
$builder = null;
if (is_null($params->origem)) {
if (!is_null($params->status_id) && !collect(['em-aberto', AgendamentoStatus::REALIZADO])->contains($params->status_id)) {
$builder = $getAgendamentos();
}
else {
$builder = $getDemandasEspontaneas()->unionAll($getAgendamentos());
}
}
else if ($params->origem === 'demanda-espontanea') {
$builder = $getDemandasEspontaneas();
}
else if ($params->origem === 'agendamento') {
$builder = $getAgendamentos();
}
self::setOrderBy($builder);
$itens = $builder->get();
$itens->each(function ($item) {
$item->paciente_cns = MaskUtil::getCnsMasked($item->paciente_cns);
$item->paciente_idade = is_null($item->paciente_data_nascimento)
? null
: AgeService::getFormattedAge(new DateTime($item->paciente_data_nascimento));
$item->procedimentos = (empty($item->procedimentos)
? collect()
: collect(explode('#', $item->procedimentos))->sort()
)->map(fn ($codigo) => $codigo = MaskUtil::getProcedimentoMasked($codigo));
$item->telefones = (empty($item->telefones)
? collect()
: collect(explode('#', $item->telefones))->sort()
)->map(fn ($numero) => $numero = MaskUtil::getPhoneMasked($numero));
});
return $itens;
}
public static function create()
{
$today = Carbon::today();
$params = (object) [
'periodo' => [
'start' => $today->copy()->setTime(0, 0, 0),
'end' => $today->copy()->setTime(23, 59, 59)
],
'inicio' => null,
'fim' => null,
'origem' => null,
'unidade_id' => null,
'infraestrutura_id' => null,
'especialidade_id' => null,
'usuario_id' => null,
'status_id' => null,
];
return [
'additionals' => [
'data_atual' => $today->format('d/m/Y'),
],
'form' => [
'origens' => self::getOrigens($params),
'unidades' => self::getUnidades($params),
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
],
'model' => [
'periodo' => ['start' => null, 'end' => null],
'inicio' => null,
'fim' => null,
'origem' => null,
'unidade_id' => null,
'infraestrutura_id' => null,
'especialidade_id' => null,
'usuario_id' => null,
'status_id' => null,
],
];
}
public static function list()
{
$params = self::getParams();
switch (request()->listar) {
case 'origens': {
return [
'origens' => self::getOrigens($params),
'unidades' => self::getUnidades($params),
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];;
}
case 'unidades': {
return [
'unidades' => self::getUnidades($params),
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];
}
case 'infraestruturas': {
return [
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];
}
case 'especialidades': {
return [
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];
}
case 'usuarios': {
return [
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];
}
case 'status': {
return [
'status' => self::getStatus($params),
];
}
}
}
private static function getParams()
{
return (object) [
'periodo' => [
'start' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['start'])->setTime(0, 0, 0),
'end' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['end'])->setTime(23, 59, 59)
],
'inicio' => request()->get('inicio'),
'fim' => request()->get('fim'),
'origem' => request()->get('origem'),
'unidade_id' => request()->get('unidade_id'),
'infraestrutura_id' => request()->get('infraestrutura_id'),
'especialidade_id' => request()->get('especialidade_id'),
'usuario_id' => request()->get('usuario_id'),
'status_id' => request()->get('status_id'),
'paciente_id' => request()->get('paciente_id'),
];
}
private static function getOrigens($params)
{
$origens = collect();
$hasAgendamentos = DB::table('ambulatorio_jornada as jornada')
->whereBetween('jornada.data', $params->periodo)
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento as agendamento')
->whereColumn('agendamento.jornada_id', 'jornada.id')
->whereIn('agendamento.status_id', self::getStatusIds())
->when($params->inicio, fn ($q, $inicio) => $q
->where('agendamento.horario', '>=', $inicio)
)
->when($params->fim, fn ($q, $fim) => $q
->where('agendamento.horario', '<=', $fim)
)
)
->exists();
$hasDemandaEspontanea = DB::table('ambulatorio_demanda_espontanea as demanda_espontanea')
->whereBetween('demanda_espontanea.data', $params->periodo)
->exists();
if ($hasAgendamentos) {
$origens->push((object) ['value' => 'agendamento', 'text' => 'CONSULTA AGENDADA']);
}
if ($hasDemandaEspontanea) {
$origens->push((object) ['value' => 'demanda-espontanea', 'text' => 'DEMANDA ESPONTÂNEA']);
}
return $origens;
}
private static function getUnidades($params)
{
return DB::table('cadastro_unidade as unidade')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_infraestrutura as infraestrutura')
->whereColumn('infraestrutura.unidade_id', 'unidade.id')
->where(fn ($q) => $q
->when(is_null($params->origem) || $params->origem === 'agendamento', fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao as lotacao')
->whereColumn('lotacao.infraestrutura_id', 'infraestrutura.id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_jornada as jornada')
->whereColumn('jornada.lotacao_id', 'lotacao.id')
->whereBetween('jornada.data', $params->periodo)
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento as agendamento')
->whereColumn('agendamento.jornada_id', 'jornada.id')
->whereIn('agendamento.status_id', self::getStatusIds())
->when($params->inicio, fn ($q, $inicio) => $q
->where('agendamento.horario', '>=', $inicio)
)
->when($params->fim, fn ($q, $fim) => $q
->where('agendamento.horario', '<=', $fim)
)
)
)
)
)
->when(is_null($params->origem) || $params->origem === 'demanda-espontanea', fn ($q) => $q
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea as demanda_espontanea')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->whereColumn('centro_custo.infraestrutura_id', 'infraestrutura.id')
->whereBetween('demanda_espontanea.data', $params->periodo)
)
)
)
)
->select(DB::raw("
unidade.id,
unidade.nome_fantasia
"))
->get();
}
private static function getInfraestruturas($params)
{
if (is_null($params->unidade_id)) {
return collect();
}
return DB::table('cadastro_infraestrutura as infraestrutura')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->where('infraestrutura.unidade_id', $params->unidade_id)
->where(fn ($q) => $q
->when(is_null($params->origem) || $params->origem === 'agendamento', fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao as lotacao')
->whereColumn('lotacao.infraestrutura_id', 'infraestrutura.id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_jornada as jornada')
->whereColumn('jornada.lotacao_id', 'lotacao.id')
->whereBetween('jornada.data', $params->periodo)
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento as agendamento')
->whereColumn('agendamento.jornada_id', 'jornada.id')
->whereIn('agendamento.status_id', self::getStatusIds())
->when($params->inicio, fn ($q, $inicio) => $q
->where('agendamento.horario', '>=', $inicio)
)
->when($params->fim, fn ($q, $fim) => $q
->where('agendamento.horario', '<=', $fim)
)
)
)
)
)
->when(is_null($params->origem) || $params->origem === 'demanda-espontanea', fn ($q) => $q
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea as demanda_espontanea')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->whereColumn('centro_custo.infraestrutura_id', 'infraestrutura.id')
->whereBetween('demanda_espontanea.data', $params->periodo)
)
)
)
->select(DB::raw("
infraestrutura.id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as nome
"))
->get();
}
private static function getEspecialidades($params)
{
return DB::table('cadastro_especialidade as especialidade')
->where(fn ($q) => $q
->when(is_null($params->origem) || $params->origem === 'agendamento', fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_jornada as jornada')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('jornada.especialidade_id', 'especialidade.id')
->whereBetween('jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('lotacao.infraestrutura_id', $infraestruturaId)
)
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento as agendamento')
->whereColumn('agendamento.jornada_id', 'jornada.id')
->whereIn('agendamento.status_id', self::getStatusIds())
->when($params->inicio, fn ($q, $inicio) => $q
->where('agendamento.horario', '>=', $inicio)
)
->when($params->fim, fn ($q, $fim) => $q
->where('agendamento.horario', '<=', $fim)
)
)
)
)
->when(is_null($params->origem) || $params->origem === 'demanda-espontanea', fn ($q) => $q
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea as demanda_espontanea')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->whereColumn('demanda_espontanea.especialidade_id', 'especialidade.id')
->whereBetween('demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('centro_custo.infraestrutura_id', $infraestruturaId)
)
)
)
)
->select(DB::raw("
especialidade.id,
especialidade.nome
"))
->get();
}
private static function getUsuarios($params)
{
return DB::table('cadastro_usuario as usuario')
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
->where(fn ($q) => $q
->when(is_null($params->origem) || $params->origem === 'agendamento', fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao as lotacao')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('lotacao.usuario_id', 'usuario.id')
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('lotacao.infraestrutura_id', $infraestruturaId)
)
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_jornada as jornada')
->whereColumn('jornada.lotacao_id', 'lotacao.id')
->whereBetween('jornada.data', $params->periodo)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('jornada.especialidade_id', $especialidadeId)
)
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento as agendamento')
->whereColumn('agendamento.jornada_id', 'jornada.id')
->whereIn('agendamento.status_id', self::getStatusIds())
->when($params->inicio, fn ($q, $inicio) => $q
->where('agendamento.horario', '>=', $inicio)
)
->when($params->fim, fn ($q, $fim) => $q
->where('agendamento.horario', '<=', $fim)
)
)
)
)
)
->when(is_null($params->origem) || $params->origem === 'demanda-espontanea', fn ($q) => $q
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea as demanda_espontanea')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->whereColumn('demanda_espontanea.usuario_id', 'usuario.id')
->whereBetween('demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('centro_custo.infraestrutura_id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('demanda_espontanea.especialidade_id', $especialidadeId)
)
)
)
)
->select(DB::raw("
usuario.id,
cidadao.nome
"))
->get();
}
private static function getStatus($params)
{
$statusAgendamento = collect();
if (is_null($params->origem) || $params->origem === 'agendamento') {
$statusAgendamento = DB::table('ambulatorio_agendamento_status as status')
->whereIn('status.id', self::getStatusIds())
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento as agendamento')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('agendamento.status_id', 'status.id')
->whereBetween('jornada.data', $params->periodo)
->when($params->inicio, fn ($q, $inicio) => $q
->where('agendamento.horario', '>=', $inicio)
)
->when($params->fim, fn ($q, $fim) => $q
->where('agendamento.horario', '<=', $fim)
)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('lotacao.infraestrutura_id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('jornada.especialidade_id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('lotacao.usuario_id', $usuarioId)
)
)
->select(DB::raw("
status.id,
status.nome
"))
->get();
}
$statusDemandaEspontanea = collect();
if (is_null($params->origem) || $params->origem === 'demanda-espontanea') {
$hasDemandaEmAberto = DB::table('ambulatorio_demanda_espontanea as demanda_espontanea')
->join('ambulatorio_atendimento as atendimento', 'atendimento.demanda_espontanea_id', 'demanda_espontanea.id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->whereNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('centro_custo.infraestrutura_id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('demanda_espontanea.especialidade_id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('demanda_espontanea.usuario_id', $usuarioId)
)
->exists();
$hasDemandaRealizada = DB::table('ambulatorio_demanda_espontanea as demanda_espontanea')
->join('ambulatorio_atendimento as atendimento', 'atendimento.demanda_espontanea_id', 'demanda_espontanea.id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('centro_custo.infraestrutura_id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('demanda_espontanea.especialidade_id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('demanda_espontanea.usuario_id', $usuarioId)
)
->exists();
if ($hasDemandaEmAberto) {
$statusDemandaEspontanea->push((object) ['id' => 'em-aberto', 'nome' => 'EM ABERTO']);
}
if ($hasDemandaRealizada) {
$statusDemandaEspontanea->push((object) ['id' => AgendamentoStatus::REALIZADO, 'nome' => 'REALIZADO']);
}
}
return $statusAgendamento->concat($statusDemandaEspontanea)->unique('id')->values();
}
private static function getStatusIds()
{
return [
AgendamentoStatus::AGENDADO,
AgendamentoStatus::REALIZADO,
];
}
private static function setOrderBy($itens)
{
if (is_null(request()->sort_by)) {
return;
}
$columns = [
'origem' => 'origem',
'paciente_nome' => 'paciente_nome',
'paciente_data_nascimento' => 'paciente_data_nascimento',
'paciente_prontuario' => 'paciente_prontuario',
'paciente_prontuario_unidade' => 'paciente_prontuario_unidade',
'paciente_cns' => 'paciente_cns',
'agendado_para_data' => 'agendado_para_data',
'agendado_para_horario' => 'agendado_para_horario',
'agendamento_tipo_nome' => 'agendamento_tipo_nome',
'paciente_municipio_nome' => 'paciente_municipio_nome',
'usuario_executante_nome' => 'usuario_executante_nome',
'agendado_na_data' => 'agendado_na_data',
'agendado_no_horario' => 'agendado_no_horario',
'agendamento_usuario_nome' => 'agendamento_usuario_nome',
'agendamento_unidade_nome_fantasia' => 'agendamento_unidade_nome_fantasia',
'agendamento_infraestrutura_nome' => 'agendamento_infraestrutura_nome',
'reagendamento_usuario_nome' => 'reagendamento_usuario_nome',
'reagendamento_unidade_nome_fantasia' => 'reagendamento_unidade_nome_fantasia',
'reagendamento_infraestrutura_nome' => 'reagendamento_infraestrutura_nome',
'agendamento_observacao' => 'agendamento.observacao',
];
$column = $columns[request()->sort_by];
$direction = DataUtil::getBooleanValueFromStringBoolean(request()->sort_desc) ? 'DESC' : 'ASC';
$itens->orderByRaw("{$column} {$direction}");
}
}

View File

@@ -0,0 +1,910 @@
<?php
namespace App\Services\Ambulatorio;
use App\Models\Administracao\Funcionalidade;
use App\Models\Ambulatorio\ParametrizacaoAgendamento;
use App\Models\Ambulatorio\ParametrizacaoAssinaturaEletronica;
use App\Models\Ambulatorio\ParametrizacaoAtendimento;
use App\Models\Ambulatorio\ParametrizacaoInfraestrutura;
use App\Models\Ambulatorio\ParametrizacaoInfraestruturaAgendadora;
use App\Models\Ambulatorio\ParametrizacaoInfraestruturaEspecialidade;
use App\Models\Ambulatorio\ParametrizacaoInfraestruturaEspecialidadeProcedimento;
use App\Models\Ambulatorio\ParametrizacaoInfraestruturaOcupacao;
use App\Models\Ambulatorio\ParametrizacaoIntegracaoAplicativo;
use App\Models\Ambulatorio\ParametrizacaoSigilo;
use App\Models\Ambulatorio\ParametrizacaoSigiloInfraestrutura;
use App\Models\Ambulatorio\ParametrizacaoSigiloOcupacao;
use App\Models\Ambulatorio\Servico;
use App\Models\Ambulatorio\SigiloTipo;
use App\Models\Cadastro\Especialidade;
use App\Models\Cadastro\Estabelecimento\Infraestrutura;
use App\Models\Cadastro\Estabelecimento\Unidade;
use App\Models\Sigtap\Ocupacao;
use App\Services\Service;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
class ParametrizacaoService extends Service
{
public static function create()
{
return [
'form' => self::getDadosForm(),
'model' => self::getDadosModel(),
];
}
private static function getDadosForm()
{
return [
'infraestrutura' => [
'unidades' => self::getInfraestruturaUnidades(),
'infraestruturas' => [],
'servicos' => [],
'atencao_basica_funcionalidades' => collect([
self::getAtencaoBasicaFuncionalidade('avaliacao'),
self::getAtencaoBasicaFuncionalidade('atendimento-domiciliar'),
self::getAtencaoBasicaFuncionalidade('atendimento-individual'),
self::getAtencaoBasicaFuncionalidade('atendimento-odontologico'),
self::getAtencaoBasicaFuncionalidade('marcador-consumo-alimentar'),
self::getAtencaoBasicaFuncionalidade('procedimento'),
]),
'assinaturas' => ParametrizacaoAssinaturaEletronica::orderBy('descricao')->get()
],
'sigilo' => [
'unidades' => self::getSigiloUnidades(),
'infraestruturas' => [],
'sigilo_tipos' => self::getSigiloTipos(),
],
];
}
private static function getAtencaoBasicaFuncionalidade($identificador)
{
return Funcionalidade::whereHas('modulo', fn ($q) => $q
->where('identificador', 'atencao-basica')
)
->where('identificador', $identificador)
->first(['id', 'nome']);
}
public static function list()
{
switch (request()->origem) {
case 'infraestrutura': {
return self::getDadosListInfraestrutura();
}
case 'sigilo': {
return self::getDadosListSigilo();
}
}
}
private static function getDadosListInfraestrutura()
{
$params = (object) request()->all();
switch (request()->listar) {
case 'infraestruturas': {
return self::getInfraestruturaInfraestruturas($params);
}
case 'servicos': {
return self::getInfraestruturaServicos();
}
}
}
private static function getDadosListSigilo()
{
$params = (object) request()->all();
switch (request()->listar) {
case 'infraestruturas': {
return self::getSigiloInfraestruturas($params);
}
}
}
private static function getInfraestruturaUnidades()
{
return Unidade::orderBy('nome_fantasia')
->whereHas('infraestruturas')
->get(['id', 'nome_fantasia']);
}
private static function getInfraestruturaInfraestruturas($params)
{
return Infraestrutura::setEagerLoads([])
->where('unidade_id', $params->unidade_id)
->get(['id', 'nome', 'principal', 'unidade_id'])
->map(fn ($infraestrutura) => [
'id' => $infraestrutura->id,
'nome' => $infraestrutura->nome,
])
->sortBy('nome')
->values();
}
private static function getInfraestruturaServicos()
{
return Servico::orderBy('nome')->get(['id', 'nome']);
}
private static function getSigiloUnidades()
{
return Unidade::orderBy('nome_fantasia')
->whereHas('infraestruturas')
->get(['id', 'nome_fantasia']);
}
private static function getSigiloInfraestruturas($params)
{
return Infraestrutura::setEagerLoads([])
->where('unidade_id', $params->unidade_id)
->get(['id', 'nome', 'principal', 'unidade_id'])
->map(fn ($infraestrutura) => [
'id' => $infraestrutura->id,
'nome' => $infraestrutura->nome,
])
->sortBy('nome')
->values();
}
private static function getSigiloTipos()
{
return SigiloTipo::orderBy('id')->get(['id', 'nome']);
}
private static function getDadosModel()
{
return [
'infraestrutura' => self::getModelInfraestrutura(),
'agendamento' => self::getModelAgendamento(),
'integracaoAplicativo' => self::getModelIntegracaoAplicativo(),
'atendimento' => self::getModelAtendimento(),
'sigilo' => self::getModelSigilo(),
];
}
private static function getModelInfraestrutura()
{
return [
'infraestruturas' => self::getInfraestruturasParametrizadas(),
];
}
private static function getInfraestruturasParametrizadas()
{
return ParametrizacaoInfraestrutura::get(['id', 'infraestrutura_id', 'envia_sms', 'fatura_procedimento_raas'])
->map(function ($parametrizacao) {
$infraestrutura = $parametrizacao->infraestrutura()
->setEagerLoads([])
->first(['id', 'nome', 'principal', 'unidade_id']);
$unidade = $infraestrutura->unidade()
->setEagerLoads([])
->first(['nome_fantasia']);
return [
'id' => $infraestrutura->id,
'deleted' => false,
'nome' => $infraestrutura->nome,
'unidade_nome_fantasia' => $unidade->nome_fantasia,
'envia_sms' => $parametrizacao->envia_sms,
'fatura_procedimento_raas' => $parametrizacao->fatura_procedimento_raas,
'ocupacoes' => $parametrizacao->ocupacoes
->map(fn ($parametrizacao) => [
'id' => $parametrizacao->ocupacao_id,
'codigo' => $parametrizacao->ocupacao->codigo,
'nome' => $parametrizacao->ocupacao->nome,
'pos_consulta' => $parametrizacao->pos_consulta,
'permite_atendimento_enfermagem' => $parametrizacao->permite_atendimento_enfermagem,
'atencao_basica_funcionalidades' => $parametrizacao->fichasAtb->pluck('id'),
]),
'especialidades' => $parametrizacao->especialidades
->map(fn ($parametrizacao) => [
'id' => $parametrizacao->especialidade_id,
'nome' => $parametrizacao->especialidade->nome,
'ocupacao_id' => $parametrizacao->especialidade->ocupacao->id,
'ocupacao_codigo' => $parametrizacao->especialidade->ocupacao->codigo,
'avisa_falta_quantidade' => $parametrizacao->avisa_falta_quantidade ?? null,
'avisa_falta_dias' => $parametrizacao->avisa_falta_dias ?? null,
'quantidade_dias_retorno' => $parametrizacao->quantidade_dias_retorno ?? null,
'demanda_espontanea_observa_vaga_atendimento' => $parametrizacao->demanda_espontanea_observa_vaga_atendimento ?? false,
'is_regulado' => $parametrizacao->especialidade->is_regulado ?? false,
'procedimentos' => $parametrizacao->procedimentos
->map(fn ($parametrizacao) => [
'codigo' => $parametrizacao->codigo,
'nome' => $parametrizacao->procedimento->nome,
]),
]),
'infraestruturas_agendadoras' => $parametrizacao->infraestruturasAgendadoras
->map(fn ($parametrizacao) => [
'id' => $parametrizacao->infraestrutura_id,
'nome' => $parametrizacao->infraestrutura->nome,
'unidade_nome_fantasia' => $parametrizacao->infraestrutura->unidade->nome_fantasia,
]),
'sms' => [
'dia_antecedencia' => $parametrizacao->sms->dia_antecedencia ?? null,
'periodo_envio' => [
'start' => is_null($parametrizacao->sms->envio_de ?? null)
? null : (new Carbon($parametrizacao->sms->envio_de))->format('d/m/Y'),
'end' => is_null($parametrizacao->sms->envio_ate ?? null)
? null : (new Carbon($parametrizacao->sms->envio_ate))->format('d/m/Y'),
],
'especialidades' => ($parametrizacao->sms->especialidades ?? collect())
->map(fn ($especialidade) => [
'id' => $especialidade->id,
'nome' => $especialidade->nome,
'ocupacao_codigo' => $especialidade->ocupacao->codigo,
]),
],
'servicos' => $parametrizacao->servicos()
->orderBy('nome')
->get(['id', 'nome'])
->map(fn ($servico) => [
'id' => $servico->id,
'nome' => $servico->nome,
]),
'assinaturas' => $parametrizacao->assinaturas
->pluck('parametrizacao_assinatura_eletronica_id')
->toArray(),
];
});
}
private static function getModelAgendamento()
{
$agendamento = ParametrizacaoAgendamento::first();
return [
'avisa_cns_provisorio' => $agendamento->avisa_cns_provisorio ?? false,
'avisa_paciente_outra_unidade' => $agendamento->avisa_paciente_outra_unidade ?? false,
'bloqueia_paciente_temporario' => $agendamento->bloqueia_paciente_temporario ?? false,
'obriga_motivo_agendamento_excedente' => $agendamento->obriga_motivo_agendamento_excedente ?? false,
'permite_agendar_mesma_especialidade' => $agendamento->permite_agendar_mesma_especialidade ?? false,
'gerenciar_tratamento' => $agendamento->gerenciar_tratamento ?? false,
];
}
private static function getModelIntegracaoAplicativo()
{
$integracao = ParametrizacaoIntegracaoAplicativo::first();
return [
'habilita_integracao_conectasus_cidadao' =>
$integracao->habilita_integracao_conectasus_cidadao ?? false,
'habilita_integracao_aplicativo_feridas' =>
$integracao->habilita_integracao_aplicativo_feridas ?? false,
];
}
private static function getModelAtendimento()
{
$atendimento = ParametrizacaoAtendimento::first();
return [
'exibe_mensagem_atendimento_retroativo_nao_finalizado' =>
$atendimento->exibe_mensagem_atendimento_retroativo_nao_finalizado ?? false,
'exibe_box_exame_laboratorial_solicitado' =>
$atendimento->exibe_box_exame_laboratorial_solicitado ?? false,
'receita_nao_padronizada_justificativa_obrigatoria' =>
$atendimento->receita_nao_padronizada_justificativa_obrigatoria ?? false,
'modelo_impressao_sadt' =>
$atendimento->modelo_impressao_sadt ?? 'padrao',
'modelo_impressao_apac' =>
$atendimento->modelo_impressao_apac ?? 'padrao',
'visualizar_remume' =>
$atendimento->visualizar_remume ?? false,
'visualizar_estoque' =>
$atendimento->visualizar_estoque ?? false,
'cadastro_prescricoes' =>
$atendimento->cadastro_prescricoes ?? false,
'permite_exame_laboratorial_repetido' =>
$atendimento->permite_exame_laboratorial_repetido ?? false,
'permite_exame_imagem_repetido' =>
$atendimento->permite_exame_imagem_repetido ?? false,
'permite_encaminhar_repetido' =>
$atendimento->permite_encaminhar_repetido ?? false,
'permite_prescricao_repetida' =>
$atendimento->permite_prescricao_repetida ?? false,
'prescricao_limite_dias' =>
$atendimento->prescricao_limite_dias ?? null,
];
}
private static function getModelSigilo()
{
return [
'sigilos' => self::getSigilosParametrizados(),
];
}
private static function getSigilosParametrizados()
{
return ParametrizacaoSigilo::get(['id', 'ocupacao_id', 'infraestrutura_id', 'sigilo_tipo_id'])
->map(function ($parametrizacao) {
$ocupacao = $parametrizacao->ocupacao()
->setEagerLoads([])
->first(['id', 'codigo', 'nome']);
$infraestrutura = $parametrizacao->infraestrutura()
->setEagerLoads([])
->first(['id', 'nome', 'principal', 'unidade_id']);
$unidade = $infraestrutura ? $infraestrutura->unidade()
->setEagerLoads([])
->first(['nome_fantasia']) : null;
$sigiloTipo = $parametrizacao->sigiloTipo()
->setEagerLoads([])
->first(['id', 'nome']);
return [
'ocupacao' => [
'id' => $ocupacao->id,
'codigo' => $ocupacao->codigo,
'nome' => $ocupacao->nome,
],
'unidade_nome_fantasia' => $unidade->nome_fantasia ?? null,
'infraestrutura_id' => $infraestrutura->id ?? null,
'infraestrutura_nome' => $infraestrutura->nome ?? null,
'sigilo_tipo_id' => $sigiloTipo->id,
'sigilo_tipo_nome' => $sigiloTipo->nome,
'infraestruturas' => $parametrizacao->infraestruturas
->map(fn ($parametrizacao) => [
'id' => $parametrizacao->infraestrutura_id,
'nome' => $parametrizacao->infraestrutura->nome,
'unidade_nome_fantasia' => $parametrizacao->infraestrutura->unidade->nome_fantasia,
]),
'ocupacoes' => $parametrizacao->ocupacoes
->map(fn ($parametrizacao) => [
'id' => $parametrizacao->ocupacao_id,
'codigo' => $parametrizacao->ocupacao->codigo,
'nome' => $parametrizacao->ocupacao->nome,
]),
'deleted' => false,
];
});
}
public static function store()
{
self::validate();
DB::transaction(function () {
self::saveInfraestrutura();
self::saveAgendamento();
self::saveIntegracaoAplicativo();
self::saveAtendimento();
self::saveSigilo();
});
}
private static function saveInfraestrutura()
{
$infraestruturas = collect(request()->infraestrutura['infraestruturas']);
ParametrizacaoInfraestrutura::whereIn('infraestrutura_id',
$infraestruturas->where('deleted', true)->pluck('id')
)->delete();
$infraestruturas->where('deleted', false)->each(function ($parametrizacaoData) {
$parametrizacao = ParametrizacaoInfraestrutura::updateOrCreate(
['infraestrutura_id' => $parametrizacaoData['id']],
[
'envia_sms' => $parametrizacaoData['envia_sms'],
'fatura_procedimento_raas' => $parametrizacaoData['fatura_procedimento_raas'],
]
);
self::saveInfraestruturaOcupacoes($parametrizacao, $parametrizacaoData);
self::saveInfraestruturaEspecialidades($parametrizacao, $parametrizacaoData);
self::saveInfraestruturaAssinaturas($parametrizacao, $parametrizacaoData);
self::saveInfraestruturaInfraestruturasAgendadoras($parametrizacao, $parametrizacaoData);
self::saveInfraestruturaSms($parametrizacao, $parametrizacaoData);
$parametrizacao->servicos()->sync($parametrizacaoData['servicos']);
});
}
private static function saveInfraestruturaOcupacoes($parametrizacao, $parametrizacaoData)
{
$ocupacoes = collect($parametrizacaoData['ocupacoes']);
$ocupacaoIds = ParametrizacaoInfraestruturaOcupacao::where('parametrizacao_infraestrutura_id', $parametrizacao->id)
->whereNotIn('ocupacao_id', $ocupacoes->pluck('id'))
->pluck('id');
DB::table('ambulatorio_parametrizacao_infraestrutura_ocupacao_ficha_atb')
->whereIn('parametrizacao_infraestrutura_ocupacao_id', $ocupacaoIds)
->delete();
ParametrizacaoInfraestruturaOcupacao::where('parametrizacao_infraestrutura_id', $parametrizacao->id)
->whereNotIn('ocupacao_id', $ocupacoes->pluck('id'))
->delete();
$ocupacoes->each(function ($data) use ($parametrizacao) {
$ocupacao = $parametrizacao->ocupacoes()->updateOrCreate(
['ocupacao_id' => $data['id']],
$data
);
$ocupacao->fichasAtb()->sync($data['atencao_basica_funcionalidades']);
});
}
private static function saveInfraestruturaEspecialidades($parametrizacao, $parametrizacaoData)
{
$especialidades = collect($parametrizacaoData['especialidades']);
ParametrizacaoInfraestruturaEspecialidade::where('parametrizacao_infraestrutura_id', $parametrizacao->id)
->whereNotIn('especialidade_id', $especialidades->pluck('id'))
->delete();
$especialidades->each(function ($data) use ($parametrizacao) {
$parametrizacaoEspecialidade = $parametrizacao->especialidades()->updateOrCreate(
['especialidade_id' => $data['id']],
$data
);
$procedimentos = collect($data['procedimentos']);
ParametrizacaoInfraestruturaEspecialidadeProcedimento::where('parametrizacao_infraestrutura_especialidade_id', $parametrizacaoEspecialidade->id)
->whereNotIn('codigo', $procedimentos->pluck('codigo'))
->delete();
$procedimentos->each(function ($data) use ($parametrizacaoEspecialidade) {
$parametrizacaoEspecialidade->procedimentos()->updateOrCreate(
['codigo' => $data['codigo']],
);
});
});
}
private static function saveInfraestruturaAssinaturas($parametrizacao, $parametrizacaoData)
{
$assinaturas = collect($parametrizacaoData['assinaturas']);
$parametrizacao->assinaturas()->delete();
foreach ($assinaturas as $id) {
$parametrizacao->assinaturas()->updateOrCreate(
['parametrizacao_assinatura_eletronica_id' => $id],
['parametrizacao_infraestrutura_id' => $parametrizacao->id]
);
}
}
private static function saveInfraestruturaInfraestruturasAgendadoras($parametrizacao, $parametrizacaoData)
{
$infraestruturasAgendadoras = collect($parametrizacaoData['infraestruturas_agendadoras']);
ParametrizacaoInfraestruturaAgendadora::where('parametrizacao_infraestrutura_id', $parametrizacao->id)
->whereNotIn('infraestrutura_id', $infraestruturasAgendadoras->pluck('id'))
->delete();
$infraestruturasAgendadoras->each(function ($data) use ($parametrizacao) {
$parametrizacao->infraestruturasAgendadoras()->updateOrCreate(
['infraestrutura_id' => $data['id']],
$data
);
});
}
private static function saveInfraestruturaSms($parametrizacao, $parametrizacaoData)
{
if (is_null($parametrizacaoData['sms']['dia_antecedencia'])) {
if (!is_null($parametrizacao->sms)) {
$parametrizacao->sms->delete();
}
}
else {
$smsData = [
'dia_antecedencia' => $parametrizacaoData['sms']['dia_antecedencia'],
'envio_de' => is_null($parametrizacaoData['sms']['envio_de'])
? null
: Carbon::createFromFormat('d/m/Y', $parametrizacaoData['sms']['envio_de'])
->format('Y-m-d'),
'envio_ate' => is_null($parametrizacaoData['sms']['envio_ate'])
? null
: Carbon::createFromFormat('d/m/Y', $parametrizacaoData['sms']['envio_ate'])
->format('Y-m-d'),
];
$sms = $parametrizacao->sms;
if (is_null($sms)) {
$sms = $parametrizacao->sms()->create($smsData);
}
else {
$sms->update($smsData);
}
$sms->especialidades()->sync($parametrizacaoData['sms']['especialidades']);
}
}
private static function saveAgendamento()
{
$agendamento = ParametrizacaoAgendamento::first();
if (is_null($agendamento)) {
ParametrizacaoAgendamento::create(request()->agendamento);
}
else {
$agendamento->update(request()->agendamento);
}
}
private static function saveIntegracaoAplicativo()
{
$integracao = ParametrizacaoIntegracaoAplicativo::first();
if (is_null($integracao)) {
ParametrizacaoIntegracaoAplicativo::create(request()->integracao_aplicativo);
}
else {
$integracao->update(request()->integracao_aplicativo);
}
}
private static function saveAtendimento()
{
$atendimento = ParametrizacaoAtendimento::first();
if (is_null($atendimento)) {
ParametrizacaoAtendimento::create(request()->atendimento);
}
else {
$atendimento->update(request()->atendimento);
}
}
private static function saveSigilo()
{
$sigilos = collect(request()->sigilo['sigilos']);
foreach ($sigilos as $sigilo) {
if ($sigilo['deleted'] === true) {
ParametrizacaoSigilo::where('ocupacao_id', $sigilo['ocupacao_id'])
->when($sigilo['infraestrutura_id'], fn ($q, $infraestruturaId) => $q->where('infraestrutura_id', $infraestruturaId))
->delete();
}
}
$sigilos->where('deleted', false)->each(function ($parametrizacaoData) {
$parametrizacao = ParametrizacaoSigilo::updateOrCreate(
[
'ocupacao_id' => $parametrizacaoData['ocupacao_id'],
'infraestrutura_id' => $parametrizacaoData['infraestrutura_id'],
],
['sigilo_tipo_id' => $parametrizacaoData['sigilo_tipo_id']]
);
self::saveSigiloOcupacoes($parametrizacao, $parametrizacaoData);
self::saveSigiloInfraestruturas($parametrizacao, $parametrizacaoData);
});
}
private static function saveSigiloOcupacoes($parametrizacao, $parametrizacaoData)
{
$ocupacoes = collect($parametrizacaoData['ocupacoes']);
ParametrizacaoSigiloOcupacao::where('parametrizacao_sigilo_id', $parametrizacao->id)
->whereNotIn('ocupacao_id', $ocupacoes->pluck('id'))
->delete();
$ocupacoes->each(function ($data) use ($parametrizacao) {
$parametrizacao->ocupacoes()->updateOrCreate(['ocupacao_id' => $data['id']]);
});
}
private static function saveSigiloInfraestruturas($parametrizacao, $parametrizacaoData)
{
$infraestruturas = collect($parametrizacaoData['infraestruturas']);
ParametrizacaoSigiloInfraestrutura::where('parametrizacao_sigilo_id', $parametrizacao->id)
->whereNotIn('infraestrutura_id', $infraestruturas->pluck('id'))
->delete();
$infraestruturas->each(function ($data) use ($parametrizacao) {
$parametrizacao->infraestruturas()->updateOrCreate(['infraestrutura_id' => $data['id']]);
});
}
private static function validate()
{
return request()->validate(array_merge(
self::getInfraestruturaValidations(),
self::getAgendamentoValidations(),
self::getIntegracaoAplicativoValidations(),
self::getAtendimentoValidations(),
self::getSigiloValidations(),
));
}
private static function getInfraestruturaValidations()
{
return [
'infraestrutura.infraestruturas' => [
'present',
'array',
],
'infraestrutura.infraestruturas.*.id' => [
'required',
'integer',
Rule::exists(Infraestrutura::class, 'id'),
],
'infraestrutura.infraestruturas.*.deleted' => [
'required',
'boolean',
],
'infraestrutura.infraestruturas.*.ocupacoes' => [
'present',
'array',
],
'infraestrutura.infraestruturas.*.ocupacoes.*.id' => [
'required',
'integer',
Rule::exists(Ocupacao::class, 'id'),
],
'infraestrutura.infraestruturas.*.ocupacoes.*.pos_consulta' => [
'required',
'boolean',
],
'infraestrutura.infraestruturas.*.ocupacoes.*.permite_atendimento_enfermagem' => [
'required',
'boolean',
],
'infraestrutura.infraestruturas.*.ocupacoes.*.atencao_basica_funcionalidades' => [
'present',
'array',
],
'infraestrutura.infraestruturas.*.ocupacoes.*.atencao_basica_funcionalidades.*' => [
'nullable',
'integer',
Rule::exists(Funcionalidade::class, 'id'),
],
'infraestrutura.infraestruturas.*.especialidades' => [
'present',
'array',
],
'infraestrutura.infraestruturas.*.especialidades.*.id' => [
'required',
'integer',
Rule::exists(Especialidade::class, 'id'),
],
'infraestrutura.infraestruturas.*.especialidades.*.avisa_falta_quantidade' => [
'nullable',
'integer',
'max:999'
],
'infraestrutura.infraestruturas.*.especialidades.*.avisa_falta_dias' => [
'nullable',
'required_with:infraestrutura.infraestruturas.*.especialidades.*.avisa_falta_quantidade',
'integer',
'max:999'
],
'infraestrutura.infraestruturas.*.especialidades.*.quantidade_dias_retorno' => [
'nullable',
'integer',
'max:999'
],
'infraestrutura.infraestruturas.*.especialidades.*.demanda_espontanea_observa_vaga_atendimento' => [
'nullable',
'boolean',
],
'infraestrutura.infraestruturas.*.especialidades.*.procedimentos' => [
'present',
'array',
],
'infraestrutura.infraestruturas.*.especialidades.*.procedimentos.*.codigo' => [
'required',
'digits:10',
],
'infraestrutura.infraestruturas.*.infraestruturas_agendadoras' => [
'present',
'array',
],
'infraestrutura.infraestruturas.*.infraestruturas_agendadoras.*.id' => [
'required',
'integer',
Rule::exists(Infraestrutura::class, 'id'),
],
'infraestrutura.infraestruturas.*.envia_sms' => [
'required',
'boolean',
],
'infraestrutura.infraestruturas.*.fatura_procedimento_raas' => [
'required',
'boolean',
],
'infraestrutura.infraestruturas.*.sms.dia_antecedencia' => [
'present',
'nullable',
'integer',
'max:365',
],
'infraestrutura.infraestruturas.*.sms.envio_de' => [
'nullable',
'required_with:infraestrutura.infraestruturas.*.sms.dia_antecedencia',
'date_format:d/m/Y',
],
'infraestrutura.infraestruturas.*.sms.envio_ate' => [
'nullable',
'required_with:infraestrutura.infraestruturas.*.sms.dia_antecedencia',
'date_format:d/m/Y',
],
'infraestrutura.infraestruturas.*.sms.especialidades' => [
'present',
'array',
],
'infraestrutura.infraestruturas.*.sms.especialidades.*' => [
'required',
'integer',
Rule::exists(Especialidade::class, 'id'),
],
'infraestrutura.infraestruturas.*.servicos' => [
'present',
'array',
],
'infraestrutura.infraestruturas.*.servicos.*' => [
'required',
'integer',
Rule::exists(Servico::class, 'id'),
]
];
}
private static function getAgendamentoValidations()
{
return [
'agendamento.avisa_cns_provisorio' => [
'required',
'boolean',
],
'agendamento.avisa_paciente_outra_unidade' => [
'required',
'boolean',
],
'agendamento.bloqueia_paciente_temporario' => [
'required',
'boolean',
],
'agendamento.obriga_motivo_agendamento_excedente' => [
'required',
'boolean',
],
'agendamento.permite_agendar_mesma_especialidade' => [
'required',
'boolean',
],
'agendamento.gerenciar_tratamento' => [
'required',
'boolean',
],
];
}
private static function getIntegracaoAplicativoValidations()
{
return [
'integracao_aplicativo.habilita_integracao_conectasus_cidadao' => [
'required',
'boolean',
],
'integracao_aplicativo.habilita_integracao_aplicativo_feridas' => [
'required',
'boolean',
],
];
}
private static function getAtendimentoValidations()
{
return [
'atendimento.exibe_mensagem_atendimento_retroativo_nao_finalizado' => [
'required',
'boolean',
],
'atendimento.prescricao_limite_dias' => [
'nullable',
'integer',
'max:730',
]
];
}
private static function getSigiloValidations()
{
return [
'sigilo.sigilos' => [
'present',
'array',
],
'sigilo.sigilos.*.ocupacao_id' => [
'required',
'integer',
Rule::exists(Ocupacao::class, 'id'),
],
'sigilo.sigilos.*.infraestrutura_id' => [
'nullable',
'integer',
Rule::exists(Infraestrutura::class, 'id'),
],
'sigilo.sigilos.*.deleted' => [
'required',
'boolean',
],
'sigilo.sigilos.*.infraestruturas' => [
'present',
'array',
],
'sigilo.sigilos.*.infraestruturas.*.id' => [
'required',
'integer',
Rule::exists(Infraestrutura::class, 'id'),
],
'sigilo.sigilos.*.ocupacoes' => [
'present',
'array',
],
'sigilo.sigilos.*.ocupacoes.*.id' => [
'required',
'integer',
Rule::exists(Ocupacao::class, 'id'),
],
];
}
public static function getQuantidadeDiasRetorno($infraestruturaId, $especialidadeId)
{
$parametrizacaoInfraestrutura = ParametrizacaoInfraestrutura::where('infraestrutura_id', $infraestruturaId)
->first();
if (!is_null($parametrizacaoInfraestrutura)) {
$parametrizacaoEspecialidade = $parametrizacaoInfraestrutura->especialidades()
->where('especialidade_id', $especialidadeId)
->first();
if (!is_null($parametrizacaoEspecialidade)) {
return $parametrizacaoEspecialidade->quantidade_dias_retorno ?? 0;
}
}
return 0;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,292 @@
<?php
namespace App\Services\Ambulatorio;
use App\Models\Ambulatorio\Agendamento;
use App\Models\Intranet\Cliente;
use Illuminate\Log\Logger;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Client\Response;
use Illuminate\Http\Response as HttpResponse;
use RuntimeException;
use Carbon\Carbon;
use Illuminate\Support\Str;
class RegistroPacienteAposAgendamento
{
private function log(): Logger
{
return logger()->channel('integracao-safecare');
}
public function integracaoPaciente(Agendamento $agendamento): void
{
$cliente = Cliente::where('link', config('database.default'))->firstOrFail();
$token = $this->autenticarSafecare($cliente);
$payload = $this->pacientePayload($agendamento, $cliente);
$this->log()->debug('SafeCare payload (final)', $payload);
$response = $this->postPaciente($payload, $agendamento, $token);
if ($response->failed()) {
$this->log()->error('Safecare: falha ao registrar paciente', [
'agendamento_id' => $agendamento->id,
'customer' => $cliente->link,
'status' => $response->status(),
'response_body' => $response->json() ?? $response->body(),
'payload' => $payload,
]);
throw new RuntimeException(sprintf(
'Erro API Safecare (status %s): %s',
$response->status(),
json_encode($response->json() ?? $response->body(), JSON_UNESCAPED_UNICODE)
));
}
$this->log()->info('Safecare: paciente registrado com sucesso', [
'agendamento_id' => $agendamento->id,
'customer' => $cliente->link,
'result' => $response->json('result'),
'patient_id' => $response->json('patientId'),
]);
}
protected function autenticarSafecare(Cliente $cliente): string
{
if (!$cliente->safecare_usuario || !$cliente->safecare_senha) {
$this->log()->error('Safecare: credenciais não configuradas', [
'customer' => $cliente->link,
]);
throw new RuntimeException(
'Credenciais Safecare não configuradas para o cliente: ' . $cliente->link
);
}
$cacheKey = 'safecare_token_' . $cliente->getKey();
$tokenCached = Cache::get($cacheKey);
if ($tokenCached && $this->tokenEstaAtivo($tokenCached)) {
return $tokenCached;
}
$this->log()->info('Safecare: solicitando novo token', ['customer' => $cliente->link]);
$token = $this->solicitarTokenSafecare($cliente);
Cache::put($cacheKey, $token, now()->addHours(23));
return $token;
}
private function solicitarTokenSafecare(Cliente $cliente): string
{
$response = Http::asJson()
->timeout(15)
->post(
rtrim(config('services.safecare.base_url'), '/') . '/api/partner/auth/login',
[
'identity' => $cliente->safecare_usuario,
'password' => $cliente->safecare_senha,
]
);
if ($response->failed()) {
$this->log()->error('Safecare: falha na autenticação', [
'customer' => $cliente->link,
'status' => $response->status(),
'response_body' => $response->json() ?? $response->body(),
]);
throw new RuntimeException(sprintf(
'Erro autenticação Safecare (status %s): %s',
$response->status(),
json_encode($response->json() ?? $response->body(), JSON_UNESCAPED_UNICODE)
));
}
$token = $response->json('token');
if (!$token) {
$this->log()->error('Safecare: token ausente na resposta de autenticação', [
'customer' => $cliente->link,
'response_body' => $response->json(),
]);
throw new RuntimeException('Token ausente na resposta de autenticação Safecare');
}
return $token;
}
private function tokenEstaAtivo(string $token): bool
{
$partes = explode('.', $token);
if (count($partes) !== 3) {
return false;
}
$payload = json_decode(base64_decode(strtr($partes[1], '-_', '+/')), true);
if (!isset($payload['exp'])) {
return false;
}
return now()->timestamp < ($payload['exp'] - 300);
}
protected function postPaciente(array $payload, Agendamento $agendamento, string $token): Response
{
$chaveIdempotencia = 'agendamento:' . $agendamento->id;
return Http::asJson()
->withHeaders([
'Authorization' => 'Bearer ' . $token,
'X-Idempotency-Key' => $chaveIdempotencia,
])
->timeout(15)
->retry(3, 200, fn($_, $response) => !$response || $response->status() !== HttpResponse::HTTP_UNAUTHORIZED)
->post(
rtrim(config('services.safecare.base_url'), '/') . '/api/partner/patients',
$payload
);
}
protected function pacientePayload(Agendamento $agendamento, Cliente $cliente): array
{
$dadosPaciente = DB::table('ambulatorio_agendamento')
->join('cadastro_paciente', 'cadastro_paciente.id', 'ambulatorio_agendamento.paciente_id')
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id')
->leftJoin('cadastro_cidadao_telefone', function ($join) {
$join->on('cadastro_cidadao_telefone.cidadao_id', '=', 'cadastro_cidadao.id')
->where('cadastro_cidadao_telefone.principal', 1);
})
->leftJoin('cadastro_sexo', 'cadastro_sexo.id', 'cadastro_cidadao.sexo_id')
->leftJoin('cadastro_nacionalidade', 'cadastro_nacionalidade.id', 'cadastro_cidadao.nacionalidade_id')
->leftJoin('cadastro_raca_cor', 'cadastro_raca_cor.id', 'cadastro_cidadao.raca_cor_id')
->leftJoin('cadastro_domicilio', 'cadastro_domicilio.id', 'cadastro_cidadao.domicilio_id')
->leftJoin('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_domicilio.endereco_id')
->leftJoin('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->leftJoin('cadastro_logradouro_tipo', 'cadastro_logradouro_tipo.id', 'cadastro_logradouro.tipo_id')
->leftJoin('cadastro_bairro', 'cadastro_bairro.id', 'cadastro_logradouro.bairro_id')
->where('ambulatorio_agendamento.id', $agendamento->id)
->select(
[
'cadastro_cidadao.nome AS name',
'cadastro_cidadao.cns',
'cadastro_cidadao.cpf',
'cadastro_cidadao.data_nascimento AS birthdate',
DB::raw("COALESCE(cadastro_cidadao_telefone.numero, '') AS phone"),
'cadastro_sexo.descricao AS sex',
DB::raw("COALESCE(cadastro_cidadao.nome_mae, '') AS motherName"),
DB::raw("COALESCE(cadastro_nacionalidade.descricao, '') AS nationality"),
DB::raw("COALESCE(cadastro_raca_cor.descricao, '') AS race"),
'cadastro_logradouro_tipo.descricao as type',
'cadastro_logradouro.nome as street',
'cadastro_endereco.numero as number',
'cadastro_bairro.nome as neighborhood',
'cadastro_logradouro.cep as zipCode'
]
)
->distinct()
->orderBy('cadastro_cidadao.nome')
->first();
if (!$dadosPaciente) {
throw new RuntimeException(
'Dados do paciente não encontrados para o agendamento: ' . $agendamento->id
);
}
$race = $this->mapearRaca($dadosPaciente->race ?? null);
$sex = $this->mapearSexo($dadosPaciente->sex ?? null);
return [
'address' => [
'city' => '',
'complement' => '',
'neighborhood' => $dadosPaciente->neighborhood ?? '',
'number' => isset($dadosPaciente->number) ? (string) $dadosPaciente->number : '',
'reference' => '',
'state' => '',
'street' => $dadosPaciente->street ?? '',
'zipCode' => $dadosPaciente->zipCode ?? '',
],
'birthdate' => $dadosPaciente->birthdate
? Carbon::parse($dadosPaciente->birthdate)->format('Y-m-d')
: '',
'cns' => $dadosPaciente->cns ?? '',
'cpf' => $dadosPaciente->cpf ?? '',
'ethnicity' => '',
'guardianName' => '',
'isHomeCare' => false,
'metaData' => $this->metaDadosSafeCare($agendamento, $cliente),
'motherName' => $dadosPaciente->motherName ?? '',
'name' => $dadosPaciente->name ?? '',
'phone' => $dadosPaciente->phone ?? '',
'race' => $race,
'sex' => $sex,
];
}
protected function metaDadosSafeCare(Agendamento $agendamento, Cliente $cliente): array
{
return [
'agendamento_id' => (string) $agendamento->id,
'jornada_id' => (string) $agendamento->jornada_id,
'paciente_id' => (string) $agendamento->paciente_id,
'customer' => $cliente->link ?? '',
];
}
private function normalizarEnum(?string $valor): string
{
if ($valor === null) {
return '';
}
return strtoupper(trim(Str::ascii($valor)));
}
private function mapearRaca(?string $raca): string
{
$normalizada = $this->normalizarEnum($raca);
$mapa = [
'BRANCA' => 'white',
'PRETA' => 'black',
'PARDA' => 'brown',
'AMARELA' => 'yellow',
'INDIGENA' => 'indigenous',
];
return $mapa[$normalizada] ?? '';
}
private function mapearSexo(?string $sexo): string
{
$normalizada = $this->normalizarEnum($sexo);
$mapa = [
'MASCULINO' => 'male',
'FEMININO' => 'female',
];
return $mapa[$normalizada] ?? '';
}
}

View File

@@ -0,0 +1,493 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Ambulatorio\AgendamentoStatus;
use App\Services\Service;
use App\Utils\DataUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RelatorioConsultaFinalizadaService extends Service
{
public static function index()
{
$params = self::getParams();
$atendimentos = DB::table('ambulatorio_agendamento')
->select([
'ambulatorio_atendimento.id AS atendimento_id',
DB::raw("'Agendada' AS demanda_tipo"),
DB::raw("DATE_FORMAT(ambulatorio_jornada.data, '%d/%m/%Y') AS data_atendimento"),
'cadastro_cidadao_usuario.nome AS usuario_nome',
'cadastro_especialidade.nome AS especialidade_nome',
'cadastro_paciente.id AS paciente_id',
'cadastro_cidadao.nome AS paciente_nome',
'cadastro_paciente.prontuario AS paciente_prontuario',
DB::raw("DATE_FORMAT(ambulatorio_agendamento.horario, '%H:%i') AS horario_atendimento"),
DB::raw("
(
SELECT GROUP_CONCAT(CONCAT(procedimento.codigo, ' - ', procedimento.nome) SEPARATOR ',')
FROM ambulatorio_atendimento_procedimento
JOIN sigtap.procedimento ON procedimento.id = ambulatorio_atendimento_procedimento.procedimento_id
WHERE ambulatorio_atendimento_procedimento.atendimento_id = ambulatorio_atendimento.id
AND ambulatorio_atendimento_procedimento.usuario_id = cadastro_usuario.id
AND (
EXISTS (
SELECT 1
FROM ambulatorio_atendimento_soap AS s
WHERE s.id = ambulatorio_atendimento_procedimento.soap_id
AND s.is_rascunho = 0
)
OR NOT EXISTS (
SELECT 1
FROM ambulatorio_atendimento_soap AS s
WHERE s.id = ambulatorio_atendimento_procedimento.soap_id
)
)
) AS procedimentos
"),
DB::raw("
(
SELECT GROUP_CONCAT(CONCAT(
IFNULL(CONCAT(cid.codigo, ' - ', cid.nome), ''),
CASE WHEN cid.id IS NOT NULL AND geral_ciap.id IS NOT NULL THEN ' / ' ELSE '' END,
IFNULL(CONCAT(geral_ciap.codigo, ' - ', geral_ciap.descricao), '')
) SEPARATOR ', ')
FROM ambulatorio_atendimento_soap_problema_condicao
INNER JOIN ambulatorio_atendimento_soap ON ambulatorio_atendimento_soap.id = ambulatorio_atendimento_soap_problema_condicao.soap_id
LEFT JOIN sigtap.cid ON cid.id = ambulatorio_atendimento_soap_problema_condicao.cid_id
LEFT JOIN geral_ciap ON geral_ciap.id = ambulatorio_atendimento_soap_problema_condicao.ciap_id
WHERE ambulatorio_atendimento_soap.atendimento_id = ambulatorio_atendimento.id
) AS cids_ciaps
"),
'ambulatorio_agendamento_status.id AS agendamento_status_id',
'ambulatorio_agendamento_status.nome AS agendamento_status_nome',
])
->leftJoin('ambulatorio_atendimento', 'ambulatorio_atendimento.agendamento_id','ambulatorio_agendamento.id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_usuario', 'cadastro_usuario.id', 'cadastro_lotacao.usuario_id')
->join('cadastro_cidadao AS cadastro_cidadao_usuario', 'cadastro_cidadao_usuario.id', 'cadastro_usuario.cidadao_id')
->join('cadastro_especialidade', 'cadastro_especialidade.id', 'ambulatorio_jornada.especialidade_id')
->join('cadastro_paciente', 'cadastro_paciente.id', 'ambulatorio_agendamento.paciente_id')
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id')
->join('ambulatorio_agendamento_status', 'ambulatorio_agendamento_status.id', 'ambulatorio_agendamento.status_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->where('cadastro_infraestrutura.id', $params->infraestrutura_id)
->when($params->especialidade_id, fn ($q) => $q->where('cadastro_especialidade.id', $params->especialidade_id))
->when($params->usuario_id, fn ($q) => $q->where('cadastro_usuario.id', $params->usuario_id))
->when($params->status_id,
fn ($q) => $q->where('ambulatorio_agendamento.status_id', $params->status_id),
fn ($q) => $q->where('ambulatorio_agendamento.status_id', '<>', AgendamentoStatus::AGENDADO),
)
->when($params->status_id === AgendamentoStatus::REALIZADO, fn ($q) => $q
->unionAll(
DB::table('ambulatorio_atendimento')
->select([
'ambulatorio_atendimento.id AS atendimento_id',
DB::raw("'Espontânea' AS demanda_tipo"),
DB::raw("DATE_FORMAT(ambulatorio_demanda_espontanea.data, '%d/%m/%Y') AS data_atendimento"),
'cadastro_cidadao_usuario.nome AS usuario_nome',
'cadastro_especialidade.nome AS especialidade_nome',
'cadastro_paciente.id AS paciente_id',
'cadastro_cidadao.nome AS paciente_nome',
'cadastro_paciente.prontuario AS paciente_prontuario',
DB::raw("NULL AS horario_atendimento"),
DB::raw("
(
SELECT GROUP_CONCAT(CONCAT(procedimento.codigo, ' - ', procedimento.nome) SEPARATOR ',')
FROM ambulatorio_atendimento_procedimento
JOIN sigtap.procedimento ON procedimento.id = ambulatorio_atendimento_procedimento.procedimento_id
WHERE ambulatorio_atendimento_procedimento.atendimento_id = ambulatorio_atendimento.id
AND ambulatorio_atendimento_procedimento.usuario_id = cadastro_usuario.id
AND (
EXISTS (
SELECT 1
FROM ambulatorio_atendimento_soap AS s
WHERE s.id = ambulatorio_atendimento_procedimento.soap_id
AND s.is_rascunho = 0
)
OR NOT EXISTS (
SELECT 1
FROM ambulatorio_atendimento_soap AS s
WHERE s.id = ambulatorio_atendimento_procedimento.soap_id
)
)
) AS procedimentos
"),
DB::raw("
(
SELECT GROUP_CONCAT(CONCAT(
IFNULL(CONCAT(cid.codigo, ' - ', cid.nome), ''),
CASE WHEN cid.id IS NOT NULL AND geral_ciap.id IS NOT NULL THEN ' / ' ELSE '' END,
IFNULL(CONCAT(geral_ciap.codigo, ' - ', geral_ciap.descricao), '')
) SEPARATOR ', ')
FROM ambulatorio_atendimento_soap_problema_condicao
INNER JOIN ambulatorio_atendimento_soap ON ambulatorio_atendimento_soap.id = ambulatorio_atendimento_soap_problema_condicao.soap_id
LEFT JOIN sigtap.cid ON cid.id = ambulatorio_atendimento_soap_problema_condicao.cid_id
LEFT JOIN geral_ciap ON geral_ciap.id = ambulatorio_atendimento_soap_problema_condicao.ciap_id
WHERE ambulatorio_atendimento_soap.atendimento_id = ambulatorio_atendimento.id
) AS cids_ciaps
"),
DB::raw(AgendamentoStatus::REALIZADO . " AS agendamento_status_id"),
DB::raw("
(
SELECT ambulatorio_agendamento_status.nome
FROM ambulatorio_agendamento_status
WHERE ambulatorio_agendamento_status.id = " . AgendamentoStatus::REALIZADO . "
) AS agendamento_status_nome
"),
])
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_usuario', 'cadastro_usuario.id', 'ambulatorio_demanda_espontanea.usuario_id')
->join('cadastro_cidadao AS cadastro_cidadao_usuario', 'cadastro_cidadao_usuario.id', 'cadastro_usuario.cidadao_id')
->join('cadastro_especialidade', 'cadastro_especialidade.id', 'ambulatorio_demanda_espontanea.especialidade_id')
->join('cadastro_paciente', 'cadastro_paciente.id', 'ambulatorio_demanda_espontanea.paciente_id')
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->where('cadastro_infraestrutura.id', $params->infraestrutura_id)
->when($params->especialidade_id, fn ($q) => $q->where('cadastro_especialidade.id', $params->especialidade_id))
->when($params->usuario_id, fn ($q) => $q->where('cadastro_usuario.id', $params->usuario_id))
)
);
self::setOrderBy($atendimentos);
$atendimentos = $atendimentos->get();
return [
'atendimentos' => $atendimentos->map(function($query) {
$query->procedimentos = $query->procedimentos ? explode(',', $query->procedimentos) : [];
$query->cids_ciaps = $query->cids_ciaps ? explode(',', $query->cids_ciaps) : [];
return $query;
}),
'totalizadores' => [
'quantidade_pacientes' => $atendimentos->unique('paciente_id')->count(),
'quantidade_atendimentos_realizados' => $atendimentos->count(),
'quantidade_faltas' => $atendimentos->sum(fn ($item) => $item->agendamento_status_id == AgendamentoStatus::FALTA_DO_PACIENTE ? 1 : 0),
'quantidade_procedimentos_lancados' => $atendimentos->sum(fn ($item) => $item->procedimentos ? count($item->procedimentos) : 0),
],
];
}
public static function create()
{
return [
'form' => [
'unidades' => [],
'infraestruturas' => [],
'especialidades' => [],
'usuarios' => [],
'status' => [],
],
'model' => [
'periodo' => ['start' => null, 'end' => null],
'inicio' => null,
'fim' => null,
'unidade_id' => null,
'infraestrutura_id' => null,
'especialidade_id' => null,
'usuario_id' => null,
'status_id' => null,
],
];
}
public static function list()
{
$params = self::getParams();
switch (request()->listar) {
case 'unidades': {
return ['unidades' => self::getUnidades($params)];
}
case 'infraestruturas': {
return ['infraestruturas' => self::getInfraestruturas($params)];
}
case 'especialidades': {
return [
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params)
];
}
case 'usuarios': {
return [
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params)
];
}
case 'status': {
return ['status' => self::getStatus($params)];
}
}
}
private static function getParams()
{
return (object) [
'periodo' => [
'start' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['start'])->setTime(0, 0, 0),
'end' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['end'])->setTime(23, 59, 59)
],
'unidade_id' => request()->get('unidade_id'),
'infraestrutura_id' => request()->get('infraestrutura_id'),
'especialidade_id' => request()->get('especialidade_id'),
'usuario_id' => request()->get('usuario_id'),
'status_id' => request()->get('status_id'),
];
}
private static function getUnidades($params)
{
return DB::table('cadastro_unidade')
->select([
'cadastro_unidade.id',
'cadastro_unidade.nome_fantasia',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_infraestrutura')
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereColumn('ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_especialidade')
->whereColumn('cadastro_especialidade.id', 'ambulatorio_jornada.especialidade_id')
)
->where('ambulatorio_agendamento.status_id', '<>', AgendamentoStatus::AGENDADO)
->whereBetween('ambulatorio_jornada.data', $params->periodo)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->whereColumn('ambulatorio_demanda_espontanea.created_lotacao_id', 'cadastro_lotacao.id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_especialidade')
->whereColumn('cadastro_especialidade.id', 'ambulatorio_demanda_espontanea.especialidade_id')
)
->whereNotNull('ambulatorio_atendimento.finalizado_em')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
)
)
)
)
->orderBy('cadastro_unidade.nome_fantasia')
->get();
}
private static function getInfraestruturas($params)
{
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_infraestrutura.unidade_id', $params->unidade_id)
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereColumn('ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_especialidade')
->whereColumn('cadastro_especialidade.id', 'ambulatorio_jornada.especialidade_id')
)
->where('ambulatorio_agendamento.status_id', '<>', AgendamentoStatus::AGENDADO)
->whereBetween('ambulatorio_jornada.data', $params->periodo)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->whereColumn('ambulatorio_demanda_espontanea.created_lotacao_id', 'cadastro_lotacao.id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_especialidade')
->whereColumn('cadastro_especialidade.id', 'ambulatorio_demanda_espontanea.especialidade_id')
)
->whereNotNull('ambulatorio_atendimento.finalizado_em')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
)
)
)
->orderByRaw('COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)')
->get();
}
private static function getEspecialidades($params)
{
return DB::table('cadastro_especialidade')
->select([
'cadastro_especialidade.id',
'cadastro_especialidade.nome',
])
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_jornada.especialidade_id', 'cadastro_especialidade.id')
->where('ambulatorio_agendamento.status_id', '<>', AgendamentoStatus::AGENDADO)
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->where('cadastro_infraestrutura.id', $params->infraestrutura_id)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_demanda_espontanea.especialidade_id', 'cadastro_especialidade.id')
->whereNotNull('ambulatorio_atendimento.finalizado_em')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->where('cadastro_infraestrutura.id', $params->infraestrutura_id)
)
)
->orderBy('cadastro_especialidade.nome')
->get();
}
private static function getUsuarios($params)
{
return DB::table('cadastro_usuario')
->select([
'cadastro_usuario.id',
'cadastro_cidadao.nome',
])
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('cadastro_lotacao.usuario_id', 'cadastro_usuario.id')
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->where('cadastro_infraestrutura.id', $params->infraestrutura_id)
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereColumn('ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->where('ambulatorio_agendamento.status_id', '<>', AgendamentoStatus::AGENDADO)
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->especialidade_id, fn ($q) => $q->where('ambulatorio_jornada.especialidade_id', $params->especialidade_id))
)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_demanda_espontanea.usuario_id', 'cadastro_usuario.id')
->whereNotNull('ambulatorio_atendimento.finalizado_em')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->where('cadastro_infraestrutura.id', $params->infraestrutura_id)
->when($params->especialidade_id, fn ($q) => $q->where('ambulatorio_demanda_espontanea.especialidade_id', $params->especialidade_id))
)
->orderBy('cadastro_cidadao.nome')
->get();
}
private static function getStatus($params)
{
return DB::table('ambulatorio_agendamento_status')
->select([
'ambulatorio_agendamento_status.id',
'ambulatorio_agendamento_status.nome',
])
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->leftJoin('ambulatorio_atendimento','ambulatorio_atendimento.agendamento_id','ambulatorio_agendamento.id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_agendamento.status_id', 'ambulatorio_agendamento_status.id')
->whereIn('ambulatorio_agendamento.status_id',[AgendamentoStatus::REALIZADO, AgendamentoStatus::FALTA_DO_PACIENTE])
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->where('cadastro_lotacao.infraestrutura_id', $params->infraestrutura_id)
->when($params->especialidade_id, fn ($q) => $q->where('ambulatorio_jornada.especialidade_id', $params->especialidade_id))
->when($params->usuario_id, fn ($q) => $q->where('cadastro_lotacao.usuario_id', $params->usuario_id))
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->where('ambulatorio_agendamento_status.id', AgendamentoStatus::REALIZADO)
->whereNotNull('ambulatorio_atendimento.finalizado_em')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->where('cadastro_infraestrutura.id', $params->infraestrutura_id)
->when($params->especialidade_id, fn ($q) => $q->where('ambulatorio_demanda_espontanea.especialidade_id', $params->especialidade_id))
->when($params->usuario_id, fn ($q) => $q->where('ambulatorio_demanda_espontanea.usuario_id', $params->usuario_id))
)
)
->orderBy('ambulatorio_agendamento_status.nome')
->get();
}
private static function setOrderBy($builder)
{
$columns = [
'demanda_tipo' => 'demanda_tipo',
'data_atendimento' => 'data_atendimento',
'usuario_nome' => 'usuario_nome',
'especialidade_nome' => 'especialidade_nome',
'paciente_nome' => 'paciente_nome',
'paciente_prontuario' => 'paciente_prontuario',
'horario_atendimento' => 'horario_atendimento',
'agendamento_status_nome' => 'agendamento_status_nome',
];
if (is_null(request()->sort_by)) {
$builder->orderByRaw(join(', ', $columns));
return;
}
$column = $columns[request()->sort_by];
$direction = DataUtil::getBooleanValueFromStringBoolean(request()->sort_desc) ? 'DESC' : 'ASC';
unset($columns[request()->sort_by]);
$builder->orderByRaw("{$column} {$direction}, " . join(', ', $columns));
}
}

View File

@@ -0,0 +1,244 @@
<?php
namespace App\Services\Ambulatorio;
use App\Services\Service;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RelatorioConsultaSolicitadaService extends Service
{
public static function index()
{
$params = self::getParams();
$agendamentos = DB::table('ambulatorio_agendamento')
->select([
DB::raw("DATE_FORMAT(ambulatorio_agendamento.created_at, '%d/%m/%Y') AS data"),
'cadastro_unidade.nome_fantasia AS unidade_nome_fantasia',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia) AS infraestrutura_nome"),
'cadastro_especialidade.nome AS especialidade_nome',
'cadastro_cidadao.nome AS usuario_nome',
DB::raw("COUNT(*) AS total"),
])
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
->join('cadastro_especialidade', 'cadastro_especialidade.id', 'ambulatorio_jornada.especialidade_id')
->join('cadastro_usuario', 'cadastro_usuario.id', 'cadastro_lotacao.usuario_id')
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->whereBetween('ambulatorio_agendamento.created_at', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_unidade.id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('cadastro_especialidade.id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('cadastro_usuario.id', $usuarioId)
)
->groupBy([
DB::raw("DATE_FORMAT(ambulatorio_agendamento.created_at, '%d/%m/%Y')"),
'cadastro_unidade.nome_fantasia',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)"),
'cadastro_especialidade.nome',
'cadastro_cidadao.nome',
])
->get();
return [
'itens' => $agendamentos,
'totalizadores' => ['quantidade_agendamentos' => $agendamentos->reduce(fn ($a, $b) => $a + $b->total)],
];
}
public static function create()
{
return [
'form' => [
'unidades' => [],
'infraestruturas' => [],
'especialidades' => [],
'usuarios' => [],
],
'model' => [
'periodo' => ['start' => null, 'end' => null],
'unidade_id' => null,
'infraestrutura_id' => null,
'especialidade_id' => null,
'usuario_id' => null,
],
];
}
public static function list()
{
$params = self::getParams();
switch (request()->listar) {
case 'unidades': {
return [
'unidades' => self::getUnidades($params),
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
];
}
case 'infraestruturas': {
return [
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
];
}
case 'especialidades': {
return [
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
];
}
case 'usuarios': {
return [
'usuarios' => self::getUsuarios($params),
];
}
}
}
private static function getParams()
{
return (object) [
'periodo' => [
'start' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['start'])->setTime(0, 0, 0),
'end' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['end'])->setTime(23, 59, 59)
],
'unidade_id' => request()->get('unidade_id'),
'infraestrutura_id' => request()->get('infraestrutura_id'),
'especialidade_id' => request()->get('especialidade_id'),
'usuario_id' => request()->get('usuario_id'),
];
}
private static function getUnidades($params)
{
return DB::table('cadastro_unidade')
->select([
'cadastro_unidade.id',
'cadastro_unidade.nome_fantasia',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_infraestrutura')
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereColumn('ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->whereBetween('ambulatorio_agendamento.created_at', $params->periodo)
)
)
)
)
->orderBy('cadastro_unidade.nome_fantasia')
->get();
}
private static function getInfraestruturas($params)
{
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_infraestrutura.unidade_id', $params->unidade_id)
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereColumn('ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->whereBetween('ambulatorio_agendamento.created_at', $params->periodo)
)
)
)
->orderByRaw('COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)')
->get();
}
private static function getEspecialidades($params)
{
return DB::table('cadastro_especialidade')
->select([
'cadastro_especialidade.id',
'cadastro_especialidade.nome',
])
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_jornada.especialidade_id', 'cadastro_especialidade.id')
->whereBetween('ambulatorio_agendamento.created_at', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
)
)
->orderBy('cadastro_especialidade.nome')
->get();
}
private static function getUsuarios($params)
{
return DB::table('cadastro_usuario')
->select([
'cadastro_usuario.id',
'cadastro_cidadao.nome',
])
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('cadastro_lotacao.usuario_id', 'cadastro_usuario.id')
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereColumn('ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->whereBetween('ambulatorio_agendamento.created_at', $params->periodo)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('ambulatorio_jornada.especialidade_id', $especialidadeId)
)
)
)
->orderBy('cadastro_cidadao.nome')
->get();
}
}

View File

@@ -0,0 +1,713 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Ambulatorio\AgendamentoStatus;
use App\Enums\Ambulatorio\AgendamentoTipo;
use App\Enums\Ambulatorio\Origem;
use App\Models\Ambulatorio\DemandaEspontanea;
use App\Services\Service;
use App\Utils\DataUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RelatorioEstatisticoConsultaService extends Service
{
public static function index()
{
$params = self::getParams();
$itens = [];
$totalizadores = [];
$getDemandasAgendadas = fn () => DB::table('ambulatorio_agendamento')
->select([
DB::raw("DATE_FORMAT(ambulatorio_jornada.data, '%d/%m/%Y') AS data"),
DB::raw("'AGENDADA' AS demanda_tipo_nome"),
'ambulatorio_agendamento_tipo.nome AS agendamento_tipo_nome',
'cadastro_municipio.nome AS municipio_nome',
'cadastro_unidade.nome_fantasia AS unidade_nome_fantasia',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia) AS infraestrutura_nome"),
'cadastro_especialidade.nome AS especialidade_nome',
'cadastro_cidadao.nome AS usuario_nome',
'ambulatorio_agendamento_status.id AS agendamento_status_id',
'ambulatorio_agendamento_status.nome AS agendamento_status_nome',
DB::raw("COUNT(*) AS quantidade"),
])
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('ambulatorio_agendamento_tipo', 'ambulatorio_agendamento_tipo.id', 'ambulatorio_agendamento.tipo_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->join('intranet.cadastro_municipio', 'cadastro_municipio.id', 'cadastro_logradouro.municipio_id')
->join('cadastro_especialidade', 'cadastro_especialidade.id', 'ambulatorio_jornada.especialidade_id')
->join('cadastro_usuario', 'cadastro_usuario.id', 'cadastro_lotacao.usuario_id')
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->join('ambulatorio_agendamento_status', 'ambulatorio_agendamento_status.id', 'ambulatorio_agendamento.status_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->agendamento_tipo_id, fn ($q) => $q->where('ambulatorio_agendamento.tipo_id', $params->agendamento_tipo_id))
->when($params->municipio_id, fn ($q) => $q->where('cadastro_logradouro.municipio_id', $params->municipio_id))
->when($params->unidade_id, fn ($q) => $q->where('cadastro_infraestrutura.unidade_id', $params->unidade_id))
->when($params->infraestrutura_id, fn ($q) => $q->where('cadastro_infraestrutura.id', $params->infraestrutura_id))
->when($params->especialidade_id, fn ($q) => $q->where('ambulatorio_jornada.especialidade_id', $params->especialidade_id))
->when($params->usuario_id, fn ($q) => $q->where('cadastro_lotacao.usuario_id', $params->usuario_id))
->when($params->status, fn ($q) => $q->where('ambulatorio_agendamento.status_id', $params->status))
->groupBy([
DB::raw("DATE_FORMAT(ambulatorio_jornada.data, '%d/%m/%Y')"),
DB::raw("'AGENDADA'"),
'ambulatorio_agendamento_tipo.id',
'ambulatorio_agendamento_tipo.nome',
'cadastro_municipio.nome',
'cadastro_unidade.nome_fantasia',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)"),
'cadastro_especialidade.nome',
'cadastro_cidadao.nome',
'ambulatorio_agendamento_status.id',
]);
$getDemandasEspontaneas = fn () => DB::table('ambulatorio_atendimento')
->select([
DB::raw("DATE_FORMAT(ambulatorio_demanda_espontanea.data, '%d/%m/%Y') AS data"),
DB::raw("'ESPONTÂNEA' AS demanda_tipo_nome"),
DB::raw("(SELECT nome FROM ambulatorio_agendamento_tipo WHERE id = " . AgendamentoTipo::CONSULTA . ") AS agendamento_tipo_nome"),
'cadastro_municipio.nome AS municipio_nome',
'cadastro_unidade.nome_fantasia AS unidade_nome_fantasia',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia) AS infraestrutura_nome"),
'cadastro_especialidade.nome AS especialidade_nome',
'cadastro_cidadao.nome AS usuario_nome',
DB::raw("
CASE
WHEN painel_senha_fila.evadido = 1 THEN " . AgendamentoStatus::EVADIDO . "
WHEN ambulatorio_atendimento.finalizado_em IS NOT NULL
AND painel_senha_fila.evadido = 0 THEN " . AgendamentoStatus::REALIZADO . "
ELSE 'aberto'
END AS agendamento_status_id
"),
DB::raw("
CASE
WHEN painel_senha_fila.evadido = 1 THEN 'EVADIDO'
WHEN ambulatorio_atendimento.finalizado_em IS NOT NULL
AND painel_senha_fila.evadido = 0 THEN 'REALIZADO'
ELSE 'EM ABERTO'
END AS agendamento_status_nome
"),
DB::raw("COUNT(*) AS quantidade"),
])
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('painel_senha_fila', 'painel_senha_fila.id', 'ambulatorio_atendimento.fila_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->join('intranet.cadastro_municipio', 'cadastro_municipio.id', 'cadastro_logradouro.municipio_id')
->leftJoin('cadastro_lotacao AS cadastro_lotacao_finalizacao', 'cadastro_lotacao_finalizacao.id', 'ambulatorio_atendimento.finalizado_lotacao_id')
->leftJoin('cadastro_especialidade', 'cadastro_especialidade.id', 'ambulatorio_demanda_espontanea.especialidade_id')
->leftJoin('cadastro_usuario', 'cadastro_usuario.id', DB::raw("COALESCE(ambulatorio_demanda_espontanea.usuario_id, cadastro_lotacao_finalizacao.usuario_id)"))
->leftJoin('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->municipio_id, fn ($q) => $q->where('cadastro_logradouro.municipio_id', $params->municipio_id))
->when($params->unidade_id, fn ($q) => $q->where('cadastro_infraestrutura.unidade_id', $params->unidade_id))
->when($params->infraestrutura_id, fn ($q) => $q->where('cadastro_infraestrutura.id', $params->infraestrutura_id))
->when($params->especialidade_id, fn ($q) => $q->where('ambulatorio_demanda_espontanea.especialidade_id', $params->especialidade_id))
->when($params->usuario_id, fn ($q) => $q->where('cadastro_usuario.id', $params->usuario_id))
->when($params->status, function ($q) use($params) {
if($params->status == AgendamentoStatus::REALIZADO){
$q->whereNotNull('ambulatorio_atendimento.finalizado_em')
->where('painel_senha_fila.evadido', false);
}elseif($params->status == AgendamentoStatus::EVADIDO){
$q->where('painel_senha_fila.evadido', true);
}else{
$q->whereNull('ambulatorio_atendimento.finalizado_em')
->where('painel_senha_fila.evadido', false);
}
})
->groupBy([
DB::raw("DATE_FORMAT(ambulatorio_demanda_espontanea.data, '%d/%m/%Y')"),
DB::raw("'ESPONTÂNEA'"),
DB::raw("(SELECT nome FROM ambulatorio_agendamento_tipo WHERE id = " . AgendamentoTipo::CONSULTA . ")"),
'cadastro_municipio.nome',
'cadastro_unidade.nome_fantasia',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)"),
'cadastro_especialidade.nome',
'cadastro_cidadao.nome',
DB::raw("
CASE
WHEN painel_senha_fila.evadido = 1 THEN " . AgendamentoStatus::EVADIDO . "
WHEN ambulatorio_atendimento.finalizado_em IS NOT NULL
AND painel_senha_fila.evadido = 0 THEN " . AgendamentoStatus::REALIZADO . "
ELSE 'aberto'
END
"),
DB::raw("
CASE
WHEN painel_senha_fila.evadido = 1 THEN 'EVADIDO'
WHEN ambulatorio_atendimento.finalizado_em IS NOT NULL
AND painel_senha_fila.evadido = 0 THEN 'REALIZADO'
ELSE 'EM ABERTO'
END
")
]);
if ($params->demanda_tipo === 'agendada') {
$itens = $getDemandasAgendadas();
} else if ($params->demanda_tipo === 'espontanea') {
$itens = $getDemandasEspontaneas();
} else {
$itens = $getDemandasAgendadas()->union($getDemandasEspontaneas());
}
self::setOrderBy($itens);
$itens = $itens->get();
$totalizadores = [
'agendado' => $itens->reduce(fn ($a, $b) => $a + ($b->agendamento_status_id == AgendamentoStatus::AGENDADO ? $b->quantidade : 0)),
'realizado' => $itens->reduce(fn ($a, $b) => $a + ($b->agendamento_status_id == AgendamentoStatus::REALIZADO ? $b->quantidade : 0)),
'reagendado_paciente' => $itens->reduce(fn ($a, $b) => $a + ($b->agendamento_status_id == AgendamentoStatus::REAGENDADO_PELO_PACIENTE ? $b->quantidade : 0)),
'reagendado_medico' => $itens->reduce(fn ($a, $b) => $a + ($b->agendamento_status_id == AgendamentoStatus::REAGENDADO_PELO_MEDICO ? $b->quantidade : 0)),
'cancelado_paciente' => $itens->reduce(fn ($a, $b) => $a + ($b->agendamento_status_id == AgendamentoStatus::CANCELADO_PELO_PACIENTE ? $b->quantidade : 0)),
'cancelado_medico' => $itens->reduce(fn ($a, $b) => $a + ($b->agendamento_status_id == AgendamentoStatus::CANCELADO_PELO_MEDICO ? $b->quantidade : 0)),
'falta_paciente' => $itens->reduce(fn ($a, $b) => $a + ($b->agendamento_status_id == AgendamentoStatus::FALTA_DO_PACIENTE ? $b->quantidade : 0)),
'falta_medica' => $itens->reduce(fn ($a, $b) => $a + ($b->agendamento_status_id == AgendamentoStatus::FALTA_DO_MEDICO ? $b->quantidade : 0)),
'aberto' => $itens->reduce(fn ($a, $b) => $a + ($b->agendamento_status_nome == 'EM ABERTO' ? $b->quantidade : 0)),
'evadido'=> $itens->reduce(fn ($a, $b) => $a + ($b->agendamento_status_id == AgendamentoStatus::EVADIDO ? $b->quantidade: 0 )),
'geral' => $itens->reduce(fn ($a, $b) => $a + $b->quantidade),
];
return [
'itens' => $itens,
'totalizadores' => $totalizadores,
];
}
public static function create()
{
return [
'form' => [
'demanda_tipos' => [],
'municipios' => [],
'agendamento_tipos' => [],
'unidades' => [],
'infraestruturas' => [],
'especialidades' => [],
'usuarios' => [],
'status' => [],
],
'model' => [
'periodo' => ['start' => null, 'end' => null],
'demanda_tipo' => null,
'municipio_id' => null,
'agendamento_tipo_id' => null,
'unidade_id' => null,
'infraestrutura_id' => null,
'especialidade_id' => null,
'usuario_id' => null,
'status' => null,
],
];
}
public static function list()
{
$params = self::getParams();
switch (request()->listar) {
case 'demanda-tipos': {
return [
'demanda_tipos' => self::getDemandaTipos($params),
'agendamento_tipos' => self::getAgendamentoTipos($params),
'municipios' => self::getMunicipios($params),
'unidades' => self::getUnidades($params),
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];
}
case 'agendamento-tipos': {
return [
'agendamento_tipos' => self::getAgendamentoTipos($params),
'municipios' => self::getMunicipios($params),
'unidades' => self::getUnidades($params),
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];
}
case 'municipios': {
return [
'municipios' => self::getMunicipios($params),
'unidades' => self::getUnidades($params),
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];
}
case 'unidades': {
return [
'unidades' => self::getUnidades($params),
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];
}
case 'infraestruturas': {
return [
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];
}
case 'especialidades': {
return [
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];
}
case 'usuarios': {
return [
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];
}
case 'status': {
return [
'status' => self::getStatus($params),
];
}
}
}
private static function getParams()
{
$periodo = (array) request()->get('periodo');
return (object) [
'periodo' => [
'start' => Carbon::createFromFormat('d/m/Y', $periodo['start'])->setTime(0, 0, 0),
'end' => Carbon::createFromFormat('d/m/Y', $periodo['end'])->setTime(23, 59, 59),
],
'demanda_tipo' => request()->get('demanda_tipo'),
'agendamento_tipo_id' => request()->get('agendamento_tipo_id'),
'municipio_id' => request()->get('municipio_id'),
'unidade_id' => request()->get('unidade_id'),
'infraestrutura_id' => request()->get('infraestrutura_id'),
'especialidade_id' => request()->get('especialidade_id'),
'usuario_id' => request()->get('usuario_id'),
'status_id' => request()->get('status_id'),
'status' => request()->get('status'),
];
}
private static function getDemandaTipos($params)
{
$tipos = collect();
$demandaAgendada = DB::table('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->exists();
$demandaEspontanea = DB::table('ambulatorio_demanda_espontanea')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->exists();
if ($demandaAgendada) {
$tipos->push([
'value' => 'agendada',
'text' => 'AGENDADA'
]);
}
if ($demandaEspontanea) {
$tipos->push([
'value' => 'espontanea',
'text' => 'ESPONTÂNEA'
]);
}
return $tipos;
}
private static function getAgendamentoTipos($params)
{
$tipos = collect();
$getAgendamentoTipos = fn () => DB::table('ambulatorio_agendamento_tipo')
->select([
'id',
'nome',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->whereColumn('ambulatorio_agendamento.tipo_id', 'ambulatorio_agendamento_tipo.id')
);
$getDemandaTipos = fn () => DB::table('ambulatorio_agendamento_tipo')
->select([
'id',
'nome',
])
->where('id', AgendamentoTipo::CONSULTA);
if ($params->demanda_tipo === 'agendada') {
$tipos = $getAgendamentoTipos();
} else if ($params->demanda_tipo === 'espontanea') {
$tipos = $getDemandaTipos();
} else {
$demandaEspontanea = DB::table('ambulatorio_demanda_espontanea')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->exists();
$tipos = $getAgendamentoTipos();
if ($demandaEspontanea) {
$tipos = $tipos->union($getDemandaTipos());
}
}
return $tipos->orderBy('nome')->get();
}
private static function getMunicipios($params)
{
return DB::table('intranet.cadastro_municipio')
->select([
'id',
'nome',
])
->where(fn($q) => $q
->when(!$params->demanda_tipo || $params->demanda_tipo === 'agendada', fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->whereColumn('cadastro_logradouro.municipio_id', 'cadastro_municipio.id')
)
)
->when(!$params->demanda_tipo || $params->demanda_tipo === 'espontanea', fn ($q) => $q
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->whereColumn('cadastro_logradouro.municipio_id', 'cadastro_municipio.id')
)
)
)
->orderBy('cadastro_municipio.nome')
->get();
}
private static function getUnidades($params)
{
return DB::table('cadastro_unidade')
->select([
'cadastro_unidade.id',
'cadastro_unidade.nome_fantasia',
])
->where(fn($q) => $q
->when(!$params->demanda_tipo || $params->demanda_tipo === 'agendada', fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->municipio_id, fn ($q) => $q->where('cadastro_logradouro.municipio_id', $params->municipio_id))
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
)
)
->when(!$params->demanda_tipo || $params->demanda_tipo === 'espontanea', fn ($q) => $q
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->municipio_id, fn ($q) => $q->where('cadastro_logradouro.municipio_id', $params->municipio_id))
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
)
)
)
->orderBy('cadastro_unidade.nome_fantasia')
->get();
}
private static function getInfraestruturas($params)
{
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')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->where(fn($q) => $q
->when(!$params->demanda_tipo || $params->demanda_tipo === 'agendada', fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
)
)
->when(!$params->demanda_tipo || $params->demanda_tipo === 'espontanea', fn ($q) => $q
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
)
)
)
->when($params->municipio_id, fn ($q) => $q->where('cadastro_logradouro.municipio_id', $params->municipio_id))
->orderByRaw('COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)')
->get();
}
private static function getEspecialidades($params)
{
return DB::table('cadastro_especialidade')
->select([
'cadastro_especialidade.id',
'cadastro_especialidade.nome',
])
->where(fn($q) => $q
->when(!$params->demanda_tipo || $params->demanda_tipo === 'agendada', fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->municipio_id, fn ($q) => $q->where('cadastro_logradouro.municipio_id', $params->municipio_id))
->when($params->unidade_id, fn ($q) => $q->where('cadastro_infraestrutura.unidade_id', $params->unidade_id))
->when($params->infraestrutura_id, fn ($q) => $q->where('cadastro_infraestrutura.id', $params->infraestrutura_id))
->whereColumn('ambulatorio_jornada.especialidade_id', 'cadastro_especialidade.id')
)
)
->when(!$params->demanda_tipo || $params->demanda_tipo === 'espontanea', fn ($q) => $q
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->municipio_id, fn ($q) => $q->where('cadastro_logradouro.municipio_id', $params->municipio_id))
->when($params->unidade_id, fn ($q) => $q->where('cadastro_infraestrutura.unidade_id', $params->unidade_id))
->when($params->infraestrutura_id, fn ($q) => $q->where('cadastro_infraestrutura.id', $params->infraestrutura_id))
->whereColumn('ambulatorio_demanda_espontanea.especialidade_id', 'cadastro_especialidade.id')
)
)
)
->orderBy('cadastro_especialidade.nome')
->get();
}
private static function getUsuarios($params)
{
return DB::table('cadastro_usuario')
->select([
'cadastro_usuario.id',
'cadastro_cidadao.nome',
])
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->where(fn($q) => $q
->when(!$params->demanda_tipo || $params->demanda_tipo === 'agendada', fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->municipio_id, fn ($q) => $q->where('cadastro_logradouro.municipio_id', $params->municipio_id))
->when($params->unidade_id, fn ($q) => $q->where('cadastro_infraestrutura.unidade_id', $params->unidade_id))
->when($params->infraestrutura_id, fn ($q) => $q->where('cadastro_infraestrutura.id', $params->infraestrutura_id))
->when($params->especialidade_id, fn ($q) => $q->where('ambulatorio_jornada.especialidade_id', $params->especialidade_id))
->whereColumn('cadastro_lotacao.usuario_id', 'cadastro_usuario.id')
)
)
->when(!$params->demanda_tipo || $params->demanda_tipo === 'espontanea', fn ($q) => $q
->orWhere(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->municipio_id, fn ($q) => $q->where('cadastro_logradouro.municipio_id', $params->municipio_id))
->when($params->unidade_id, fn ($q) => $q->where('cadastro_infraestrutura.unidade_id', $params->unidade_id))
->when($params->infraestrutura_id, fn ($q) => $q->where('cadastro_infraestrutura.id', $params->infraestrutura_id))
->when($params->especialidade_id, fn ($q) => $q->where('ambulatorio_demanda_espontanea.especialidade_id', $params->especialidade_id))
->whereColumn('ambulatorio_demanda_espontanea.usuario_id', 'cadastro_usuario.id')
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_atendimento.finalizado_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->municipio_id, fn ($q) => $q->where('cadastro_logradouro.municipio_id', $params->municipio_id))
->when($params->unidade_id, fn ($q) => $q->where('cadastro_infraestrutura.unidade_id', $params->unidade_id))
->when($params->infraestrutura_id, fn ($q) => $q->where('cadastro_infraestrutura.id', $params->infraestrutura_id))
->when($params->especialidade_id, fn ($q) => $q->where('ambulatorio_demanda_espontanea.especialidade_id', $params->especialidade_id))
->whereColumn('cadastro_lotacao.usuario_id', 'cadastro_usuario.id')
)
)
)
)
->orderBy('cadastro_cidadao.nome')
->get();
}
private static function getStatus($params)
{
$status = collect();
$getAgendamentoSatus = fn () => DB::table('ambulatorio_agendamento_status')
->select([
'ambulatorio_agendamento_status.id',
'ambulatorio_agendamento_status.nome',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->municipio_id, fn ($q) => $q->where('cadastro_logradouro.municipio_id', $params->municipio_id))
->when($params->unidade_id, fn ($q) => $q->where('cadastro_infraestrutura.unidade_id', $params->unidade_id))
->when($params->infraestrutura_id, fn ($q) => $q->where('cadastro_infraestrutura.id', $params->infraestrutura_id))
->when($params->especialidade_id, fn ($q) => $q->where('ambulatorio_jornada.especialidade_id', $params->especialidade_id))
->when($params->usuario_id, fn ($q) => $q->where('cadastro_lotacao.usuario_id', $params->usuario_id))
->whereColumn('ambulatorio_agendamento.status_id', 'ambulatorio_agendamento_status.id')
);
$getDemandasEspontaneasStatus = fn () => DB::table('ambulatorio_atendimento')
->select([
DB::raw("
CASE
WHEN painel_senha_fila.evadido = 1 THEN " . AgendamentoStatus::EVADIDO . "
WHEN ambulatorio_atendimento.finalizado_em IS NOT NULL
AND painel_senha_fila.evadido = 0 THEN " . AgendamentoStatus::REALIZADO . "
ELSE 'EM ABERTO'
END AS id
"),
DB::raw("
CASE
WHEN painel_senha_fila.evadido = 1 THEN 'EVADIDO'
WHEN ambulatorio_atendimento.finalizado_em IS NOT NULL
AND painel_senha_fila.evadido = 0 THEN 'REALIZADO'
ELSE 'EM ABERTO'
END AS nome
")
])
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('painel_senha_fila', 'painel_senha_fila.id', 'ambulatorio_atendimento.fila_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_endereco', 'cadastro_endereco.id', 'cadastro_infraestrutura.endereco_id')
->join('cadastro_logradouro', 'cadastro_logradouro.id', 'cadastro_endereco.logradouro_id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->municipio_id, fn ($q) => $q->where('cadastro_logradouro.municipio_id', $params->municipio_id))
->when($params->unidade_id, fn ($q) => $q->where('cadastro_infraestrutura.unidade_id', $params->unidade_id))
->when($params->infraestrutura_id, fn ($q) => $q->where('cadastro_infraestrutura.id', $params->infraestrutura_id))
->when($params->especialidade_id, fn ($q) => $q->where('ambulatorio_demanda_espontanea.especialidade_id', $params->especialidade_id))
->when($params->usuario_id, fn ($q) => $q->where('ambulatorio_demanda_espontanea.usuario_id', $params->usuario_id))
->distinct();
if ($params->demanda_tipo === 'agendada') {
$status = $getAgendamentoSatus();
} else if ($params->demanda_tipo === 'espontanea') {
$status = $getDemandasEspontaneasStatus();
} else {
$demandasEspontaneas = DB::table('ambulatorio_demanda_espontanea')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->exists();
$status = $getAgendamentoSatus();
if ($demandasEspontaneas) {
$status = $status->union($getDemandasEspontaneasStatus());
}
}
return $status->orderBy('nome')->get();
}
private static function setOrderBy($builder)
{
$columns = [
'data' => 'data',
'agendamento_tipo_nome' => 'agendamento_tipo_nome',
'municipio_nome' => 'municipio_nome',
'unidade_nome_fantasia' => 'unidade_nome_fantasia',
'infraestrutura_nome' => 'infraestrutura_nome',
'especialidade_nome' => 'especialidade_nome',
'usuario_nome' => 'usuario_nome',
'agendamento_status_nome' => 'agendamento_status_nome',
];
if (is_null(request()->sort_by)) {
$builder->orderByRaw(join(', ', $columns));
return;
}
$column = $columns[request()->sort_by];
$direction = DataUtil::getBooleanValueFromStringBoolean(request()->sort_desc) ? 'DESC' : 'ASC';
unset($columns[request()->sort_by]);
$builder->orderByRaw("{$column} {$direction}, " . join(', ', $columns));
}
}

View File

@@ -0,0 +1,426 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Ambulatorio\AgendamentoStatus;
use App\Services\Service;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RelatorioEstatisticoPacienteService extends Service
{
public static function index()
{
$params = self::getParams();
$itens = DB::table('ambulatorio_agendamento')
->select([
'ambulatorio_agendamento.id',
DB::raw("DATE_FORMAT(ambulatorio_jornada.data, '%d/%m/%Y') AS data"),
'cadastro_especialidade.nome AS especialidade_nome',
'cadastro_cidadao_usuario.nome AS usuario_nome',
'cadastro_cidadao.nome AS paciente_nome',
'cadastro_cidadao.cns AS paciente_cns',
DB::raw("CONCAT(cadastro_cidadao.nome, ' / ', IFNULL(cadastro_cidadao.cns, '')) AS paciente"),
'ambulatorio_agendamento_status.nome AS agendamento_status_nome',
'cadastro_cidadao.data_nascimento',
DB::raw("TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, CURRENT_DATE) AS paciente_idade"),
])
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_especialidade', 'cadastro_especialidade.id', 'ambulatorio_jornada.especialidade_id')
->join('cadastro_usuario', 'cadastro_usuario.id', 'cadastro_lotacao.usuario_id')
->join('cadastro_cidadao AS cadastro_cidadao_usuario', 'cadastro_cidadao_usuario.id', 'cadastro_usuario.cidadao_id')
->join('cadastro_paciente', 'cadastro_paciente.id', 'ambulatorio_agendamento.paciente_id')
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id')
->join('ambulatorio_agendamento_status', 'ambulatorio_agendamento_status.id', 'ambulatorio_agendamento.status_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('cadastro_especialidade.id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('cadastro_usuario.id', $usuarioId)
)
->when($params->status_id, fn ($q, $statusId) => $q
->where('ambulatorio_agendamento_status.id', $statusId)
)
->when($params->idade_de, fn ($q, $idadeDe) => $q
->whereRaw(DB::raw("TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, CURRENT_DATE) >= " . $idadeDe))
)
->when($params->idade_ate, fn ($q, $idadeAte) => $q
->whereRaw(DB::raw("TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, CURRENT_DATE) <= " . $idadeAte))
)
->union(
DB::table('ambulatorio_atendimento')
->select([
'ambulatorio_atendimento.id',
DB::raw("DATE_FORMAT(ambulatorio_demanda_espontanea.data, '%d/%m/%Y') AS data"),
'cadastro_especialidade.nome AS especialidade_nome',
'cadastro_cidadao_usuario.nome AS usuario_nome',
'cadastro_cidadao.nome AS paciente_nome',
'cadastro_cidadao.cns AS paciente_cns',
DB::raw("CONCAT(cadastro_cidadao.nome, ' / ', IFNULL(cadastro_cidadao.cns, '')) AS paciente"),
DB::raw("
(
SELECT ambulatorio_agendamento_status.nome
FROM ambulatorio_agendamento_status
WHERE ambulatorio_agendamento_status.id = " . AgendamentoStatus::REALIZADO . "
) AS agendamento_status_nome
"),
'cadastro_cidadao.data_nascimento',
DB::raw("TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, CURRENT_DATE) AS paciente_idade"),
])
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_especialidade', 'cadastro_especialidade.id', 'ambulatorio_demanda_espontanea.especialidade_id')
->join('cadastro_usuario', 'cadastro_usuario.id', 'ambulatorio_demanda_espontanea.usuario_id')
->join('cadastro_cidadao AS cadastro_cidadao_usuario', 'cadastro_cidadao_usuario.id', 'cadastro_usuario.cidadao_id')
->join('cadastro_paciente', 'cadastro_paciente.id', 'ambulatorio_demanda_espontanea.paciente_id')
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id')
->whereNotNull('ambulatorio_atendimento.finalizado_em')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('cadastro_especialidade.id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('cadastro_usuario.id', $usuarioId)
)
->when(
$params->status_id,
fn($q, $statusId) => $q
->where(DB::raw("
(
SELECT ambulatorio_agendamento_status.id
FROM ambulatorio_agendamento_status
WHERE ambulatorio_agendamento_status.id = " . AgendamentoStatus::REALIZADO . "
)
"), $statusId)
)
->when($params->idade_de, fn ($q, $idadeDe) => $q
->whereRaw(DB::raw("TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, CURRENT_DATE) >= " . $idadeDe))
)
->when($params->idade_ate, fn ($q, $idadeAte) => $q
->whereRaw(DB::raw("TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, CURRENT_DATE) <= " . $idadeAte))
)
)
->get();
return [
'itens' => $itens,
'totalizadores' => ['quantidade_atendimentos' => $itens->count()],
];
}
public static function create()
{
return [
'form' => [
'unidades' => [],
'infraestruturas' => [],
'especialidades' => [],
'usuarios' => [],
'status' => [],
],
'model' => [
'periodo' => ['start' => null, 'end' => null],
'unidade_id' => null,
'infraestrutura_id' => null,
'especialidade_id' => null,
'usuario_id' => null,
'status_id' => null,
'idade_de' => null,
'idade_ate' => null,
],
];
}
public static function list()
{
$params = self::getParams();
switch (request()->listar) {
case 'unidades': {
return [
'unidades' => self::getUnidades($params),
];
}
case 'infraestruturas': {
return [
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];
}
case 'especialidades': {
return [
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];
}
case 'usuarios': {
return [
'usuarios' => self::getUsuarios($params),
'status' => self::getStatus($params),
];
}
case 'status': {
return [
'status' => self::getStatus($params),
];
}
}
}
private static function getParams()
{
return (object) [
'periodo' => [
'start' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['start'])->setTime(0, 0, 0),
'end' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['end'])->setTime(23, 59, 59)
],
'unidade_id' => request()->get('unidade_id'),
'infraestrutura_id' => request()->get('infraestrutura_id'),
'especialidade_id' => request()->get('especialidade_id'),
'usuario_id' => request()->get('usuario_id'),
'status_id' => request()->get('status_id'),
'idade_de' => request()->get('idade_de'),
'idade_ate' => request()->get('idade_ate'),
];
}
private static function getUnidades($params)
{
return DB::table('cadastro_unidade')
->select([
'cadastro_unidade.id',
'cadastro_unidade.nome_fantasia',
])
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_infraestrutura')
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereColumn('ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
)
)
)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_infraestrutura')
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea')
->whereColumn('ambulatorio_demanda_espontanea.created_lotacao_id', 'cadastro_lotacao.id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
)
)
)
)
)
->orderBy('cadastro_unidade.nome_fantasia')
->get();
}
private static function getInfraestruturas($params)
{
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_infraestrutura.unidade_id', $params->unidade_id)
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereColumn('ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
)
)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea')
->whereColumn('ambulatorio_demanda_espontanea.created_lotacao_id', 'cadastro_lotacao.id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
)
)
)
)
->orderByRaw('COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)')
->get();
}
private static function getEspecialidades($params)
{
return DB::table('cadastro_especialidade')
->select([
'cadastro_especialidade.id',
'cadastro_especialidade.nome',
])
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_jornada.especialidade_id', 'cadastro_especialidade.id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_demanda_espontanea.especialidade_id', 'cadastro_especialidade.id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
)
)
->orderBy('cadastro_especialidade.nome')
->get();
}
private static function getUsuarios($params)
{
$queryAgendamentos = DB::table('cadastro_usuario')
->select([
'cadastro_usuario.id',
'cadastro_cidadao.nome',
])
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->join('cadastro_lotacao', 'cadastro_lotacao.usuario_id', 'cadastro_usuario.id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->where('cadastro_lotacao.ativo', 1)
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->infraestrutura_id, function ($q, $infraestruturaId) {
return $q->where('cadastro_infraestrutura.id', $infraestruturaId);
})
->when($params->especialidade_id, function ($q, $especialidadeId) {
return $q->where('ambulatorio_jornada.especialidade_id', $especialidadeId);
});
$queryDemandas = DB::table('cadastro_usuario')
->select([
'cadastro_usuario.id',
'cadastro_cidadao.nome',
])
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.usuario_id', 'cadastro_usuario.id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->where('cadastro_lotacao.ativo', 1)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->infraestrutura_id, function ($q, $infraestruturaId) {
return $q->where('cadastro_infraestrutura.id', $infraestruturaId);
})
->when($params->especialidade_id, function ($q, $especialidadeId) {
return $q->where('ambulatorio_demanda_espontanea.especialidade_id', $especialidadeId);
});
return $queryAgendamentos
->union($queryDemandas)
->orderBy('nome')
->get();
}
private static function getStatus($params)
{
return DB::table('ambulatorio_agendamento_status')
->select([
'ambulatorio_agendamento_status.id',
'ambulatorio_agendamento_status.nome',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_agendamento.status_id', 'ambulatorio_agendamento_status.id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('ambulatorio_jornada.especialidade_id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('cadastro_lotacao.usuario_id', $usuarioId)
)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->where('ambulatorio_agendamento_status.id', AgendamentoStatus::REALIZADO)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('ambulatorio_demanda_espontanea.especialidade_id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('ambulatorio_demanda_espontanea.usuario_id', $usuarioId)
)
)
->orderBy('ambulatorio_agendamento_status.nome')
->get();
}
}

View File

@@ -0,0 +1,523 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Ambulatorio\AgendamentoStatus;
use App\Services\Service;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RelatorioEstatisticoStatusService extends Service
{
public static function index()
{
$params = self::getParams();
$demandas = collect();
if (is_null($params->origem) || $params->origem === 'agendamento') {
DB::table('ambulatorio_agendamento')
->select([
'cadastro_usuario.id AS usuario_id',
'cadastro_cidadao.nome AS usuario_nome',
'cadastro_especialidade.id AS especialidade_id',
'cadastro_especialidade.nome AS especialidade_nome',
'cadastro_unidade.id AS unidade_id',
'cadastro_unidade.nome_fantasia AS unidade_nome_fantasia',
'cadastro_infraestrutura.id AS infraestrutura_id',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia) AS infraestrutura_nome"),
DB::raw("SUM(CASE WHEN ambulatorio_agendamento.status_id IN (" . AgendamentoStatus::REALIZADO . ", " . AgendamentoStatus::FALTA_DO_PACIENTE . ", " . AgendamentoStatus::FALTA_DO_MEDICO . ") THEN 1 ELSE 0 END) AS quantidade_atendimento"),
DB::raw("SUM(CASE WHEN ambulatorio_agendamento.status_id = " . AgendamentoStatus::REALIZADO . " THEN 1 ELSE 0 END) AS quantidade_atendimento_realizado"),
DB::raw("SUM(CASE WHEN ambulatorio_agendamento.status_id = " . AgendamentoStatus::FALTA_DO_PACIENTE . " THEN 1 ELSE 0 END) AS quantidade_falta_paciente"),
DB::raw("SUM(CASE WHEN ambulatorio_agendamento.status_id = " . AgendamentoStatus::FALTA_DO_MEDICO . " THEN 1 ELSE 0 END) AS quantidade_falta_medico"),
])
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
->join('cadastro_especialidade', 'cadastro_especialidade.id', 'ambulatorio_jornada.especialidade_id')
->join('cadastro_usuario', 'cadastro_usuario.id', 'cadastro_lotacao.usuario_id')
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->whereIn('ambulatorio_agendamento.status_id', [AgendamentoStatus::REALIZADO, AgendamentoStatus::FALTA_DO_PACIENTE, AgendamentoStatus::FALTA_DO_MEDICO])
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_unidade.id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('cadastro_especialidade.id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('cadastro_usuario.id', $usuarioId)
)
->groupBy([
'cadastro_usuario.id',
'cadastro_cidadao.nome',
'cadastro_especialidade.id',
'cadastro_especialidade.nome',
'cadastro_unidade.id',
'cadastro_unidade.nome_fantasia',
'cadastro_infraestrutura.id',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)"),
])
->get()
->each(function($query) use ($demandas) {
$demandas->push((object) [
'usuario_id' => $query->usuario_id,
'usuario_nome' => $query->usuario_nome,
'especialidade_id' => $query->especialidade_id,
'especialidade_nome' => $query->especialidade_nome,
'unidade_id' => $query->unidade_id,
'unidade_nome_fantasia' => $query->unidade_nome_fantasia,
'infraestrutura_id' => $query->infraestrutura_id,
'infraestrutura_nome' => $query->infraestrutura_nome,
'agendamento_quantidade_atendimento_realizado' => $query->quantidade_atendimento_realizado,
'agendamento_porcentagem_atendimento_realizado' => round($query->quantidade_atendimento > 0 ? $query->quantidade_atendimento_realizado * 100 / $query->quantidade_atendimento : 0),
'agendamento_quantidade_falta_paciente' => $query->quantidade_falta_paciente,
'agendamento_porcentagem_falta_paciente' => round($query->quantidade_atendimento > 0 ? $query->quantidade_falta_paciente * 100 / $query->quantidade_atendimento : 0),
'agendamento_quantidade_falta_medico' => $query->quantidade_falta_medico,
'agendamento_porcentagem_falta_medico' => round($query->quantidade_atendimento > 0 ? $query->quantidade_falta_medico * 100 / $query->quantidade_atendimento : 0),
'agendamento_quantidade_atendimento' => $query->quantidade_atendimento,
'demanda_espontanea_quantidade_atendimento_realizado' => 0,
'demanda_espontanea_porcentagem_atendimento_realizado' => 0,
'demanda_espontanea_quantidade_atendimento' => 0,
]);
});
}
if (is_null($params->origem) || $params->origem === 'demanda-espontanea') {
DB::table('ambulatorio_demanda_espontanea')
->select([
'cadastro_usuario.id AS usuario_id',
'cadastro_cidadao.nome AS usuario_nome',
'cadastro_especialidade.id AS especialidade_id',
'cadastro_especialidade.nome AS especialidade_nome',
'cadastro_unidade.id AS unidade_id',
'cadastro_unidade.nome_fantasia AS unidade_nome_fantasia',
'cadastro_infraestrutura.id AS infraestrutura_id',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia) AS infraestrutura_nome"),
DB::raw("COUNT(*) AS quantidade_atendimento_realizado"),
])
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.demanda_espontanea_id', 'ambulatorio_demanda_espontanea.id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
->leftJoin('cadastro_especialidade', 'cadastro_especialidade.id', 'ambulatorio_demanda_espontanea.especialidade_id')
->leftJoin('cadastro_usuario', 'cadastro_usuario.id', 'ambulatorio_demanda_espontanea.usuario_id')
->leftJoin('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->whereNotNull('ambulatorio_atendimento.finalizado_em')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_unidade.id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('cadastro_especialidade.id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('cadastro_usuario.id', $usuarioId)
)
->groupBy([
'cadastro_usuario.id',
'cadastro_cidadao.nome',
'cadastro_especialidade.id',
'cadastro_especialidade.nome',
'cadastro_unidade.id',
'cadastro_unidade.nome_fantasia',
'cadastro_infraestrutura.id',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)"),
])
->get()
->each(function($query) use ($demandas) {
$demanda = $demandas->where('usuario_id', $query->usuario_id)
->where('especialidade_id', $query->especialidade_id)
->where('unidade_id', $query->unidade_id)
->where('infraestrutura_id', $query->infraestrutura_id)
->first();
if (is_null($demanda)) {
$demanda = (object) [
'usuario_id' => $query->usuario_id,
'usuario_nome' => $query->usuario_nome,
'especialidade_id' => $query->especialidade_id,
'especialidade_nome' => $query->especialidade_nome,
'unidade_id' => $query->unidade_id,
'unidade_nome_fantasia' => $query->unidade_nome_fantasia,
'infraestrutura_id' => $query->infraestrutura_id,
'infraestrutura_nome' => $query->infraestrutura_nome,
'agendamento_quantidade_atendimento_realizado' => 0,
'agendamento_porcentagem_atendimento_realizado' => 0,
'agendamento_quantidade_falta_paciente' => 0,
'agendamento_porcentagem_falta_paciente' => 0,
'agendamento_quantidade_falta_medico' => 0,
'agendamento_porcentagem_falta_medico' => 0,
'agendamento_quantidade_atendimento' => 0,
];
$demandas->push($demanda);
}
$demanda->demanda_espontanea_quantidade_atendimento_realizado = $query->quantidade_atendimento_realizado;
$demanda->demanda_espontanea_porcentagem_atendimento_realizado = $query->quantidade_atendimento_realizado > 0 ? 100 : 0;
$demanda->demanda_espontanea_quantidade_atendimento = $query->quantidade_atendimento_realizado;
});
}
$demandas->each(function ($query) {
unset(
$query->usuario_id,
$query->especialidade_id,
$query->unidade_id,
$query->infraestrutura_id
);
});
$agendamentoQuantidadeAtendimentoRealizado = $demandas->reduce(fn ($a, $b) => $a + $b->agendamento_quantidade_atendimento_realizado);
$agendamentoQuantidadeFaltaPaciente = $demandas->reduce(fn ($a, $b) => $a + $b->agendamento_quantidade_falta_paciente);
$agendamentoQuantidadeFaltaMedico = $demandas->reduce(fn ($a, $b) => $a + $b->agendamento_quantidade_falta_medico);
$agendamentoQuantidadeAtendimento = $demandas->reduce(fn ($a, $b) => $a + $b->agendamento_quantidade_atendimento);
$demandaEspontaneaQuantidadeAtendimentoRealizado = $demandas->reduce(fn ($a, $b) => $a + $b->demanda_espontanea_quantidade_atendimento_realizado);
$demandaEspontaneaQuantidadeAtendimento = $demandas->reduce(fn ($a, $b) => $a + $b->demanda_espontanea_quantidade_atendimento);
return [
'itens' => $demandas,
'totalizadores' => [
'agendamento_quantidade_atendimento_realizado' => $agendamentoQuantidadeAtendimentoRealizado,
'agendamento_porcentagem_atendimento_realizado' => round($agendamentoQuantidadeAtendimento > 0 ? $agendamentoQuantidadeAtendimentoRealizado * 100 / $agendamentoQuantidadeAtendimento : 0, 2),
'agendamento_quantidade_falta_paciente' => $agendamentoQuantidadeFaltaPaciente,
'agendamento_porcentagem_falta_paciente' => round($agendamentoQuantidadeAtendimento > 0 ? $agendamentoQuantidadeFaltaPaciente * 100 / $agendamentoQuantidadeAtendimento : 0, 2),
'agendamento_quantidade_falta_medico' => $agendamentoQuantidadeFaltaMedico,
'agendamento_porcentagem_falta_medico' => round($agendamentoQuantidadeAtendimento > 0 ? $agendamentoQuantidadeFaltaMedico * 100 / $agendamentoQuantidadeAtendimento : 0, 2),
'agendamento_quantidade_atendimento' => $agendamentoQuantidadeAtendimento,
'demanda_espontanea_quantidade_atendimento_realizado' => $demandaEspontaneaQuantidadeAtendimentoRealizado,
'demanda_espontanea_porcentagem_atendimento_realizado' => $demandaEspontaneaQuantidadeAtendimentoRealizado > 0 ? 100 : 0,
'demanda_espontanea_quantidade_atendimento' => $demandaEspontaneaQuantidadeAtendimento
],
];
}
public static function create()
{
return [
'form' => [
'unidades' => [],
'infraestruturas' => [],
'especialidades' => [],
'usuarios' => [],
'origens' => [],
],
'model' => [
'periodo' => ['start' => null, 'end' => null],
'unidade_id' => null,
'infraestrutura_id' => null,
'especialidade_id' => null,
'usuario_id' => null,
'origem' => null,
],
];
}
public static function list()
{
$params = self::getParams();
switch (request()->listar) {
case 'unidades': {
return [
'unidades' => self::getUnidades($params),
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'origens' => self::getOrigens($params),
];
}
case 'infraestruturas': {
return [
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'origens' => self::getOrigens($params),
];
}
case 'especialidades': {
return [
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'origens' => self::getOrigens($params),
];
}
case 'usuarios': {
return [
'usuarios' => self::getUsuarios($params),
'origens' => self::getOrigens($params),
];
}
case 'origens': {
return [
'origens' => self::getOrigens($params),
];
}
}
}
private static function getParams()
{
return (object) [
'periodo' => [
'start' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['start'])->setTime(0, 0, 0),
'end' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['end'])->setTime(23, 59, 59)
],
'unidade_id' => request()->get('unidade_id'),
'infraestrutura_id' => request()->get('infraestrutura_id'),
'especialidade_id' => request()->get('especialidade_id'),
'usuario_id' => request()->get('usuario_id'),
'origem' => request()->get('origem'),
];
}
private static function getUnidades($params)
{
return DB::table('cadastro_unidade')
->select([
'cadastro_unidade.id',
'cadastro_unidade.nome_fantasia',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_infraestrutura')
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereColumn('ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->whereIn('ambulatorio_agendamento.status_id', [AgendamentoStatus::REALIZADO, AgendamentoStatus::FALTA_DO_PACIENTE, AgendamentoStatus::FALTA_DO_MEDICO])
->whereBetween('ambulatorio_jornada.data', $params->periodo)
)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.demanda_espontanea_id', 'ambulatorio_demanda_espontanea.id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->whereNotNull('ambulatorio_atendimento.finalizado_em')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
)
)
)
->orderBy('cadastro_unidade.nome_fantasia')
->get();
}
private static function getInfraestruturas($params)
{
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_infraestrutura.unidade_id', $params->unidade_id)
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereColumn('ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->whereIn('ambulatorio_agendamento.status_id', [AgendamentoStatus::REALIZADO, AgendamentoStatus::FALTA_DO_PACIENTE, AgendamentoStatus::FALTA_DO_MEDICO])
->whereBetween('ambulatorio_jornada.data', $params->periodo)
)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.demanda_espontanea_id', 'ambulatorio_demanda_espontanea.id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->whereNotNull('ambulatorio_atendimento.finalizado_em')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
)
)
->orderByRaw('COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)')
->get();
}
private static function getEspecialidades($params)
{
return DB::table('cadastro_especialidade')
->select([
'cadastro_especialidade.id',
'cadastro_especialidade.nome',
])
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_jornada.especialidade_id', 'cadastro_especialidade.id')
->whereIn('ambulatorio_agendamento.status_id', [AgendamentoStatus::REALIZADO, AgendamentoStatus::FALTA_DO_PACIENTE, AgendamentoStatus::FALTA_DO_MEDICO])
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.demanda_espontanea_id', 'ambulatorio_demanda_espontanea.id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_demanda_espontanea.especialidade_id', 'cadastro_especialidade.id')
->whereNotNull('ambulatorio_atendimento.finalizado_em')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
)
)
->orderBy('cadastro_especialidade.nome')
->get();
}
private static function getUsuarios($params)
{
return DB::table('cadastro_usuario')
->select([
'cadastro_usuario.id',
'cadastro_cidadao.nome',
])
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('cadastro_lotacao.usuario_id', 'cadastro_usuario.id')
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereColumn('ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->whereIn('ambulatorio_agendamento.status_id', [AgendamentoStatus::REALIZADO, AgendamentoStatus::FALTA_DO_PACIENTE, AgendamentoStatus::FALTA_DO_MEDICO])
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('ambulatorio_jornada.especialidade_id', $especialidadeId)
)
)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_demanda_espontanea')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.demanda_espontanea_id', 'ambulatorio_demanda_espontanea.id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_demanda_espontanea.usuario_id', 'cadastro_usuario.id')
->whereNotNull('ambulatorio_atendimento.finalizado_em')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('ambulatorio_demanda_espontanea.especialidade_id', $especialidadeId)
)
)
)
->orderBy('cadastro_cidadao.nome')
->get();
}
private static function getOrigens($params)
{
$origens = collect();
$hasDemandaAgendada = DB::table('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereIn('ambulatorio_agendamento.status_id', [AgendamentoStatus::REALIZADO, AgendamentoStatus::FALTA_DO_PACIENTE, AgendamentoStatus::FALTA_DO_MEDICO])
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('ambulatorio_jornada.especialidade_id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('cadastro_lotacao.usuario_id', $usuarioId)
)
->exists();
$hasDemandaEspontanea = DB::table('ambulatorio_demanda_espontanea')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.demanda_espontanea_id', 'ambulatorio_demanda_espontanea.id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereNotNull('ambulatorio_atendimento.finalizado_em')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('ambulatorio_demanda_espontanea.especialidade_id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('ambulatorio_demanda_espontanea.usuario_id', $usuarioId)
)
->exists();
if ($hasDemandaAgendada) {
$origens->push((object) ['value' => 'agendamento', 'text' => 'Agendamento']);
}
if ($hasDemandaEspontanea) {
$origens->push((object) ['value' => 'demanda-espontanea', 'text' => 'Demanda espontânea']);
}
return $origens;
}
}

View File

@@ -0,0 +1,559 @@
<?php
namespace App\Services\Ambulatorio;
use App\Services\Service;
use App\Utils\MaskUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RelatorioIdentificacaoService extends Service
{
public static function index()
{
$params = self::getParams();
$atendimentos = DB::table('ambulatorio_atendimento_procedimento')
->select([
DB::raw("DATE_FORMAT(ambulatorio_jornada.data, '%d/%m/%Y') AS data"),
'cadastro_unidade.nome_fantasia AS unidade_nome_fantasia',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia) AS infraestrutura_nome"),
'cadastro_especialidade.nome AS especialidade_nome',
'cadastro_cidadao.nome AS usuario_nome',
'procedimento.codigo AS procedimento_codigo',
'procedimento.nome AS procedimento_nome',
DB::raw("COUNT(*) AS quantidade"),
])
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
->join('cadastro_especialidade', 'cadastro_especialidade.id', 'ambulatorio_jornada.especialidade_id')
->join('cadastro_usuario', 'cadastro_usuario.id', 'cadastro_lotacao.usuario_id')
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->join('sigtap.procedimento', 'procedimento.id', 'ambulatorio_atendimento_procedimento.procedimento_id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
)
)
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_unidade.id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('cadastro_especialidade.id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('cadastro_usuario.id', $usuarioId)
)
->when($params->procedimento_id, fn ($q, $procedimentoId) => $q
->where('procedimento.id', $procedimentoId)
)
->union(
DB::table('ambulatorio_atendimento_procedimento')
->select([
DB::raw("DATE_FORMAT(ambulatorio_demanda_espontanea.data, '%d/%m/%Y') AS data"),
'cadastro_unidade.nome_fantasia AS unidade_nome_fantasia',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia) AS infraestrutura_nome"),
'cadastro_especialidade.nome AS especialidade_nome',
'cadastro_cidadao.nome AS usuario_nome',
'procedimento.codigo AS procedimento_codigo',
'procedimento.nome AS procedimento_nome',
DB::raw("COUNT(*) AS quantidade"),
])
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
->join('sigtap.procedimento', 'procedimento.id', 'ambulatorio_atendimento_procedimento.procedimento_id')
->join('cadastro_especialidade', 'cadastro_especialidade.id', 'ambulatorio_demanda_espontanea.especialidade_id')
->join('cadastro_usuario', 'cadastro_usuario.id', 'ambulatorio_demanda_espontanea.usuario_id')
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
)
)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_unidade.id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('cadastro_especialidade.id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('cadastro_usuario.id', $usuarioId)
)
->when($params->procedimento_id, fn ($q, $procedimentoId) => $q
->where('procedimento.id', $procedimentoId)
)
->groupBy([
DB::raw("DATE_FORMAT(ambulatorio_demanda_espontanea.data, '%d/%m/%Y')"),
'cadastro_unidade.nome_fantasia',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)"),
'cadastro_especialidade.nome',
'cadastro_cidadao.nome',
'procedimento.codigo',
'procedimento.nome',
])
)
->groupBy([
DB::raw("DATE_FORMAT(ambulatorio_jornada.data, '%d/%m/%Y')"),
'cadastro_unidade.nome_fantasia',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)"),
'cadastro_especialidade.nome',
'cadastro_cidadao.nome',
'procedimento.codigo',
'procedimento.nome',
])
->get()
->map(function($query) {
$query->procedimento = MaskUtil::getProcedimentoMasked($query->procedimento_codigo) . ' - ' . $query->procedimento_nome;
unset($query->procedimento_codigo);
unset($query->procedimento_nome);
return $query;
});
return [
'itens' => $atendimentos,
'totalizadores' => ['quantidade' => $atendimentos->reduce(fn ($a, $b) => $a + $b->quantidade)],
];
}
public static function create()
{
return [
'form' => [
'unidades' => [],
'infraestruturas' => [],
'especialidades' => [],
'usuarios' => [],
],
'model' => [
'periodo' => ['start' => null, 'end' => null],
'unidade_id' => null,
'infraestrutura_id' => null,
'especialidade_id' => null,
'usuario_id' => null,
'procedimento' => null,
],
];
}
public static function list()
{
$params = self::getParams();
switch (request()->listar) {
case 'unidades': {
return [
'unidades' => self::getUnidades($params),
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
];
}
case 'infraestruturas': {
return [
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
];
}
case 'especialidades': {
return [
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
];
}
case 'usuarios': {
return [
'usuarios' => self::getUsuarios($params),
];
}
}
}
private static function getParams()
{
return (object) [
'periodo' => [
'start' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['start'])->setTime(0, 0, 0),
'end' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['end'])->setTime(23, 59, 59)
],
'unidade_id' => request()->get('unidade_id'),
'infraestrutura_id' => request()->get('infraestrutura_id'),
'especialidade_id' => request()->get('especialidade_id'),
'usuario_id' => request()->get('usuario_id'),
'procedimento_id' => request()->get('procedimento_id'),
];
}
private static function getUnidades($params)
{
return DB::table('cadastro_unidade')
->select([
'cadastro_unidade.id',
'cadastro_unidade.nome_fantasia',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_procedimento')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
)
)
->whereBetween('ambulatorio_jornada.data', $params->periodo)
)
->orWhereExists(fn ($q) => $q
->from('ambulatorio_atendimento_procedimento')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
)
)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
)
->orderBy('cadastro_unidade.nome_fantasia')
->get();
}
private static function getInfraestruturas($params)
{
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_infraestrutura.unidade_id', $params->unidade_id)
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_procedimento')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
)
)
->whereBetween('ambulatorio_jornada.data', $params->periodo)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_procedimento')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
)
)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
)
)
->orderByRaw('COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)')
->get();
}
private static function getEspecialidades($params)
{
return DB::table('cadastro_especialidade')
->select([
'cadastro_especialidade.id',
'cadastro_especialidade.nome',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_procedimento')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_jornada.especialidade_id', 'cadastro_especialidade.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
)
)
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_procedimento')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_demanda_espontanea.especialidade_id', 'cadastro_especialidade.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
)
)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
)
->orderBy('cadastro_especialidade.nome')
->get();
}
private static function getUsuarios($params)
{
return DB::table('cadastro_usuario')
->select([
'cadastro_usuario.id',
'cadastro_cidadao.nome',
])
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_procedimento')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('cadastro_lotacao.usuario_id', 'cadastro_usuario.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
)
)
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('ambulatorio_jornada.especialidade_id', $especialidadeId)
)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_procedimento')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_demanda_espontanea.usuario_id', 'cadastro_usuario.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'ambulatorio_atendimento_procedimento.soap_id')
)
)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('ambulatorio_demanda_espontanea.especialidade_id', $especialidadeId)
)
)
->orderBy('cadastro_cidadao.nome')
->get();
}
public static function autocomplete()
{
$params = self::getParams();
$procedimentos = DB::table('ambulatorio_atendimento_procedimento')
->select([
'ambulatorio_jornada.data',
'cadastro_infraestrutura.unidade_id',
'cadastro_lotacao.infraestrutura_id',
'ambulatorio_jornada.especialidade_id',
'cadastro_lotacao.usuario_id',
'ambulatorio_atendimento_procedimento.procedimento_id',
'ambulatorio_atendimento_procedimento.soap_id',
])
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->union(
DB::table('ambulatorio_atendimento_procedimento')
->select([
'ambulatorio_demanda_espontanea.data',
'cadastro_infraestrutura.unidade_id',
'cadastro_lotacao.infraestrutura_id',
'ambulatorio_demanda_espontanea.especialidade_id',
'ambulatorio_demanda_espontanea.usuario_id',
'ambulatorio_atendimento_procedimento.procedimento_id',
'ambulatorio_atendimento_procedimento.soap_id',
])
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('sigtap.procedimento', 'procedimento.id', 'ambulatorio_atendimento_procedimento.procedimento_id')
);
return DB::table('sigtap.procedimento')
->select([
'procedimento.id',
'procedimento.codigo',
'procedimento.nome',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from(DB::raw("({$procedimentos->toSql()}) AS x"))
->whereColumn('x.procedimento_id', 'procedimento.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'x.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'x.soap_id')
)
)
->whereBetween('x.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('x.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('x.infraestrutura_id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('x.especialidade_id', $especialidadeId)
)
->when($params->usuario_id, fn ($q, $usuarioId) => $q
->where('x.usuario_id', $usuarioId)
)
);
}
}

View File

@@ -0,0 +1,521 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Ambulatorio\AgendamentoStatus;
use App\Enums\Ambulatorio\AgendamentoTipo;
use App\Services\Service;
use App\Utils\DataUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class RelatorioJornadaService extends Service
{
public static function index()
{
$totalizadores = (object) [
'quantidade_consulta' => (object) ['agendado' => 0, 'total' => 0],
'quantidade_retorno' => (object) ['agendado' => 0, 'total' => 0],
'quantidade_total' => (object) ['agendado' => 0, 'total' => 0],
];
$periodo = [
'start' => Carbon::createFromFormat('d/m/Y', request()->periodo['start'])->startOfDay(),
'end' => Carbon::createFromFormat('d/m/Y', request()->periodo['end'])->endOfDay(),
];
$status = DataUtil::isStringBoolean(request()->status)
? DataUtil::getBooleanValueFromStringBoolean(request()->status)
: null;
$jornadas = DB::table('ambulatorio_jornada as jornada')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->join('sigtap.ocupacao as ocupacao', 'ocupacao.id', 'lotacao.ocupacao_id')
->join('cadastro_usuario as usuario', 'usuario.id', 'lotacao.usuario_id')
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
->join('cadastro_especialidade as especialidade', 'especialidade.id', 'jornada.especialidade_id')
->leftJoin('ambulatorio_jornada_situacao as situacao', 'situacao.id', 'jornada.situacao_id')
->whereBetween('jornada.data', $periodo)
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when($status, fn ($q) => $q->whereNull('jornada.situacao_id'))
->when($status === false, fn ($q) => $q->whereNotNull('jornada.situacao_id'))
->when(request()->situacao_id, fn ($q, $id) => $q->where('jornada.situacao_id', $id))
->when(request()->ocupacao_id, fn ($q, $id) => $q->where('lotacao.ocupacao_id', $id))
->when(request()->especialidade_id, fn ($q, $id) => $q->where('jornada.especialidade_id', $id))
->when(request()->usuario_id, fn ($q, $id) => $q->where('lotacao.usuario_id', $id))
->selectRaw("
jornada.data,
unidade.nome_fantasia as unidade_nome_fantasia,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura_nome,
ocupacao.codigo as ocupacao_codigo,
especialidade.nome as especialidade_nome,
cidadao.nome as usuario_nome,
DATE_FORMAT(jornada.inicio, '%H:%i') as inicio,
DATE_FORMAT(jornada.fim, '%H:%i') as fim,
IF(jornada.situacao_id IS NULL, 'ATIVO', 'INATIVO') as status,
situacao.nome as situacao_nome,
COALESCE(jornada.quantidade_consulta, 0) as quantidade_consulta_total,
COALESCE(jornada.quantidade_retorno, 0) as quantidade_retorno_total
")
->addSelect([
'quantidade_consulta_agendado' => function ($query) {
$query->selectRaw('COUNT(*)')
->from('ambulatorio_agendamento as agendamento')
->whereColumn('agendamento.jornada_id', 'jornada.id')
->where('agendamento.tipo_id', AgendamentoTipo::CONSULTA)
->whereNotIn('agendamento.status_id', self::getStatusLiberamHorario());
},
'quantidade_retorno_agendado' => function ($query) {
$query->selectRaw('COUNT(*)')
->from('ambulatorio_agendamento as agendamento')
->whereColumn('agendamento.jornada_id', 'jornada.id')
->where('agendamento.tipo_id', AgendamentoTipo::RETORNO)
->whereNotIn('agendamento.status_id', self::getStatusLiberamHorario());
},
])
->get();
$jornadas->each(function ($jornada) use ($totalizadores) {
$jornada->dia_semana = Str::ucfirst((new Carbon($jornada->data))->translatedFormat('l'));
$jornada->quantidade_total_agendado = $jornada->quantidade_consulta_agendado
+ $jornada->quantidade_retorno_agendado;
$jornada->quantidade_total_total = $jornada->quantidade_consulta_total
+ $jornada->quantidade_retorno_total;
$totalizadores->quantidade_consulta->agendado += $jornada->quantidade_consulta_agendado;
$totalizadores->quantidade_consulta->total += $jornada->quantidade_consulta_total;
$totalizadores->quantidade_retorno->agendado += $jornada->quantidade_retorno_agendado;
$totalizadores->quantidade_retorno->total += $jornada->quantidade_retorno_total;
$totalizadores->quantidade_total->agendado += $jornada->quantidade_total_agendado;
$totalizadores->quantidade_total->total += $jornada->quantidade_total_total;
});
return compact('jornadas', 'totalizadores');
}
private static function getStatusLiberamHorario()
{
return [
AgendamentoStatus::REAGENDADO_PELO_PACIENTE,
AgendamentoStatus::REAGENDADO_PELO_MEDICO,
AgendamentoStatus::CANCELADO_PELO_PACIENTE,
AgendamentoStatus::CANCELADO_PELO_MEDICO,
];
}
public static function list()
{
$data = (object) [
'additionals' => [],
'form' => [],
'model' => [],
];
$params = self::getParams();
$sets = [
'periodo' => function () use ($data) {
$data->model['periodo'] = ['start' => null, 'end' => null];
},
'unidade' => function () use ($data, $params) {
$unidadesData = self::getUnidadesData($params);
$data->form['unidades'] = $unidadesData['form'];
$data->model['unidade_id'] = $unidadesData['model'];
},
'infraestrutura' => function () use ($data, $params) {
$infraestruturasData = self::getInfraestruturasData($params);
$data->form['infraestruturas'] = $infraestruturasData['form'];
$data->model['infraestrutura_id'] = $infraestruturasData['model'];
},
'status' => function () use ($data, $params) {
$statusData = self::getStatusData($params);
$data->form['status'] = $statusData['form'];
$data->model['status'] = $statusData['model'];
},
'situacao' => function () use ($data, $params) {
$situacoesData = self::getSituacoesData($params);
$data->form['situacoes'] = $situacoesData['form'];
$data->model['situacao_id'] = $situacoesData['model'];
},
'ocupacao' => function () use ($data, $params) {
$ocupacoesData = self::getOcupacoesData($params);
$data->form['ocupacoes'] = $ocupacoesData['form'];
$data->model['ocupacao_id'] = $ocupacoesData['model'];
},
'especialidade' => function () use ($data, $params) {
$especialidadesData = self::getEspecialidadesData($params);
$data->form['especialidades'] = $especialidadesData['form'];
$data->model['especialidade_id'] = $especialidadesData['model'];
},
'usuario' => function () use ($data, $params) {
$usuariosData = self::getUsuariosData($params);
$data->form['usuarios'] = $usuariosData['form'];
$data->model['usuario_id'] = $usuariosData['model'];
},
];
$load = is_null(request()->load_from);
if ($load) {
$data->additionals = [];
}
foreach ($sets as $field => $set) {
if ($load) {
$set();
}
else if ($field === request()->load_from) {
$load = true;
}
}
foreach ($data as $property => $itens) {
if (empty($itens)) {
unset($data->{$property});
}
}
return $data;
}
private static function getParams()
{
$params = request()->only([
'periodo',
'unidade_id',
'infraestrutura_id',
'status',
'situacao_id',
'ocupacao_id',
'especialidade_id',
'usuario_id',
]);
if (isset($params['periodo'])
&& !is_null($params['periodo']['start'])
&& !is_null($params['periodo']['end'])
) {
$start = Carbon::createFromFormat('d/m/Y', $params['periodo']['start'])->startOfDay();
$end = Carbon::createFromFormat('d/m/Y', $params['periodo']['end'])->endOfDay();
$params['periodo']['start'] = $start;
$params['periodo']['end'] = $end;
}
else {
$params['periodo'] = null;
}
if (isset($params['status']) && DataUtil::isStringBoolean($params['status'])) {
$params['status'] = DataUtil::getBooleanValueFromStringBoolean($params['status']);
}
return $params;
}
private static function getUnidadesData($params)
{
$unidades = collect();
$id = null;
if (!is_null($params['periodo'])) {
$unidades = DB::table('cadastro_unidade as unidade')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('cadastro_infraestrutura as infraestrutura')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('cadastro_lotacao as lotacao')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_jornada as jornada')
->whereColumn('jornada.lotacao_id', 'lotacao.id')
->whereBetween('jornada.data', $params['periodo'])
)
->whereColumn('lotacao.infraestrutura_id', 'infraestrutura.id')
->whereNull('lotacao.deleted_at')
)
->whereColumn('infraestrutura.unidade_id', 'unidade.id')
->whereNull('infraestrutura.deleted_at')
)
->whereNull('unidade.deleted_at')
->orderBy('unidade.nome_fantasia')
->selectRaw("
unidade.id,
unidade.nome_fantasia
")
->get();
}
return ['form' => $unidades, 'model' => $id];
}
private static function getInfraestruturasData($params)
{
$infraestruturas = collect();
$id = null;
if (!is_null($params['periodo']) && !is_null($params['unidade_id'])) {
$infraestruturas = DB::table('cadastro_infraestrutura as infraestrutura')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->where('infraestrutura.unidade_id', $params['unidade_id'])
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('cadastro_lotacao as lotacao')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_jornada as jornada')
->whereColumn('jornada.lotacao_id', 'lotacao.id')
->whereBetween('jornada.data', $params['periodo'])
)
->whereColumn('lotacao.infraestrutura_id', 'infraestrutura.id')
->whereNull('lotacao.deleted_at')
)
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->orderByRaw("COALESCE(infraestrutura.nome, unidade.nome_fantasia)")
->selectRaw("
infraestrutura.id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as nome
")
->get();
}
return ['form' => $infraestruturas, 'model' => $id];
}
private static function getStatusData($params)
{
$status = collect();
$ativo = null;
if (!is_null($params['periodo'])) {
$hasJornada = function ($ativo) use ($params) {
return DB::table('ambulatorio_jornada as jornada')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when($ativo,
fn ($q) => $q->whereNull('jornada.situacao_id'),
fn ($q) => $q->whereNotNull('jornada.situacao_id')
)
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->exists();
};
if ($hasJornada(true)) {
$status->push(self::getStatus(true));
}
if ($hasJornada(false)) {
$status->push(self::getStatus(false));
}
}
return ['form' => $status, 'model' => $ativo];
}
public static function getStatus($ativo)
{
if ($ativo === null) {
return null;
}
return collect([
(object) ['value' => true, 'text' => 'ATIVO'],
(object) ['value' => false, 'text' => 'INATIVO'],
])->where('value', $ativo)->first();
}
private static function getSituacoesData($params)
{
$situacoes = collect();
$id = null;
if (!is_null($params['periodo']) && $params['status'] === false) {
$situacoes = DB::table('ambulatorio_jornada_situacao as situacao')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_jornada as jornada')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('jornada.situacao_id', 'situacao.id')
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orderBy('situacao.nome')
->selectRaw("
situacao.id,
situacao.nome
")
->get();
}
return ['form' => $situacoes, 'model' => $id];
}
private static function getOcupacoesData($params)
{
$ocupacoes = collect();
$id = null;
if (!is_null($params['periodo'])) {
$ocupacoes = DB::table('sigtap.ocupacao as ocupacao')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('cadastro_lotacao as lotacao')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_jornada as jornada')
->whereColumn('jornada.lotacao_id', 'lotacao.id')
->whereBetween('jornada.data', $params['periodo'])
->when($params['status'], fn ($q) => $q->whereNull('jornada.situacao_id'))
->when($params['status'] === false, fn ($q) => $q->whereNotNull('jornada.situacao_id'))
->when($params['situacao_id'], fn ($q, $id) => $q->where('jornada.situacao_id', $id))
)
->whereColumn('lotacao.ocupacao_id', 'ocupacao.id')
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orderByRaw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome)")
->selectRaw("
ocupacao.id,
CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) as descricao
")
->get();
}
return ['form' => $ocupacoes, 'model' => $id];
}
private static function getEspecialidadesData($params)
{
$especialidades = collect();
$id = null;
if (!is_null($params['periodo']) && !is_null($params['ocupacao_id'])) {
$especialidades = DB::table('cadastro_especialidade as especialidade')
->where('especialidade.ocupacao_id', $params['ocupacao_id'])
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_jornada as jornada')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('jornada.especialidade_id', 'especialidade.id')
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when($params['status'], fn ($q) => $q->whereNull('jornada.situacao_id'))
->when($params['status'] === false, fn ($q) => $q->whereNotNull('jornada.situacao_id'))
->when($params['situacao_id'], fn ($q, $id) => $q->where('jornada.situacao_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('lotacao.ocupacao_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orderBy('especialidade.nome')
->selectRaw("
especialidade.id,
especialidade.nome
")
->get();
}
return ['form' => $especialidades, 'model' => $id];
}
private static function getUsuariosData($params)
{
$usuarios = collect();
$id = null;
if (!is_null($params['periodo'])) {
$usuarios = DB::table('cadastro_usuario as usuario')
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('cadastro_lotacao as lotacao')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('lotacao.ocupacao_id', $id))
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_jornada as jornada')
->whereColumn('jornada.lotacao_id', 'lotacao.id')
->whereBetween('jornada.data', $params['periodo'])
->when($params['status'], fn ($q) => $q->whereNull('jornada.situacao_id'))
->when($params['status'] === false, fn ($q) => $q->whereNotNull('jornada.situacao_id'))
->when($params['situacao_id'], fn ($q, $id) => $q->where('jornada.situacao_id', $id))
->when($params['especialidade_id'], fn ($q, $id) => $q->where('jornada.especialidade_id', $id))
)
->whereColumn('lotacao.usuario_id', 'usuario.id')
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->whereNull('usuario.deleted_at')
->whereNull('cidadao.deleted_at')
->orderBy('cidadao.nome')
->selectRaw("
usuario.id,
cidadao.nome
")
->get();
}
return ['form' => $usuarios, 'model' => $id];
}
}

View File

@@ -0,0 +1,376 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Ambulatorio\AgendamentoStatus;
use App\Services\Service;
use App\Utils\DataUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RelatorioPacienteAtendimentoService extends Service
{
public static function index()
{
$periodo = [
'start' => Carbon::createFromFormat('d/m/Y', request()->periodo['start'])->startOfDay(),
'end' => Carbon::createFromFormat('d/m/Y', request()->periodo['end'])->endOfDay(),
];
$agendamentos = DB::table('ambulatorio_agendamento as agendamento')
->join('cadastro_paciente as paciente', 'paciente.id', 'agendamento.paciente_id')
->join('cadastro_cidadao as paciente_cidadao', 'paciente_cidadao.id', 'paciente.cidadao_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->join('sigtap.ocupacao as ocupacao', 'ocupacao.id', 'lotacao.ocupacao_id')
->join('cadastro_usuario as usuario', 'usuario.id', 'lotacao.usuario_id')
->join('cadastro_cidadao as usuario_cidadao', 'usuario_cidadao.id', 'usuario.cidadao_id')
->join('cadastro_especialidade as especialidade', 'especialidade.id', 'jornada.especialidade_id')
->leftJoin('ambulatorio_jornada_situacao as situacao', 'situacao.id', 'jornada.situacao_id')
->where('agendamento.status_id', AgendamentoStatus::AGENDADO)
->whereBetween('jornada.data', $periodo)
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when(request()->ocupacao_id, fn ($q, $id) => $q->where('lotacao.ocupacao_id', $id))
->when(request()->especialidade_id, fn ($q, $id) => $q->where('jornada.especialidade_id', $id))
->when(request()->usuario_id, fn ($q, $id) => $q->where('lotacao.usuario_id', $id))
->selectRaw("
jornada.data,
paciente_cidadao.nome as paciente_nome,
LPAD(paciente.prontuario, 6, '0') as prontuario,
unidade.nome_fantasia as unidade_nome_fantasia,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura_nome,
ocupacao.codigo as ocupacao_codigo,
especialidade.nome as especialidade_nome,
usuario_cidadao.nome as usuario_nome
")
->get();
return compact('agendamentos');
}
public static function list()
{
$data = (object) [
'additionals' => [],
'form' => [],
'model' => [],
];
$params = self::getParams();
$sets = [
'periodo' => function () use ($data) {
$data->model['periodo'] = ['start' => null, 'end' => null];
},
'unidade' => function () use ($data, $params) {
$unidadesData = self::getUnidadesData($params);
$data->form['unidades'] = $unidadesData['form'];
$data->model['unidade_id'] = $unidadesData['model'];
},
'infraestrutura' => function () use ($data, $params) {
$infraestruturasData = self::getInfraestruturasData($params);
$data->form['infraestruturas'] = $infraestruturasData['form'];
$data->model['infraestrutura_id'] = $infraestruturasData['model'];
},
'ocupacao' => function () use ($data, $params) {
$ocupacoesData = self::getOcupacoesData($params);
$data->form['ocupacoes'] = $ocupacoesData['form'];
$data->model['ocupacao_id'] = $ocupacoesData['model'];
},
'especialidade' => function () use ($data, $params) {
$especialidadesData = self::getEspecialidadesData($params);
$data->form['especialidades'] = $especialidadesData['form'];
$data->model['especialidade_id'] = $especialidadesData['model'];
},
'usuario' => function () use ($data, $params) {
$usuariosData = self::getUsuariosData($params);
$data->form['usuarios'] = $usuariosData['form'];
$data->model['usuario_id'] = $usuariosData['model'];
},
];
$load = is_null(request()->load_from);
if ($load) {
$data->additionals = [];
}
foreach ($sets as $field => $set) {
if ($load) {
$set();
}
else if ($field === request()->load_from) {
$load = true;
}
}
foreach ($data as $property => $itens) {
if (empty($itens)) {
unset($data->{$property});
}
}
return $data;
}
private static function getParams()
{
$params = request()->only([
'periodo',
'unidade_id',
'infraestrutura_id',
'ocupacao_id',
'especialidade_id',
'usuario_id',
]);
if (isset($params['periodo'])
&& !is_null($params['periodo']['start'])
&& !is_null($params['periodo']['end'])
) {
$start = Carbon::createFromFormat('d/m/Y', $params['periodo']['start'])->startOfDay();
$end = Carbon::createFromFormat('d/m/Y', $params['periodo']['end'])->endOfDay();
$params['periodo']['start'] = $start;
$params['periodo']['end'] = $end;
}
else {
$params['periodo'] = null;
}
return $params;
}
private static function getUnidadesData($params)
{
$unidades = collect();
$id = null;
if (!is_null($params['periodo'])) {
$unidades = DB::table('cadastro_unidade as unidade')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('cadastro_infraestrutura as infraestrutura')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('cadastro_lotacao as lotacao')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_jornada as jornada')
->whereColumn('jornada.lotacao_id', 'lotacao.id')
->whereBetween('jornada.data', $params['periodo'])
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_agendamento as agendamento')
->whereColumn('agendamento.jornada_id', 'jornada.id')
->where('agendamento.status_id', AgendamentoStatus::AGENDADO)
)
)
->whereColumn('lotacao.infraestrutura_id', 'infraestrutura.id')
->whereNull('lotacao.deleted_at')
)
->whereColumn('infraestrutura.unidade_id', 'unidade.id')
->whereNull('infraestrutura.deleted_at')
)
->whereNull('unidade.deleted_at')
->orderBy('unidade.nome_fantasia')
->selectRaw("
unidade.id,
unidade.nome_fantasia
")
->get();
}
return ['form' => $unidades, 'model' => $id];
}
private static function getInfraestruturasData($params)
{
$infraestruturas = collect();
$id = null;
if (!is_null($params['periodo']) && !is_null($params['unidade_id'])) {
$infraestruturas = DB::table('cadastro_infraestrutura as infraestrutura')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->where('infraestrutura.unidade_id', $params['unidade_id'])
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('cadastro_lotacao as lotacao')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_jornada as jornada')
->whereColumn('jornada.lotacao_id', 'lotacao.id')
->whereBetween('jornada.data', $params['periodo'])
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_agendamento as agendamento')
->whereColumn('agendamento.jornada_id', 'jornada.id')
->where('agendamento.status_id', AgendamentoStatus::AGENDADO)
)
)
->whereColumn('lotacao.infraestrutura_id', 'infraestrutura.id')
->whereNull('lotacao.deleted_at')
)
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->orderByRaw("COALESCE(infraestrutura.nome, unidade.nome_fantasia)")
->selectRaw("
infraestrutura.id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as nome
")
->get();
}
return ['form' => $infraestruturas, 'model' => $id];
}
private static function getOcupacoesData($params)
{
$ocupacoes = collect();
$id = null;
if (!is_null($params['periodo'])) {
$ocupacoes = DB::table('sigtap.ocupacao as ocupacao')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('cadastro_lotacao as lotacao')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_jornada as jornada')
->whereColumn('jornada.lotacao_id', 'lotacao.id')
->whereBetween('jornada.data', $params['periodo'])
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_agendamento as agendamento')
->whereColumn('agendamento.jornada_id', 'jornada.id')
->where('agendamento.status_id', AgendamentoStatus::AGENDADO)
)
)
->whereColumn('lotacao.ocupacao_id', 'ocupacao.id')
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orderByRaw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome)")
->selectRaw("
ocupacao.id,
CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) as descricao
")
->get();
}
return ['form' => $ocupacoes, 'model' => $id];
}
private static function getEspecialidadesData($params)
{
$especialidades = collect();
$id = null;
if (!is_null($params['periodo']) && !is_null($params['ocupacao_id'])) {
$especialidades = DB::table('cadastro_especialidade as especialidade')
->where('especialidade.ocupacao_id', $params['ocupacao_id'])
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_jornada as jornada')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('jornada.especialidade_id', 'especialidade.id')
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('lotacao.ocupacao_id', $id))
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_agendamento as agendamento')
->whereColumn('agendamento.jornada_id', 'jornada.id')
->where('agendamento.status_id', AgendamentoStatus::AGENDADO)
)
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orderBy('especialidade.nome')
->selectRaw("
especialidade.id,
especialidade.nome
")
->get();
}
return ['form' => $especialidades, 'model' => $id];
}
private static function getUsuariosData($params)
{
$usuarios = collect();
$id = null;
if (!is_null($params['periodo'])) {
$usuarios = DB::table('cadastro_usuario as usuario')
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('cadastro_lotacao as lotacao')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('lotacao.ocupacao_id', $id))
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_jornada as jornada')
->whereColumn('jornada.lotacao_id', 'lotacao.id')
->whereBetween('jornada.data', $params['periodo'])
->when($params['especialidade_id'], fn ($q, $id) => $q->where('jornada.especialidade_id', $id))
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_agendamento as agendamento')
->whereColumn('agendamento.jornada_id', 'jornada.id')
->where('agendamento.status_id', AgendamentoStatus::AGENDADO)
)
)
->whereColumn('lotacao.usuario_id', 'usuario.id')
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->whereNull('usuario.deleted_at')
->whereNull('cidadao.deleted_at')
->orderBy('cidadao.nome')
->selectRaw("
usuario.id,
cidadao.nome
")
->get();
}
return ['form' => $usuarios, 'model' => $id];
}
}

View File

@@ -0,0 +1,813 @@
<?php
namespace App\Services\Ambulatorio;
use App\Services\Service;
use App\Utils\MaskUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RelatorioProcedimentoLancadoPeriodoService extends Service
{
public static function index()
{
$totalizadores = (object) [
'quantidade_atendimentos' => [],
'quantidade_procedimentos' => 0,
];
$periodo = [
'start' => Carbon::createFromFormat('d/m/Y', request()->periodo['start'])->startOfDay(),
'end' => Carbon::createFromFormat('d/m/Y', request()->periodo['end'])->endOfDay(),
];
$procedimentos = collect();
DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->join('cadastro_usuario as usuario', 'usuario.id', 'atendimento_procedimento.usuario_id')
->join('cadastro_cidadao as usuario_cidadao', 'usuario_cidadao.id', 'usuario.cidadao_id')
->join('sigtap.ocupacao as ocupacao', 'ocupacao.id', 'atendimento_procedimento.ocupacao_id')
->leftJoin('cadastro_especialidade as especialidade', 'especialidade.id', 'atendimento_procedimento.especialidade_id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereBetween('jornada.data', $periodo)
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when(request()->usuario_id, fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->when(request()->ocupacao_id, fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when(request()->especialidade_id, fn ($q, $id) => $q->where('atendimento_procedimento.especialidade_id', $id))
->when(request()->procedimento_codigo, fn ($q, $codigo) => $q->where('procedimento.codigo', $codigo))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->whereNull('usuario.deleted_at')
->whereNull('usuario_cidadao.deleted_at')
->selectRaw("
atendimento_procedimento.atendimento_id,
atendimento_procedimento.pre_atendimento_id,
unidade.nome_fantasia as unidade_nome_fantasia,
infraestrutura.id as infraestrutura_id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura_nome,
usuario.id as usuario_id,
usuario_cidadao.nome as usuario_nome,
ocupacao.codigo as ocupacao_codigo,
especialidade.id as especialidade_id,
especialidade.nome as especialidade_nome,
procedimento.codigo as procedimento_codigo,
procedimento.nome as procedimento_nome,
atendimento_procedimento.quantidade
")
->unionAll(DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.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_usuario as usuario', 'usuario.id', 'atendimento_procedimento.usuario_id')
->join('cadastro_cidadao as usuario_cidadao', 'usuario_cidadao.id', 'usuario.cidadao_id')
->join('sigtap.ocupacao as ocupacao', 'ocupacao.id', 'atendimento_procedimento.ocupacao_id')
->leftJoin('cadastro_especialidade as especialidade', 'especialidade.id', 'atendimento_procedimento.especialidade_id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereBetween('demanda_espontanea.data', $periodo)
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->when(request()->usuario_id, fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->when(request()->ocupacao_id, fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when(request()->especialidade_id, fn ($q, $id) => $q->where('atendimento_procedimento.especialidade_id', $id))
->when(request()->procedimento_codigo, fn ($q, $codigo) => $q->where('procedimento.codigo', $codigo))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->whereNull('usuario.deleted_at')
->whereNull('usuario_cidadao.deleted_at')
->selectRaw("
atendimento_procedimento.atendimento_id,
atendimento_procedimento.pre_atendimento_id,
unidade.nome_fantasia as unidade_nome_fantasia,
infraestrutura.id as infraestrutura_id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura_nome,
usuario.id as usuario_id,
usuario_cidadao.nome as usuario_nome,
ocupacao.codigo as ocupacao_codigo,
especialidade.id as especialidade_id,
especialidade.nome as especialidade_nome,
procedimento.codigo as procedimento_codigo,
procedimento.nome as procedimento_nome,
atendimento_procedimento.quantidade
")
)
->get()
->each(function ($item) use ($procedimentos, $totalizadores) {
$infraestrutura = $procedimentos->where('infraestrutura_id', $item->infraestrutura_id)->first();
if (is_null($infraestrutura)) {
$infraestrutura = (object) [
'infraestrutura_id' => $item->infraestrutura_id,
'infraestrutura_nome' => $item->infraestrutura_nome,
'unidade_nome_fantasia' => $item->unidade_nome_fantasia,
'usuarios' => collect(),
'quantidade_atendimentos' => [],
'quantidade_procedimentos' => 0,
];
$procedimentos->push($infraestrutura);
}
if (is_null($item->pre_atendimento_id)) {
$infraestrutura->quantidade_atendimentos["atendimento_{$item->atendimento_id}"] = 1;
}
else {
$infraestrutura->quantidade_atendimentos["pre_atendimento_{$item->pre_atendimento_id}"] = 1;
}
$infraestrutura->quantidade_procedimentos += $item->quantidade;
$usuario = $infraestrutura->usuarios->where('usuario_id', $item->usuario_id)->first();
if (is_null($usuario)) {
$usuario = (object) [
'usuario_id' => $item->usuario_id,
'usuario_nome' => $item->usuario_nome,
'procedimentos' => collect(),
'quantidade_atendimentos' => [],
'quantidade_procedimentos' => 0,
];
$infraestrutura->usuarios->push($usuario);
}
if (is_null($item->pre_atendimento_id)) {
$usuario->quantidade_atendimentos["atendimento_{$item->atendimento_id}"] = 1;
}
else {
$usuario->quantidade_atendimentos["pre_atendimento_{$item->pre_atendimento_id}"] = 1;
}
$usuario->quantidade_procedimentos += $item->quantidade;
$procedimento = $usuario->procedimentos
->where('especialidade_id', $item->especialidade_id)
->where('procedimento_codigo', $item->procedimento_codigo)
->first();
if (is_null($procedimento)) {
$procedimento = (object) [
'especialidade_id' => $item->especialidade_id,
'especialidade_nome' => $item->especialidade_nome,
'ocupacao_codigo' => $item->ocupacao_codigo,
'procedimento_codigo' => $item->procedimento_codigo,
'procedimento_descricao' => MaskUtil::getProcedimentoMasked($item->procedimento_codigo)
. " - {$item->procedimento_nome}",
'quantidade' => 0,
];
$usuario->procedimentos->push($procedimento);
}
$procedimento->quantidade += $item->quantidade;
if (is_null($item->pre_atendimento_id)) {
$totalizadores->quantidade_atendimentos["atendimento_{$item->atendimento_id}"] = 1;
}
else {
$totalizadores->quantidade_atendimentos["pre_atendimento_{$item->pre_atendimento_id}"] = 1;
}
$totalizadores->quantidade_procedimentos += $item->quantidade;
});
$procedimentos->each(function ($procedimento) {
$procedimento->quantidade_atendimentos = collect($procedimento->quantidade_atendimentos)->sum();
$procedimento->usuarios->each(function ($usuario) {
$usuario->quantidade_atendimentos = collect($usuario->quantidade_atendimentos)->sum();
});
});
$totalizadores->quantidade_atendimentos = collect($totalizadores->quantidade_atendimentos)->sum();
return compact('procedimentos', 'totalizadores');
}
public static function list()
{
$data = (object) [
'additionals' => [],
'form' => [],
'model' => [],
];
$params = self::getParams();
$sets = [
'periodo' => function () use ($data) {
$data->model['periodo'] = ['start' => null, 'end' => null];
},
'unidade' => function () use ($data, $params) {
$unidadesData = self::getUnidadesData($params);
$data->form['unidades'] = $unidadesData['form'];
$data->model['unidade_id'] = $unidadesData['model'];
},
'infraestrutura' => function () use ($data, $params) {
$infraestruturasData = self::getInfraestruturasData($params);
$data->form['infraestruturas'] = $infraestruturasData['form'];
$data->model['infraestrutura_id'] = $infraestruturasData['model'];
},
'usuario' => function () use ($data, $params) {
$usuariosData = self::getUsuariosData($params);
$data->form['usuarios'] = $usuariosData['form'];
$data->model['usuario_id'] = $usuariosData['model'];
},
'ocupacao' => function () use ($data, $params) {
$ocupacoesData = self::getOcupacoesData($params);
$data->form['ocupacoes'] = $ocupacoesData['form'];
$data->model['ocupacao_id'] = $ocupacoesData['model'];
},
'especialidade' => function () use ($data, $params) {
$especialidadesData = self::getEspecialidadesData($params);
$data->form['especialidades'] = $especialidadesData['form'];
$data->model['especialidade_id'] = $especialidadesData['model'];
},
'procedimento' => function () use ($data, $params) {
$procedimentosData = self::getProcedimentosData($params);
$data->form['procedimentos'] = $procedimentosData['form'];
$data->model['procedimento_codigo'] = $procedimentosData['model'];
},
];
$load = is_null(request()->load_from);
if ($load) {
$data->additionals = [
'data_atual' => Carbon::today()->format('d/m/Y')
];
}
foreach ($sets as $field => $set) {
if ($load) {
$set();
}
else if ($field === request()->load_from) {
$load = true;
}
}
foreach ($data as $property => $itens) {
if (empty($itens)) {
unset($data->{$property});
}
}
return $data;
}
private static function getParams()
{
$params = request()->only([
'periodo',
'unidade_id',
'infraestrutura_id',
'ocupacao_id',
'especialidade_id',
'usuario_id',
'procedimento_codigo',
]);
if (isset($params['periodo'])
&& !is_null($params['periodo']['start'])
&& !is_null($params['periodo']['end'])
) {
$start = Carbon::createFromFormat('d/m/Y', $params['periodo']['start'])->startOfDay();
$end = Carbon::createFromFormat('d/m/Y', $params['periodo']['end'])->endOfDay();
$params['periodo']['start'] = $start;
$params['periodo']['end'] = $end;
}
else {
$params['periodo'] = null;
}
return $params;
}
private static function getUnidadesData($params)
{
$unidades = collect();
$id = null;
if (!is_null($params['periodo'])) {
$unidades = DB::table('cadastro_unidade as unidade')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('cadastro_infraestrutura as infraestrutura')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->whereColumn('lotacao.infraestrutura_id', 'infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereBetween('jornada.data', $params['periodo'])
->whereNull('lotacao.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->whereColumn('centro_custo.infraestrutura_id', 'infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereBetween('demanda_espontanea.data', $params['periodo'])
->whereNull('centro_custo.deleted_at')
)
)
->whereColumn('infraestrutura.unidade_id', 'unidade.id')
->whereNull('infraestrutura.deleted_at')
)
->whereNull('unidade.deleted_at')
->orderBy('unidade.nome_fantasia')
->selectRaw("
unidade.id,
unidade.nome_fantasia
")
->get();
}
return ['form' => $unidades, 'model' => $id];
}
private static function getInfraestruturasData($params)
{
$infraestruturas = collect();
$id = null;
if (!is_null($params['periodo']) && !is_null($params['unidade_id'])) {
$infraestruturas = DB::table('cadastro_infraestrutura as infraestrutura')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->where('infraestrutura.unidade_id', $params['unidade_id'])
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->whereColumn('lotacao.infraestrutura_id', 'infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereBetween('jornada.data', $params['periodo'])
->whereNull('lotacao.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->whereColumn('centro_custo.infraestrutura_id', 'infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereBetween('demanda_espontanea.data', $params['periodo'])
->whereNull('centro_custo.deleted_at')
)
)
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->orderByRaw("COALESCE(infraestrutura.nome, unidade.nome_fantasia)")
->selectRaw("
infraestrutura.id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as nome
")
->get();
}
return ['form' => $infraestruturas, 'model' => $id];
}
private static function getUsuariosData($params)
{
$usuarios = collect();
$id = null;
if (!is_null($params['periodo'])) {
$usuarios = DB::table('cadastro_usuario as usuario')
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('atendimento_procedimento.usuario_id', 'usuario.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->whereColumn('atendimento_procedimento.usuario_id', 'usuario.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereBetween('demanda_espontanea.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
)
->whereNull('usuario.deleted_at')
->whereNull('cidadao.deleted_at')
->orderBy('cidadao.nome')
->selectRaw("
usuario.id,
cidadao.nome
")
->get();
}
return ['form' => $usuarios, 'model' => $id];
}
private static function getOcupacoesData($params)
{
$ocupacoes = collect();
$id = null;
if (!is_null($params['periodo'])) {
$ocupacoes = DB::table('sigtap.ocupacao as ocupacao')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('atendimento_procedimento.ocupacao_id', 'ocupacao.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when($params['usuario_id'], fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->whereColumn('atendimento_procedimento.ocupacao_id', 'ocupacao.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereBetween('demanda_espontanea.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->when($params['usuario_id'], fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
)
->orderByRaw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome)")
->selectRaw("
ocupacao.id,
CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) as descricao
")
->get();
}
return ['form' => $ocupacoes, 'model' => $id];
}
private static function getEspecialidadesData($params)
{
$especialidades = collect();
$id = null;
if (!is_null($params['periodo']) && !is_null($params['ocupacao_id'])) {
$especialidades = DB::table('cadastro_especialidade as especialidade')
->where('especialidade.ocupacao_id', $params['ocupacao_id'])
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('atendimento_procedimento.especialidade_id', 'especialidade.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when($params['usuario_id'], fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->whereColumn('atendimento_procedimento.especialidade_id', 'especialidade.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereBetween('demanda_espontanea.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->when($params['usuario_id'], fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
)
->orderBy('especialidade.nome')
->selectRaw("
especialidade.id,
especialidade.nome
")
->get();
}
return ['form' => $especialidades, 'model' => $id];
}
private static function getProcedimentosData($params)
{
$procedimentos = collect();
$codigo = null;
if (!is_null($params['periodo'])) {
$procedimentos = DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_agendamento as agendamento')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('agendamento.id', 'atendimento.agendamento_id')
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_demanda_espontanea as demanda_espontanea')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->whereColumn('demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
)
->when($params['usuario_id'], fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when($params['especialidade_id'], fn ($q, $id) => $q->where('atendimento_procedimento.especialidade_id', $id))
->orderByRaw("CONCAT(procedimento.codigo, ' - ', procedimento.nome)")
->selectRaw("
procedimento.codigo,
procedimento.nome
")
->distinct()
->get();
$procedimentos->each(function ($procedimento) {
$procedimento->descricao = MaskUtil::getProcedimentoMasked($procedimento->codigo)
. " - {$procedimento->nome}";
unset($procedimento->nome);
});
}
return ['form' => $procedimentos, 'model' => $codigo];
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,439 @@
<?php
namespace App\Services\Ambulatorio;
use App\Services\Service;
use App\Utils\MaskUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RelatorioProducaoAmbulatorialService extends Service
{
public static function index()
{
$totalizadores = (object) [
'quantidade' => 0,
];
$periodo = [
'start' => Carbon::createFromFormat('d/m/Y', request()->periodo['start'])->startOfDay(),
'end' => Carbon::createFromFormat('d/m/Y', request()->periodo['end'])->endOfDay(),
];
$procedimentos = DB::query()
->fromSub(DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('cadastro_paciente as paciente', 'paciente.id', 'agendamento.paciente_id')
->join('cadastro_cidadao as paciente_cidadao', 'paciente_cidadao.id', 'paciente.cidadao_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->join('sigtap.ocupacao as ocupacao', 'ocupacao.id', 'atendimento_procedimento.ocupacao_id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('jornada.data', $periodo)
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when(request()->ocupacao_id, fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when(request()->procedimento_codigo, fn ($q, $codigo) => $q->where('procedimento.codigo', $codigo))
->when(request()->idade_de, fn ($q, $idadeDe) => $q
->whereRaw("TIMESTAMPDIFF(YEAR, paciente_cidadao.data_nascimento, NOW()) >= {$idadeDe}")
)
->when(request()->idade_ate, fn ($q, $idadeAte) => $q
->whereRaw("TIMESTAMPDIFF(YEAR, paciente_cidadao.data_nascimento, NOW()) <= {$idadeAte}")
)
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->selectRaw("
procedimento.codigo as procedimento_codigo,
ocupacao.codigo as ocupacao_codigo,
TIMESTAMPDIFF(YEAR, paciente_cidadao.data_nascimento, NOW()) AS idade,
SUM(atendimento_procedimento.quantidade) as quantidade
")
->groupByRaw("
procedimento.codigo,
ocupacao.codigo,
TIMESTAMPDIFF(YEAR, paciente_cidadao.data_nascimento, NOW())
")
->unionAll(DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_paciente as paciente', 'paciente.id', 'demanda_espontanea.paciente_id')
->join('cadastro_cidadao as paciente_cidadao', 'paciente_cidadao.id', 'paciente.cidadao_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->join('sigtap.ocupacao as ocupacao', 'ocupacao.id', 'atendimento_procedimento.ocupacao_id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $periodo)
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->when(request()->ocupacao_id, fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when(request()->procedimento_codigo, fn ($q, $codigo) => $q->where('procedimento.codigo', $codigo))
->when(request()->idade_de, fn ($q, $idadeDe) => $q
->whereRaw("TIMESTAMPDIFF(YEAR, paciente_cidadao.data_nascimento, NOW()) >= {$idadeDe}")
)
->when(request()->idade_ate, fn ($q, $idadeAte) => $q
->whereRaw("TIMESTAMPDIFF(YEAR, paciente_cidadao.data_nascimento, NOW()) <= {$idadeAte}")
)
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
->selectRaw("
procedimento.codigo as procedimento_codigo,
ocupacao.codigo as ocupacao_codigo,
TIMESTAMPDIFF(YEAR, paciente_cidadao.data_nascimento, NOW()) AS idade,
SUM(atendimento_procedimento.quantidade) as quantidade
")
->groupByRaw("
procedimento.codigo,
ocupacao.codigo,
TIMESTAMPDIFF(YEAR, paciente_cidadao.data_nascimento, NOW())
")
)
, 'sub')
->groupByRaw("
sub.procedimento_codigo,
sub.ocupacao_codigo,
sub.idade
")
->selectRaw("
sub.procedimento_codigo,
sub.ocupacao_codigo,
sub.idade,
SUM(sub.quantidade) as quantidade
")
->get();
$procedimentos->each(function ($procedimento) use ($totalizadores) {
$procedimento->procedimento_codigo = MaskUtil::getProcedimentoMasked($procedimento->procedimento_codigo);
$totalizadores->quantidade += $procedimento->quantidade;
});
return compact('procedimentos', 'totalizadores');
}
public static function list()
{
$data = (object) [
'additionals' => [],
'form' => [],
'model' => [],
];
$params = self::getParams();
$sets = [
'periodo' => function () use ($data) {
$data->model['periodo'] = ['start' => null, 'end' => null];
},
'unidade' => function () use ($data, $params) {
$unidadesData = self::getUnidadesData($params);
$data->form['unidades'] = $unidadesData['form'];
$data->model['unidade_id'] = $unidadesData['model'];
},
'infraestrutura' => function () use ($data, $params) {
$infraestruturasData = self::getInfraestruturasData($params);
$data->form['infraestruturas'] = $infraestruturasData['form'];
$data->model['infraestrutura_id'] = $infraestruturasData['model'];
},
'ocupacao' => function () use ($data, $params) {
$ocupacoesData = self::getOcupacoesData($params);
$data->form['ocupacoes'] = $ocupacoesData['form'];
$data->model['ocupacao_id'] = $ocupacoesData['model'];
},
'procedimento' => function () use ($data, $params) {
$procedimentosData = self::getProcedimentosData($params);
$data->form['procedimentos'] = $procedimentosData['form'];
$data->model['procedimento_codigo'] = $procedimentosData['model'];
},
];
$load = is_null(request()->load_from);
if ($load) {
$data->additionals = [
'data_atual' => Carbon::today()->format('d/m/Y')
];
$data->model['idade_de'] = null;
$data->model['idade_ate'] = null;
}
foreach ($sets as $field => $set) {
if ($load) {
$set();
}
else if ($field === request()->load_from) {
$load = true;
}
}
foreach ($data as $property => $itens) {
if (empty($itens)) {
unset($data->{$property});
}
}
return $data;
}
private static function getParams()
{
$params = request()->only([
'periodo',
'unidade_id',
'infraestrutura_id',
'ocupacao_id',
'procedimento_codigo',
]);
if (isset($params['periodo'])
&& !is_null($params['periodo']['start'])
&& !is_null($params['periodo']['end'])
) {
$start = Carbon::createFromFormat('d/m/Y', $params['periodo']['start'])->startOfDay();
$end = Carbon::createFromFormat('d/m/Y', $params['periodo']['end'])->endOfDay();
$params['periodo']['start'] = $start;
$params['periodo']['end'] = $end;
}
else {
$params['periodo'] = null;
}
return $params;
}
private static function getUnidadesData($params)
{
$unidades = collect();
$id = null;
if (!is_null($params['periodo'])) {
$unidades = DB::table('cadastro_unidade as unidade')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('cadastro_infraestrutura as infraestrutura')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->whereColumn('lotacao.infraestrutura_id', 'infraestrutura.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('jornada.data', $params['periodo'])
->whereNull('lotacao.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->whereColumn('centro_custo.infraestrutura_id', 'infraestrutura.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->whereNull('centro_custo.deleted_at')
)
)
->whereColumn('infraestrutura.unidade_id', 'unidade.id')
->whereNull('infraestrutura.deleted_at')
)
->whereNull('unidade.deleted_at')
->orderBy('unidade.nome_fantasia')
->selectRaw("
unidade.id,
unidade.nome_fantasia
")
->get();
}
return ['form' => $unidades, 'model' => $id];
}
private static function getInfraestruturasData($params)
{
$infraestruturas = collect();
$id = null;
if (!is_null($params['periodo']) && !is_null($params['unidade_id'])) {
$infraestruturas = DB::table('cadastro_infraestrutura as infraestrutura')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->where('infraestrutura.unidade_id', $params['unidade_id'])
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->whereColumn('lotacao.infraestrutura_id', 'infraestrutura.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('jornada.data', $params['periodo'])
->whereNull('lotacao.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->whereColumn('centro_custo.infraestrutura_id', 'infraestrutura.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->whereNull('centro_custo.deleted_at')
)
)
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->orderByRaw("COALESCE(infraestrutura.nome, unidade.nome_fantasia)")
->selectRaw("
infraestrutura.id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as nome
")
->get();
}
return ['form' => $infraestruturas, 'model' => $id];
}
private static function getOcupacoesData($params)
{
$ocupacoes = collect();
$id = null;
if (!is_null($params['periodo'])) {
$ocupacoes = DB::table('sigtap.ocupacao as ocupacao')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('atendimento_procedimento.ocupacao_id', 'ocupacao.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->whereColumn('atendimento_procedimento.ocupacao_id', 'ocupacao.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
)
->orderByRaw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome)")
->selectRaw("
ocupacao.id,
CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) as descricao
")
->get();
}
return ['form' => $ocupacoes, 'model' => $id];
}
private static function getProcedimentosData($params)
{
$procedimentos = collect();
$codigo = null;
if (!is_null($params['periodo'])) {
$procedimentos = DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNotNull('atendimento.finalizado_em')
->orderByRaw("CONCAT(procedimento.codigo, ' - ', procedimento.nome)")
->selectRaw("
procedimento.codigo,
procedimento.nome
")
->distinct()
->union(
DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNotNull('atendimento.finalizado_em')
->orderByRaw("CONCAT(procedimento.codigo, ' - ', procedimento.nome)")
->selectRaw("
procedimento.codigo,
procedimento.nome
")
->distinct()
)
->get();
$procedimentos->each(function ($procedimento) {
$procedimento->descricao = MaskUtil::getProcedimentoMasked($procedimento->codigo)
. " - {$procedimento->nome}";
unset($procedimento->nome);
});
}
return ['form' => $procedimentos, 'model' => $codigo];
}
}

View File

@@ -0,0 +1,639 @@
<?php
namespace App\Services\Ambulatorio;
use App\Services\Service;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use App\Enums\Ambulatorio\AgendamentoStatus;
class RelatorioQuantitativoAtendimentoService extends Service
{
public static function index()
{
$totalizadores = (object) [
'quantidade' => 0,
];
self::setDays($totalizadores);
$periodo = [
'start' => Carbon::create(request()->periodo['ano'], request()->periodo['mes'])
->modify('first day of this month')
->startOfDay(),
'end' => Carbon::create(request()->periodo['ano'], request()->periodo['mes'])
->modify('last day of this month')
->endOfDay()
];
$infraestruturas = collect();
DB::query()
->fromSub(DB::table('ambulatorio_atendimento as atendimento')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->join('cadastro_usuario as usuario', 'usuario.id', 'lotacao.usuario_id')
->join('cadastro_cidadao as usuario_cidadao', 'usuario_cidadao.id', 'usuario.cidadao_id')
->whereNotNull('atendimento.finalizado_em')
->where('agendamento.status_id', AgendamentoStatus::REALIZADO)
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.atendimento_id', 'atendimento.id')
)
->whereBetween('jornada.data', $periodo)
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when(request()->ocupacao_id, fn ($q, $id) => $q->where('lotacao.ocupacao_id', $id))
->when(request()->especialidade_id, fn ($q, $id) => $q->where('jornada.especialidade_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->whereNull('usuario.deleted_at')
->whereNull('usuario_cidadao.deleted_at')
->selectRaw("
atendimento.id as id,
LPAD(EXTRACT(DAY FROM jornada.data), 2, '0') as dia,
unidade.nome_fantasia as unidade_nome_fantasia,
infraestrutura.id as infraestrutura_id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura_nome,
usuario.id as usuario_id,
usuario_cidadao.nome as usuario_nome
")
->unionAll(DB::table('ambulatorio_atendimento as atendimento')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.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_usuario as usuario', 'usuario.id', 'demanda_espontanea.usuario_id')
->join('cadastro_cidadao as usuario_cidadao', 'usuario_cidadao.id', 'usuario.cidadao_id')
->join('cadastro_lotacao as lotacao', function ($join) {
$join->on('lotacao.usuario_id', '=', 'usuario.id')
->on('lotacao.infraestrutura_id', '=', 'infraestrutura.id');
})
->whereNotNull('atendimento.finalizado_em')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.atendimento_id', 'atendimento.id')
)
->whereBetween('demanda_espontanea.data', $periodo)
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->when(request()->ocupacao_id, fn ($q, $id) => $q->where('demanda_espontanea.ocupacao_id', $id))
->when(request()->especialidade_id, fn ($q, $id) => $q->where('demanda_espontanea.especialidade_id', $id))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->whereNull('usuario.deleted_at')
->whereNull('usuario_cidadao.deleted_at')
->selectRaw("
atendimento.id as id,
LPAD(EXTRACT(DAY FROM demanda_espontanea.data), 2, '0') as dia,
unidade.nome_fantasia as unidade_nome_fantasia,
infraestrutura.id as infraestrutura_id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura_nome,
usuario.id as usuario_id,
usuario_cidadao.nome as usuario_nome
")
->distinct()
)
->when(is_null(request()->especialidade_id), fn ($q) => $q
->unionAll(DB::table('ambulatorio_atendimento_pre_atendimento as pre_atendimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'pre_atendimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'pre_atendimento.created_lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->join('cadastro_usuario as usuario', 'usuario.id', 'lotacao.usuario_id')
->join('cadastro_cidadao as usuario_cidadao', 'usuario_cidadao.id', 'usuario.cidadao_id')
->whereNotNull('atendimento.finalizado_em')
->where('agendamento.status_id', AgendamentoStatus::REALIZADO)
->whereBetween('jornada.data', $periodo)
->where('usuario.id', 'lotacao.usuario_id')
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when(request()->ocupacao_id, fn ($q, $id) => $q->where('lotacao.ocupacao_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->whereNull('usuario.deleted_at')
->whereNull('usuario_cidadao.deleted_at')
->selectRaw("
atendimento.id as id,
LPAD(EXTRACT(DAY FROM jornada.data), 2, '0') as dia,
unidade.nome_fantasia as unidade_nome_fantasia,
infraestrutura.id as infraestrutura_id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura_nome,
usuario.id as usuario_id,
usuario_cidadao.nome as usuario_nome
")
)
->unionAll(DB::table('ambulatorio_atendimento_pre_atendimento as pre_atendimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'pre_atendimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'pre_atendimento.created_lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->join('cadastro_usuario as usuario', 'usuario.id', 'lotacao.usuario_id')
->join('cadastro_cidadao as usuario_cidadao', 'usuario_cidadao.id', 'usuario.cidadao_id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $periodo)
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when(request()->ocupacao_id, fn ($q, $id) => $q->where('lotacao.ocupacao_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->whereNull('usuario.deleted_at')
->whereNull('usuario_cidadao.deleted_at')
->selectRaw("
atendimento.id as id,
LPAD(EXTRACT(DAY FROM demanda_espontanea.data), 2, '0') as dia,
unidade.nome_fantasia as unidade_nome_fantasia,
infraestrutura.id as infraestrutura_id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura_nome,
usuario.id as usuario_id,
usuario_cidadao.nome as usuario_nome
")
)
)
, 'sub')
->groupByRaw("
sub.dia,
sub.unidade_nome_fantasia,
sub.infraestrutura_id,
sub.infraestrutura_nome,
sub.usuario_id,
sub.usuario_nome
")
->selectRaw("
sub.dia,
sub.unidade_nome_fantasia,
sub.infraestrutura_id,
sub.infraestrutura_nome,
sub.usuario_id,
sub.usuario_nome,
COUNT(*) as quantidade
")
->get()
->each(function ($item) use ($infraestruturas, $totalizadores) {
$infraestrutura = $infraestruturas->where('infraestrutura_id', $item->infraestrutura_id)->first();
if (is_null($infraestrutura)) {
$infraestrutura = (object) [
'infraestrutura_id' => $item->infraestrutura_id,
'infraestrutura_nome' => $item->infraestrutura_nome,
'unidade_nome_fantasia' => $item->unidade_nome_fantasia,
'usuarios' => collect(),
'quantidade' => 0,
];
self::setDays($infraestrutura);
$infraestruturas->push($infraestrutura);
}
$infraestrutura->{"quantidade{$item->dia}"} += $item->quantidade;
$infraestrutura->quantidade += $item->quantidade;
$usuario = $infraestrutura->usuarios->where('usuario_id', $item->usuario_id)->first();
if (is_null($usuario)) {
$usuario = (object) [
'usuario_id' => $item->usuario_id,
'usuario_nome' => $item->usuario_nome,
'quantidade' => 0,
];
self::setDays($usuario);
$infraestrutura->usuarios->push($usuario);
}
$usuario->{"quantidade{$item->dia}"} = $item->quantidade;
$usuario->quantidade += $item->quantidade;
$totalizadores->{"quantidade{$item->dia}"} += $item->quantidade;
$totalizadores->quantidade += $item->quantidade;
});
return self::setZeroToHypen(compact('infraestruturas', 'totalizadores'));
}
private static function setDays($data)
{
$date = Carbon::create(request()->periodo['ano'], request()->periodo['mes']);
$month = $date->month;
$lastDay = $date->modify('last day of this month')->day;
$date->modify('first day of this month');
while ($date->month === $month && $date->day <= $lastDay) {
$currentDay = Str::padLeft($date->day, 2, '0');
$data->{"quantidade{$currentDay}"} = 0;
$date->addDay();
}
}
private static function setZeroToHypen($data)
{
$setEmpty = function ($item) {
for ($i = 1; $i <= 31; $i++) {
$key = 'quantidade' . Str::padLeft($i, 2, '0');
if (isset($item->{$key}) && $item->{$key} === 0) {
$item->{$key} = '-';
}
}
};
foreach ($data['infraestruturas'] as $infraestrutura) {
$setEmpty($infraestrutura);
foreach ($infraestrutura->usuarios as $usuario) {
$setEmpty($usuario);
}
}
$setEmpty($data['totalizadores']);
return $data;
}
public static function list()
{
$data = (object) [
'additionals' => [],
'form' => [],
'model' => [],
];
$params = self::getParams();
$sets = [
'periodo' => function () use ($data) {
$data->form['meses'] = self::getMeses();
$data->model['periodo'] = ['ano' => null, 'mes' => null];
},
'unidade' => function () use ($data, $params) {
$unidadesData = self::getUnidadesData($params);
$data->form['unidades'] = $unidadesData['form'];
$data->model['unidade_id'] = $unidadesData['model'];
},
'infraestrutura' => function () use ($data, $params) {
$infraestruturasData = self::getInfraestruturasData($params);
$data->form['infraestruturas'] = $infraestruturasData['form'];
$data->model['infraestrutura_id'] = $infraestruturasData['model'];
},
'ocupacao' => function () use ($data, $params) {
$ocupacoesData = self::getOcupacoesData($params);
$data->form['ocupacoes'] = $ocupacoesData['form'];
$data->model['ocupacao_id'] = $ocupacoesData['model'];
},
'especialidade' => function () use ($data, $params) {
$especialidadesData = self::getEspecialidadesData($params);
$data->form['especialidades'] = $especialidadesData['form'];
$data->model['especialidade_id'] = $especialidadesData['model'];
},
];
$load = is_null(request()->load_from);
if ($load) {
$data->additionals = [
'data_atual' => Carbon::today()->format('d/m/Y')
];
}
foreach ($sets as $field => $set) {
if ($load) {
$set();
}
else if ($field === request()->load_from) {
$load = true;
}
}
foreach ($data as $property => $itens) {
if (empty($itens)) {
unset($data->{$property});
}
}
return $data;
}
private static function getParams()
{
$params = request()->only([
'periodo',
'unidade_id',
'infraestrutura_id',
'ocupacao_id',
'especialidade_id',
]);
if (isset($params['periodo'])
&& !is_null($params['periodo']['ano'])
&& !is_null($params['periodo']['mes'])
) {
$start = Carbon::create($params['periodo']['ano'], $params['periodo']['mes'])
->modify('first day of this month')
->startOfDay();
$end = Carbon::create($params['periodo']['ano'], $params['periodo']['mes'])
->modify('last day of this month')
->endOfDay();
$params['periodo'] = ['start' => $start, 'end' => $end];
}
else {
$params['periodo'] = null;
}
return $params;
}
public static function getMeses()
{
return collect([
['value' => 1, 'text' => 'JANEIRO'],
['value' => 2, 'text' => 'FEVEREIRO'],
['value' => 3, 'text' => 'MARÇO'],
['value' => 4, 'text' => 'ABRIL'],
['value' => 5, 'text' => 'MAIO'],
['value' => 6, 'text' => 'JUNHO'],
['value' => 7, 'text' => 'JULHO'],
['value' => 8, 'text' => 'AGOSTO'],
['value' => 9, 'text' => 'SETEMBRO'],
['value' => 10, 'text' => 'OUTUBRO'],
['value' => 11, 'text' => 'NOVEMBRO'],
['value' => 12, 'text' => 'DEZEMBRO'],
]);
}
private static function getUnidadesData($params)
{
$unidades = collect();
$id = null;
if (!is_null($params['periodo'])) {
$unidades = DB::table('cadastro_unidade as unidade')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('cadastro_infraestrutura as infraestrutura')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento as atendimento')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->whereColumn('lotacao.infraestrutura_id', 'infraestrutura.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('jornada.data', $params['periodo'])
->whereNull('lotacao.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento as atendimento')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->whereColumn('centro_custo.infraestrutura_id', 'infraestrutura.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->whereNull('centro_custo.deleted_at')
)
)
->whereColumn('infraestrutura.unidade_id', 'unidade.id')
->whereNull('infraestrutura.deleted_at')
)
->whereNull('unidade.deleted_at')
->orderBy('unidade.nome_fantasia')
->selectRaw("
unidade.id,
unidade.nome_fantasia
")
->get();
}
return ['form' => $unidades, 'model' => $id];
}
private static function getInfraestruturasData($params)
{
$infraestruturas = collect();
$id = null;
if (!is_null($params['periodo']) && !is_null($params['unidade_id'])) {
$infraestruturas = DB::table('cadastro_infraestrutura as infraestrutura')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->where('infraestrutura.unidade_id', $params['unidade_id'])
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento as atendimento')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->whereColumn('lotacao.infraestrutura_id', 'infraestrutura.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('jornada.data', $params['periodo'])
->whereNull('lotacao.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento as atendimento')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->whereColumn('centro_custo.infraestrutura_id', 'infraestrutura.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->whereNull('centro_custo.deleted_at')
)
)
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->orderByRaw("COALESCE(infraestrutura.nome, unidade.nome_fantasia)")
->selectRaw("
infraestrutura.id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as nome
")
->get();
}
return ['form' => $infraestruturas, 'model' => $id];
}
private static function getOcupacoesData($params)
{
$ocupacoes = collect();
$id = null;
if (!is_null($params['periodo'])) {
$ocupacoes = DB::table('sigtap.ocupacao as ocupacao')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_pre_atendimento as pre_atendimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'pre_atendimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'pre_atendimento.created_lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('lotacao.ocupacao_id', 'ocupacao.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_pre_atendimento as pre_atendimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'pre_atendimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'pre_atendimento.created_lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('lotacao.ocupacao_id', 'ocupacao.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('lotacao.ocupacao_id', 'ocupacao.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->whereColumn('demanda_espontanea.ocupacao_id', 'ocupacao.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
)
->orderByRaw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome)")
->selectRaw("
ocupacao.id,
CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) as descricao
")
->get();
}
return ['form' => $ocupacoes, 'model' => $id];
}
private static function getEspecialidadesData($params)
{
$especialidades = collect();
$id = null;
if (!is_null($params['periodo']) && !is_null($params['ocupacao_id'])) {
$especialidades = DB::table('cadastro_especialidade as especialidade')
->where('especialidade.ocupacao_id', $params['ocupacao_id'])
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('jornada.especialidade_id', 'especialidade.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'soap.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->whereColumn('demanda_espontanea.especialidade_id', 'especialidade.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
)
->orderBy('especialidade.nome')
->selectRaw("
especialidade.id,
especialidade.nome
")
->get();
}
return ['form' => $especialidades, 'model' => $id];
}
}

View File

@@ -0,0 +1,335 @@
<?php
namespace App\Services\Ambulatorio;
use App\Services\Service;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RelatorioQuantitativoCidService extends Service
{
public static function index()
{
$params = self::getParams();
$atendimentos = DB::table('ambulatorio_atendimento_soap_problema_condicao')
->select([
'cid.codigo AS cid_codigo',
'cid.nome AS cid_nome',
'cadastro_unidade.nome_fantasia AS unidade_nome_fantasia',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia) AS infraestrutura_nome"),
DB::raw("COALESCE(COUNT(IF(ambulatorio_jornada.data BETWEEN '" . $params->periodo['start'] . "' AND '" . $params->periodo['end'] . "', 1, NULL)), 0) AS quantidade_jornada"),
DB::raw("COALESCE(COUNT(IF(ambulatorio_demanda_espontanea.data BETWEEN '{$params->periodo['start']}' AND '{$params->periodo['end']}', 1, NULL)), 0) AS quantidade_demanda"),
])
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_problema_condicao.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->leftJoin('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->leftJoin('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->leftJoin('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->leftJoin('cadastro_lotacao', function ($join) {
$join->on('cadastro_lotacao.id', '=', 'ambulatorio_jornada.lotacao_id')
->orOn('cadastro_lotacao.id', '=', 'ambulatorio_demanda_espontanea.created_lotacao_id');
})
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
->join('sigtap.cid', 'cid.id', 'ambulatorio_atendimento_soap_problema_condicao.cid_id')
->leftJoin('cadastro_paciente as paciente_agendamento', 'paciente_agendamento.id', '=', 'ambulatorio_agendamento.paciente_id')
->leftJoin('cadastro_paciente as paciente_demanda', 'paciente_demanda.id', '=', 'ambulatorio_demanda_espontanea.paciente_id')
->join('cadastro_cidadao', function($join) {
$join->on('cadastro_cidadao.id', '=', DB::raw('COALESCE(paciente_agendamento.cidadao_id, paciente_demanda.cidadao_id)'));
})
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereNull('cadastro_lotacao.deleted_at')
->whereNull('cadastro_infraestrutura.deleted_at')
->whereNull('cadastro_unidade.deleted_at')
->havingRaw("quantidade_demanda + quantidade_jornada > 0")
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->ocupacao_id, function ($q, $ocupacaoId) {
$q->where(function ($query) use ($ocupacaoId) {
$query->where('cadastro_lotacao.ocupacao_id', $ocupacaoId)
->orWhere('ambulatorio_demanda_espontanea.ocupacao_id', $ocupacaoId);
});
})
->when($params->cid_id, fn ($q, $cidId) => $q
->where('cid.id', $cidId)
)
->when($params->idade_de, fn ($q, $idadeDe) => $q
->whereRaw(DB::raw("TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, CURRENT_DATE) >= " . $idadeDe))
)
->when($params->idade_ate, fn ($q, $idadeAte) => $q
->whereRaw(DB::raw("TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, CURRENT_DATE) <= " . $idadeAte))
)
->groupBy([
'cid.codigo',
'cid.nome',
'cadastro_unidade.nome_fantasia',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)"),
])
->get()
->map(function($query) {
$query->cid = $query->cid_codigo . ' - ' . $query->cid_nome;
$query->quantidade = $query->quantidade_jornada + $query->quantidade_demanda;
unset($query->cid_codigo, $query->cid_nome, $query->quantidade_jornada, $query->quantidade_demanda);
return $query;
});
return ['itens' => $atendimentos];
}
public static function create()
{
return [
'form' => [
'unidades' => [],
'infraestruturas' => [],
'ocupacoes' => [],
],
'model' => [
'periodo' => ['start' => null, 'end' => null],
'unidade_id' => null,
'infraestrutura_id' => null,
'ocupacao_id' => null,
'cid' => null,
'idade_de' => null,
'idade_ate' => null,
],
];
}
public static function list()
{
$params = self::getParams();
switch (request()->listar) {
case 'unidades': {
return [
'unidades' => self::getUnidades($params),
'infraestruturas' => self::getInfraestruturas($params),
'ocupacoes' => self::getOcupacoes($params),
];
}
case 'infraestruturas': {
return [
'infraestruturas' => self::getInfraestruturas($params),
'ocupacoes' => self::getOcupacoes($params),
];
}
case 'ocupacoes': {
return [
'ocupacoes' => self::getOcupacoes($params),
];
}
}
}
private static function getParams()
{
return (object) [
'periodo' => [
'start' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['start'])->setTime(0, 0, 0),
'end' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['end'])->setTime(23, 59, 59)
],
'unidade_id' => request()->get('unidade_id'),
'infraestrutura_id' => request()->get('infraestrutura_id'),
'ocupacao_id' => request()->get('ocupacao_id'),
'cid_id' => request()->get('cid_id'),
'idade_de' => request()->get('idade_de'),
'idade_ate' => request()->get('idade_ate'),
];
}
private static function getUnidades($params)
{
return DB::table('cadastro_unidade')
->select([
'cadastro_unidade.id',
'cadastro_unidade.nome_fantasia',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_problema_condicao')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_problema_condicao.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereNotNull('ambulatorio_atendimento_soap_problema_condicao.cid_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
)
->orWhereExists(fn ($q) => $q
->from('ambulatorio_atendimento_soap_problema_condicao')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_problema_condicao.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereNotNull('ambulatorio_atendimento_soap_problema_condicao.cid_id')
->whereNotNull('ambulatorio_demanda_espontanea.ocupacao_id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
)
->orderBy('cadastro_unidade.nome_fantasia')
->get();
}
private static function getInfraestruturas($params)
{
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_infraestrutura.unidade_id', $params->unidade_id)
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_problema_condicao')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_problema_condicao.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereNotNull('ambulatorio_atendimento_soap_problema_condicao.cid_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_problema_condicao')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_problema_condicao.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereNotNull('ambulatorio_atendimento_soap_problema_condicao.cid_id')
->whereNotNull('ambulatorio_demanda_espontanea.ocupacao_id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
)
)
->orderByRaw('COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)')
->get();
}
private static function getOcupacoes($params)
{
return DB::table('sigtap.ocupacao')
->select([
'ocupacao.id',
DB::raw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) AS nome"),
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_problema_condicao')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_problema_condicao.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('cadastro_lotacao.ocupacao_id', 'ocupacao.id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereNotNull('ambulatorio_atendimento_soap_problema_condicao.cid_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_problema_condicao')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_problema_condicao.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_demanda_espontanea.ocupacao_id', 'ocupacao.id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereNotNull('ambulatorio_atendimento_soap_problema_condicao.cid_id')
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->where('cadastro_infraestrutura.unidade_id', $params->unidade_id)
->where('cadastro_infraestrutura.id', $params->infraestrutura_id)
)
->orderByRaw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome)")
->get();
}
public static function autocomplete()
{
$params = self::getParams();
$cids = DB::table('ambulatorio_atendimento_soap_problema_condicao')
->select([
'ambulatorio_jornada.data',
'cadastro_infraestrutura.unidade_id',
'cadastro_infraestrutura.id AS infraestrutura_id',
'cadastro_lotacao.ocupacao_id',
'ambulatorio_atendimento_soap_problema_condicao.cid_id',
'cadastro_cidadao.data_nascimento',
'ambulatorio_atendimento_soap.is_rascunho',
])
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_problema_condicao.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_paciente', 'cadastro_paciente.id', 'ambulatorio_agendamento.paciente_id')
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id')
->union(
DB::table('ambulatorio_atendimento_soap_problema_condicao')
->select([
'ambulatorio_demanda_espontanea.data',
'cadastro_infraestrutura.unidade_id',
'cadastro_infraestrutura.id AS infraestrutura_id',
'ambulatorio_demanda_espontanea.ocupacao_id',
'ambulatorio_atendimento_soap_problema_condicao.cid_id',
'cadastro_cidadao.data_nascimento',
'ambulatorio_atendimento_soap.is_rascunho',
])
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_problema_condicao.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_paciente', 'cadastro_paciente.id', 'ambulatorio_demanda_espontanea.paciente_id')
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id')
);
return DB::table('sigtap.cid')
->select([
'cid.id',
'cid.codigo',
'cid.nome',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from(DB::raw("({$cids->toSql()}) AS x"))
->whereColumn('x.cid_id', 'cid.id')
->where('x.is_rascunho', false)
->whereBetween('x.data', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('x.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('x.infraestrutura_id', $infraestruturaId)
)
);
}
}

View File

@@ -0,0 +1,190 @@
<?php
namespace App\Services\Ambulatorio;
use App\Services\Service;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RelatorioQuantitativoConsultaSolicitadaService extends Service
{
public static function index()
{
$params = self::getParams();
$agendamentos = DB::table('ambulatorio_agendamento')
->select([
'cadastro_unidade.nome_fantasia AS unidade_nome_fantasia',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia) AS infraestrutura_nome"),
'cadastro_especialidade.nome AS especialidade_nome',
DB::raw("COUNT(*) AS total"),
])
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
->join('cadastro_especialidade', 'cadastro_especialidade.id', 'ambulatorio_jornada.especialidade_id')
->whereBetween('ambulatorio_agendamento.created_at', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_unidade.id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
->when($params->especialidade_id, fn ($q, $especialidadeId) => $q
->where('cadastro_especialidade.id', $especialidadeId)
)
->groupBy([
'cadastro_unidade.nome_fantasia',
DB::raw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)"),
'cadastro_especialidade.nome',
])
->get();
return [
'itens' => $agendamentos,
'totalizadores' => ['quantidade_agendamentos' => $agendamentos->reduce(fn ($a, $b) => $a + $b->total)],
];
}
public static function create()
{
return [
'form' => [
'unidades' => [],
'infraestruturas' => [],
'especialidades' => [],
],
'model' => [
'periodo' => ['start' => null, 'end' => null],
'unidade_id' => null,
'infraestrutura_id' => null,
'especialidade_id' => null,
],
];
}
public static function list()
{
$params = self::getParams();
switch (request()->listar) {
case 'unidades': {
return [
'unidades' => self::getUnidades($params),
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
];
}
case 'infraestruturas': {
return [
'infraestruturas' => self::getInfraestruturas($params),
'especialidades' => self::getEspecialidades($params),
];
}
case 'especialidades': {
return [
'especialidades' => self::getEspecialidades($params),
];
}
}
}
private static function getParams()
{
return (object) [
'periodo' => [
'start' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['start'])->setTime(0, 0, 0),
'end' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['end'])->setTime(23, 59, 59)
],
'unidade_id' => request()->get('unidade_id'),
'infraestrutura_id' => request()->get('infraestrutura_id'),
'especialidade_id' => request()->get('especialidade_id'),
];
}
private static function getUnidades($params)
{
return DB::table('cadastro_unidade')
->select([
'cadastro_unidade.id',
'cadastro_unidade.nome_fantasia',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_infraestrutura')
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereColumn('ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->whereBetween('ambulatorio_agendamento.created_at', $params->periodo)
)
)
)
)
->orderBy('cadastro_unidade.nome_fantasia')
->get();
}
private static function getInfraestruturas($params)
{
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_infraestrutura.unidade_id', $params->unidade_id)
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('cadastro_lotacao')
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->whereColumn('ambulatorio_jornada.lotacao_id', 'cadastro_lotacao.id')
->whereBetween('ambulatorio_agendamento.created_at', $params->periodo)
)
)
)
->orderByRaw('COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)')
->get();
}
private static function getEspecialidades($params)
{
return DB::table('cadastro_especialidade')
->select([
'cadastro_especialidade.id',
'cadastro_especialidade.nome',
])
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_agendamento')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereColumn('ambulatorio_jornada.especialidade_id', 'cadastro_especialidade.id')
->whereBetween('ambulatorio_agendamento.created_at', $params->periodo)
->when($params->unidade_id, fn ($q, $unidadeId) => $q
->where('cadastro_infraestrutura.unidade_id', $unidadeId)
)
->when($params->infraestrutura_id, fn ($q, $infraestruturaId) => $q
->where('cadastro_infraestrutura.id', $infraestruturaId)
)
)
)
->orderBy('cadastro_especialidade.nome')
->get();
}
}

View File

@@ -0,0 +1,625 @@
<?php
namespace App\Services\Ambulatorio;
use App\Services\Service;
use App\Utils\MaskUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RelatorioQuantitativoProcedimentoService extends Service
{
public static function index()
{
$totalizadores = (object) [
'quantidade' => 0,
];
$periodo = [
'start' => Carbon::createFromFormat('d/m/Y', request()->periodo['start'])->startOfDay(),
'end' => Carbon::createFromFormat('d/m/Y', request()->periodo['end'])->endOfDay(),
];
$procedimentos = DB::query()
->fromSub(DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->join('cadastro_usuario as usuario', 'usuario.id', 'atendimento_procedimento.usuario_id')
->join('cadastro_cidadao as usuario_cidadao', 'usuario_cidadao.id', 'usuario.cidadao_id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereBetween('jornada.data', $periodo)
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when(request()->ocupacao_id, fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when(request()->especialidade_id, fn ($q, $id) => $q->where('atendimento_procedimento.especialidade_id', $id))
->when(request()->usuario_id, fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->when(request()->procedimento_codigo, fn ($q, $codigo) => $q->where('procedimento.codigo', $codigo))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNull('usuario.deleted_at')
->whereNull('usuario_cidadao.deleted_at')
->selectRaw("
usuario_cidadao.nome as usuario_nome,
procedimento.codigo as procedimento_codigo,
procedimento.nome as procedimento_nome,
SUM(atendimento_procedimento.quantidade) as quantidade
")
->groupByRaw("
usuario_cidadao.nome,
procedimento.codigo,
procedimento.nome
")
->unionAll(DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->join('cadastro_usuario as usuario', 'usuario.id', 'atendimento_procedimento.usuario_id')
->join('cadastro_cidadao as usuario_cidadao', 'usuario_cidadao.id', 'usuario.cidadao_id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
->where('soap.is_rascunho', false)
)
->orWhereNotExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_soap as soap')
->whereColumn('soap.id', 'atendimento_procedimento.soap_id')
)
)
->whereBetween('demanda_espontanea.data', $periodo)
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->when(request()->ocupacao_id, fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when(request()->especialidade_id, fn ($q, $id) => $q->where('atendimento_procedimento.especialidade_id', $id))
->when(request()->usuario_id, fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->when(request()->procedimento_codigo, fn ($q, $codigo) => $q->where('procedimento.codigo', $codigo))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNull('usuario.deleted_at')
->whereNull('usuario_cidadao.deleted_at')
->selectRaw("
usuario_cidadao.nome as usuario_nome,
procedimento.codigo as procedimento_codigo,
procedimento.nome as procedimento_nome,
SUM(atendimento_procedimento.quantidade) as quantidade
")
->groupByRaw("
usuario_cidadao.nome,
procedimento.codigo,
procedimento.nome
")
)
, 'sub')
->groupByRaw("
sub.usuario_nome,
sub.procedimento_codigo,
sub.procedimento_nome
")
->selectRaw("
sub.usuario_nome,
sub.procedimento_codigo,
sub.procedimento_nome,
SUM(sub.quantidade) as quantidade
")
->get();
$procedimentos->each(function ($procedimento) use ($totalizadores) {
$procedimento->procedimento_descricao = MaskUtil::getProcedimentoMasked($procedimento->procedimento_codigo)
. " - {$procedimento->procedimento_nome}";
unset($procedimento->codigo, $procedimento->nome);
$totalizadores->quantidade += $procedimento->quantidade;
});
return compact('procedimentos', 'totalizadores');
}
public static function list()
{
$data = (object) [
'additionals' => [],
'form' => [],
'model' => [],
];
$params = self::getParams();
$sets = [
'periodo' => function () use ($data) {
$data->model['periodo'] = ['start' => null, 'end' => null];
},
'unidade' => function () use ($data, $params) {
$unidadesData = self::getUnidadesData($params);
$data->form['unidades'] = $unidadesData['form'];
$data->model['unidade_id'] = $unidadesData['model'];
},
'infraestrutura' => function () use ($data, $params) {
$infraestruturasData = self::getInfraestruturasData($params);
$data->form['infraestruturas'] = $infraestruturasData['form'];
$data->model['infraestrutura_id'] = $infraestruturasData['model'];
},
'ocupacao' => function () use ($data, $params) {
$ocupacoesData = self::getOcupacoesData($params);
$data->form['ocupacoes'] = $ocupacoesData['form'];
$data->model['ocupacao_id'] = $ocupacoesData['model'];
},
'especialidade' => function () use ($data, $params) {
$especialidadesData = self::getEspecialidadesData($params);
$data->form['especialidades'] = $especialidadesData['form'];
$data->model['especialidade_id'] = $especialidadesData['model'];
},
'usuario' => function () use ($data, $params) {
$usuariosData = self::getUsuariosData($params);
$data->form['usuarios'] = $usuariosData['form'];
$data->model['usuario_id'] = $usuariosData['model'];
},
'procedimento' => function () use ($data, $params) {
$procedimentosData = self::getProcedimentosData($params);
$data->form['procedimentos'] = $procedimentosData['form'];
$data->model['procedimento_codigo'] = $procedimentosData['model'];
},
];
$load = is_null(request()->load_from);
if ($load) {
$data->additionals = [
'data_atual' => Carbon::today()->format('d/m/Y')
];
}
foreach ($sets as $field => $set) {
if ($load) {
$set();
}
else if ($field === request()->load_from) {
$load = true;
}
}
foreach ($data as $property => $itens) {
if (empty($itens)) {
unset($data->{$property});
}
}
return $data;
}
private static function getParams()
{
$params = request()->only([
'periodo',
'unidade_id',
'infraestrutura_id',
'ocupacao_id',
'especialidade_id',
'usuario_id',
'procedimento_codigo',
]);
if (isset($params['periodo'])
&& !is_null($params['periodo']['start'])
&& !is_null($params['periodo']['end'])
) {
$start = Carbon::createFromFormat('d/m/Y', $params['periodo']['start'])->startOfDay();
$end = Carbon::createFromFormat('d/m/Y', $params['periodo']['end'])->endOfDay();
$params['periodo']['start'] = $start;
$params['periodo']['end'] = $end;
}
else {
$params['periodo'] = null;
}
return $params;
}
private static function getUnidadesData($params)
{
$unidades = collect();
$id = null;
if (!is_null($params['periodo'])) {
$queryAgendados = DB::table('cadastro_unidade as unidade')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.unidade_id', 'unidade.id')
->join('cadastro_lotacao as lotacao', 'lotacao.infraestrutura_id', 'infraestrutura.id')
->join('ambulatorio_jornada as jornada', 'jornada.lotacao_id', 'lotacao.id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.jornada_id', 'jornada.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.agendamento_id', 'agendamento.id')
->leftJoin('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.atendimento_id', 'atendimento.id')
->join('ambulatorio_atendimento_soap as soap', 'soap.id', 'atendimento_procedimento.soap_id')
->whereBetween('jornada.data', $params['periodo'])
->where('soap.is_rascunho', false)
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->selectRaw("unidade.id, unidade.nome_fantasia");
$queryEspontanea = DB::table('cadastro_unidade as unidade')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.unidade_id', 'unidade.id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.infraestrutura_id', 'infraestrutura.id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.created_centro_custo_id', 'centro_custo.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.demanda_espontanea_id', 'demanda_espontanea.id')
->leftJoin('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.atendimento_id', 'atendimento.id')
->join('ambulatorio_atendimento_soap as soap', 'soap.id', 'atendimento_procedimento.soap_id')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->where('soap.is_rascunho', false)
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->selectRaw("unidade.id, unidade.nome_fantasia");
$unidades = $queryAgendados
->union($queryEspontanea)
->distinct()
->orderBy('nome_fantasia')
->get();
}
return ['form' => $unidades, 'model' => $id];
}
private static function getInfraestruturasData($params)
{
$infraestruturas = collect();
$id = null;
if (!is_null($params['periodo']) && !is_null($params['unidade_id'])) {
$queryAgendados = DB::table('cadastro_infraestrutura as infraestrutura')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->join('cadastro_lotacao as lotacao', 'lotacao.infraestrutura_id', 'infraestrutura.id')
->join('ambulatorio_jornada as jornada', 'jornada.lotacao_id', 'lotacao.id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.jornada_id', 'jornada.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.agendamento_id', 'agendamento.id')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.atendimento_id', 'atendimento.id')
->leftJoin('ambulatorio_atendimento_soap as soap', 'soap.id', 'atendimento_procedimento.soap_id')
->where('infraestrutura.unidade_id', $params['unidade_id'])
->whereBetween('jornada.data', $params['periodo'])
->where(function ($q) {
$q->where('soap.is_rascunho', false)
->orWhereNull('soap.id');
})
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->selectRaw("
infraestrutura.id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as nome
");
$queryEspontanea = DB::table('cadastro_infraestrutura as infraestrutura')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.infraestrutura_id', 'infraestrutura.id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.created_centro_custo_id', 'centro_custo.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.demanda_espontanea_id', 'demanda_espontanea.id')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.atendimento_id', 'atendimento.id')
->leftJoin('ambulatorio_atendimento_soap as soap', 'soap.id', 'atendimento_procedimento.soap_id')
->where('infraestrutura.unidade_id', $params['unidade_id'])
->whereBetween('demanda_espontanea.data', $params['periodo'])
->where(function ($q) {
$q->where('soap.is_rascunho', false)
->orWhereNull('soap.id');
})
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->selectRaw("
infraestrutura.id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as nome
");
$infraestruturas = $queryAgendados
->union($queryEspontanea)
->distinct()
->orderBy('nome')
->get();
}
return ['form' => $infraestruturas, 'model' => $id];
}
private static function getOcupacoesData($params)
{
$ocupacoes = collect();
$id = null;
if (!is_null($params['periodo'])) {
$queryAgendados = DB::table('sigtap.ocupacao as ocupacao')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.ocupacao_id', 'ocupacao.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->leftJoin('ambulatorio_atendimento_soap as soap', 'soap.id', 'atendimento_procedimento.soap_id')
->whereBetween('jornada.data', $params['periodo'])
->where(function ($q) {
$q->where('soap.is_rascunho', false)
->orWhereNull('soap.id');
})
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->selectRaw("
ocupacao.id,
CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) as descricao,
ocupacao.codigo,
ocupacao.nome
");
$queryEspontanea = DB::table('sigtap.ocupacao as ocupacao')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.ocupacao_id', 'ocupacao.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->leftJoin('ambulatorio_atendimento_soap as soap', 'soap.id', 'atendimento_procedimento.soap_id')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->where(function ($q) {
$q->where('soap.is_rascunho', false)
->orWhereNull('soap.id');
})
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
->selectRaw("
ocupacao.id,
CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) as descricao,
ocupacao.codigo,
ocupacao.nome
");
$ocupacoes = $queryAgendados
->union($queryEspontanea)
->distinct()
->orderBy('codigo')
->orderBy('nome')
->get()
->map(function($item) {
return [
'id' => $item->id,
'descricao' => $item->descricao
];
});
}
return ['form' => $ocupacoes, 'model' => $id];
}
private static function getEspecialidadesData($params)
{
$especialidades = collect();
$id = null;
if (!is_null($params['periodo']) && !is_null($params['ocupacao_id'])) {
$queryAgendados = DB::table('cadastro_especialidade as especialidade')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.especialidade_id', 'especialidade.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->leftJoin('ambulatorio_atendimento_soap as soap', 'soap.id', 'atendimento_procedimento.soap_id')
->where('especialidade.ocupacao_id', $params['ocupacao_id'])
->whereBetween('jornada.data', $params['periodo'])
->where(function ($q) {
$q->where('soap.is_rascunho', false)
->orWhereNull('soap.id');
})
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->selectRaw("especialidade.id, especialidade.nome");
$queryEspontanea = DB::table('cadastro_especialidade as especialidade')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.especialidade_id', 'especialidade.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->leftJoin('ambulatorio_atendimento_soap as soap', 'soap.id', 'atendimento_procedimento.soap_id')
->where('especialidade.ocupacao_id', $params['ocupacao_id'])
->whereBetween('demanda_espontanea.data', $params['periodo'])
->where(function ($q) {
$q->where('soap.is_rascunho', false)
->orWhereNull('soap.id');
})
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
->selectRaw("especialidade.id, especialidade.nome");
$especialidades = $queryAgendados
->union($queryEspontanea)
->distinct()
->orderBy('nome')
->get();
}
return ['form' => $especialidades, 'model' => $id];
}
private static function getUsuariosData($params)
{
$usuarios = collect();
$id = null;
if (!is_null($params['periodo'])) {
$queryAgendados = DB::table('cadastro_usuario as usuario')
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.usuario_id', 'usuario.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->leftJoin('ambulatorio_atendimento_soap as soap', 'soap.id', 'atendimento_procedimento.soap_id')
->whereBetween('jornada.data', $params['periodo'])
->where(function ($q) {
$q->where('soap.is_rascunho', false)
->orWhereNull('soap.id');
})
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when($params['especialidade_id'], fn ($q, $id) => $q->where('atendimento_procedimento.especialidade_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNull('usuario.deleted_at')
->whereNull('cidadao.deleted_at')
->selectRaw("usuario.id, cidadao.nome");
$queryEspontanea = DB::table('cadastro_usuario as usuario')
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.usuario_id', 'usuario.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->leftJoin('ambulatorio_atendimento_soap as soap', 'soap.id', 'atendimento_procedimento.soap_id')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->where(function ($q) {
$q->where('soap.is_rascunho', false)
->orWhereNull('soap.id');
})
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when($params['especialidade_id'], fn ($q, $id) => $q->where('atendimento_procedimento.especialidade_id', $id))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereNull('usuario.deleted_at')
->whereNull('cidadao.deleted_at')
->selectRaw("usuario.id, cidadao.nome");
$usuarios = $queryAgendados
->union($queryEspontanea)
->distinct()
->orderBy('nome')
->get();
}
return ['form' => $usuarios, 'model' => $id];
}
private static function getProcedimentosData($params)
{
$procedimentos = collect();
$codigo = null;
if (!is_null($params['periodo'])) {
$queryAgendados = DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->leftJoin('ambulatorio_atendimento_soap as soap', 'soap.id', 'atendimento_procedimento.soap_id')
->whereBetween('jornada.data', $params['periodo'])
->where(function ($q) {
$q->where('soap.is_rascunho', false)
->orWhereNull('soap.id');
})
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when($params['especialidade_id'], fn ($q, $id) => $q->where('atendimento_procedimento.especialidade_id', $id))
->when($params['usuario_id'], fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->select('procedimento.codigo', 'procedimento.nome');
$queryEspontanea = DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->leftJoin('ambulatorio_atendimento_soap as soap', 'soap.id', 'atendimento_procedimento.soap_id')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->where(function ($q) {
$q->where('soap.is_rascunho', false)
->orWhereNull('soap.id');
})
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when($params['especialidade_id'], fn ($q, $id) => $q->where('atendimento_procedimento.especialidade_id', $id))
->when($params['usuario_id'], fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
->select('procedimento.codigo', 'procedimento.nome');
$procedimentos = $queryAgendados
->union($queryEspontanea)
->distinct()
->orderBy('codigo')
->orderBy('nome')
->get();
$procedimentos->each(function ($procedimento) {
$procedimento->descricao = MaskUtil::getProcedimentoMasked($procedimento->codigo)
. " - {$procedimento->nome}";
unset($procedimento->nome);
});
}
return ['form' => $procedimentos, 'model' => $codigo];
}
}

View File

@@ -0,0 +1,580 @@
<?php
namespace App\Services\Ambulatorio;
use App\Models\Cadastro\Estabelecimento\Infraestrutura;
use App\Models\Cadastro\Estabelecimento\Unidade;
use App\Models\Cadastro\SujeitoAtencao\Usuario;
use App\Models\Sigtap\Ocupacao;
use App\Models\Sigtap\Procedimento;
use App\Services\Service;
use App\Utils\DataUtil;
use App\Utils\MaskUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RelatorioQuantitativoProducaoService extends Service
{
public static function index()
{
$totalizadores = (object) [
'quantidade' => 0,
];
$periodo = [
'start' => Carbon::createFromFormat('d/m/Y', request()->periodo['start'])->startOfDay(),
'end' => Carbon::createFromFormat('d/m/Y', request()->periodo['end'])->endOfDay(),
];
$procedimentosBuilder = DB::query()
->fromSub(DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('cadastro_paciente as paciente', 'paciente.id', 'agendamento.paciente_id')
->join('cadastro_cidadao as paciente_cidadao', 'paciente_cidadao.id', 'paciente.cidadao_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->join('sigtap.ocupacao as ocupacao', 'ocupacao.id', 'atendimento_procedimento.ocupacao_id')
->join('cadastro_usuario as usuario', 'usuario.id', 'atendimento_procedimento.usuario_id')
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('jornada.data', $periodo)
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when(request()->ocupacao_id, fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when(request()->usuario_id, fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->when(request()->procedimento_codigo, fn ($q, $codigo) => $q->where('procedimento.codigo', $codigo))
->when(request()->idade_de, fn ($q, $idadeDe) => $q
->whereRaw("TIMESTAMPDIFF(YEAR, paciente_cidadao.data_nascimento, NOW()) >= {$idadeDe}")
)
->when(request()->idade_ate, fn ($q, $idadeAte) => $q
->whereRaw("TIMESTAMPDIFF(YEAR, paciente_cidadao.data_nascimento, NOW()) <= {$idadeAte}")
)
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->selectRaw("
procedimento.codigo as procedimento_codigo,
procedimento.nome as procedimento_nome,
ocupacao.codigo as ocupacao_codigo,
ocupacao.nome as ocupacao_nome,
usuario.id as usuario_id,
cidadao.nome as usuario_nome,
SUM(atendimento_procedimento.quantidade) as quantidade
")
->groupByRaw("
procedimento.codigo,
ocupacao.codigo,
usuario.id
")
->unionAll(DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_paciente as paciente', 'paciente.id', 'demanda_espontanea.paciente_id')
->join('cadastro_cidadao as paciente_cidadao', 'paciente_cidadao.id', 'paciente.cidadao_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->join('sigtap.ocupacao as ocupacao', 'ocupacao.id', 'atendimento_procedimento.ocupacao_id')
->join('cadastro_usuario as usuario', 'usuario.id', 'atendimento_procedimento.usuario_id')
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $periodo)
->when(request()->unidade_id, fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when(request()->infraestrutura_id, fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->when(request()->ocupacao_id, fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when(request()->usuario_id, fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->when(request()->procedimento_codigo, fn ($q, $codigo) => $q->where('procedimento.codigo', $codigo))
->when(request()->idade_de, fn ($q, $idadeDe) => $q
->whereRaw("TIMESTAMPDIFF(YEAR, paciente_cidadao.data_nascimento, NOW()) >= {$idadeDe}")
)
->when(request()->idade_ate, fn ($q, $idadeAte) => $q
->whereRaw("TIMESTAMPDIFF(YEAR, paciente_cidadao.data_nascimento, NOW()) <= {$idadeAte}")
)
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
->selectRaw("
procedimento.codigo as procedimento_codigo,
procedimento.nome as procedimento_nome,
ocupacao.codigo as ocupacao_codigo,
ocupacao.nome as ocupacao_nome,
usuario.id as usuario_id,
cidadao.nome as usuario_nome,
SUM(atendimento_procedimento.quantidade) as quantidade
")
->groupByRaw("
procedimento.codigo,
ocupacao.codigo,
usuario.id
")
)
, 'sub')
->groupByRaw("
sub.procedimento_codigo,
sub.ocupacao_codigo,
sub.usuario_id
")
->selectRaw("
sub.procedimento_codigo,
sub.procedimento_nome,
sub.ocupacao_codigo,
sub.ocupacao_nome,
sub.usuario_nome,
SUM(sub.quantidade) as quantidade
");
self::setOrderBy($procedimentosBuilder);
$procedimentos = $procedimentosBuilder->get();
$procedimentos->each(function ($procedimento) use ($totalizadores) {
$procedimento->procedimento_codigo = MaskUtil::getProcedimentoMasked($procedimento->procedimento_codigo);
$totalizadores->quantidade += $procedimento->quantidade;
});
return compact('procedimentos', 'totalizadores');
}
public static function list()
{
$data = (object) [
'additionals' => [],
'form' => [],
'model' => [],
];
$params = self::getParams();
$sets = [
'periodo' => function () use ($data) {
$data->model['periodo'] = ['start' => null, 'end' => null];
},
'unidade' => function () use ($data, $params) {
$unidadesData = self::getUnidadesData($params);
$data->form['unidades'] = $unidadesData['form'];
$data->model['unidade_id'] = $unidadesData['model'];
},
'infraestrutura' => function () use ($data, $params) {
$infraestruturasData = self::getInfraestruturasData($params);
$data->form['infraestruturas'] = $infraestruturasData['form'];
$data->model['infraestrutura_id'] = $infraestruturasData['model'];
},
'ocupacao' => function () use ($data, $params) {
$ocupacoesData = self::getOcupacoesData($params);
$data->form['ocupacoes'] = $ocupacoesData['form'];
$data->model['ocupacao_id'] = $ocupacoesData['model'];
},
'usuario' => function () use ($data, $params) {
$usuarioData = self::getUsuariosData($params);
$data->form['usuarios'] = $usuarioData['form'];
$data->model['usuario_id'] = $usuarioData['model'];
},
'procedimento' => function () use ($data, $params) {
$procedimentosData = self::getProcedimentosData($params);
$data->form['procedimentos'] = $procedimentosData['form'];
$data->model['procedimento_codigo'] = $procedimentosData['model'];
},
];
$load = is_null(request()->load_from);
if ($load) {
$data->additionals = [
'data_atual' => Carbon::today()->format('d/m/Y')
];
$data->model['idade_de'] = null;
$data->model['idade_ate'] = null;
}
foreach ($sets as $field => $set) {
if ($load) {
$set();
}
else if ($field === request()->load_from) {
$load = true;
}
}
foreach ($data as $property => $itens) {
if (empty($itens)) {
unset($data->{$property});
}
}
return $data;
}
private static function getParams()
{
$params = request()->only([
'periodo',
'unidade_id',
'infraestrutura_id',
'ocupacao_id',
'usuario_id',
'procedimento_codigo',
]);
if (isset($params['periodo'])
&& !is_null($params['periodo']['start'])
&& !is_null($params['periodo']['end'])
) {
$start = Carbon::createFromFormat('d/m/Y', $params['periodo']['start'])->startOfDay();
$end = Carbon::createFromFormat('d/m/Y', $params['periodo']['end'])->endOfDay();
$params['periodo']['start'] = $start;
$params['periodo']['end'] = $end;
}
else {
$params['periodo'] = null;
}
return $params;
}
private static function getUnidadesData($params)
{
$unidades = collect();
$id = null;
if (!is_null($params['periodo'])) {
$unidades = DB::table('cadastro_unidade as unidade')
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('cadastro_infraestrutura as infraestrutura')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->whereColumn('lotacao.infraestrutura_id', 'infraestrutura.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('jornada.data', $params['periodo'])
->whereNull('lotacao.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->whereColumn('centro_custo.infraestrutura_id', 'infraestrutura.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->whereNull('centro_custo.deleted_at')
)
)
->whereColumn('infraestrutura.unidade_id', 'unidade.id')
->whereNull('infraestrutura.deleted_at')
)
->whereNull('unidade.deleted_at')
->orderBy('unidade.nome_fantasia')
->selectRaw("
unidade.id,
unidade.nome_fantasia
")
->get();
}
return ['form' => $unidades, 'model' => $id];
}
private static function getInfraestruturasData($params)
{
$infraestruturas = collect();
$id = null;
if (!is_null($params['periodo']) && !is_null($params['unidade_id'])) {
$infraestruturas = DB::table('cadastro_infraestrutura as infraestrutura')
->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id')
->where('infraestrutura.unidade_id', $params['unidade_id'])
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->whereColumn('lotacao.infraestrutura_id', 'infraestrutura.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('jornada.data', $params['periodo'])
->whereNull('lotacao.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->whereColumn('centro_custo.infraestrutura_id', 'infraestrutura.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->whereNull('centro_custo.deleted_at')
)
)
->whereNull('infraestrutura.deleted_at')
->whereNull('unidade.deleted_at')
->orderByRaw("COALESCE(infraestrutura.nome, unidade.nome_fantasia)")
->selectRaw("
infraestrutura.id,
COALESCE(infraestrutura.nome, unidade.nome_fantasia) as nome
")
->get();
}
return ['form' => $infraestruturas, 'model' => $id];
}
private static function getOcupacoesData($params)
{
$ocupacoes = collect();
$id = null;
if (!is_null($params['periodo'])) {
$ocupacoes = DB::table('sigtap.ocupacao as ocupacao')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereColumn('atendimento_procedimento.ocupacao_id', 'ocupacao.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_atendimento_procedimento as atendimento_procedimento')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->whereColumn('atendimento_procedimento.ocupacao_id', 'ocupacao.id')
->whereNotNull('atendimento.finalizado_em')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
)
->orderByRaw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome)")
->selectRaw("
ocupacao.id,
CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) as descricao
")
->get();
}
return ['form' => $ocupacoes, 'model' => $id];
}
private static function getUsuariosData($params)
{
$usuarios = collect();
$id = null;
if (!is_null($params['periodo'])) {
$usuarios = DB::table('cadastro_usuario as usuario')
->join('cadastro_cidadao as cidadao', 'cidadao.id', 'usuario.cidadao_id')
->where(fn ($q) => $q
->whereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_agendamento as agendamento')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.agendamento_id', 'agendamento.id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.atendimento_id', 'atendimento.id')
->whereColumn('atendimento_procedimento.usuario_id', 'usuario.id')
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->whereNotNull('atendimento.finalizado_em')
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
->orWhereExists(fn ($q) => $q
->selectRaw(1)
->from('ambulatorio_demanda_espontanea as demanda_espontanea')
->join('ambulatorio_atendimento as atendimento', 'atendimento.demanda_espontanea_id', 'demanda_espontanea.id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.atendimento_id', 'atendimento.id')
->whereColumn('atendimento_procedimento.usuario_id', 'usuario.id')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->whereNotNull('atendimento.finalizado_em')
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
)
)
->orderBy('cidadao.nome')
->selectRaw("
usuario.id,
cidadao.nome
")
->get();
}
return ['form' => $usuarios, 'model' => $id];
}
private static function getProcedimentosData($params)
{
$procedimentos = collect();
$codigo = null;
if (!is_null($params['periodo'])) {
$procedimentos = DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_agendamento as agendamento', 'agendamento.id', 'atendimento.agendamento_id')
->join('ambulatorio_jornada as jornada', 'jornada.id', 'agendamento.jornada_id')
->join('cadastro_lotacao as lotacao', 'lotacao.id', 'jornada.lotacao_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'lotacao.infraestrutura_id')
->whereNotNull('atendimento.finalizado_em')
->whereNull('lotacao.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereBetween('jornada.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('lotacao.infraestrutura_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when($params['usuario_id'], fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->selectRaw("
procedimento.codigo,
procedimento.nome
")
->distinct()
->union(DB::table('sigtap.procedimento as procedimento')
->join('ambulatorio_atendimento_procedimento as atendimento_procedimento', 'atendimento_procedimento.procedimento_id', 'procedimento.id')
->join('ambulatorio_atendimento as atendimento', 'atendimento.id', 'atendimento_procedimento.atendimento_id')
->join('ambulatorio_demanda_espontanea as demanda_espontanea', 'demanda_espontanea.id', 'atendimento.demanda_espontanea_id')
->join('cadastro_centro_custo as centro_custo', 'centro_custo.id', 'demanda_espontanea.created_centro_custo_id')
->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'centro_custo.infraestrutura_id')
->whereNotNull('atendimento.finalizado_em')
->whereNull('centro_custo.deleted_at')
->whereNull('infraestrutura.deleted_at')
->whereBetween('demanda_espontanea.data', $params['periodo'])
->when($params['unidade_id'], fn ($q, $id) => $q->where('infraestrutura.unidade_id', $id))
->when($params['infraestrutura_id'], fn ($q, $id) => $q->where('centro_custo.infraestrutura_id', $id))
->when($params['ocupacao_id'], fn ($q, $id) => $q->where('atendimento_procedimento.ocupacao_id', $id))
->when($params['usuario_id'], fn ($q, $id) => $q->where('atendimento_procedimento.usuario_id', $id))
->selectRaw("
procedimento.codigo,
procedimento.nome
")
->distinct()
)
->orderByRaw("CONCAT(codigo, ' - ', nome)")
->get();
$procedimentos->each(function ($procedimento) {
$procedimento->descricao = MaskUtil::getProcedimentoMasked($procedimento->codigo)
. " - {$procedimento->nome}";
unset($procedimento->nome);
});
}
return ['form' => $procedimentos, 'model' => $codigo];
}
private static function setOrderBy($builder)
{
$columns = [
'procedimento_codigo' => 'sub.procedimento_codigo',
'procedimento_nome' => 'sub.procedimento_nome',
'ocupacao_codigo' => 'sub.ocupacao_codigo',
'ocupacao_nome' => 'sub.ocupacao_nome',
'usuario_nome' => 'sub.usuario_nome',
'quantidade' => 'quantidade',
];
if (is_null(request()->sortBy)) {
$builder->orderByRaw(join(', ', $columns));
return;
}
$column = $columns[request()->sortBy];
$direction = DataUtil::getBooleanValueFromStringBoolean(request()->sortDesc) ? 'DESC' : 'ASC';
unset($columns[request()->sortBy]);
$builder->orderByRaw(
"{$column} {$direction}, " . join(', ', $columns)
);
}
public static function getPrintExportData()
{
$resultado = self::index();
$itens = $resultado['procedimentos'];
$unidade = Unidade::find(request()->unidade_id);
$infraestrutura = Infraestrutura::find(request()->infraestrutura_id);
$ocupacao = Ocupacao::find(request()->ocupacao_id);
$usuario = Usuario::find(request()->usuario_id);
$procedimento = Procedimento::where('codigo', request()->procedimento_codigo)->orderByDesc('competencia_id')->first();
return [
'inicio' => request()->periodo['start'],
'fim' => request()->periodo['end'],
'unidade' => $unidade->nome_fantasia ?? 'Todas',
'infraestrutura' => $infraestrutura->nome ?? 'Todos',
'ocupacao' => $ocupacao ? "{$ocupacao->codigo} - {$ocupacao->nome}" : 'Todas',
'usuario' => $usuario->cidadao->nome ?? 'Todos',
'procedimento' => $procedimento ? MaskUtil::getProcedimentoMasked($procedimento->codigo) . " - {$procedimento->nome}" : 'Todos',
'idadeDe' => request()->idade_de,
'idadeAte' => request()->idade_ate,
'colunas' => collect(request()->columns),
'itens' => $itens,
'totalizadores' => $resultado['totalizadores'],
];
}
}

View File

@@ -0,0 +1,959 @@
<?php
namespace App\Services\Ambulatorio;
use App\Services\Service;
use App\Enums\Ambulatorio\FeridaStatus;
use App\Models\Cadastro\Especialidade;
use App\Models\Cadastro\Estabelecimento\Infraestrutura;
use App\Models\Cadastro\Estabelecimento\Unidade;
use App\Models\Cadastro\SujeitoAtencao\Usuario;
use App\Models\Sigtap\Ocupacao;
use App\Utils\MaskUtil;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class RelatorioRastreioFeridaService extends Service
{
public static function index()
{
$params = self::getParams();
$itens = DB::table('ambulatorio_atendimento_soap_ferida_procedimento')
->select([
DB::raw("DATE_FORMAT(ambulatorio_jornada.data, '%d/%m/%Y') AS data"),
'ambulatorio_atendimento.id AS atendimento_id',
'cadastro_paciente.id AS paciente_id',
'cadastro_cidadao_paciente.nome AS paciente_nome',
DB::raw("DATE_FORMAT(cadastro_cidadao_paciente.data_nascimento, '%d/%m/%Y') AS paciente_data_nascimento"),
DB::raw("LPAD(cadastro_paciente.prontuario, 6, '0') AS paciente_prontuario"),
'cadastro_unidade.nome_fantasia AS unidade_nome_fantasia',
'cadastro_cidadao_usuario.nome AS usuario_nome',
'cadastro_ferida.nome AS ferida_nome',
'cadastro_especialidade.nome AS especialidade_nome',
'ocupacao.codigo AS ocupacao_codigo',
DB::raw("
CASE WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = TRUE THEN
'Cicatrizada'
WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = FALSE THEN
'Não Cicatrizada'
ELSE
'Indefinido'
END AS status
"),
DB::raw("GROUP_CONCAT(procedimento.codigo SEPARATOR ', ') AS procedimentos"),
DB::raw("GROUP_CONCAT(cadastro_material.descricao SEPARATOR ', ') AS materiais"),
DB::raw("SUM(COALESCE(procedimento.valor_servico_ambilatorial, 0)) AS valor_custo_procedimento"),
DB::raw("
COALESCE((
SELECT SUM(almoxarifado_entrada_item.valor_unitario * almoxarifado_saida_item_entrada_item.quantidade_saida)
FROM almoxarifado_saida_item_entrada_item
INNER JOIN almoxarifado_entrada_item ON almoxarifado_entrada_item.id = almoxarifado_saida_item_entrada_item.entrada_item_id
WHERE almoxarifado_saida_item_entrada_item.saida_item_id = ambulatorio_atendimento_soap_ferida_material.saida_item_id
), 0) AS valor_custo_material
"),
DB::raw("
(
SUM(COALESCE(procedimento.valor_servico_ambilatorial, 0)) + COALESCE((
SELECT SUM(almoxarifado_entrada_item.valor_unitario * almoxarifado_saida_item_entrada_item.quantidade_saida)
FROM almoxarifado_saida_item_entrada_item
INNER JOIN almoxarifado_entrada_item ON almoxarifado_entrada_item.id = almoxarifado_saida_item_entrada_item.entrada_item_id
WHERE almoxarifado_saida_item_entrada_item.saida_item_id = ambulatorio_atendimento_soap_ferida_material.saida_item_id
), 0)
) AS valor_total
"),
DB::raw("COUNT(DISTINCT ambulatorio_atendimento_soap.id) AS soaps_geradas"),
DB::Raw("COUNT(DISTINCT ambulatorio_atendimento_soap_ferida.id) AS feridas_registradas"),
DB::Raw("COUNT(ambulatorio_atendimento_soap_ferida_procedimento.id) AS procedimentos_lancados"),
DB::Raw("COUNT(ambulatorio_atendimento_soap_ferida_material.id) AS kits_materiais_consumidos"),
])
->from('ambulatorio_atendimento_soap_ferida_procedimento')
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
->join('cadastro_paciente', 'cadastro_paciente.id', 'ambulatorio_agendamento.paciente_id')
->join('cadastro_cidadao AS cadastro_cidadao_paciente', 'cadastro_cidadao_paciente.id', 'cadastro_paciente.cidadao_id')
->join('cadastro_usuario', 'cadastro_usuario.id', 'cadastro_lotacao.usuario_id')
->join('cadastro_cidadao AS cadastro_cidadao_usuario', 'cadastro_cidadao_usuario.id', 'cadastro_usuario.cidadao_id')
->join('cadastro_ferida', 'cadastro_ferida.id', 'ambulatorio_atendimento_soap_ferida.ferida_id')
->leftJoin('cadastro_especialidade', 'cadastro_especialidade.id', 'ambulatorio_atendimento_procedimento.especialidade_id')
->leftJoin('sigtap.ocupacao', 'ocupacao.id', 'ambulatorio_atendimento_procedimento.ocupacao_id')
->leftJoin('sigtap.procedimento', 'procedimento.id', 'ambulatorio_atendimento_procedimento.procedimento_id')
->leftJoin('ambulatorio_atendimento_soap_ferida_material', 'ambulatorio_atendimento_soap_ferida_material.atendimento_procedimento_id', 'ambulatorio_atendimento_procedimento.id')
->leftJoin('cadastro_material', 'cadastro_material.id', 'ambulatorio_atendimento_soap_ferida_material.material_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->when($params->ocupacao_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.ocupacao_id', $id))
->when($params->especialidade_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.especialidade_id', $id))
->when($params->usuario_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.usuario_id', $id))
->when($params->feridas, fn ($q, $ids) => $q->whereIn('ambulatorio_atendimento_soap_ferida.ferida_id', $ids))
->when($params->status, fn ($q, $status) => $q->where(function ($q) use ($status) {
if ($status === 'cicatrizada') {
$q->orWhere('ambulatorio_atendimento_soap_ferida.cicatrizada', true);
}
else if ($status === 'não_cicatrizada') {
$q->orWhere('ambulatorio_atendimento_soap_ferida.cicatrizada', false);
}
else if ($status === 'indefinido') {
$q->orWhereNull('ambulatorio_atendimento_soap_ferida.cicatrizada');
}
}))
->when($params->procedimentos, fn ($q, $ids) => $q->whereIn('ambulatorio_atendimento_procedimento.procedimento_id', $ids))
->when($params->paciente_id, fn ($q, $id) => $q->where('cadastro_paciente.id', $id))
->unionAll(
DB::table('ambulatorio_atendimento_soap_ferida_procedimento')
->select([
DB::raw("DATE_FORMAT(ambulatorio_demanda_espontanea.data, '%d/%m/%Y') AS data"),
'ambulatorio_atendimento.id AS atendimento_id',
'cadastro_paciente.id AS paciente_id',
'cadastro_cidadao_paciente.nome AS paciente_nome',
DB::raw("DATE_FORMAT(cadastro_cidadao_paciente.data_nascimento, '%d/%m/%Y') AS paciente_data_nascimento"),
DB::raw("LPAD(cadastro_paciente.prontuario, 6, '0') AS paciente_prontuario"),
'cadastro_unidade.nome_fantasia AS unidade_nome_fantasia',
'cadastro_cidadao_usuario.nome AS usuario_nome',
'cadastro_ferida.nome AS ferida_nome',
'cadastro_especialidade.nome AS especialidade_nome',
'ocupacao.codigo AS ocupacao_codigo',
DB::raw("
CASE WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = TRUE THEN
'Cicatrizada'
WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = FALSE THEN
'Não Cicatrizada'
ELSE
'Indefinido'
END AS status
"),
DB::raw("GROUP_CONCAT(procedimento.codigo SEPARATOR ', ') AS procedimentos"),
DB::raw("GROUP_CONCAT(cadastro_material.descricao SEPARATOR ', ') AS materiais"),
DB::raw("SUM(COALESCE(procedimento.valor_servico_ambilatorial, 0)) AS valor_custo_procedimento"),
DB::raw("
COALESCE((
SELECT SUM(almoxarifado_entrada_item.valor_unitario * almoxarifado_saida_item_entrada_item.quantidade_saida)
FROM almoxarifado_saida_item_entrada_item
INNER JOIN almoxarifado_entrada_item ON almoxarifado_entrada_item.id = almoxarifado_saida_item_entrada_item.entrada_item_id
WHERE almoxarifado_saida_item_entrada_item.saida_item_id = ambulatorio_atendimento_soap_ferida_material.saida_item_id
), 0) AS valor_custo_material
"),
DB::raw("
(
SUM(COALESCE(procedimento.valor_servico_ambilatorial, 0)) + COALESCE((
SELECT SUM(almoxarifado_entrada_item.valor_unitario * almoxarifado_saida_item_entrada_item.quantidade_saida)
FROM almoxarifado_saida_item_entrada_item
INNER JOIN almoxarifado_entrada_item ON almoxarifado_entrada_item.id = almoxarifado_saida_item_entrada_item.entrada_item_id
WHERE almoxarifado_saida_item_entrada_item.saida_item_id = ambulatorio_atendimento_soap_ferida_material.saida_item_id
), 0)
) AS valor_total
"),
DB::raw("COUNT(DISTINCT ambulatorio_atendimento_soap.id) AS soaps_geradas"),
DB::Raw("COUNT(DISTINCT ambulatorio_atendimento_soap_ferida.id) AS feridas_registradas"),
DB::Raw("COUNT(ambulatorio_atendimento_soap_ferida_procedimento.id) AS procedimentos_lancados"),
DB::Raw("COUNT(ambulatorio_atendimento_soap_ferida_material.id) AS kits_materiais_consumidos"),
])
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id')
->join('cadastro_paciente', 'cadastro_paciente.id', 'ambulatorio_demanda_espontanea.paciente_id')
->join('cadastro_cidadao AS cadastro_cidadao_paciente', 'cadastro_cidadao_paciente.id', 'cadastro_paciente.cidadao_id')
->join('cadastro_usuario', 'cadastro_usuario.id', 'cadastro_lotacao.usuario_id')
->join('cadastro_cidadao AS cadastro_cidadao_usuario', 'cadastro_cidadao_usuario.id', 'cadastro_usuario.cidadao_id')
->join('cadastro_ferida', 'cadastro_ferida.id', 'ambulatorio_atendimento_soap_ferida.ferida_id')
->leftJoin('cadastro_especialidade', 'cadastro_especialidade.id', 'ambulatorio_atendimento_procedimento.especialidade_id')
->leftJoin('sigtap.ocupacao', 'ocupacao.id', 'ambulatorio_atendimento_procedimento.ocupacao_id')
->leftJoin('sigtap.procedimento', 'procedimento.id', 'ambulatorio_atendimento_procedimento.procedimento_id')
->leftJoin('ambulatorio_atendimento_soap_ferida_material', 'ambulatorio_atendimento_soap_ferida_material.atendimento_procedimento_id', 'ambulatorio_atendimento_procedimento.id')
->leftJoin('cadastro_material', 'cadastro_material.id', 'ambulatorio_atendimento_soap_ferida_material.material_id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->when($params->ocupacao_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.ocupacao_id', $id))
->when($params->especialidade_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.especialidade_id', $id))
->when($params->usuario_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.usuario_id', $id))
->when($params->feridas, fn ($q, $ids) => $q->whereIn('ambulatorio_atendimento_soap_ferida.ferida_id', $ids))
->when($params->status, fn ($q, $status) => $q->where(function ($q) use ($status) {
if ($status === 'cicatrizada') {
$q->orWhere('ambulatorio_atendimento_soap_ferida.cicatrizada', true);
}
else if ($status === 'não_cicatrizada') {
$q->orWhere('ambulatorio_atendimento_soap_ferida.cicatrizada', false);
}
else if ($status === 'indefinido') {
$q->orWhereNull('ambulatorio_atendimento_soap_ferida.cicatrizada');
}
}))
->when($params->procedimentos, fn ($q, $ids) => $q->whereIn('ambulatorio_atendimento_procedimento.procedimento_id', $ids))
->when($params->paciente_id, fn ($q, $id) => $q->where('cadastro_paciente.id', $id))
->groupBy([
DB::raw("DATE_FORMAT(ambulatorio_demanda_espontanea.data, '%d/%m/%Y')"),
'ambulatorio_atendimento.id',
'cadastro_paciente.id',
'cadastro_cidadao_paciente.nome',
DB::raw("DATE_FORMAT(cadastro_cidadao_paciente.data_nascimento, '%d/%m/%Y')"),
DB::raw("LPAD(cadastro_paciente.prontuario, 6, '0')"),
'cadastro_unidade.nome_fantasia',
'cadastro_cidadao_usuario.nome',
'cadastro_ferida.nome',
'cadastro_especialidade.nome',
'ocupacao.codigo',
DB::raw("
CASE WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = TRUE THEN
'Cicatrizada'
WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = FALSE THEN
'Não Cicatrizada'
ELSE
'Indefinido'
END
"),
])
)
->groupBy([
DB::raw("DATE_FORMAT(ambulatorio_jornada.data, '%d/%m/%Y')"),
'ambulatorio_atendimento.id',
'cadastro_paciente.id',
'cadastro_cidadao_paciente.nome',
DB::raw("DATE_FORMAT(cadastro_cidadao_paciente.data_nascimento, '%d/%m/%Y')"),
DB::raw("LPAD(cadastro_paciente.prontuario, 6, '0')"),
'cadastro_unidade.nome_fantasia',
'cadastro_cidadao_usuario.nome',
'cadastro_ferida.nome',
'cadastro_especialidade.nome',
'ocupacao.codigo',
DB::raw("
CASE WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = TRUE THEN
'Cicatrizada'
WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = FALSE THEN
'Não Cicatrizada'
ELSE
'Indefinido'
END
"),
])
->get();
return [
'totalizadores' => [
'pacientes_distintos_atendidos' => count($itens->pluck('paciente_id')->unique()),
'atendimentos_realizados' => count($itens->pluck('atendimento_id')->unique()),
'soaps_geradas' => $itens->sum('soaps_geradas'),
'feridas_registradas' => $itens->sum('feridas_registradas'),
'procedimentos_lancados' => $itens->sum('procedimentos_lancados'),
'kits_materiais_consumidos' => $itens->sum('kits_materiais_consumidos'),
'valor_custo_procedimento' => number_format($itens->sum('valor_custo_procedimento'), 2, ',', '.'),
'valor_custo_material' => number_format($itens->sum('valor_custo_material'), 2, ',', '.'),
'valor_custo_total' => number_format($itens->sum('valor_total'), 2, ',', '.'),
],
'itens' => $itens->map(function ($item) {
return [
'data' => $item->data,
'paciente_nome' => $item->paciente_nome,
'paciente_data_nascimento' => $item->paciente_data_nascimento,
'paciente_prontuario' => $item->paciente_prontuario,
'unidade_nome_fantasia' => $item->unidade_nome_fantasia,
'usuario_nome' => $item->usuario_nome,
'ferida_nome' => $item->ferida_nome,
'especialidade_nome' => $item->especialidade_nome,
'ocupacao_codigo' => $item->ocupacao_codigo,
'status' => $item->status,
'procedimentos' => $item->procedimentos,
'materiais' => $item->materiais,
'valor_total' => number_format($item->valor_total, 2, ',', '.'),
];
}),
];
}
public static function create()
{
return [
'additionals' => [
'data_atual' => Carbon::now()->format('d/m/Y'),
],
'form' => [
'unidades' => [],
'infraestruturas' => [],
'ocupacoes' => [],
'especialidades' => [],
'usuarios' => [],
'feridas' => [],
'status' => [],
'procedimentos' => [],
],
'model' => [
'periodo' => ['start' => null, 'end' => null],
'unidade_id' => null,
'infraestrutura_id' => null,
'ocupacao_id' => null,
'especialidade_id' => null,
'usuario_id' => null,
'feridas' => null,
'status' => null,
'procedimentos' => null,
],
];
}
public static function autocomplete()
{
$params = self::getParams();
return DB::table('cadastro_paciente')
->select([
'cadastro_paciente.id',
'cadastro_cidadao.nome',
'cadastro_cidadao.nome_social',
'cadastro_cidadao.cns',
])
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida_procedimento')
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->when($params->ocupacao_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.ocupacao_id', $id))
->when($params->especialidade_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.especialidade_id', $id))
->when($params->usuario_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.usuario_id', $id))
->when($params->feridas, fn ($q, $ids) => $q->whereIn('ambulatorio_atendimento_soap_ferida.ferida_id', $ids))
->when($params->status, fn ($q, $status) => $q->where(function ($q) use ($status) {
if ($status === 'cicatrizada') {
$q->orWhere('ambulatorio_atendimento_soap_ferida.cicatrizada', true);
}
else if ($status === 'não_cicatrizada') {
$q->orWhere('ambulatorio_atendimento_soap_ferida.cicatrizada', false);
}
else if ($status === 'indefinido') {
$q->orWhereNull('ambulatorio_atendimento_soap_ferida.cicatrizada');
}
}))
->when($params->procedimentos, fn ($q, $ids) => $q->whereIn('ambulatorio_atendimento_procedimento.procedimento_id', $ids))
->whereColumn('ambulatorio_agendamento.paciente_id', 'cadastro_paciente.id')
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida_procedimento')
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->when($params->ocupacao_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.ocupacao_id', $id))
->when($params->especialidade_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.especialidade_id', $id))
->when($params->usuario_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.usuario_id', $id))
->when($params->feridas, fn ($q, $ids) => $q->whereIn('ambulatorio_atendimento_soap_ferida.ferida_id', $ids))
->when($params->status, fn ($q, $status) => $q->where(function ($q) use ($status) {
if ($status === 'cicatrizada') {
$q->orWhere('ambulatorio_atendimento_soap_ferida.cicatrizada', true);
}
else if ($status === 'não_cicatrizada') {
$q->orWhere('ambulatorio_atendimento_soap_ferida.cicatrizada', false);
}
else if ($status === 'indefinido') {
$q->orWhereNull('ambulatorio_atendimento_soap_ferida.cicatrizada');
}
}))
->when($params->procedimentos, fn ($q, $ids) => $q->whereIn('ambulatorio_atendimento_procedimento.procedimento_id', $ids))
->whereColumn('ambulatorio_demanda_espontanea.paciente_id', 'cadastro_paciente.id')
);
}
public static function list()
{
$params = self::getParams();
switch (request()->listar) {
case 'unidades': {
return [
'unidades' => self::getUnidades($params),
'infraestruturas' => self::getInfraestruturas($params),
'ocupacoes' => self::getOcupacoes($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'feridas' => self::getFeridas($params),
'status' => self::getStatus($params),
'procedimentos' => self::getProcedimentos($params),
];
}
case 'infraestruturas': {
return [
'infraestruturas' => self::getInfraestruturas($params),
'ocupacoes' => self::getOcupacoes($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'feridas' => self::getFeridas($params),
'status' => self::getStatus($params),
'procedimentos' => self::getProcedimentos($params),
];
}
case 'ocupacoes': {
return [
'ocupacoes' => self::getOcupacoes($params),
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'feridas' => self::getFeridas($params),
'status' => self::getStatus($params),
'procedimentos' => self::getProcedimentos($params),
];
}
case 'especialidades': {
return [
'especialidades' => self::getEspecialidades($params),
'usuarios' => self::getUsuarios($params),
'feridas' => self::getFeridas($params),
'status' => self::getStatus($params),
'procedimentos' => self::getProcedimentos($params),
];
}
case 'usuarios': {
return [
'usuarios' => self::getUsuarios($params),
'feridas' => self::getFeridas($params),
'status' => self::getStatus($params),
'procedimentos' => self::getProcedimentos($params),
];
}
case 'feridas': {
return [
'feridas' => self::getFeridas($params),
'status' => self::getStatus($params),
'procedimentos' => self::getProcedimentos($params),
];
}
case 'status': {
return [
'status' => self::getStatus($params),
'procedimentos' => self::getProcedimentos($params),
];
}
case 'procedimentos': {
return [
'procedimentos' => self::getProcedimentos($params),
];
}
}
}
private static function getParams()
{
return (object) [
'periodo' => [
'start' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['start'])->setTime(0, 0, 0),
'end' => Carbon::createFromFormat('d/m/Y', request()->get('periodo')['end'])->setTime(23, 59, 59)
],
'unidade_id' => request()->get('unidade_id'),
'infraestrutura_id' => request()->get('infraestrutura_id'),
'ocupacao_id' => request()->get('ocupacao_id'),
'especialidade_id' => request()->get('especialidade_id'),
'usuario_id' => request()->get('usuario_id'),
'feridas' => request()->get('feridas'),
'status' => request()->get('status'),
'procedimentos' => request()->get('procedimentos'),
'paciente_id' => request()->get('paciente')['id'] ?? null,
];
}
private static function getUnidades($params)
{
return DB::table('cadastro_unidade')
->select([
'cadastro_unidade.id',
'cadastro_unidade.nome_fantasia'
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->whereColumn('cadastro_infraestrutura.unidade_id', 'cadastro_unidade.id')
)
->orderBy('cadastro_unidade.nome_fantasia')
->get();
}
private static function getInfraestruturas($params)
{
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')
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_unidade.id', $id))
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->whereColumn('cadastro_lotacao.infraestrutura_id', 'cadastro_infraestrutura.id')
)
->orderByRaw("COALESCE(cadastro_infraestrutura.nome, cadastro_unidade.nome_fantasia)")
->get();
}
private static function getOcupacoes($params)
{
return DB::table('sigtap.ocupacao')
->select([
'ocupacao.id',
DB::raw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome) AS nome"),
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida_procedimento')
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->whereColumn('ambulatorio_atendimento_procedimento.ocupacao_id', 'ocupacao.id')
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida_procedimento')
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->whereColumn('ambulatorio_atendimento_procedimento.ocupacao_id', 'ocupacao.id')
)
->orderByRaw("CONCAT(ocupacao.codigo, ' - ', ocupacao.nome)")
->get();
}
private static function getEspecialidades($params)
{
return DB::table('cadastro_especialidade')
->select([
'cadastro_especialidade.id',
'cadastro_especialidade.nome',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida_procedimento')
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->when($params->ocupacao_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.ocupacao_id', $id))
->whereColumn('ambulatorio_atendimento_procedimento.especialidade_id', 'cadastro_especialidade.id')
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida_procedimento')
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->when($params->ocupacao_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.ocupacao_id', $id))
->whereColumn('ambulatorio_atendimento_procedimento.especialidade_id', 'cadastro_especialidade.id')
)
->orderBy('cadastro_especialidade.nome')
->get();
}
private static function getUsuarios($params)
{
return DB::table('cadastro_usuario')
->select([
'cadastro_usuario.id',
'cadastro_cidadao.nome',
])
->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_usuario.cidadao_id')
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida_procedimento')
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->when($params->ocupacao_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.ocupacao_id', $id))
->when($params->especialidade_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.especialidade_id', $id))
->whereColumn('ambulatorio_atendimento_procedimento.usuario_id', 'cadastro_usuario.id')
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida_procedimento')
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->when($params->ocupacao_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.ocupacao_id', $id))
->when($params->especialidade_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.especialidade_id', $id))
->whereColumn('ambulatorio_atendimento_procedimento.usuario_id', 'cadastro_usuario.id')
)
->orderBy('cadastro_cidadao.nome')
->get();
}
private static function getFeridas($params)
{
return DB::table('cadastro_ferida')
->select([
'cadastro_ferida.id',
'cadastro_ferida.nome',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida_procedimento')
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->when($params->ocupacao_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.ocupacao_id', $id))
->when($params->especialidade_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.especialidade_id', $id))
->when($params->usuario_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.usuario_id', $id))
->whereColumn('ambulatorio_atendimento_soap_ferida.ferida_id', 'cadastro_ferida.id')
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida_procedimento')
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->when($params->ocupacao_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.ocupacao_id', $id))
->when($params->especialidade_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.especialidade_id', $id))
->when($params->usuario_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.usuario_id', $id))
->whereColumn('ambulatorio_atendimento_soap_ferida.ferida_id', 'cadastro_ferida.id')
)
->orderBy('cadastro_ferida.nome')
->get();
}
private static function getStatus($params)
{
return DB::table('ambulatorio_atendimento_soap_ferida_procedimento')
->select([
DB::raw("
CASE WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = TRUE THEN
'cicatrizada'
WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = FALSE THEN
'não_cicatrizada'
ELSE
'indefinido'
END AS value
"),
DB::raw("
CASE WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = TRUE THEN
'Cicatrizada'
WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = FALSE THEN
'Não Cicatrizada'
ELSE
'Indefinido'
END AS text
"),
])
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->when($params->ocupacao_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.ocupacao_id', $id))
->when($params->especialidade_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.especialidade_id', $id))
->when($params->usuario_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.usuario_id', $id))
->when($params->feridas, fn ($q, $ids) => $q->whereIn('ambulatorio_atendimento_soap_ferida.ferida_id', $ids))
->unionAll(
DB::table('ambulatorio_atendimento_soap_ferida_procedimento')
->select([
DB::raw("
CASE WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = TRUE THEN
'cicatrizada'
WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = FALSE THEN
'não_cicatrizada'
ELSE
'indefinido'
END AS value
"),
DB::raw("
CASE WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = TRUE THEN
'Cicatrizada'
WHEN ambulatorio_atendimento_soap_ferida.cicatrizada = FALSE THEN
'Não Cicatrizada'
ELSE
'Indefinido'
END AS text
"),
])
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->when($params->ocupacao_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.ocupacao_id', $id))
->when($params->especialidade_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.especialidade_id', $id))
->when($params->usuario_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.usuario_id', $id))
->when($params->feridas, fn ($q, $ids) => $q->whereIn('ambulatorio_atendimento_soap_ferida.ferida_id', $ids))
->distinct()
)
->distinct()
->get();
}
private static function getProcedimentos($params)
{
return DB::table('sigtap.procedimento')
->select([
'procedimento.id',
'procedimento.codigo',
'procedimento.nome',
])
->whereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida_procedimento')
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id')
->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->whereBetween('ambulatorio_jornada.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->when($params->ocupacao_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.ocupacao_id', $id))
->when($params->especialidade_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.especialidade_id', $id))
->when($params->usuario_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.usuario_id', $id))
->when($params->feridas, fn ($q, $ids) => $q->whereIn('ambulatorio_atendimento_soap_ferida.ferida_id', $ids))
->when($params->status, fn ($q, $status) => $q->where(function ($q) use ($status) {
if ($status === 'cicatrizada') {
$q->orWhere('ambulatorio_atendimento_soap_ferida.cicatrizada', true);
}
else if ($status === 'não_cicatrizada') {
$q->orWhere('ambulatorio_atendimento_soap_ferida.cicatrizada', false);
}
else if ($status === 'indefinido') {
$q->orWhereNull('ambulatorio_atendimento_soap_ferida.cicatrizada');
}
}))
->whereColumn('ambulatorio_atendimento_procedimento.procedimento_id', 'procedimento.id')
)
->orWhereExists(fn ($q) => $q
->select(DB::raw(1))
->from('ambulatorio_atendimento_soap_ferida_procedimento')
->join('ambulatorio_atendimento_procedimento', 'ambulatorio_atendimento_procedimento.id', 'ambulatorio_atendimento_soap_ferida_procedimento.atendimento_procedimento_id')
->join('ambulatorio_atendimento_soap_ferida', 'ambulatorio_atendimento_soap_ferida.id', 'ambulatorio_atendimento_soap_ferida_procedimento.soap_ferida_id')
->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', 'ambulatorio_atendimento_soap_ferida.soap_id')
->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_soap.atendimento_id')
->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id')
->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_demanda_espontanea.created_lotacao_id')
->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id')
->where('ambulatorio_atendimento_soap.is_rascunho', false)
->whereBetween('ambulatorio_demanda_espontanea.data', $params->periodo)
->when($params->unidade_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.unidade_id', $id))
->when($params->infraestrutura_id, fn ($q, $id) => $q->where('cadastro_infraestrutura.id', $id))
->when($params->ocupacao_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.ocupacao_id', $id))
->when($params->especialidade_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.especialidade_id', $id))
->when($params->usuario_id, fn ($q, $id) => $q->where('ambulatorio_atendimento_procedimento.usuario_id', $id))
->when($params->feridas, fn ($q, $ids) => $q->whereIn('ambulatorio_atendimento_soap_ferida.ferida_id', $ids))
->when($params->status, fn ($q, $status) => $q->where(function ($q) use ($status) {
if ($status === 'cicatrizada') {
$q->orWhere('ambulatorio_atendimento_soap_ferida.cicatrizada', true);
}
else if ($status === 'não_cicatrizada') {
$q->orWhere('ambulatorio_atendimento_soap_ferida.cicatrizada', false);
}
else if ($status === 'indefinido') {
$q->orWhereNull('ambulatorio_atendimento_soap_ferida.cicatrizada');
}
}))
->whereColumn('ambulatorio_atendimento_procedimento.procedimento_id', 'procedimento.id')
)
->orderBy('procedimento.nome')
->get()
->map(function ($procedimento) {
$procedimento->nome = MaskUtil::getProcedimentoMasked($procedimento->codigo) . " - {$procedimento->nome}";
return $procedimento;
});
}
public static function getPrintExportData()
{
$itens = RelatorioRastreioFeridaService::index();
$unidade = Unidade::find(request()->unidade_id);
$infraestrutura = Infraestrutura::find(request()->infraestrutura_id);
$especialidade = Especialidade::find(request()->especialidade_id);
$usuario = Usuario::find(request()->usuario_id);
$ocupacao = Ocupacao::find(request()->ocupacao_id);
$status = request()->status_id;
if (!is_null($status)) {
switch ($status) {
case FeridaStatus::ATIVO:
$status = (object) ['nome' => 'Ativo'];
break;
case FeridaStatus::CICATRIZADA:
$status = (object) ['nome' => 'Cicatrizada'];
break;
default:
break;
}
}else{
$status = (object) ['nome' => 'Todos'];
}
if (isset($itens['atendimentos']) && is_array($itens['atendimentos'])) {
$itens['atendimentos'] = collect($itens['atendimentos'])->map(function ($atendimento) {
switch ((int) ($atendimento['cicatrizada'] ?? -1)) {
case FeridaStatus::ATIVO:
$atendimento['cicatrizada'] = 'Ativo';
break;
case FeridaStatus::CICATRIZADA:
$atendimento['cicatrizada'] = 'Cicatrizada';
break;
default:
$atendimento['cicatrizada'] = '-';
break;
}
return $atendimento;
})->toArray();
}
return [
'periodo' => [
'inicio' => request()->periodo['start'],
'fim' => request()->periodo['end'],
],
'unidade' => $unidade->nome_fantasia ?? 'Todas',
'infraestrutura' => $infraestrutura->nome ?? 'Todas',
'especialidade' => $especialidade->nome ?? 'Todas',
'usuario' => $usuario->nome ?? 'Todos',
'cbo' => $ocupacao->codigo ?? 'Todos',
'status' => $status->nome,
'colunas' => collect(request()->columns),
'itens' => $itens,
];
}
}

View File

@@ -0,0 +1,100 @@
<?php
namespace App\Services\Ambulatorio;
use App\Models\Ambulatorio\Servico;
use App\Models\Ambulatorio\ServicoTipo;
use App\Services\Service;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
class ServicoService extends Service
{
public static function datatable()
{
return DB::table('ambulatorio_servico as servico')
->leftJoin(
'ambulatorio_servico_tipo as tipo',
'tipo.id',
'servico.tipo_id'
)
->select(
'servico.id',
'servico.nome',
DB::raw('tipo.nome as tipo'),
);
}
public static function create()
{
return [
'form' => self::getForm(),
'model' => [
'nome' => null,
'tipo_id' => null,
]
];
}
public static function edit($id)
{
$servico = Servico::findOrFail($id);
return [
'form' => self::getForm(),
'model' => [
'nome' => $servico->nome,
'tipo_id' => $servico->tipo_id,
]
];
}
private static function getForm()
{
return [
'tipos' => ServicoTipo::orderBy('nome')->get(['id', 'nome']),
];
}
public static function store()
{
self::validate();
return Servico::create(request()->all())->fresh();
}
public static function update($id)
{
self::validate();
return (tap(Servico::findOrFail($id))->update(request()->all()))->fresh();
}
public static function validate()
{
$rules = [
'nome' => [
'required',
'string',
'between:3,100',
Rule::unique(Servico::class, 'nome')->ignore(request()->route('servico')),
],
'tipo_id' => [
'nullable',
'integer',
Rule::exists(ServicoTipo::class, 'id'),
],
];
$messages = [
'nome.unique' => 'O nome do Serviço já foi inserido anteriormente.',
];
request()->validate($rules, $messages);
}
public static function destroy($id)
{
Servico::findOrFail($id)->delete();
}
}

View File

@@ -0,0 +1,144 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Ambulatorio\AgendamentoTipo;
use App\Models\Ambulatorio\Agendamento;
use App\Models\Ambulatorio\ParametrizacaoInfraestrutura;
use App\Models\Geral\DiaSemana;
use App\Services\Service;
use App\Services\Sms\SmsService as BaseSmsService;
use App\Utils\MaskUtil;
use Carbon\Carbon;
use Illuminate\Support\Str;
use RuntimeException;
class SmsService extends Service
{
private $baseSmsService;
private $agendamento;
private $parametrizacao;
public function __construct($agendamentoId)
{
$this->baseSmsService = new BaseSmsService();
$this->agendamento = Agendamento::findOrFail($agendamentoId);
$this->parametrizacao = ParametrizacaoInfraestrutura::where(
'infraestrutura_id',
$this->agendamento->jornada->lotacao->infraestrutura_id
)->first();
}
public function send()
{
if ($this->agendamento->jornada->data->isToday()) {
return;
}
$cellPhone = $this->getCellPhone();
if (is_null($cellPhone)) {
return;
}
if (!$this->parametrizacao->envia_sms || ($this->parametrizacao->envia_sms && is_null($this->parametrizacao->sms))) {
return;
}
$schedule = $this->getSchedule();
if (!$this->isAllowedToSend($schedule)) {
return;
}
try {
$smsEnvio = $this->baseSmsService->send($cellPhone, $this->getMessage(), $schedule);
$this->agendamento->sms_envio_id = $smsEnvio->id;
$this->agendamento->save();
}
catch (RuntimeException $e) {}
}
private function isAllowedToSend($schedule)
{
if (is_null($schedule)) {
$schedule = Carbon::now();
}
$envioDe = $this->parametrizacao->sms->envio_de->startOfDay();
$envioAte = $this->parametrizacao->sms->envio_ate->endOfDay();
if ($schedule >= $envioDe && $schedule <= $envioAte) {
return $this->parametrizacao->sms->especialidades->pluck('id')
->contains($this->agendamento->jornada->especialidade_id);
}
return false;
}
private function getCellPhone()
{
return $this->agendamento->paciente->cidadao->telefones()
->where('autoriza_sms', true)
->first()->numero ?? null;
}
private function getMessage()
{
$nomePaciente = $this->agendamento->paciente->cidadao->nome;
$agendamentoTipo = Str::lower($this->agendamento->tipo->nome);
$especialidade = $this->agendamento->jornada->especialidade->nome;
$data = $this->agendamento->jornada->data->format('d/m/Y');
$diaSemana = DiaSemana::findOrFail($this->agendamento->jornada->dia_semana)->descricao;
$horario = $this->agendamento->horario->format('H:i');
$unidade = $this->agendamento->jornada->lotacao->infraestrutura->unidade->nome_fantasia;
$infraestrutura = $this->agendamento->jornada->lotacao->infraestrutura->nome;
$usuario = $this->agendamento->jornada->lotacao->usuario->cidadao->nome;
$telefone = MaskUtil::getPhoneMasked(
$this->agendamento->jornada->lotacao->infraestrutura->telefone
);
$pronomeAgendamentoTipo = $this->agendamento->tipo_id === AgendamentoTipo::CONSULTA ? 'sua' : 'seu';
$unidade .= $infraestrutura === $unidade ? '' : " ({$infraestrutura})";
return "Sr(a) {$nomePaciente}, {$pronomeAgendamentoTipo} {$agendamentoTipo} para a especialidade"
. " {$especialidade} está agendada para {$data} ({$diaSemana}) às {$horario} na unidade {$unidade} com"
. " o profissional {$usuario}. Caso não possa comparecer, entrar em contato no telefone {$telefone}";
}
private function getSchedule()
{
$schedule = $this->agendamento->jornada->data->copy()->subDays($this->parametrizacao->sms->dia_antecedencia);
if ($schedule <= Carbon::today()) {
return null;
}
return $schedule;
}
public function cancel()
{
if (is_null($this->agendamento->sms_envio_id)) {
return;
}
try {
$this->baseSmsService->cancel($this->agendamento->sms_envio_id);
}
catch (RuntimeException $e) {}
}
}

View File

@@ -0,0 +1,834 @@
<?php
namespace App\Services\Ambulatorio;
use App\Enums\Ambulatorio\ProblemaCondicaoSituacao;
use App\Enums\AtencaoBasica\AtendimentoIndividual\CondicaoAvaliada;
use App\Enums\AtencaoBasica\AtendimentoIndividual\Conduta as AtendimentoIndividualConduta;
use App\Enums\AtencaoBasica\AtendimentoIndividual\TipoAtendimento;
use App\Enums\AtencaoBasica\AtendimentoOdontologico\CondutaEncaminhamento as AtendimentoOdontologicoCondutaEncaminhamento;
use App\Enums\AtencaoBasica\AtendimentoOdontologico\Fornecimento;
use App\Enums\AtencaoBasica\AtendimentoOdontologico\Procedimento;
use App\Enums\AtencaoBasica\Avaliacao\Cuidador as EnumCuidador;
use App\Enums\Geral\Ciap;
use App\Enums\Sigtap\Procedimento as SigtapProcedimento;
use App\Models\Administracao\Funcionalidade;
use App\Models\Ambulatorio\AtendimentoSoap;
use App\Models\Ambulatorio\AtendimentoSoapProblemaCondicao;
use App\Models\Ambulatorio\ParametrizacaoInfraestruturaOcupacao;
use App\Models\AtencaoBasica\AtendimentoIndividual\AtendimentoIndividual;
use App\Models\AtencaoBasica\AtendimentoIndividual\ExameSolicitadoAvaliado;
use App\Models\AtencaoBasica\AtendimentoIndividual\TriagemNeonatal;
use App\Models\AtencaoBasica\AtendimentoOdontologico\AtendimentoOdontologico;
use App\Models\AtencaoBasica\Avaliacao\Avaliacao;
use App\Models\AtencaoBasica\MarcadorConsumoAlimentar\MarcadorConsumoAlimentar;
use App\Services\AtencaoBasica\AtendimentoDomiciliar\AtendimentoDomiciliarService;
use App\Services\AtencaoBasica\AtendimentoIndividual\AtendimentoIndividualService;
use App\Services\AtencaoBasica\AtendimentoOdontologico\AtendimentoOdontologicoService;
use App\Services\AtencaoBasica\Avaliacao\AvaliacaoService;
use App\Services\AtencaoBasica\MarcadorConsumoAlimentar\MarcadorConsumoAlimentarService;
use App\Services\Service;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class SoapAtencaoBasicaFichaService extends Service
{
public static function store($soap, $data = [])
{
if (is_null($soap->equipe_id)) {
return;
}
if ($soap->is_atendimento_saude_bucal) {
self::storeAtendimentoOdontologico($soap);
}
else {
self::storeAtendimentoIndividual($soap, $data);
}
self::storeMarcadorConsumoAlimentar($soap, $data['marcador_consumo_alimentar']);
self::storeAtendimentoDomiciliar($soap, $data);
self::storeAvaliacao($soap, $data);
}
public static function storeAtendimentoOdontologico($soap)
{
if (!self::criaFicha($soap, 'atendimento-odontologico')) {
return;
}
$getCondutas = function () use ($soap) {
return $soap->condutas->map(function ($conduta) {
switch ($conduta->id) {
case AtendimentoIndividualConduta::RETORNO_PARA_CONSULTA_AGENDADA:
return AtendimentoOdontologicoCondutaEncaminhamento::RETORNO_CONSULTA_AGENDADA;
case AtendimentoIndividualConduta::AGENDAMENTO_PARA_GRUPOS:
return AtendimentoOdontologicoCondutaEncaminhamento::AGENDAMENTO_GRUPOS;
case AtendimentoIndividualConduta::AGENDAMENTO_PARA_NASF:
return AtendimentoOdontologicoCondutaEncaminhamento::AGENDAMENTO_NASF;
case AtendimentoIndividualConduta::ALTA_DO_EPISODIO:
return AtendimentoOdontologicoCondutaEncaminhamento::ALTA_EPISODIO;
case AtendimentoIndividualConduta::AGENDAMENTO_PARA_E_MULTI:
return AtendimentoOdontologicoCondutaEncaminhamento::AGENDAMENTO_PARA_E_MULTI;
case AtendimentoIndividualConduta::RETORNO_PARA_CUIDADO_CONTINUADO_PROGRAMADO:
return AtendimentoOdontologicoCondutaEncaminhamento::RETORNO_CONSULTA_AGENDADA;
case AtendimentoIndividualConduta::TRATAMENTO_CONCLUIDO:
return AtendimentoOdontologicoCondutaEncaminhamento::TRATAMENTO_CONCLUIDO;
}
})
->filter();
};
$getProcedimentos = function () use ($soap) {
$procedimentos = $soap->procedimentos()
->get()
->map(fn ($atendimentoProcedimento) => [
'codigo' => $atendimentoProcedimento->procedimento->codigo,
'quantidade' => $atendimentoProcedimento->quantidade,
])
->all();
if ($soap->orientacao_individual_em_saude) {
$procedimentos[] = [
'codigo' => Procedimento::ORIENTACAO_INDIVIDUAL_EM_SAUDE,
'quantidade' => 1,
];
}
return $procedimentos;
};
$getCondicoesAvaliadas = function () use ($soap) {
$condicoes = $soap->condicoesAvaliadas->pluck('id');
if ($soap->is_atendimento_pre_natal) {
$condicoes->push(CondicaoAvaliada::PRE_NATAL);
}
if ($soap->is_atendimento_puericultura) {
$condicoes->push(CondicaoAvaliada::PUERICULTURA);
}
return $condicoes->all();
};
$problemasCondicoes = AtendimentoSoapProblemaCondicao::where('soap_id', $soap->id)
->get()
->map(fn ($problemaCondicao) => [
'ciap' => is_null($problemaCondicao->ciap_id) ? null : [
'id' => $problemaCondicao->ciap->id,
],
'cid' => is_null($problemaCondicao->cid_id) ? null : [
'id' => $problemaCondicao->cid->id,
],
]);
$existeSoap = AtendimentoSoap::where('atendimento_id', $soap->atendimento_id)
->get(['id', 'turno_id'])
->toArray();
$atOdontologico = AtendimentoOdontologico::whereIn('soap_id', array_column($existeSoap, 'id'))
->get(['id', 'turno_id', 'data_atendimento']);
$atOdontId = null;
foreach ($atOdontologico as $odontologico) {
if ($odontologico->turno_id == $soap->turno_id &&
$odontologico->data_atendimento == $soap->created_at->format('Y-m-d')) {
$atOdontId = $odontologico->id;
break;
}
}
$tipoAtendimentoId = $soap->atendimento_tipo_id;
$procedimentos = [
SigtapProcedimento::TELECONSULTA_NA_ATENCAO_PRIMARIA,
SigtapProcedimento::TELECONSULTA_POR_PROFISSIONAIS_DE_NIVEL_SUPERIOR_NA_ATENCAO_ESPECIALIZADA_EXCETO_MEDICO,
SigtapProcedimento::TELECONSULTA_MEDICA_NA_ATENCAO_ESPECIALIZADA,
];
$soap->procedimentos()
->get()
->each(function ($soapProcedimento) use (&$tipoAtendimentoId, $procedimentos) {
if (in_array($soapProcedimento->procedimento->codigo, $procedimentos)) {
$tipoAtendimentoId = TipoAtendimento::CONSULTA_AGENDADA;
}
});
if(empty($atOdontId)){
AtendimentoOdontologicoService::saveStore([
'soap_id' => $soap->id,
'paciente_id' => $soap->atendimento->paciente->id,
'usuario_id' => $soap->createdLotacao->usuario_id,
'ocupacao_id' => $soap->createdLotacao->ocupacao_id,
'usuario_auxiliar_id ' => null,
'ocupacao_auxiliar_id ' => null,
'data_atendimento' => $soap->created_at->format('Y-m-d'),
'turno_id' => $soap->turno_id,
'local_atendimento_id' => $soap->atencao_basica_local_atendimento_id,
'tipo_atendimento_id' => $tipoAtendimentoId,
'tipo_consulta_id' => $soap->saude_bucal_consulta_tipo_id,
'necessidades_especiais' => $soap->paciente_com_necessidade_especial ?? false,
'gestante' => AtendimentoService::isPacienteGestante($soap),
'unidade_id' => $soap->createdCentroCusto->infraestrutura->unidade_id,
'equipe_id' => $soap->equipe_id,
'equipe_auxiliar_id ' => null,
'escova_dental' => $soap->saudeBucalFornecimentos()->where('id', Fornecimento::ESCOVA_DENTAL)->exists(),
'creme_dental' => $soap->saudeBucalFornecimentos()->where('id', Fornecimento::CREME_DENTAL)->exists(),
'fio_dental' => $soap->saudeBucalFornecimentos()->where('id', Fornecimento::FIO_DENTAL)->exists(),
'vigilancia' => $soap->saudeBucalVigilancias->pluck('codigo_esus'),
'conduta_encaminhamento' => $getCondutas(),
'procedimentos' => $getProcedimentos($soap),
'condicao_avaliada' => $getCondicoesAvaliadas(),
'doenca_transmissivel' => $soap->doencasTransmissiveis->pluck('id')->all(),
'rastreamento' => $soap->rastreamentos->pluck('id')->all(),
'problemas_condicoes' => $problemasCondicoes,
'medicoes' => [
'perimetro_cefalico' => $soap->objetivoAntropometria->atendimentoAntropometria->perimetro_cefalico ?? null,
'circunferencia_abdominal' => $soap->objetivoAntropometria->atendimentoAntropometria->circunferencia_abdominal ?? null,
'perimetro_panturrilha' => $soap->objetivoAntropometria->atendimentoAntropometria->perimetro_panturrilha ?? null,
'peso' => $soap->objetivoAntropometria->atendimentoAntropometria->peso ?? null,
'altura' => $soap->objetivoAntropometria->atendimentoAntropometria->altura ?? null,
'temperatura' => $soap->objetivoSinalVital->atendimentoSinalVital->temperatura ?? null,
'pressao_arterial' => $soap->objetivoSinalVital->atendimentoSinalVital->pressao_arterial ?? null,
'frequencia_respiratoria' => $soap->objetivoSinalVital->atendimentoSinalVital->frequencia_respiratoria ?? null,
'frequencia_cardiaca' => $soap->objetivoSinalVital->atendimentoSinalVital->frequencia_cardiaca ?? null,
'saturacao_o2' => $soap->objetivoSinalVital->atendimentoSinalVital->saturacao_o2 ?? null,
'glicemia' => $soap->objetivoGlicemiaCapilar->atendimentoGlicemiaCapilar->valor ?? null,
'momento_coleta_id' => $soap->objetivoGlicemiaCapilar->atendimentoGlicemiaCapilar->momento_coleta_id ?? null,
],
'ivcf' => array_merge(
[
'deseja_preencher' => $soap->ivcf ? true : false,
],
$soap->ivcf ? $soap->ivcf->toArray() : [],
),
]);
}else {
AtendimentoOdontologicoService::update($atOdontId,
[
'id' => $atOdontId,
'soap_id' => $soap->id,
'paciente_id' => $soap->atendimento->paciente->id,
'usuario_id' => $soap->createdLotacao->usuario_id,
'ocupacao_id' => $soap->createdLotacao->ocupacao_id,
'usuario_auxiliar_id' => null,
'ocupacao_auxiliar_id' => null,
'data_atendimento' => $soap->created_at->format('Y-m-d'),
'turno_id' => $soap->turno_id,
'local_atendimento_id' => $soap->atencao_basica_local_atendimento_id,
'tipo_atendimento_id' => $tipoAtendimentoId,
'tipo_consulta_id' => $soap->saude_bucal_consulta_tipo_id,
'necessidades_especiais' => $soap->paciente_com_necessidade_especial ?? false,
'gestante' => AtendimentoService::isPacienteGestante($soap),
'unidade_id' => $soap->createdCentroCusto->infraestrutura->unidade_id,
'equipe_id' => $soap->equipe_id,
'equipe_auxiliar_id ' => null,
'escova_dental' => $soap->saudeBucalFornecimentos()->where('id', Fornecimento::ESCOVA_DENTAL)->exists(),
'creme_dental' => $soap->saudeBucalFornecimentos()->where('id', Fornecimento::CREME_DENTAL)->exists(),
'fio_dental' => $soap->saudeBucalFornecimentos()->where('id', Fornecimento::FIO_DENTAL)->exists(),
'vigilancia' => $soap->saudeBucalVigilancias->pluck('codigo_esus'),
'conduta_encaminhamento' => $getCondutas(),
'procedimentos' => $getProcedimentos($soap),
'condicao_avaliada' => $getCondicoesAvaliadas(),
'doenca_transmissivel' => $soap->doencasTransmissiveis->pluck('id')->all(),
'rastreamento' => $soap->rastreamentos->pluck('id')->all(),
'problemas_condicoes' => $problemasCondicoes,
'medicoes' => [
'perimetro_cefalico' => $soap->objetivoAntropometria->atendimentoAntropometria->perimetro_cefalico ?? null,
'circunferencia_abdominal' => $soap->objetivoAntropometria->atendimentoAntropometria->circunferencia_abdominal ?? null,
'perimetro_panturrilha' => $soap->objetivoAntropometria->atendimentoAntropometria->perimetro_panturrilha ?? null,
'peso' => $soap->objetivoAntropometria->atendimentoAntropometria->peso ?? null,
'altura' => $soap->objetivoAntropometria->atendimentoAntropometria->altura ?? null,
'temperatura' => $soap->objetivoSinalVital->atendimentoSinalVital->temperatura ?? null,
'pressao_arterial' => $soap->objetivoSinalVital->atendimentoSinalVital->pressao_arterial ?? null,
'frequencia_respiratoria' => $soap->objetivoSinalVital->atendimentoSinalVital->frequencia_respiratoria ?? null,
'frequencia_cardiaca' => $soap->objetivoSinalVital->atendimentoSinalVital->frequencia_cardiaca ?? null,
'saturacao_o2' => $soap->objetivoSinalVital->atendimentoSinalVital->saturacao_o2 ?? null,
'glicemia' => $soap->objetivoGlicemiaCapilar->atendimentoGlicemiaCapilar->valor ?? null,
'momento_coleta_id' => $soap->objetivoGlicemiaCapilar->atendimentoGlicemiaCapilar->momento_coleta_id ?? null,
]
]);
}
}
public static function storeAtendimentoIndividual($soap, $data)
{
if (!self::criaFicha($soap, 'atendimento-individual')) {
return;
}
$getProcedimentos = function () use ($soap) {
$procedimentos = collect();
$soap->procedimentos()
->get()
->each(function ($atendimentoProcedimento) use ($procedimentos) {
for ($i = 1; $i <= $atendimentoProcedimento->quantidade; $i++) {
$procedimentos->push([
'procedimento_id' => $atendimentoProcedimento->procedimento->id,
]);
}
});
return $procedimentos->all();
};
$getDpp = function () use ($soap) {
$ultimaDum = AtendimentoService::getUltimaDum($soap->atendimento->paciente);
if (!is_null($ultimaDum)) {
$ultimaDum = Carbon::createFromFormat('d/m/Y', $ultimaDum);
return $ultimaDum->addMonths(9)->addDays(7)->format('Y-m-d');
}
return null;
};
$getCondicoesAvaliadas = function () use ($soap) {
$condicoes = $soap->condicoesAvaliadas->pluck('id');
if ($soap->is_atendimento_pre_natal) {
$condicoes->push(CondicaoAvaliada::PRE_NATAL);
}
if ($soap->is_atendimento_puericultura) {
$condicoes->push(CondicaoAvaliada::PUERICULTURA);
}
return $condicoes->all();
};
$getExamesAvaliados = function () use ($data, $soap) {
$exames = [];
foreach ($data['exame_avaliado'] as $avaliacao) {
$exames[] = 'a_'. $avaliacao['id'];
}
foreach ($data['exame_solicitado']['exames'] as $solicitado) {
$exames[] = 's_'. $solicitado['exame_id'];
}
foreach ($soap->solicitacoesExames as $solicitacao) {
foreach ($solicitacao->itens as $item) {
if ($item->exame->codigo) {
$exameSolicitado = ExameSolicitadoAvaliado::where('codigo_procedimento', $item->exame->codigo)->first();
if ($exameSolicitado) {
$exames[] = 's_'. $exameSolicitado->id;
} else {
$exameSolicitado = TriagemNeonatal::where('codigo_procedimento', $item->exame->codigo)->first();
if ($exameSolicitado) {
$exames[] = 's_'. $exameSolicitado->id;
}
}
}
}
}
foreach ($soap->resultadosExames as $solicitacao) {
if ($solicitacao->exame->codigo) {
$exameSolicitado = ExameSolicitadoAvaliado::where('codigo_procedimento', $solicitacao->exame->codigo)->first();
if ($exameSolicitado) {
$exames[] = 'a_'. $exameSolicitado->id;
} else {
$exameSolicitado = TriagemNeonatal::where('codigo_procedimento', $solicitacao->exame->codigo)->first();
if ($exameSolicitado) {
$exames[] = 'a_'. $exameSolicitado->id;
}
}
}
}
return $exames;
};
$getTriagensNeonatal = function () use ($data) {
$exames = [];
foreach ($data['triagem_neonatal'] as $avaliacao) {
$exames[] = 'a_'. $avaliacao['id'];
}
foreach ($data['triagem_neonatal_solicitado']['exames'] as $solicitado) {
$exames[] = 's_'. $solicitado['exame_id'];
}
return $exames;
};
$getOutrosExames = function () use ($soap) {
$exames = collect();
$soap->solicitacoesExames->each(function ($solicitacao) use ($exames) {
$solicitacao->itens->each(function ($item) use ($exames) {
if (is_null($item->exame->codigo)) {
return;
}
$exames->push([
'exame_id' => $item->exame_id,
'avaliado' => false,
'solicitado' => true,
]);
});
});
$soap->resultadosExames->each(function ($resultado) use ($exames) {
if (is_null($resultado->exame->codigo)) {
return;
}
$exames->push([
'exame_id' => $resultado->exame_id,
'avaliado' => true,
'solicitado' => false,
]);
});
return $exames;
};
$idadeGestacional = ['semanas' => null, 'dias' => null];
$dataInicioGravidez = AtendimentoService::getDataInicioGravidezNaoResolvida($soap->atendimento->paciente);
if (!is_null($dataInicioGravidez)) {
$interval = Carbon::today()->diff(Carbon::createFromFormat('d/m/Y', $dataInicioGravidez));
$idadeGestacional['semanas'] = (int) floor($interval->days / 7);
$idadeGestacional['dias'] = $interval->days % 7;
}
$existeSoap = AtendimentoSoap::where('atendimento_id', $soap->atendimento_id)
->get(['id', 'turno_id'])
->toArray();
$atIndividual = AtendimentoIndividual::whereIn('soap_id', array_column($existeSoap, 'id'))
->get(['id', 'turno_id', 'data_usuario_responsavel', 'usuario_id']);
$atIndId = null;
foreach ($atIndividual as $individual) {
if ($individual->turno_id == $soap->turno_id &&
$individual->data_usuario_responsavel == $soap->created_at->format('Y-m-d') &&
$individual->usuario_id == $soap->createdLotacao->usuario_id) {
$atIndId = $individual->id;
break;
}
}
$problemasCondicoes = $soap->problemasCondicoes()
->where(fn ($q) => $q
->doesntHave('ciap')
->orWhereHas('ciap', fn ($q) => $q
->whereNotIn('codigo', [Ciap::GRAVIDEZ, Ciap::MEDICINA_PREVENTIVA_MANUTENCAO_DA_SAUDE])
)
)
->get()
->map(function ($problemaCondicao) use ($atIndId) {
$problemaCondicaoAnteriorId = null;
if ($problemaCondicao->problema_condicao_anterior_id) {
$problemaCondicaoAnteriorId = self::getProblemaCondicaoAnteriorId($problemaCondicao->problema_condicao_anterior_id, $atIndId);
}
return [
'id' => null,
'automatico' => $problemaCondicao->automatico,
'soap_problema_condicao_id' => $problemaCondicao->id,
'problema_condicao_anterior_id' => $problemaCondicaoAnteriorId,
'ciap_id' => $problemaCondicao->ciap_id,
'cid_id' => $problemaCondicao->cid_id,
'situacao_id' => $problemaCondicao->situacao_id,
'inicio' => $problemaCondicao->inicio
? $problemaCondicao->inicio->format('d/m/Y')
: null,
'fim' => $problemaCondicao->fim
? $problemaCondicao->fim->format('d/m/Y')
: null,
'observacao' => $problemaCondicao->observacao,
];
})
->toArray();
$tipoAtendimentoId = $soap->atendimento_tipo_id;
$procedimentos = [
SigtapProcedimento::TELECONSULTA_NA_ATENCAO_PRIMARIA,
SigtapProcedimento::TELECONSULTA_POR_PROFISSIONAIS_DE_NIVEL_SUPERIOR_NA_ATENCAO_ESPECIALIZADA_EXCETO_MEDICO,
SigtapProcedimento::TELECONSULTA_MEDICA_NA_ATENCAO_ESPECIALIZADA,
];
$soap->procedimentos()
->get()
->each(function ($soapProcedimento) use (&$tipoAtendimentoId, $procedimentos) {
if (in_array($soapProcedimento->procedimento->codigo, $procedimentos)) {
$tipoAtendimentoId = TipoAtendimento::CONSULTA_AGENDADA;
}
});
AtendimentoIndividualService::saveStore([
'soap_id' => $soap->id,
'paciente_id' => $soap->atendimento->paciente->id,
'complemento' => null,
'procedimentos' => $getProcedimentos($soap),
'condicao' => [
'gestante' => AtendimentoService::isPacienteGestante($soap),
],
'cadastro' => [
'data_usuario_responsavel' => $soap->created_at->format('Y-m-d'),
'unidade_id' => $soap->equipe->unidade_id,
'usuario_id' => $soap->createdLotacao->usuario_id,
'equipe_id' => $soap->equipe_id,
'ocupacao_id' => $soap->createdLotacao->ocupacao_id,
'usuario_auxiliar_id' => null,
'equipe_auxiliar_id' => null,
'ocupacao_auxiliar_id' => null,
],
'atendimento' => [
'id' => $atIndId,
'turno_id' => $soap->turno_id,
'local_atendimento_id' => $soap->atencao_basica_local_atendimento_id,
'tipo_atendimento_id' => $tipoAtendimentoId,
'perimetro_cefalico' => $soap->objetivoAntropometria->atendimentoAntropometria->perimetro_cefalico ?? null,
'circunferencia_abdominal' => $soap->objetivoAntropometria->atendimentoAntropometria->circunferencia_abdominal ?? null,
'perimetro_panturrilha' => $soap->objetivoAntropometria->atendimentoAntropometria->perimetro_panturrilha ?? null,
'peso' => $soap->objetivoAntropometria->atendimentoAntropometria->peso ?? null,
'altura' => $soap->objetivoAntropometria->atendimentoAntropometria->altura ?? null,
'temperatura' => $soap->objetivoSinalVital->atendimentoSinalVital->temperatura ?? null,
'pressao_arterial' => $soap->objetivoSinalVital->atendimentoSinalVital->pressao_arterial ?? null,
'frequencia_respiratoria' => $soap->objetivoSinalVital->atendimentoSinalVital->frequencia_respiratoria ?? null,
'frequencia_cardiaca' => $soap->objetivoSinalVital->atendimentoSinalVital->frequencia_cardiaca ?? null,
'saturacao_o2' => $soap->objetivoSinalVital->atendimentoSinalVital->saturacao_o2 ?? null,
'glicemia' => $soap->objetivoGlicemiaCapilar->atendimentoGlicemiaCapilar->valor ?? null,
'momento_coleta_id' => $soap->objetivoGlicemiaCapilar->atendimentoGlicemiaCapilar->momento_coleta_id ?? null,
'vacinacao' => $soap->vacinacao_em_dia,
'modalidade_atencao_domiciliar_id' => null,
'aleitamento_materno_id' => $soap->puericultura_aleitamento_tipo_id,
'racionalidade_saude_id' => $soap->racionalidade_saude_id,
'dum' => $soap->dum ? $soap->dum->format('Y-m-d') : null,
'idade_gestacional_semanas' => $idadeGestacional['semanas'],
'idade_gestacional_dias' => $idadeGestacional['dias'],
'data_possivel_parto' => $getDpp($soap),
'gravidez_planejada' => $soap->pre_natal_gravidez_planejada,
'gestacao_previa' => $soap->antecedente->gestas_previas ?? null,
'parto' => $soap->antecedente->partos_realizados ?? null,
'problemas_condicoes' => $problemasCondicoes,
'observacao' => null,
'condicao_avaliada' => $getCondicoesAvaliadas(),
'doenca_transmissivel' => $soap->doencasTransmissiveis->pluck('id')->all(),
'rastreamento' => $soap->rastreamentos->pluck('id')->all(),
'exame_solicitado_avaliado' => $getExamesAvaliados(),
'triagem_neonatal' => $getTriagensNeonatal(),
'outros_exames' => $getOutrosExames(),
'nasf' => [],
'conduta' => $soap->condutas->pluck('id')->all(),
'encaminhamento' => $soap->encaminhamentos->pluck('tipo_id')->all(),
'ivcf' => array_merge(
[
'deseja_preencher' => $soap->ivcf ? true : false,
],
$soap->ivcf ? $soap->ivcf->toArray() : [],
),
],
]);
}
private static function getProblemaCondicaoAnteriorId($soapProblemaCondicaoAnteriorId, $atendimentoIndividualId = null)
{
$problemaCondicaoAnteriorId = null;
$problemaCondicaoAnterior = self::getProblemaCondicaoAtendendimentoIndividual($soapProblemaCondicaoAnteriorId, $atendimentoIndividualId);
if (!is_null($problemaCondicaoAnterior)) {
$problemaCondicaoAnteriorId = self::getLastProblemaCondicaoId($problemaCondicaoAnterior->id, $problemaCondicaoAnterior->situacao_id, $atendimentoIndividualId);
}
return $problemaCondicaoAnteriorId;
}
private static function getProblemaCondicaoAtendendimentoIndividual($soapProblemaCondicaoId, $atendimentoIndividualId = null)
{
$problemaCondicaoAtendimentoIndividual = DB::table('atencao_basica_atendimento_individual_problema_condicao')
->when($atendimentoIndividualId, fn ($q) => $q->where('atendimento_individual_id', '<>', $atendimentoIndividualId))
->where('soap_problema_condicao_id', $soapProblemaCondicaoId)
->select('id', 'situacao_id')
->first();
if (is_null($problemaCondicaoAtendimentoIndividual)) {
$problemaCondicaoSoap = DB::table('ambulatorio_atendimento_soap_problema_condicao')
->where('id', $soapProblemaCondicaoId)
->select('problema_condicao_anterior_id')
->first();
if (isset($problemaCondicaoSoap->problema_condicao_anterior_id)) {
return self::getProblemaCondicaoAtendendimentoIndividual($problemaCondicaoSoap->problema_condicao_anterior_id, $atendimentoIndividualId);
}
return null;
}
return $problemaCondicaoAtendimentoIndividual;
}
private static function getLastProblemaCondicaoId($id, $situacaoId, $atendimentoIndividualId = null)
{
$proximo = DB::table('atencao_basica_atendimento_individual_problema_condicao')
->when($atendimentoIndividualId, fn ($q) => $q->where('atendimento_individual_id', '<>', $atendimentoIndividualId))
->where('problema_condicao_anterior_id', $id)
->select('id', 'situacao_id')
->first();
if (is_null($proximo)) {
if ($situacaoId == ProblemaCondicaoSituacao::RESOLVIDO) {
return null;
}
else {
return $id;
}
}
return self::getLastProblemaCondicaoId($proximo->id, $proximo->situacao_id, $atendimentoIndividualId);
}
public static function storeAtendimentoDomiciliar($soap, $data)
{
if (!self::criaFicha($soap, 'atendimento-domiciliar')) {
return;
}
$atendimentos = [];
$problemas_condicoes = [];
foreach ($data['problemas_condicoes'] as $problemaCondicao) {
$problemas_condicoes[] = [
'id' => $problemaCondicao['id'],
'ciap' => ['id' => $problemaCondicao['ciap_id']],
'cid' => ['id' => $problemaCondicao['cid_id']],
];
}
$atendimentos[] = [
'data' => $soap->created_at->format('Y-m-d'),
'paciente_id' => $soap->atendimento->paciente->id,
'local_atendimento_id' => $soap->atencao_basica_local_atendimento_id,
'tipo_atendimento_id' => $soap->emad_tipo_atendimento_id,
'modalidade_id' => $soap->emad_modalidade_id,
'turno_id' => $soap->turno_id,
'conduta_desfecho_id' => $soap->emad_conduta_desfecho_id,
'codigo_cid' => $soap->cid ?? null,
'codigo_ciap' => $soap->ciap ?? null,
'procedimentos' => $data['procedimentos_emad'],
'condicoes' => $data['condicoes_emad'],
'problemas_condicoes' => $problemas_condicoes,
'condicao_avaliada' => $data['condicoes_avaliadas'],
'doenca_transmissivel' => $data['doencas_transmissiveis'],
'rastreamento' => $data['rastreamentos'],
'observacao_perfil_epidemiologico' => $soap->observacao_perfil_epidemiologico,
'perfis_epidemiologicos' => $soap->perfisEpidemiologicos->pluck('id'),
'ivcf' => array_merge(
[
'deseja_preencher' => $soap->ivcf ? true : false,
],
$soap->ivcf ? $soap->ivcf->toArray() : [],
),
];
AtendimentoDomiciliarService::saveStore([
'soap_id' => $soap->id,
'data' => $soap->created_at->format('Y-m-d'),
'usuario_id' => $soap->createdLotacao->usuario_id,
'equipe_id' => $soap->equipe_id,
'ocupacao_id' => $soap->createdLotacao->ocupacao_id,
'usuario_auxiliar_id' => null,
'equipe_auxiliar_id' => null,
'ocupacao_auxiliar_id' => null,
'atendimentos' => $atendimentos,
]);
}
public static function storeAvaliacao($soap, $data)
{
$hasAvaliacao = Avaliacao::where('paciente_id', $soap->atendimento->paciente->id)->first() ? true : false;
if (!self::criaFicha($soap, 'avaliacao') || $hasAvaliacao || !$data['ficha_avaliacao']) {
return;
}
AvaliacaoService::saveStore([
'soap_id' => $soap->id,
'data' => $soap->created_at->format('Y-m-d'),
'usuario_id' => $soap->createdLotacao->usuario_id,
'equipe_id' => $soap->equipe_id,
'unidade_id' => $soap->createdLotacao->infraestrutura->unidade_id,
'infraestrutura_id' => $soap->createdLotacao->infraestrutura->id,
'ocupacao_id' => $soap->createdLotacao->ocupacao_id,
'usuario_auxiliar_id' => null,
'equipe_auxiliar_id' => null,
'ocupacao_auxiliar_id' => null,
'condicoes' => $data['condicoes_emad'],
'condicao_avaliada' => $data['condicoes_avaliadas'],
'data' => $soap->created_at->format('Y-m-d'),
'paciente_id' => $soap->atendimento->paciente->id,
'turno_id' => $soap->turno_id,
'cid_primario' => $soap->emad_cid_primario_id,
'conclusao_id' => $soap->emad_conclusao_id,
'procedencia_id' => $soap->emad_procedencia_id,
'cuidador_id' => $soap->emad_cuidador_id,
'cpf_cuidador' => $soap->emad_cpf_cuidador,
'cns_cuidador' => $soap->emad_cns_cuidador,
'justificativa' => $data['emad_conclusao_justificativa'],
]);
}
public static function storeMarcadorConsumoAlimentar($soap, $data)
{
if (!self::criaFicha($soap, 'marcador-consumo-alimentar')) {
return;
}
$existeSoap = AtendimentoSoap::where('atendimento_id', $soap->atendimento_id)
->get(['id', 'turno_id'])
->toArray();
$mConsumo = MarcadorConsumoAlimentar::whereIn('soap_id', array_column($existeSoap, 'id'))
->get(['id', 'soap_id','data_atendimento'])
->map(function ($item) use ($existeSoap) {
$soap = collect($existeSoap)->firstWhere('id', $item->soap_id);
$item->turno_id = $soap['turno_id'] ?? null;
return $item;
});
$marCon = null;
foreach ($mConsumo as $marConsumo) {
if ($marConsumo->turno_id == $soap->turno_id
&& $marConsumo->data_atendimento == $soap->created_at->format('Y-m-d')) {
$marCon = $marConsumo->id;
break;
}
}
$respostaUnica = array_filter($data['pergunta_unica'], fn ($valor) => $valor !== null);
$respostaMultipla = array_filter($data['pergunta_multipla'], fn ($valor) => $valor !== null);
if ((!empty($respostaUnica) || !empty($respostaMultipla)) && empty($marCon)) {
MarcadorConsumoAlimentarService::saveStore([
'soap_id' => $soap->id,
'data_atendimento' => $soap->created_at->format('Y-m-d'),
'local_atendimento' => $soap->atencao_basica_local_atendimento_id,
'paciente' => $soap->atendimento->paciente->id,
'usuario' => $soap->createdLotacao->usuario_id,
'cbo_codigo' => $soap->createdLotacao->ocupacao_id,
'unidade' => $soap->createdLotacao->infraestrutura->unidade_id,
'equipe' => $soap->equipe_id,
'pergunta' => [
'resposta_unica' => $respostaUnica,
'resposta_multipla' => $respostaMultipla,
],
]);
}elseif((!empty($respostaUnica) || !empty($respostaMultipla)) && !empty($marCon)) {
MarcadorConsumoAlimentarService::update($marCon,[
'soap_id' => $soap->id,
'data_atendimento' => $soap->created_at->format('Y-m-d'),
'local_atendimento' => $soap->atencao_basica_local_atendimento_id,
'paciente' => $soap->atendimento->paciente->id,
'usuario' => $soap->createdLotacao->usuario_id,
'cbo_codigo' => $soap->createdLotacao->ocupacao_id,
'unidade' => $soap->createdLotacao->infraestrutura->unidade_id,
'equipe' => $soap->equipe_id,
'pergunta' => [
'resposta_unica' => $respostaUnica,
'resposta_multipla' => $respostaMultipla,
],
]);
}
}
private static function criaFicha($soap, $funcionalidadeIdentificador)
{
return ParametrizacaoInfraestruturaOcupacao::whereHas('parametrizacaoInfraestrutura', fn ($q) => $q
->where('infraestrutura_id', $soap->createdLotacao->infraestrutura_id)
)
->where('ocupacao_id', $soap->createdLotacao->ocupacao_id)
->whereHas('fichasAtb', fn ($q) => $q
->where('funcionalidade_id', self::getAtencaoBasicaFuncionalidadeId($funcionalidadeIdentificador))
)
->exists();
}
private static function getAtencaoBasicaFuncionalidadeId($identificador)
{
return Funcionalidade::whereHas('modulo', fn ($q) => $q
->where('identificador', 'atencao-basica')
)
->where('identificador', $identificador)
->first('id')->id;
}
}

View File

@@ -0,0 +1,218 @@
<?php
namespace App\Services\Ambulatorio;
use App\Models\Ambulatorio\Supervisor;
use App\Models\Cadastro\Estabelecimento\Infraestrutura;
use App\Models\Cadastro\Estabelecimento\Unidade;
use App\Models\Cadastro\SujeitoAtencao\Usuario;
use App\Services\Service;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
class SupervisorService extends Service
{
public static function datatable()
{
$supervisores = DB::table('ambulatorio_supervisor as supervisor')
->join(
'cadastro_infraestrutura as infraestrutura',
'infraestrutura.id',
'supervisor.infraestrutura_id'
)
->join(
'cadastro_unidade as unidade',
'unidade.id',
'infraestrutura.unidade_id'
)
->join(
'cadastro_usuario as usuario',
'usuario.id',
'supervisor.usuario_id'
)
->join(
'cadastro_cidadao as cidadao',
'cidadao.id',
'usuario.cidadao_id'
)
->select(
'supervisor.id',
DB::raw('unidade.nome_fantasia as unidade'),
DB::raw('COALESCE(infraestrutura.nome, unidade.nome_fantasia) as infraestrutura'),
DB::raw('cidadao.nome as usuario'),
);
return datatables()
->of($supervisores)
->filterColumn('infraestrutura.nome', function ($query, $keyword) {
$query->whereRaw("COALESCE(infraestrutura.nome, unidade.nome_fantasia) like ?", ["%{$keyword}%"]);
})
->skipTotalRecords()
->toJson();
}
public static function isSupervisor($usuarioId, $infraestruturaId = null, $lotacaoInfraestruturaId = null)
{
if($infraestruturaId != $lotacaoInfraestruturaId) return false;
return Supervisor::where('usuario_id', $usuarioId)
->where('infraestrutura_id', $infraestruturaId)
->exists();
}
public static function isUsuarioLogadoSupervisor()
{
$lotacaoLogada = self::getCurrentLotacao();
return Supervisor::where('infraestrutura_id', $lotacaoLogada->infraestrutura_id)
->where('usuario_id', $lotacaoLogada->usuario_id)
->exists();
}
public static function create()
{
return [
'form' => [
'unidades' => self::getUnidades(),
'infraestruturas' => [],
'usuarios' => [],
],
'model' => [
'unidade_id' => null,
'infraestrutura_id' => null,
'usuario_id' => null,
]
];
}
public static function edit($id)
{
$supervisor = Supervisor::findOrFail($id);
$params = (object) [
'unidade_id' => $supervisor->infraestrutura->unidade_id,
'infraestrutura_id' => $supervisor->infraestrutura_id
];
return [
'form' => [
'unidades' => self::getUnidades($supervisor->infraestrutura->unidade_id),
'infraestruturas' => self::getInfraestruturas($params, $supervisor->infraestrutura_id),
'usuarios' => self::getUsuarios($params),
],
'model' => [
'unidade_id' => $supervisor->infraestrutura->unidade_id,
'infraestrutura_id' => $supervisor->infraestrutura_id,
'usuario_id' => $supervisor->usuario_id,
]
];
}
public static function list()
{
$params = (object) request()->all();
switch (request()->listar) {
case 'infraestruturas': {
return self::getInfraestruturas($params);
}
case 'usuarios': {
return self::getUsuarios($params);
}
}
}
private static function getUnidades($unidadeId = null)
{
return Unidade::where(fn ($q) => $q
->when($unidadeId, fn ($q, $id) => $q->where('id', $id))
->orWhereHas('infraestruturas', fn ($q) => $q
->whereHas('ambulatorioParametrizacaoJornadaInfraestrutura')
->whereHas('lotacoes')
)
)
->orderBy('nome_fantasia')
->get(['id', 'nome_fantasia']);
}
private static function getInfraestruturas($params, $infraestruturaId = null)
{
return Infraestrutura::setEagerLoads([])
->where('unidade_id', $params->unidade_id)
->where(fn ($q) => $q
->when($infraestruturaId, fn ($q, $id) => $q->where('id', $id))
->orWhereHas('ambulatorioParametrizacaoJornadaInfraestrutura')
)
->whereHas('lotacoes')
->get(['id', 'unidade_id', 'nome', 'principal'])
->map(fn ($infraestrutura) => [
'id' => $infraestrutura->id,
'nome' => $infraestrutura->nome
])
->sortBy('nome')
->values();
}
private static function getUsuarios($params)
{
return Usuario::setEagerLoads([])
->whereHas('lotacoes', fn ($q) => $q
->where('infraestrutura_id', $params->infraestrutura_id)
)
->get(['id', 'cidadao_id'])
->map(fn ($usuario) => [
'id' => $usuario->id,
'nome' => $usuario->cidadao()->setEagerLoads([])->first('nome')->nome,
])
->sortBy('nome')
->values();
}
public static function store()
{
self::validate();
return Supervisor::create(request()->all())->fresh();
}
public static function update($id)
{
self::validate();
return (tap(Supervisor::findOrFail($id))->update(request()->all()))->fresh();
}
public static function validate()
{
$rules = [
'infraestrutura_id' => [
'required',
'integer',
Rule::exists(Infraestrutura::class, 'id'),
],
'usuario_id' => [
'required',
'integer',
Rule::exists(Usuario::class, 'id'),
Rule::unique(Supervisor::class, 'usuario_id')
->where('infraestrutura_id', request()->infraestrutura_id)
->ignore(request()->route('supervisor'))
],
];
$messages = [
'usuario_id.unique' => 'O local de atendimento e o profissional já foram inseridos anteriormente.',
];
request()->validate($rules, $messages);
}
public static function destroy($id)
{
Supervisor::findOrFail($id)->delete();
}
}