format('Y-m-d'); $currentLotacao = self::getCurrentLotacao(); $cliente = Cliente::where('link', app('config')->get('database.default'))->firstOrFail(); $reagendarExame = ReagendarExame::select('exibir')->first(); return [ 'form' => [ 'periodo' => [ 'start' => $currentDate, 'end' => $currentDate, ], 'data_atual' => Carbon::now()->format('d/m/Y'), 'unidades_faturamento' => self::getUnidadesFaturamento(), 'laboratorios_faturamento' => self::getLaboratoriosFaturamento(), 'status' => Status::where(function ($query) { $query->where('id', StatusAgendamento::AGENDADO) ->orWhere('id', StatusAgendamento::DUPLICIDADE) ->orWhere('id', StatusAgendamento::REALIZADO) ->orWhere('id', StatusAgendamento::OUTROS) ->orWhere('id', StatusAgendamento::FALTOU); }) ->orderBy('id') ->get() ->map(fn ($status) => [ 'id' => $status->id, 'descricao' => $status->descricao ]), 'unidade' => $currentLotacao->infraestrutura->unidade->nome_fantasia, 'unidade_id' => $currentLotacao->infraestrutura->unidade->id, 'infraestrutura_id' => $currentLotacao->infraestrutura->id, 'infraestrutura' => $currentLotacao->infraestrutura->nome, 'usuario_id' => $currentLotacao->usuario->id, 'is_supervisor' => Supervisor::where('usuario_id', $currentLotacao->usuario->id)->first() ? true : false, 'sistema' => [ 'ramo_atividade' => [ 'nome' => $cliente->sistema->ramoAtividade->nome ?? null, ], 'nome' => $cliente->sistema->nome ?? null, 'versao' => $cliente->sistema->versao ?? null, ], 'exibir_reagendar_exame' => $reagendarExame ? $reagendarExame->exibir : false ], 'model' => [ 'periodo' => [ 'start' => $currentDate, 'end' => $currentDate, ], ] ]; } public static function getUnidadesFaturamento() { return UnidadeFaturamento::get() ->map(fn ($query) => [ 'id' => $query->id, 'unidade_id' => $query->unidade_id, 'nomeFantasia' => $query->unidade->nome_fantasia, 'infraestrutura_id' => $query->infraestrutura_id, 'infraestrutura_nome' => $query->infraestrutura->nome, 'profissionais' => $query->unidadeFaturamentoUsuario ->filter(function ($profissional) { return $profissional->usuario && is_null($profissional->usuario->deleted_at); }) ->map(function ($profissional) use ($query) { return [ 'usuario' => [ 'id' => $profissional->usuario_id, 'usuario_ocupacao' => $profissional->usuario() ->setEagerLoads([]) ->first('cidadao_id') ->cidadao() ->setEagerLoads([]) ->first('nome')->nome . ' - ' . $profissional->ocupacao->codigo, 'ocupacao_id' => $profissional->ocupacao_id, 'infraestrutura_id' => $query->infraestrutura_id, ], ]; })->values(), 'faturamento_relacionado' => $query->unidadeFaturamentoUnidade ->map(function ($relacionada) { return [ 'id' => $relacionada->id, 'relacionada_unidade_id' => $relacionada->unidade_id, 'relacionada_infraestrutura_id' => $relacionada->infraestrutura_id, 'unidade_relacionada' => $relacionada->infraestrutura->unidade->nome_fantasia, 'infraestrutura_nome' => $relacionada->infraestrutura->nome, ]; }) ]); } public static function getLaboratoriosFaturamento() { return LaboratorioFatura::get() ->map(fn ($query) => [ 'id' => $query->id, 'unidade_id' => $query->unidade_id, 'nomeFantasia' => $query->unidade->nome_fantasia, 'infraestrutura_id' => $query->infraestrutura_id, 'infraestrutura_nome' => $query->infraestrutura->nome, 'profissionais' => $query->laboratorioFaturaUsuario ->map(function ($profissional) use ($query) { return [ 'usuario' => [ 'id' => $profissional->usuario_id, 'usuario_ocupacao' => $profissional->usuario->nome . ' - ' . $profissional->ocupacao->codigo, 'ocupacao_id' => $profissional->ocupacao_id, 'infraestrutura_id' => $query->infraestrutura_id, ], ]; }), 'faturamento_relacionado' => $query->laboratorioFaturaUnidade ->map(function ($relacionada) { return [ 'id' => $relacionada->id, 'relacionada_unidade_id' => $relacionada->unidade_id, 'relacionada_infraestrutura_id' => $relacionada->infraestrutura_id, 'unidade_relacionada' => $relacionada->infraestrutura->unidade->nome_fantasia, 'infraestrutura_nome' => $relacionada->infraestrutura->nome, ]; }) ]); } public static function list() { $now = Carbon::now(); $currentDate = $now->format('Y-m-d'); $agendamentos = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento.id AS agendamento_id', 'exame_laboratorial_agendamento.agendamento_numero AS agendamento_numero', 'exame_laboratorial_agendamento.coleta_infraestrutura_id AS coleta_infraestrutura_id', 'exame_laboratorial_agendamento.coleta_unidade_id AS coleta_unidade_id', 'exame_laboratorial_agendamento.data AS data', 'exame_laboratorial_agendamento.ultima_menstruacao AS ultima_menstruacao', 'exame_laboratorial_agendamento.gestante AS gestante', DB::raw('TIME_FORMAT(exame_laboratorial_agendamento.horario, "%h:%i") AS hora_inicial'), 'exame_laboratorial_agendamento.infraestrutura_id AS infraestrutura_id', 'exame_laboratorial_agendamento.jornada_id AS jornada_id', 'exame_laboratorial_agendamento.laboratorio_infraestrutura_id AS laboratorio_infraestrutura_id', 'exame_laboratorial_agendamento.laboratorio_unidade_id AS laboratorio_id', 'exame_laboratorial_agendamento.medico_id AS medico_id', 'cadastro_cidadao_medico.nome AS medico_nome', 'exame_laboratorial_agendamento.observacao AS observacao', 'exame_laboratorial_agendamento.responsavel AS responsavel', 'exame_laboratorial_agendamento.suspeita_clinica AS suspeita', 'exame_laboratorial_agendamento.ultima_menstruacao AS data_menstruacao', 'exame_laboratorial_agendamento.unidade_id AS unidade_id', 'exame_laboratorial_agendamento.urgente AS urgente', 'exame_laboratorial_agendamento.regulacao_solicitacao_id AS regulacao_solicitacao_id', 'regulacao_parametrizacao_prestador_interno.controla_protocolo_fechamento AS controla_protocolo_fechamento', DB::raw('group_concat(parametrizacao_exame.sigla_exame separator ", ") as sigla_exame'), 'cadastro_paciente.id AS paciente_id', 'cadastro_cidadao.nome AS paciente_nome', 'cadastro_cidadao_agendador.nome AS agendador_nome', 'cadastro_unidade.nome_fantasia as unidade_nome', 'cadastro_unidade_laboratorio.nome_fantasia as laboratorio_unidade_nome', 'cadastro_cidadao.preferencia_nome_id AS paciente_preferencia_nome_id', 'cadastro_cidadao.nome_social AS paciente_nome_social', 'cadastro_cidadao.sexo_id AS paciente_sexo_id', 'cadastro_raca_cor.descricao as cidadao_raca_cor', DB::raw('LPAD(cadastro_paciente.prontuario,7,0) as paciente_prontuario'), DB::raw('DATE_FORMAT(cadastro_cidadao.data_nascimento, "%d/%m/%Y") AS data_nascimento'), DB::raw('CONCAT(TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, exame_laboratorial_agendamento.data), " anos") AS paciente_idade'), DB::raw(' CASE WHEN cadastro_infraestrutura.principal THEN cadastro_unidade.nome_fantasia ELSE cadastro_infraestrutura.nome END AS infraestrutura_nome' ), DB::raw('CONCAT( cadastro_unidade_coleta.nome_fantasia, " - ", CASE WHEN cadastro_infraestrutura_coleta.principal THEN cadastro_unidade_coleta.nome_fantasia ELSE cadastro_infraestrutura_coleta.nome END) AS coleta_infraestrutura_nome'), DB::raw(' CASE WHEN cadastro_infraestrutura_laboratorio.principal THEN cadastro_unidade_laboratorio.nome_fantasia ELSE cadastro_infraestrutura_laboratorio.nome END AS laboratorio_infraestrutura_nome'), 'exame_laboratorial_agendamento.regulacao_solicitacao_id', 'regulacao_solicitacao.numero as regulacao_solicitacao_numero', DB::raw('IF(faturamento_automatico_usuario.usuario_id IS NULL, NULL, exame_laboratorial_agendamento.usuario_id) AS usuario_id'), 'exame_laboratorial_agendamento_exame.ocupacao_id AS ocupacao_id', DB::raw('IF(laboratorio_automatico_usuario.usuario_id IS NULL, NULL, exame_laboratorial_agendamento.laboratorio_usuario_id) AS laboratorio_usuario_id'), DB::raw('IF(laboratorio_automatico_usuario.ocupacao_id IS NULL, NULL, exame_laboratorial_agendamento.laboratorio_ocupacao_id) AS laboratorio_ocupacao_id'), 'cadastro_cidadao.cpf AS cidadao_cpf', 'cadastro_cidadao.cns AS cidadao_cns', ]) ->leftJoin('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->leftJoin('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->leftJoin('cadastro_grupo', 'cadastro_grupo.id', 'parametrizacao_exame.grupo_tipo_id') ->leftJoin('cadastro_paciente', 'cadastro_paciente.id', 'exame_laboratorial_agendamento.paciente_id') ->leftJoin('cadastro_usuario', 'cadastro_usuario.id', 'exame_laboratorial_agendamento.medico_id') ->leftJoin('cadastro_cidadao as cadastro_cidadao_medico', 'cadastro_cidadao_medico.id', 'cadastro_usuario.cidadao_id') ->leftJoin('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id') ->leftJoin('cadastro_raca_cor', 'cadastro_raca_cor.id', 'cadastro_cidadao.raca_cor_id') ->leftJoin('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'exame_laboratorial_agendamento.infraestrutura_id') ->leftJoin('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->leftJoin('cadastro_infraestrutura as cadastro_infraestrutura_coleta', 'cadastro_infraestrutura_coleta.id', 'exame_laboratorial_agendamento.coleta_infraestrutura_id') ->leftJoin('cadastro_unidade as cadastro_unidade_coleta', 'cadastro_unidade_coleta.id', 'cadastro_infraestrutura_coleta.unidade_id') ->leftJoin('cadastro_infraestrutura as cadastro_infraestrutura_laboratorio', 'cadastro_infraestrutura_laboratorio.id', 'exame_laboratorial_agendamento.laboratorio_infraestrutura_id') ->leftJoin('cadastro_unidade as cadastro_unidade_laboratorio', 'cadastro_unidade_laboratorio.id', 'cadastro_infraestrutura_laboratorio.unidade_id') ->leftJoin('cadastro_lotacao', 'cadastro_lotacao.id', 'exame_laboratorial_agendamento.created_lotacao_id') ->leftJoin('cadastro_usuario as agendador', 'agendador.id', 'cadastro_lotacao.usuario_id') ->leftJoin('cadastro_cidadao AS cadastro_cidadao_agendador', 'cadastro_cidadao_agendador.id', 'agendador.cidadao_id') ->leftJoin('regulacao_solicitacao', 'regulacao_solicitacao.id', 'exame_laboratorial_agendamento.regulacao_solicitacao_id') ->leftJoin('regulacao_parametrizacao_prestador_interno', function ($join) { $join->on('regulacao_parametrizacao_prestador_interno.infraestrutura_id', 'cadastro_infraestrutura_laboratorio.id') ->where('regulacao_parametrizacao_prestador_interno.ativo', true); }) ->leftJoin('exame_laboratorial_parametrizacao_uni_fatu_auto_usuario as faturamento_automatico_usuario', function ($join) { $join->on('faturamento_automatico_usuario.usuario_id', '=', 'exame_laboratorial_agendamento.usuario_id') ->where(function ($query) { $query->whereExists(function ($subQuery) { $subQuery ->select(DB::raw(1)) ->from('exame_laboratorial_parametrizacao_unidade_faturamento_automatico as principal') ->join('exame_laboratorial_parametrizacao_uni_fatu_auto_usuario as automatico_usuario', 'automatico_usuario.unidade_faturamento_automatico_id', '=', 'principal.id') ->whereColumn('automatico_usuario.usuario_id', '=', 'faturamento_automatico_usuario.usuario_id') ->where('principal.infraestrutura_id', '=', request()->coleta_infraestrutura_id); }); }) ->orWhere(function ($query) { $query->whereExists(function ($subQuery) { $subQuery ->select(DB::raw(1)) ->from('exame_laboratorial_parametrizacao_uni_fatu_auto_unidade as sub') ->join('exame_laboratorial_parametrizacao_unidade_faturamento_automatico as principal', 'principal.id', '=', 'sub.unidade_faturamento_automatico_id') ->join('exame_laboratorial_parametrizacao_uni_fatu_auto_usuario as automatico_usuario', 'automatico_usuario.unidade_faturamento_automatico_id', '=', 'principal.id') ->whereColumn('automatico_usuario.usuario_id', '=', 'faturamento_automatico_usuario.usuario_id') ->where('sub.infraestrutura_id', '=', request()->coleta_infraestrutura_id); }); }); }) ->leftJoin('exame_laboratorial_parametrizacao_lab_fatu_auto_usuario as laboratorio_automatico_usuario', function ($join) { $join->on('laboratorio_automatico_usuario.usuario_id', '=', 'exame_laboratorial_agendamento.laboratorio_usuario_id') ->where(function ($query) { $query->whereExists(function ($subQuery) { $subQuery ->select(DB::raw(1)) ->from('exame_laboratorial_parametrizacao_laboratorio_fatura_automatico as principal') ->join('exame_laboratorial_parametrizacao_lab_fatu_auto_usuario as automatico_usuario', 'automatico_usuario.laboratorio_fatura_automatico_id', '=', 'principal.id') ->whereColumn('automatico_usuario.usuario_id', '=', 'laboratorio_automatico_usuario.usuario_id') ->whereColumn('principal.infraestrutura_id', '=', 'exame_laboratorial_agendamento.laboratorio_infraestrutura_id'); }); }) ->orWhere(function ($query) { $query->whereExists(function ($subQuery) { $subQuery ->select(DB::raw(1)) ->from('exame_laboratorial_parametrizacao_lab_fatu_auto_unidade as sub') ->join('exame_laboratorial_parametrizacao_laboratorio_fatura_automatico as principal', 'principal.id', '=', 'sub.laboratorio_fatura_automatico_id') ->join('exame_laboratorial_parametrizacao_lab_fatu_auto_usuario as automatico_usuario', 'automatico_usuario.laboratorio_fatura_automatico_id', '=', 'principal.id') ->whereColumn('automatico_usuario.usuario_id', '=', 'laboratorio_automatico_usuario.usuario_id') ->whereColumn('sub.infraestrutura_id', '=', 'exame_laboratorial_agendamento.laboratorio_infraestrutura_id'); }); }); }) ->groupBy([ 'exame_laboratorial_agendamento.id', ]); if (request()->periodo) { $agendamentos->where('exame_laboratorial_agendamento.data', '>=', request()->periodo['start']); $agendamentos->where('exame_laboratorial_agendamento.data', '<=', request()->periodo['end']); } else { $agendamentos->where('exame_laboratorial_agendamento.data', $currentDate); } if (request()->paciente_id) { $agendamentos->where('exame_laboratorial_agendamento.paciente_id', request()->paciente_id); } if (request()->agendamento_numero) { $agendamentos->where('exame_laboratorial_agendamento.agendamento_numero', request()->agendamento_numero); } if (request()->prontuario) { $agendamentos->where('cadastro_paciente.prontuario', request()->prontuario); } if (request()->unidade_id) { $agendamentos->where('exame_laboratorial_agendamento.unidade_id', request()->unidade_id); } if (request()->infraestrutura_id) { $agendamentos->where('exame_laboratorial_agendamento.infraestrutura_id', request()->infraestrutura_id); } if (request()->coleta_unidade_id) { $agendamentos->where('exame_laboratorial_agendamento.coleta_unidade_id', request()->coleta_unidade_id); } if (request()->coleta_infraestrutura_id) { $agendamentos->where('exame_laboratorial_agendamento.coleta_infraestrutura_id', request()->coleta_infraestrutura_id); } if (request()->status_id) { $agendamentos->where('exame_laboratorial_agendamento_exame.status_id', request()->status_id); } if (request()->exame_id && request()->pertence_grupo) { if (request()->mapa_agrupado) { $agendamentos->where('cadastro_grupo.id', request()->exame_id); } else { $agendamentos->where('parametrizacao_exame.id', request()->exame_id); } } if (request()->exame_id && !request()->pertence_grupo) { $agendamentos->where('parametrizacao_exame.id', request()->exame_id); } $agendamentos->where(function($status) { $status->where('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::AGENDADO) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::DUPLICIDADE) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::REALIZADO) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::OUTROS) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::FALTOU) ->orWhereNull('exame_laboratorial_agendamento_exame.status_id'); }); $agendamentos = $agendamentos->get(); return [ 'form' => [ 'periodo' => [ 'start' => $currentDate, 'end' => $currentDate, ], 'data_atual' => Carbon::now()->format('d/m/Y'), 'agendado' => self::getTotal($agendamentos, StatusAgendamento::AGENDADO), 'duplicidade' => self::getTotal($agendamentos, StatusAgendamento::DUPLICIDADE), 'realizado' => self::getTotal($agendamentos, StatusAgendamento::REALIZADO), 'outros' => self::getTotal($agendamentos, StatusAgendamento::OUTROS), 'faltou' => self::getTotal($agendamentos, StatusAgendamento::FALTOU), ], 'model' => [ 'periodo' => [ 'start' => $currentDate, 'end' => $currentDate, ], 'agendamentos' => $agendamentos->map(function ($agendamento) { $exames = self::getExames($agendamento); $realizado = collect($exames)->contains(fn($item) => $item->status_id !== StatusAgendamento::AGENDADO); return [ 'data' => $agendamento->data ?? null, 'hora_inicial' => $agendamento->hora_inicial ?? null, 'agendamento_id' => $agendamento->agendamento_id ?? null, 'agendador_nome' => $agendamento->agendador_nome ?? null, 'cidadao_raca_cor' => $agendamento->cidadao_raca_cor, 'agendamento_numero' => $agendamento->agendamento_numero ?? null, 'ultima_menstruacao' => $agendamento->ultima_menstruacao ?? null, 'coleta_infraestrutura_id' => $agendamento->coleta_infraestrutura_id ?? null, 'coleta_unidade_id' => $agendamento->coleta_unidade_id ?? null, 'controla_protocolo_fechamento' => $agendamento->controla_protocolo_fechamento ?? false, 'gestante' => $agendamento->gestante ?? null, 'paciente_id' => $agendamento->paciente_id ?? null, 'paciente_nome' => $agendamento->paciente_nome ?? null, 'paciente_nome_social' => $agendamento->paciente_nome_social, 'paciente_preferencia_nome' => $agendamento->paciente_preferencia_nome_id === PreferenciaNome::NOME_SOCIAL, 'paciente_prontuario' => $agendamento->paciente_prontuario, 'paciente_nascimento' => $agendamento->data_nascimento, 'paciente_idade' => $agendamento->paciente_idade, 'unidade_nome' => $agendamento->unidade_nome, 'infraestrutura_nome' => $agendamento->infraestrutura_nome, 'coleta_infraestrutura_nome' => $agendamento->coleta_infraestrutura_nome, 'laboratorio_infraestrutura_nome' => $agendamento->laboratorio_infraestrutura_nome, 'laboratorio_infraestrutura_id' => $agendamento->laboratorio_infraestrutura_id, 'medico_nome' => $agendamento->medico_nome, 'sigla_exame' => $agendamento->sigla_exame ?? null, 'exames' => $exames, 'regulacao_solicitacao_id' => $agendamento->regulacao_solicitacao_id ?? null, 'regulacao_solicitacao_numero' => $agendamento->regulacao_solicitacao_numero ?? null, 'status_id' => null, 'usuario_id' => $agendamento->usuario_id ?? null, 'ocupacao_id' => $agendamento->ocupacao_id ?? null, 'laboratorio_usuario_id' => $agendamento->laboratorio_usuario_id ?? null, 'laboratorio_ocupacao_id' => $agendamento->laboratorio_ocupacao_id ?? null, 'usuarios' => [], 'protocolo_fechamento' => $realizado ? $agendamento->regulacao_solicitacao_numero : null, 'faturamento_laboratorio_infraestrutura_id' => null, 'faturamento_coleta_infraestrutura_id' => null, 'cidadao_cpf' => $agendamento->cidadao_cpf, 'cidadao_cns' => $agendamento->cidadao_cns, ]; }), ], ]; } public static function getExames($agendamento) { if (!request()->exame_id && request()->coleta_infraestrutura_id || request()->exame_id && request()->pertence_grupo && request()->coleta_infraestrutura_id) { $agendamentosComGrupo = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento_exame.id AS id', 'exame_laboratorial_agendamento.jornada_id AS jornada_id', 'cadastro_grupo.id AS exame_grupo_id', 'cadastro_grupo.nome AS exame_grupo_nome', DB::raw('group_concat(parametrizacao_exame.nome separator ", ") as nomes_exame'), DB::raw('group_concat(parametrizacao_exame.sigla_exame separator ", ") as sigla_exame'), DB::raw('true AS pertence_grupo'), 'exame_laboratorial_agendamento_exame.status_id AS status_id', 'exame_laboratorial_agendamento_exame.observacao AS observacao', ]) ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->join('cadastro_grupo', 'cadastro_grupo.id', 'parametrizacao_exame.grupo_tipo_id') ->groupBy([ 'exame_laboratorial_agendamento.id', 'cadastro_grupo.id', ]); $agendamentosComGrupo->where('parametrizacao_exame.mapa_agrupado', true); $agendamentosComGrupo->where('exame_laboratorial_agendamento.id', $agendamento->agendamento_id); if (request()->exame_id && request()->pertence_grupo) { $agendamentosComGrupo->where('cadastro_grupo.id', request()->exame_id); } $agendamentosComGrupo->where(function($status) { $status->where('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::AGENDADO) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::DUPLICIDADE) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::REALIZADO) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::OUTROS) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::FALTOU) ->orWhereNull('exame_laboratorial_agendamento_exame.status_id'); }); $agendamentosComGrupo = $agendamentosComGrupo->get()->toArray(); } else { $agendamentosComGrupo = []; } if (!request()->exame_id && request()->coleta_infraestrutura_id || request()->exame_id && request()->pertence_grupo && request()->coleta_infraestrutura_id) { $agendamentosSemMapaAgrupado = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento_exame.id AS id', 'parametrizacao_exame.id AS exame_grupo_id', 'parametrizacao_exame.nome AS exame_grupo_nome', DB::raw('group_concat(parametrizacao_exame.nome separator ", ") as nomes_exame'), DB::raw('null as nomes_exame'), DB::raw('false AS pertence_grupo'), 'parametrizacao_exame.sigla_exame AS sigla_exame', 'exame_laboratorial_agendamento_exame.observacao AS observacao', 'exame_laboratorial_agendamento_exame.status_id AS status_id', ]) ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->groupBy([ 'exame_laboratorial_agendamento.id', 'parametrizacao_exame.id', ]); $agendamentosSemMapaAgrupado->where(function ($query) { $query->where('parametrizacao_exame.mapa_agrupado', false) ->orWhereNull('parametrizacao_exame.mapa_agrupado'); }); if (request()->exame_id) { $agendamentosSemMapaAgrupado->where('parametrizacao_exame.id', request()->exame_id); } $agendamentosSemMapaAgrupado->where('exame_laboratorial_agendamento.id', $agendamento->agendamento_id); $agendamentosSemMapaAgrupado->where(function($status) { $status->where('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::AGENDADO) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::DUPLICIDADE) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::REALIZADO) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::OUTROS) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::FALTOU) ->orWhereNull('exame_laboratorial_agendamento_exame.status_id'); }); $agendamentosSemMapaAgrupado = $agendamentosSemMapaAgrupado->get()->toArray(); } else { $agendamentosSemMapaAgrupado = []; } if (!request()->exame_id && request()->coleta_infraestrutura_id || request()->exame_id && !request()->pertence_grupo && request()->coleta_infraestrutura_id) { $agendamentosSemGrupo = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento_exame.id AS id', 'parametrizacao_exame.id AS exame_grupo_id', 'parametrizacao_exame.nome AS exame_grupo_nome', 'parametrizacao_exame.sigla_exame AS sigla_exame', DB::raw('null as nomes_exame'), DB::raw('false AS pertence_grupo'), 'exame_laboratorial_agendamento_exame.status_id AS status_id', 'exame_laboratorial_agendamento_exame.observacao AS observacao', ]) ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->whereNull('parametrizacao_exame.grupo_tipo_id'); $agendamentosSemGrupo->where('exame_laboratorial_agendamento.id', request()->agendamento_id); $agendamentosSemGrupo->where(function($status) { $status->where('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::AGENDADO) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::DUPLICIDADE) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::REALIZADO) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::OUTROS) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::FALTOU) ->orWhereNull('exame_laboratorial_agendamento_exame.status_id'); }); if (request()->exame_id) { $agendamentosSemGrupo->where('parametrizacao_exame.id', request()->exame_id); } $agendamentosSemGrupo = $agendamentosSemGrupo->get()->toArray(); } else { $agendamentosSemGrupo = []; } return array_merge($agendamentosComGrupo, $agendamentosSemGrupo, $agendamentosSemMapaAgrupado); } public static function loadFields() { $now = Carbon::now(); $currentDate = $now->format('Y-m-d'); $currentLotacao = self::getCurrentLotacao(); $isSupervisor = Supervisor::where('usuario_id', $currentLotacao->usuario->id)->first() ? true : false; if (!request()->exame_id || request()->exame_id && request()->pertence_grupo) { $agendamentosComGrupo = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento.coleta_infraestrutura_id AS coleta_infraestrutura_id', 'exame_laboratorial_agendamento.coleta_unidade_id AS coleta_unidade_id', 'cadastro_unidade_coleta.nome_fantasia AS coleta_unidade_nome', 'exame_laboratorial_agendamento.data AS data', 'exame_laboratorial_agendamento.infraestrutura_id AS infraestrutura_id', 'cadastro_unidade.nome_fantasia AS unidade_nome', 'exame_laboratorial_agendamento.unidade_id AS unidade_id', 'cadastro_grupo.id AS exame_grupo_id', 'cadastro_grupo.nome AS exame_grupo_nome', 'exame_laboratorial_agendamento_exame_status.id AS status_id', 'exame_laboratorial_agendamento_exame_status.descricao AS status_descricao', 'cadastro_infraestrutura_coleta.principal as coleta_principal', 'cadastro_infraestrutura.principal as unidade_principal', DB::raw('CASE WHEN cadastro_infraestrutura_coleta.principal THEN cadastro_unidade_coleta.nome_fantasia ELSE cadastro_infraestrutura_coleta.nome END AS coleta_infraestrutura_nome'), DB::raw('CASE WHEN cadastro_infraestrutura.principal THEN cadastro_unidade.nome_fantasia ELSE cadastro_infraestrutura.nome END AS infraestrutura_nome'), DB::raw('group_concat(parametrizacao_exame.sigla_exame separator ", ") as sigla_exame'), DB::raw('true AS pertence_grupo'), DB::raw('true AS mapa_agrupado'), ]) ->leftJoin('exame_laboratorial_agendamento_exame_status', 'exame_laboratorial_agendamento_exame_status.id', 'exame_laboratorial_agendamento_exame.status_id') ->leftJoin('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->leftJoin('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->leftJoin('cadastro_grupo', 'cadastro_grupo.id', 'parametrizacao_exame.grupo_tipo_id') ->leftJoin('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'exame_laboratorial_agendamento.infraestrutura_id') ->leftJoin('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->leftJoin('cadastro_infraestrutura as cadastro_infraestrutura_coleta', 'cadastro_infraestrutura_coleta.id', 'exame_laboratorial_agendamento.coleta_infraestrutura_id') ->leftJoin('cadastro_unidade as cadastro_unidade_coleta', 'cadastro_unidade_coleta.id', 'cadastro_infraestrutura_coleta.unidade_id') ->groupBy([ 'exame_laboratorial_agendamento.id', 'cadastro_grupo.id', ]); $agendamentosComGrupo->where('parametrizacao_exame.mapa_agrupado', true); $agendamentosComGrupo->whereNotNull('parametrizacao_exame.grupo_tipo_id'); if (request()->periodo) { $agendamentosComGrupo->where('exame_laboratorial_agendamento.data', '>=', request()->periodo['start']); $agendamentosComGrupo->where('exame_laboratorial_agendamento.data', '<=', request()->periodo['end']); } else { $agendamentosComGrupo->where('exame_laboratorial_agendamento.data', $currentDate); } if (!$isSupervisor) { $agendamentosComGrupo->where('exame_laboratorial_agendamento.coleta_infraestrutura_id', $currentLotacao->infraestrutura->id); } $agendamentosComGrupo = $agendamentosComGrupo->get()->toArray(); } else { $agendamentosComGrupo = []; } if (!request()->exame_id || request()->exame_id && request()->pertence_grupo) { $agendamentosSemMapaAgrupado = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento.coleta_infraestrutura_id AS coleta_infraestrutura_id', 'exame_laboratorial_agendamento.coleta_unidade_id AS coleta_unidade_id', 'cadastro_unidade_coleta.nome_fantasia AS coleta_unidade_nome', 'exame_laboratorial_agendamento.data AS data', 'exame_laboratorial_agendamento.infraestrutura_id AS infraestrutura_id', 'cadastro_unidade.nome_fantasia AS unidade_nome', 'exame_laboratorial_agendamento.unidade_id AS unidade_id', 'parametrizacao_exame.id AS exame_grupo_id', 'parametrizacao_exame.nome AS exame_grupo_nome', 'exame_laboratorial_agendamento_exame_status.id AS status_id', 'exame_laboratorial_agendamento_exame_status.descricao AS status_descricao', 'cadastro_infraestrutura_coleta.principal as coleta_principal', 'cadastro_infraestrutura.principal as unidade_principal', DB::raw('CASE WHEN cadastro_infraestrutura_coleta.principal THEN cadastro_unidade_coleta.nome_fantasia ELSE cadastro_infraestrutura_coleta.nome END AS coleta_infraestrutura_nome'), DB::raw('CASE WHEN cadastro_infraestrutura.principal THEN cadastro_unidade.nome_fantasia ELSE cadastro_infraestrutura.nome END AS infraestrutura_nome'), DB::raw('group_concat(parametrizacao_exame.sigla_exame separator ", ") as sigla_exame'), DB::raw('true AS pertence_grupo'), DB::raw('false AS mapa_agrupado'), ]) ->leftJoin('exame_laboratorial_agendamento_exame_status', 'exame_laboratorial_agendamento_exame_status.id', 'exame_laboratorial_agendamento_exame.status_id') ->leftJoin('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->leftJoin('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->leftJoin('cadastro_grupo', 'cadastro_grupo.id', 'parametrizacao_exame.grupo_tipo_id') ->leftJoin('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'exame_laboratorial_agendamento.infraestrutura_id') ->leftJoin('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->leftJoin('cadastro_infraestrutura as cadastro_infraestrutura_coleta', 'cadastro_infraestrutura_coleta.id', 'exame_laboratorial_agendamento.coleta_infraestrutura_id') ->leftJoin('cadastro_unidade as cadastro_unidade_coleta', 'cadastro_unidade_coleta.id', 'cadastro_infraestrutura_coleta.unidade_id') ->groupBy([ 'exame_laboratorial_agendamento.id', 'cadastro_grupo.id', ]); $agendamentosSemMapaAgrupado->where('parametrizacao_exame.mapa_agrupado', false); $agendamentosSemMapaAgrupado->whereNotNull('parametrizacao_exame.grupo_tipo_id'); if (request()->periodo) { $agendamentosSemMapaAgrupado->where('exame_laboratorial_agendamento.data', '>=', request()->periodo['start']); $agendamentosSemMapaAgrupado->where('exame_laboratorial_agendamento.data', '<=', request()->periodo['end']); } else { $agendamentosSemMapaAgrupado->where('exame_laboratorial_agendamento.data', $currentDate); } if (!$isSupervisor) { $agendamentosSemMapaAgrupado->where('exame_laboratorial_agendamento.coleta_infraestrutura_id', $currentLotacao->infraestrutura->id); } $agendamentosSemMapaAgrupado = $agendamentosSemMapaAgrupado->get()->toArray(); } else { $agendamentosSemMapaAgrupado = []; } if (!request()->exame_id || request()->exame_id && !request()->pertence_grupo) { $agendamentosSemGrupo = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento.coleta_infraestrutura_id AS coleta_infraestrutura_id', 'exame_laboratorial_agendamento.coleta_unidade_id AS coleta_unidade_id', 'cadastro_unidade_coleta.nome_fantasia AS coleta_unidade_nome', 'exame_laboratorial_agendamento.data AS data', 'exame_laboratorial_agendamento.infraestrutura_id AS infraestrutura_id', 'cadastro_unidade.nome_fantasia AS unidade_nome', 'exame_laboratorial_agendamento.unidade_id AS unidade_id', 'parametrizacao_exame.id AS exame_grupo_id', 'parametrizacao_exame.nome AS exame_grupo_nome', 'exame_laboratorial_agendamento_exame_status.id AS status_id', 'exame_laboratorial_agendamento_exame_status.descricao AS status_descricao', 'parametrizacao_exame.sigla_exame AS sigla_exame', 'cadastro_infraestrutura_coleta.principal as coleta_principal', 'cadastro_infraestrutura.principal as unidade_principal', DB::raw('CASE WHEN cadastro_infraestrutura_coleta.principal THEN cadastro_unidade_coleta.nome_fantasia ELSE cadastro_infraestrutura_coleta.nome END AS coleta_infraestrutura_nome'), DB::raw('CASE WHEN cadastro_infraestrutura.principal THEN cadastro_unidade.nome_fantasia ELSE cadastro_infraestrutura.nome END AS infraestrutura_nome'), DB::raw('false AS pertence_grupo'), ]) ->leftJoin('exame_laboratorial_agendamento_exame_status', 'exame_laboratorial_agendamento_exame_status.id', 'exame_laboratorial_agendamento_exame.status_id') ->leftJoin('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->leftJoin('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->leftJoin('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'exame_laboratorial_agendamento.infraestrutura_id') ->leftJoin('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->leftJoin('cadastro_infraestrutura as cadastro_infraestrutura_coleta', 'cadastro_infraestrutura_coleta.id', 'exame_laboratorial_agendamento.coleta_infraestrutura_id') ->leftJoin('cadastro_unidade as cadastro_unidade_coleta', 'cadastro_unidade_coleta.id', 'cadastro_infraestrutura_coleta.unidade_id') ->whereNull('parametrizacao_exame.grupo_tipo_id'); if (request()->periodo) { $agendamentosSemGrupo->where('exame_laboratorial_agendamento.data', '>=', request()->periodo['start']); $agendamentosSemGrupo->where('exame_laboratorial_agendamento.data', '<=', request()->periodo['end']); } else { $agendamentosSemGrupo->where('exame_laboratorial_agendamento.data', $currentDate); } if (!$isSupervisor) { $agendamentosSemGrupo->where('exame_laboratorial_agendamento.coleta_infraestrutura_id', $currentLotacao->infraestrutura->id); } $agendamentosSemGrupo = $agendamentosSemGrupo->get()->toArray(); } else { $agendamentosSemGrupo = []; } $agendamentos = array_merge($agendamentosComGrupo, $agendamentosSemGrupo, $agendamentosSemMapaAgrupado); return [ 'form' => [], 'model' => [ 'agendamentos' => $agendamentos, 'unidades_coleta' => self::getUnidadesColeta($agendamentos, $currentLotacao->infraestrutura->id, $isSupervisor), 'unidades_solicitante' => self::getUnidadesSolicitante($agendamentos, $currentLotacao->infraestrutura->id, $isSupervisor), 'status' => self::getStatus($agendamentos), ], ]; } private static function getUnidadesColeta($agendamentos, $lotacaoInfraestruturaId, $isSupervisor) { $unidades = []; foreach ($agendamentos as $item) { if (!$isSupervisor && $item->coleta_infraestrutura_id !== $lotacaoInfraestruturaId) { continue; } $unidadeInserida = null; foreach ($unidades as &$unidade) { if ($unidade['unidade_id'] === $item->coleta_unidade_id) { $unidadeInserida = $unidade; break; } } if ($unidadeInserida) { $exist = null; foreach ($unidadeInserida['infraestruturas'] as $infraestrutura) { if ($infraestrutura['id'] === $item->coleta_infraestrutura_id) { $exist = $infraestrutura; break; } } if (!$exist) { $unidadeInserida['infraestruturas'][] = [ 'id' => $item->coleta_infraestrutura_id, 'nome' => $item->coleta_infraestrutura_nome, 'principal' => $item->coleta_principal == 1 ? true : false, ]; } } else { $unidades[] = [ 'unidade_id' => $item->coleta_unidade_id, 'nome_fantasia' => $item->coleta_unidade_nome, 'infraestruturas' => [ [ 'id' => $item->coleta_infraestrutura_id, 'nome' => $item->coleta_infraestrutura_nome, 'principal' => $item->coleta_principal == 1 ? true : false, ] ] ]; } } return $unidades; } private static function getUnidadesSolicitante($agendamentos, $lotacaoInfraestruturaId, $isSupervisor) { $unidades = []; foreach ($agendamentos as $item) { if (!$isSupervisor && $item->coleta_infraestrutura_id !== $lotacaoInfraestruturaId) { continue; } $unidadeInserida = null; foreach ($unidades as &$unidade) { if ($unidade['unidade_id'] === $item->unidade_id) { $unidadeInserida = $unidade; break; } } if ($unidadeInserida) { $exist = null; foreach ($unidadeInserida['infraestruturas'] as $infraestrutura) { if ($infraestrutura['id'] === $item->infraestrutura_id) { $exist = $infraestrutura; break; } } if (!$exist) { $unidadeInserida['infraestruturas'][] = [ 'id' => $item->infraestrutura_id, 'nome' => $item->infraestrutura_nome, 'principal' => $item->unidade_principal == 1 ? true : false, ]; } } else { $unidades[] = [ 'unidade_id' => $item->unidade_id, 'nome_fantasia' => $item->unidade_nome, 'infraestruturas' => [ [ 'id' => $item->infraestrutura_id, 'nome' => $item->infraestrutura_nome, 'principal' => $item->unidade_principal == 1 ? true : false, ] ] ]; } } return $unidades; } private static function getStatus($agendamentos) { $status = []; foreach ($agendamentos as $item) { $statusInserido = null; foreach ($status as &$statu) { if ($statu['status_id'] === $item->status_id) { $statusInserido = $statu; break; } } if (!$statusInserido) { $status[] = [ 'status_id' => $item->status_id, 'descricao' => $item->status_descricao, ]; } } return $status; } public static function store() { DB::transaction(function () { self::saveStatusExame(request()->agendamentos); }); } public static function saveStatusExame($agendamentos, $additionalParams = []) { foreach ($agendamentos as $agendamento) { if ($agendamento['regulacao_solicitacao_id'] && $agendamento['controla_protocolo_fechamento']) { if ($agendamento['protocolo_fechamento'] !== $agendamento['regulacao_solicitacao_numero']) { $examesNaoAgendados = array_filter( $agendamento['exames'], fn($exame) => $exame['status_id'] !== StatusAgendamento::AGENDADO ); if (!empty($examesNaoAgendados)) { throw new ProtocoloFechamentoException(); } } } $hasExameRealizado = array_filter($agendamento['exames'], function($params) { return $params['status_id'] == StatusAgendamento::REALIZADO; }); if (!empty($hasExameRealizado)) { $agendamentoRealizado = Agendamento::where('id', $agendamento['agendamento_id'])->first(); $lotacao = Lotacao::where('usuario_id', $agendamento['usuario_id']) ->where('infraestrutura_id', $agendamento['faturamento_coleta_infraestrutura_id']) ->where('ocupacao_id', $agendamento['ocupacao_id']) ->first(); if($lotacao){ $agendamentoRealizado->lotacao_id = $lotacao['id']; } $agendamentoRealizado->usuario_id = $agendamento['usuario_id']; $agendamentoRealizado->ocupacao_id = $agendamento['ocupacao_id']; $lotacaoLaboratorio = Lotacao::where('usuario_id', $agendamento['laboratorio_usuario_id']) ->where('infraestrutura_id', $agendamento['faturamento_laboratorio_infraestrutura_id']) ->where('ocupacao_id', $agendamento['laboratorio_ocupacao_id']) ->first(); if($lotacaoLaboratorio){ $agendamentoRealizado->laboratorio_lotacao_id = $lotacaoLaboratorio['id']; } $agendamentoRealizado->laboratorio_usuario_id = $agendamento['laboratorio_usuario_id']; $agendamentoRealizado->laboratorio_ocupacao_id = $agendamento['laboratorio_ocupacao_id']; $agendamentoRealizado->save(); } foreach ($agendamento['exames'] as $params) { if (!$params['pertence_grupo']) { $exames = AgendamentoExame::where('agendamento_id', $agendamento['agendamento_id']) ->where('exame_id', $params['exame_grupo_id']) ->get(); if ($exames->isEmpty()) { continue; } $agendamentoObj = (object) $agendamento; $agendamentoObj->id = $agendamentoObj->agendamento_id; $agendamentoObj->horario = $agendamentoObj->hora_inicial; foreach ($exames as $exame) { $exame->status_id = $params['status_id']; $exame->observacao = $params['observacao']; if ($params['status_id'] == StatusAgendamento::REALIZADO) { $exame->data_coleta = Carbon::now(); } if (isset($additionalParams['pre_atendimento_id'])) { $exame->pre_atendimento_id = $additionalParams['pre_atendimento_id']; } $exame->save(); AgendamentoExameHistoricoService::store($exame, $agendamentoObj, Acao::ALTERACAO); } if (!is_null($agendamentoObj->regulacao_solicitacao_id)) { self::updateRegulacao($agendamentoObj); } } if ($params['pertence_grupo']) { $exame = AgendamentoExame::whereHas('exame', function($query) use ($params) { $query->where('grupo_tipo_id', $params['exame_grupo_id']); $query->where('mapa_agrupado', true); }) ->where('agendamento_id', $agendamento['agendamento_id']) ->update(array_merge(self::getParams($params, $agendamento), $additionalParams)); if (!is_null($agendamento['regulacao_solicitacao_id'])) { self::updateRegulacao($agendamento); } } } } } private static function updateRegulacao($agendamento) { if (is_array($agendamento)) { $exames = $agendamento['exames']; $regulacaoSolicitacaoId = $agendamento['regulacao_solicitacao_id']; } elseif (is_object($agendamento)) { $exames = $agendamento->exames; $regulacaoSolicitacaoId = $agendamento->regulacao_solicitacao_id; } $statusReferencia = $exames[0]['status_id']; $todosStatusIguais = true; foreach ($exames as $exame) { if ($exame['status_id'] !== $statusReferencia) { $todosStatusIguais = false; break; } } if ($todosStatusIguais) { $statusTipoId = null; if ($statusReferencia == StatusAgendamento::REALIZADO) { $statusTipoId = RegulacaoStatusTipoEnum::REALIZADO; } else if ($statusReferencia == StatusAgendamento::FALTOU) { $statusTipoId = RegulacaoStatusTipoEnum::FALTA; } if (!is_null($statusTipoId)) { RegulacaoSolicitacaoService::updateStatus($regulacaoSolicitacaoId, $statusTipoId); } } } private static function getParams($params, $agendamento) { if ($params['status_id'] == StatusAgendamento::REALIZADO) { return [ 'observacao' => $params['observacao'], 'status_id' => $params['status_id'], 'usuario_id' => $agendamento['usuario_id'], 'ocupacao_id' => $agendamento['ocupacao_id'], 'data_coleta' => Carbon::now(), ]; } else { return [ 'status_id' => $params['status_id'], 'observacao' => $params['observacao'], ]; } } public static function getTotal($agendamentos, $status_id) { $total = 0; foreach ($agendamentos as $agendamento) { foreach (self::getExames($agendamento) as $agendamento) { if ($agendamento->status_id == $status_id) { $total += 1; } } } return $total; } }