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

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));
}
}