first(); $cboLogado = Lotacao::findOrFail(auth()->payload()->get('lotacao_id'))->ocupacao->codigo; $exameAmbulatorioAtendimento = ExameAmbulatorioAtendimento::select('exibir')->first(); return [ 'additionals' => [ 'permissoes_atualizacao_cadastro_paciente' => self::getPermissoesAtualizacaoCadastroPaciente(), ], 'form' => [ 'data_atual' => Carbon::now()->format('d/m/Y'), 'paciente' => self::getPaciente($id), 'usuario' => $currentLotacao->usuario->cidadao->nome, 'unidades' => self::getUnidadeSolicitante(), 'unidades_parametrizada' => self::getUnidadeParametrizada(), 'unidade' => $currentLotacao->infraestrutura->unidade->nome_fantasia, 'unidade_id' => $currentLotacao->infraestrutura->unidade->id, 'infraestrutura_id' => $currentLotacao->infraestrutura->id, 'infraestrutura' => $currentLotacao->infraestrutura->nome, 'is_supervisor' => Supervisor::where('usuario_id', $currentLotacao->usuario->id)->first() ? true : false, 'feriados' => Feriado::orderBy('id') ->whereHas('modulos', function ($query) { $query->where('id', ModuloService::getId(Modulo::EXAME_LABORATORIAL)); }) ->get() ->map(fn ($feriado) => [ 'id' => $feriado->id, 'data' => (new Carbon($feriado->data))->format('d/m/Y') ?? null, 'tipo_id' => $feriado->tipo_id, 'tipo_nome' => $feriado->tipo->descricao, 'observacao' => $feriado->observacao, ]), 'impressao_agendamento_tipo_id' => $impressaoAgendamento->tipo_id ?? EnumsTipoImpressaoAgendamento::PROTOCOLO_ETIQUETA, 'kits' => KitExame::orderBy('nome') ->get() ->map(fn ($kit) => [ 'id' => $kit->id, 'nome' => $kit->nome, 'checked' => false, 'exames' => DB::table('parametrizacao_kit_exame_item') ->join( 'parametrizacao_exame', 'parametrizacao_exame.id', 'parametrizacao_kit_exame_item.exame_id' ) ->join('sigtap.procedimento', function ($join) { $join->on('sigtap.procedimento.codigo', 'parametrizacao_exame.codigo') ->where('sigtap.procedimento.competencia_id', '=', function ($query) { $query->select('sigtap.competencia.id') ->from('sigtap.competencia') ->orderByDesc('sigtap.competencia.valor') ->limit(1); }); }) ->leftJoin( 'parametrizacao_procedimento', 'parametrizacao_procedimento.procedimento_codigo', 'parametrizacao_exame.codigo' ) ->whereNull('parametrizacao_kit_exame_item.deleted_at') ->whereNull('parametrizacao_exame.regulacao_tipo_id') ->where('parametrizacao_kit_exame_item.kit_exame_id', $kit->id) ->when($kit->tipo_id === Tipo::IMAGEM, function ($query) use ($cboLogado) { $query->whereExists(function($query) use ($cboLogado) { $query->select(DB::raw(1)) ->from('sigtap.procedimento_ocupacao') ->whereColumn('sigtap.procedimento_ocupacao.procedimento_id', 'sigtap.procedimento.id') ->join('sigtap.ocupacao', 'sigtap.ocupacao.id', 'sigtap.procedimento_ocupacao.ocupacao_id') ->where('sigtap.ocupacao.codigo', $cboLogado); })->orWhereNotExists(function($query) { $query->select(DB::raw(1)) ->from('sigtap.procedimento_ocupacao') ->whereColumn('sigtap.procedimento_ocupacao.procedimento_id', 'sigtap.procedimento.id'); }); }) ->orderBy('parametrizacao_exame.nome') ->select( 'parametrizacao_exame.id', 'parametrizacao_exame.tipo_id', 'parametrizacao_exame.grupo_tipo_id', 'parametrizacao_exame.codigo', 'parametrizacao_exame.nome', 'parametrizacao_exame.sigla_exame', 'parametrizacao_exame.ativo', 'parametrizacao_exame.observacao', 'parametrizacao_exame.sexo_id', 'parametrizacao_procedimento.apelido', 'sigtap.procedimento.nome as procedimento_nome', 'sigtap.procedimento.id as procedimento_id', 'sigtap.procedimento.quantidade_maxima_execucao', 'parametrizacao_exame.valor', 'parametrizacao_exame.valor_sigtap', 'parametrizacao_exame.validade', 'parametrizacao_exame.quantidade_maxima', 'parametrizacao_exame.prazo_entrega', 'parametrizacao_exame.provisorio', 'parametrizacao_exame.outro_municipio', 'parametrizacao_exame.quantidade_reagente', 'parametrizacao_exame.permite_repeticao', 'sigtap.procedimento.valor_servico_ambilatorial', 'sigtap.procedimento.sexo', ) ->get() ->map(fn($exame) => [ 'id' => $exame->id, 'exame_id' => $exame->id, 'tipo_id' => $exame->tipo_id, 'grupo_tipo_id' => $exame->grupo_tipo_id, 'codigo' => $exame->codigo, 'nome' => $exame->nome, 'sigla_exame' => $exame->sigla_exame, 'ativo' => $exame->ativo, 'observacao' => $exame->observacao, 'sexo_id' => $exame->sexo_id, 'apelido' => $exame->apelido, 'procedimento_nome' => $exame->procedimento_nome, 'procedimento_id' => $exame->procedimento_id, 'quantidade_maxima_execucao' => $exame->quantidade_maxima_execucao, 'valor' => $exame->valor, 'valor_sigtap' => $exame->valor_sigtap, 'validade' => $exame->validade, 'quantidade_maxima' => $exame->quantidade_maxima, 'prazo_entrega' => $exame->prazo_entrega, 'provisorio' => $exame->provisorio, 'outro_municipio' => $exame->outro_municipio, 'quantidade_reagente' => $exame->quantidade_reagente, 'permite_repeticao' => $exame->permite_repeticao, 'valor_servico_ambilatorial' => $exame->valor_servico_ambilatorial, 'sexo' => $exame->sexo, 'checked' => false, 'supervisor_id' => null ]) ->values() ]) ->filter(fn ($kit) => count($kit['exames']) > 0) ->values(), 'is_unidade_solicitante_parametrizada' => UnidadeSolicitanteExame::first() ? true : false, 'exibir_exame_ambulatorio_atendimento' => $exameAmbulatorioAtendimento ? $exameAmbulatorioAtendimento->exibir : false, 'datas_bloqueadas' => [], ], 'model' => [ 'data_atual' => Carbon::now()->format('d/m/Y'), 'agendamentos' => Agendamento::where('paciente_id', $id) ->get() ->map(fn ($agendamento) => [ 'agendamento_id' => $agendamento->id, 'is_em_processamento_webservice' => $agendamento->web_service_laboratorio_cliente_pedido_status_id === PedidoStatus::PROCESSANDO, 'alterado' => false, 'impressao' => false, 'agendamento_numero' => $agendamento->agendamento_numero, 'data' => (new Carbon($agendamento->data))->format('Y-m-d') ?? null, 'hora_inicial' => (new Carbon($agendamento->horario))->format('H:i') ?? null, 'incluido' => AgendamentoExame::where('agendamento_id', $agendamento->id) ->get() ->map(function ($query) { return [ 'id' => $query->id, 'exame_id' => $query->exame_id, 'nome' => $query->exame->nome, 'codigo' => $query->exame->codigo ?? null, 'valor' => $query->valor, 'status_id' => $query->status_id, 'prazo_entrega' => $query->exame->prazo_entrega ?? null, 'observacao' => $query->exame->observacao ?? null, 'procedimento_id' => $query->procedimento_id ?? null, 'supervisor_id' => $query->supervisor_id ?? null, 'ambulatorio_atendimento_id' => $query->soap_solicitacao_exame_item_id ?? null, 'acompanhamento_oci_id' => $query->acompanhamento_oci_id ?? null, ]; }) ->values(), 'alterar_agendamento' => AgendamentoExame::where('agendamento_id', $agendamento->id) ->where(function ($query) { $query->whereNotNull('status_id') ->where('status_id', '!=', StatusAgendamento::AGENDADO); }) ->first() ? false : true, 'excluir_agendamento' => AgendamentoExame::where('agendamento_id', $agendamento->id) ->where(function ($query) { $query->whereNotNull('status_id') ->where('status_id', '!=', StatusAgendamento::AGENDADO); }) ->first() ? true : false, 'regulacao_solicitacao_id' => $agendamento->regulacao_solicitacao_id ?? false, 'infraestrutura_id' => $agendamento->infraestrutura_id, 'infraestrutura_nome' => $agendamento->infraestrutura->nome, 'medico_id' => $agendamento->medico_id, 'medico_nome' => $agendamento->medico->nome, 'medico_solicitante' => [ 'id' => $agendamento->medico_id, 'cidadao_nome' => $agendamento->medico->nome, ], 'paciente_id' => $agendamento->paciente_id, 'supervisor_id' => $agendamento->supervisor_id, 'unidade_id' => $agendamento->unidade_id, 'unidade_nome' => $agendamento->unidade->nome_fantasia, 'urgente' => $agendamento->urgente, 'retroativo' => $agendamento->retroativo, ]) ->sortBy('data') ->values(), 'agendamentos_not_save' => [], 'agendamentos_search' => [], 'agendamentos_deletados' => [], 'periodo' => [ 'start' => Carbon::now()->format('d/m/Y'), 'end' => Carbon::now()->format('d/m/Y'), ], ], ]; } public static function getHistoricoMedicamento($id) { return AgendamentoHistoricoMedicamento::where('paciente_id', $id) ->get() ->map(function ($query) { return [ 'data' => (new Carbon($query->data))->format('d/m/Y') ?? null, 'uso_medicamento' => $query->uso_medicamento, ]; }) ->values(); } public static function getDetalhamento($id) { $agendamento = Agendamento::findOrFail($id); return [ 'agendamento_numero' => $agendamento->agendamento_numero, 'data' => (new Carbon($agendamento->data))->format('Y-m-d') ?? null, 'ultima_menstruacao' => $agendamento->ultima_menstruacao ? $agendamento->ultima_menstruacao->format('Y-m-d') : null, 'gestante' => $agendamento->gestante, 'hora_inicial' => (new Carbon($agendamento->horario))->format('H:i') ?? null, 'incluido' => AgendamentoExame::where('agendamento_id', $agendamento->id) ->get() ->map(function ($query) { return [ 'nome' => $query->exame->nome ]; }) ->values(), 'infraestrutura_nome' => $agendamento->infraestrutura->nome, 'coleta_infraestrutura_nome' => $agendamento->coletaInfraestrutura->nome, 'laboratorio_infraestrutura_nome' => $agendamento->laboratorioInfraestrutura->nome, 'medico_nome' => $agendamento->medico->nome, 'observacao' => $agendamento->observacao, 'responsavel' => $agendamento->responsavel, 'suspeita' => $agendamento->suspeita_clinica, 'data_menstruacao' => $agendamento->ultima_menstruacao, 'unidade_nome' => $agendamento->unidade->nome_fantasia, 'coleta_nome' => $agendamento->coletaUnidade->nome_fantasia, 'laboratorio_nome' => $agendamento->laboratorioUnidade->nome_fantasia, 'urgente' => $agendamento->urgente, 'medicamentos' => $agendamento->uso_medicamento ]; } public static function getAgendamento($id) { $agendamento = Agendamento::findOrFail($id); return [ 'agendamento_id' => $agendamento->id, 'alterado' => true, 'impressao' => true, 'supervisor' => true, 'showInfo' => true, 'agendamento_numero' => $agendamento->agendamento_numero, 'coleta_infraestrutura_id' => $agendamento->coleta_infraestrutura_id, 'coleta_unidade_id' => $agendamento->coleta_unidade_id, 'data' => (new Carbon($agendamento->data))->format('Y-m-d') ?? null, 'ultima_menstruacao' => $agendamento->ultima_menstruacao ? $agendamento->ultima_menstruacao->format('Y-m-d') : null, 'gestante' => $agendamento->gestante, 'hora_inicial' => (new Carbon($agendamento->horario))->format('H:i') ?? null, 'incluido' => AgendamentoExame::where('agendamento_id', $agendamento->id) ->get() ->map(function ($query) { return [ 'id' => $query->id, 'exame_id' => $query->exame_id, 'nome' => $query->exame->nome, 'codigo' => $query->exame->codigo ?? null, 'valor' => $query->valor, 'status_id' => $query->status_id, 'supervisor_id' => $query->supervisor_id ?? null, 'prazo_entrega' => $query->exame->prazo_entrega ?? null, 'observacao' => $query->exame->observacao ?? null, 'procedimento_id' => $query->procedimento_id ?? null, 'ambulatorio_atendimento_id' => $query->soap_solicitacao_exame_item_id ?? null, 'acompanhamento_oci_id' => $query->acompanhamento_oci_id ?? null, ]; }) ->values(), 'alterar_agendamento' => AgendamentoExame::where('agendamento_id', $agendamento->id) ->where(function ($query) { $query->whereNotNull('status_id') ->where('status_id', '!=', StatusAgendamento::AGENDADO); }) ->first() ? false : true, 'excluir_agendamento' => AgendamentoExame::where('agendamento_id', $agendamento->id) ->where(function ($query) { $query->whereNotNull('status_id') ->where('status_id', '!=', StatusAgendamento::AGENDADO); }) ->first() ? true : false, 'infraestrutura_id' => $agendamento->infraestrutura_id, 'infraestrutura_nome' => $agendamento->infraestrutura->nome, 'coleta_infraestrutura_nome' => $agendamento->coletaInfraestrutura->nome, 'laboratorio_infraestrutura_nome' => $agendamento->laboratorioInfraestrutura->nome, 'jornada_id' => $agendamento->jornada_id, 'laboratorio_infraestrutura_id' => $agendamento->laboratorio_infraestrutura_id, 'laboratorio_id' => $agendamento->laboratorio_unidade_id, 'medico_id' => $agendamento->medico_id, 'medico_nome' => $agendamento->medico->nome, 'medico_solicitante' => [ 'id' => $agendamento->medico_id, 'cidadao_nome' => $agendamento->medico->nome, ], 'observacao' => $agendamento->observacao, 'paciente_id' => $agendamento->paciente_id, 'supervisor_id' => $agendamento->supervisor_id, 'responsavel' => $agendamento->responsavel, 'suspeita' => $agendamento->suspeita_clinica, 'data_menstruacao' => $agendamento->ultima_menstruacao, 'unidade_id' => $agendamento->unidade_id, 'unidade_nome' => $agendamento->unidade->nome_fantasia, 'coleta_nome' => $agendamento->coletaUnidade->nome_fantasia, 'laboratorio_nome' => $agendamento->laboratorioUnidade->nome_fantasia, 'urgente' => $agendamento->urgente, 'medicamentos' => $agendamento->uso_medicamento, 'retroativo' => $agendamento->retroativo, ]; } public static function printEtiqueta($id) { $agendamento = Agendamento::findOrFail($id); $currentLotacao = self::getCurrentLotacao(); $cliente = Cliente::where('link', app('config')->get('database.default'))->firstOrFail(); return [ 'agendamento_numero' => $agendamento->agendamento_numero, 'unidade_nome' => $agendamento->unidade->nome_fantasia, 'laboratorio_nome' => $agendamento->laboratorioUnidade->nome_fantasia, 'cliente' => [ 'sistema' => [ 'ramo_atividade' => [ 'nome' => $cliente->sistema->ramoAtividade->nome ?? null, ], 'nome' => $cliente->sistema->nome ?? null, 'versao' => $cliente->sistema->versao ?? null, ], 'municipio' => [ 'estado' => [ 'uf' => $cliente->municipio->estado->uf ?? null, ], 'nome' => $cliente->municipio->nome ?? null, ], 'nome' => $cliente->nome ?? null, 'email' => $cliente->email ?? null, 'site' => $cliente->site ?? null, 'logotipo' => $cliente->logotipo ?? null, ], 'unidade' => $currentLotacao->infraestrutura->unidade->nome_fantasia, ]; } public static function printProtocolo($id) { $agendamento = Agendamento::findOrFail($id); $currentLotacao = self::getCurrentLotacao(); $cliente = Cliente::where('link', app('config')->get('database.default'))->firstOrFail(); $mensagemProtocolo = MensagemProtocolo::select('mensagem')->first(); return [ 'agendamento_numero' => $agendamento->agendamento_numero, 'regulacao_solicitacao_numero' => $agendamento->regulacaoSolicitacao->numero ?? null, 'data' => (new Carbon($agendamento->data))->format('Y-m-d') ?? null, 'hora_inicial' => (new Carbon($agendamento->horario))->format('H:i') ?? null, 'incluido' => AgendamentoExame::where('agendamento_id', $agendamento->id) ->get() ->map(function ($query) { return [ 'nome' => $query->exame->nome, 'codigo' => $query->exame->codigo ?? null, 'prazo_entrega' => $query->exame->prazo_entrega ?? null, 'observacao' => $query->exame->observacao ?? null, ]; }) ->values(), 'infraestrutura_nome' => $agendamento->infraestrutura->nome, 'coleta_infraestrutura_nome' => $agendamento->coletaInfraestrutura->nome, 'coleta_endereco' => $agendamento->coletaInfraestrutura->endereco->logradouro->nome, 'coleta_numero_endereco' => $agendamento->coletaInfraestrutura->endereco->numero ?? 'S/N', 'coleta_bairro' => $agendamento->coletaInfraestrutura->endereco->logradouro->bairro->nome, 'coleta_cep' => MaskUtil::getCepMasked($agendamento->coletaInfraestrutura->endereco->logradouro->cep), 'coleta_tipo' => $agendamento->coletaInfraestrutura->endereco->logradouro->tipo->descricao, 'coleta_telefone' => $agendamento->coletaInfraestrutura->telefone ? MaskUtil::getPhoneMasked($agendamento->coletaInfraestrutura->telefone) : 'NÃO INFORMADO', 'laboratorio_infraestrutura_nome' => $agendamento->laboratorioInfraestrutura->nome, 'medico_nome' => $agendamento->medico->nome, 'observacao' => $agendamento->observacao, 'responsavel' => $agendamento->responsavel, 'data_menstruacao' => $agendamento->ultima_menstruacao, 'unidade_nome' => $agendamento->unidade->nome_fantasia, 'unidade_endereco' => $agendamento->infraestrutura->endereco->logradouro->nome, 'unidade_numero_endereco' => $agendamento->infraestrutura->endereco->numero ?? 'S/N', 'unidade_bairro' => $agendamento->infraestrutura->endereco->logradouro->bairro->nome, 'unidade_cep' => MaskUtil::getCepMasked($agendamento->infraestrutura->endereco->logradouro->cep), 'unidade_tipo' => $agendamento->infraestrutura->endereco->logradouro->tipo->descricao, 'unidade_telefone' => $agendamento->infraestrutura->telefone ? MaskUtil::getPhoneMasked($agendamento->infraestrutura->telefone) : 'NÃO INFORMADO', 'coleta_nome' => $agendamento->coletaUnidade->nome_fantasia, 'laboratorio_nome' => $agendamento->laboratorioUnidade->nome_fantasia, 'laboratorio_endereco' => $agendamento->laboratorioInfraestrutura->endereco->logradouro->nome, 'laboratorio_numero_endereco' => $agendamento->laboratorioInfraestrutura->endereco->numero ?? 'S/N', 'laboratorio_bairro' => $agendamento->laboratorioInfraestrutura->endereco->logradouro->bairro->nome, 'laboratorio_cep' => MaskUtil::getCepMasked($agendamento->laboratorioInfraestrutura->endereco->logradouro->cep), 'laboratorio_tipo' => $agendamento->laboratorioInfraestrutura->endereco->logradouro->tipo->descricao, 'laboratorio_telefone' => $agendamento->laboratorioInfraestrutura->telefone ? MaskUtil::getPhoneMasked($agendamento->laboratorioInfraestrutura->telefone) : 'NÃO INFORMADO', 'urgente' => $agendamento->urgente, 'cliente' => [ 'sistema' => [ 'ramo_atividade' => [ 'nome' => $cliente->sistema->ramoAtividade->nome ?? null, ], 'nome' => $cliente->sistema->nome ?? null, 'versao' => $cliente->sistema->versao ?? null, ], 'municipio' => [ 'estado' => [ 'uf' => $cliente->municipio->estado->uf ?? null, ], 'nome' => $cliente->municipio->nome ?? null, ], 'nome' => $cliente->nome ?? null, 'email' => $cliente->email ?? null, 'site' => $cliente->site ?? null, 'logotipo' => $cliente->logotipo ?? null, ], 'unidade' => $currentLotacao->infraestrutura->unidade->nome_fantasia, 'usuario' => $currentLotacao->usuario->cidadao->nome, 'usuario_nome_social' => $currentLotacao->usuario->cidadao->nome_social ?? null, 'mensagem_protocolo' => $mensagemProtocolo->mensagem, ]; } public static function getJornadas($request) { return [ 'agendamentos' => Agendamento::where('coleta_unidade_id', $request->unidade_id) ->where('coleta_infraestrutura_id', $request->infraestrutura_id) ->whereHas('agendamentoExame', function ($query) { $query->whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]); }) ->get() ->map(fn ($agendamento) => [ 'agendamento_id' => $agendamento->id, 'agendamento_numero' => $agendamento->agendamento_numero, 'coleta_infraestrutura_id' => $agendamento->coleta_infraestrutura_id, 'coleta_unidade_id' => $agendamento->coleta_unidade_id, 'data' => (new Carbon($agendamento->data))->format('d/m/Y') ?? null, 'hora_inicial' => (new Carbon($agendamento->horario))->format('H:i') ?? null, ]) ->sortBy('data') ->values(), 'jornadas' => Jornada::where('unidade_id', $request->unidade_id) ->where('infraestrutura_id', $request->infraestrutura_id) ->get() ->map(fn ($jornada) => [ 'jornada_id' => $jornada->id, 'unidade_id' => $jornada->unidade_id, 'infraestrutura_id' => $jornada->infraestrutura_id, 'semana_id' => $jornada->semana_id, 'dias_semana' => $jornada->semana_id, 'tipo_id' => $jornada->tipo_id, 'tipo_nome' => $jornada->tipo->nome ?? null, 'data' => (new Carbon($jornada->data))->format('d/m/Y') ?? null, 'periodo' => [ 'start' => (new Carbon($jornada->data))->format('d/m/Y') ?? null, 'end' => (new Carbon($jornada->data))->format('d/m/Y') ?? null, ], 'hora_inicial' => (new Carbon($jornada->hora_inicial))->format('H:i') ?? null, 'hora_fim' => (new Carbon($jornada->hora_fim))->format('H:i') ?? null, 'vagas' => $jornada->vagas ?? null, 'vagas_app' => $jornada->vagas_app ?? null, 'tempo_atendimento' => $jornada->tempo_atendimento ?? null, 'selecionado' => false, ]) ->sortBy('data') ->sortBy('hora_inicial') ->values(), 'datas_bloqueadas' => self::getCadastroDatasBloqueadas($request), ]; } private static function getUnidadeSolicitante() { $unidade = DB::table('exame_laboratorial_parametrizacao_cota_unidade_solicitante as unidade_solicitante') ->select([ 'cadastro_unidade.id AS unidade_id', 'cadastro_infraestrutura.id AS infraestrutura_id', 'cadastro_unidade.nome_fantasia as nome_fantasia', 'exame_laboratorial_parametrizacao_unidade_solicitante_exame.urgencia', DB::raw(" CASE WHEN cadastro_infraestrutura.nome IS NOT NULL THEN cadastro_infraestrutura.nome ELSE cadastro_unidade.nome_fantasia END AS nome_infraestrutura "), 'cadastro_infraestrutura.principal as principal' ]) ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'unidade_solicitante.infraestrutura_solicitante_id') ->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->leftJoin('exame_laboratorial_parametrizacao_unidade_solicitante_exame', 'exame_laboratorial_parametrizacao_unidade_solicitante_exame.infraestrutura_id', 'cadastro_infraestrutura.id') ->whereNull('unidade_solicitante.deleted_at') ->whereNull('cadastro_infraestrutura.deleted_at') ->whereNull('cadastro_unidade.deleted_at') ->distinct('infraestrutura_id') ->union( DB::table('exame_laboratorial_parametrizacao_cota_exame_unidade as unidade_exame') ->select([ 'cadastro_unidade.id AS unidade_id', 'cadastro_infraestrutura.id AS infraestrutura_id', 'cadastro_unidade.nome_fantasia as nome_fantasia', 'exame_laboratorial_parametrizacao_unidade_solicitante_exame.urgencia', DB::raw(" CASE WHEN cadastro_infraestrutura.nome IS NOT NULL THEN cadastro_infraestrutura.nome ELSE cadastro_unidade.nome_fantasia END AS nome_infraestrutura "), 'cadastro_infraestrutura.principal as principal' ]) ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'unidade_exame.infraestrutura_solicitante_id') ->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->leftJoin('exame_laboratorial_parametrizacao_unidade_solicitante_exame', 'exame_laboratorial_parametrizacao_unidade_solicitante_exame.infraestrutura_id', 'cadastro_infraestrutura.id') ->whereNull('unidade_exame.deleted_at') ->whereNull('cadastro_infraestrutura.deleted_at') ->distinct('infraestrutura_id') ) ->union( DB::table('exame_laboratorial_parametrizacao_cota as unidade_solicitante') ->select([ 'cadastro_unidade.id AS unidade_id', 'cadastro_infraestrutura.id AS infraestrutura_id', 'cadastro_unidade.nome_fantasia as nome_fantasia', 'exame_laboratorial_parametrizacao_unidade_solicitante_exame.urgencia', DB::raw(" CASE WHEN cadastro_infraestrutura.nome IS NOT NULL THEN cadastro_infraestrutura.nome ELSE cadastro_unidade.nome_fantasia END AS nome_infraestrutura "), 'cadastro_infraestrutura.principal as principal' ]) ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'unidade_solicitante.infraestrutura_id') ->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->leftJoin('exame_laboratorial_parametrizacao_unidade_solicitante_exame', 'exame_laboratorial_parametrizacao_unidade_solicitante_exame.infraestrutura_id', 'cadastro_infraestrutura.id') ->where('unidade_solicitante.unidade_tipo_id', TipoUnidade::UNIDADE_SOLICITANTE) ->whereNull('unidade_solicitante.deleted_at') ->whereNull('cadastro_infraestrutura.deleted_at') ->distinct('infraestrutura_id') ) ->orderBy('nome_fantasia') ->get(); if ($unidade->isEmpty()) { $unidade = DB::table('exame_laboratorial_parametrizacao_unidade_solicitante as unidade_solicitante') ->select([ 'cadastro_unidade.id AS unidade_id', 'cadastro_infraestrutura.id AS infraestrutura_id', 'cadastro_unidade.nome_fantasia as nome_fantasia', 'exame_laboratorial_parametrizacao_unidade_solicitante_exame.urgencia', DB::raw(" CASE WHEN cadastro_infraestrutura.nome IS NOT NULL THEN cadastro_infraestrutura.nome ELSE cadastro_unidade.nome_fantasia END AS nome_infraestrutura "), 'cadastro_infraestrutura.principal as principal' ]) ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'unidade_solicitante.unidade_solicitante_infraestrutura_id') ->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->leftJoin('exame_laboratorial_parametrizacao_unidade_solicitante_exame', 'exame_laboratorial_parametrizacao_unidade_solicitante_exame.infraestrutura_id', 'cadastro_infraestrutura.id') ->where('unidade_solicitante.unidade_tipo_id', TipoUnidade::COLETA) ->whereNull('unidade_solicitante.deleted_at') ->whereNull('cadastro_infraestrutura.deleted_at') ->distinct('infraestrutura_id') ->orderBy('nome_fantasia') ->get(); } if ($unidade->isEmpty()) { $unidade = DB::table('cadastro_infraestrutura') ->select([ 'cadastro_unidade.id AS unidade_id', 'cadastro_infraestrutura.id AS infraestrutura_id', 'cadastro_unidade.nome_fantasia as nome_fantasia', 'exame_laboratorial_parametrizacao_unidade_solicitante_exame.urgencia', DB::raw(" CASE WHEN cadastro_infraestrutura.nome IS NOT NULL THEN cadastro_infraestrutura.nome ELSE cadastro_unidade.nome_fantasia END AS nome_infraestrutura "), 'cadastro_infraestrutura.principal as principal' ]) ->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->leftJoin('exame_laboratorial_parametrizacao_unidade_solicitante_exame', 'exame_laboratorial_parametrizacao_unidade_solicitante_exame.infraestrutura_id', 'cadastro_infraestrutura.id') ->whereNull('cadastro_infraestrutura.deleted_at') ->distinct('infraestrutura_id') ->orderBy('nome_fantasia') ->get(); } $resultadoAgrupado = []; foreach ($unidade as $item) { $unidadeId = $item->unidade_id; $infraestruturaId = $item->infraestrutura_id; $nomeInfraestrutura = $item->nome_infraestrutura; $urgencia = $item->urgencia ? true : false; if (!isset($resultadoAgrupado[$unidadeId])) { $resultadoAgrupado[$unidadeId] = [ 'id' => $unidadeId, 'urgencia' => $urgencia, 'nome_fantasia' => $item->nome_fantasia, 'infraestruturas' => [] ]; } $resultadoAgrupado[$unidadeId]['infraestruturas'][] = [ 'id' => $infraestruturaId, 'urgencia' => $urgencia, 'nome' => $nomeInfraestrutura, 'principal' => $item->principal ]; } usort($resultadoAgrupado, function ($a, $b) { return strcmp($a['nome_fantasia'], $b['nome_fantasia']); }); return $resultadoAgrupado; } private static function getUnidadeParametrizada() { $unidade = DB::table('exame_laboratorial_parametrizacao_unidade_solicitante as unidade_solicitante') ->select([ 'unidade_solicitante.unidade_solicitante_infraestrutura_id as unidade_solicitante_infraestrutura_id', 'exame_laboratorial_parametrizacao_unidade.laboratorio AS laboratorio', 'exame_laboratorial_parametrizacao_unidade.unidade_coleta AS coleta', 'exame_laboratorial_parametrizacao_unidade.laboratorio_padrao_infraestrutura_id', 'cadastro_unidade.id AS unidade_id', 'cadastro_infraestrutura.id AS infraestrutura_id', 'cadastro_unidade.nome_fantasia as nome_fantasia', DB::raw(" CASE WHEN cadastro_infraestrutura.nome IS NOT NULL THEN cadastro_infraestrutura.nome ELSE cadastro_unidade.nome_fantasia END AS nome_infraestrutura "), 'cadastro_infraestrutura.principal as principal' ]) ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'unidade_solicitante.infraestrutura_id') ->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->join('exame_laboratorial_parametrizacao_unidade', 'exame_laboratorial_parametrizacao_unidade.infraestrutura_id', 'cadastro_infraestrutura.id') ->whereNull('unidade_solicitante.deleted_at') ->whereNull('cadastro_infraestrutura.deleted_at') ->distinct('infraestrutura_id') ->orderBy('nome_fantasia') ->get(); $resultadoAgrupado = []; foreach ($unidade as $item) { $unidadeId = $item->unidade_id; $infraestruturaId = $item->infraestrutura_id; $nomeInfraestrutura = $item->nome_infraestrutura; if (!isset($resultadoAgrupado[$unidadeId])) { $resultadoAgrupado[$unidadeId] = [ 'id' => $unidadeId, 'nome_fantasia' => $item->nome_fantasia, 'laboratorio' => $item->laboratorio, 'coleta' => $item->coleta, 'laboratorio_padrao_infraestrutura_id' => $item->laboratorio_padrao_infraestrutura_id, 'infraestruturas' => [] ]; } $resultadoAgrupado[$unidadeId]['infraestruturas'][] = [ 'id' => $infraestruturaId, 'unidade_solicitante_infraestrutura_id' => $item->unidade_solicitante_infraestrutura_id, 'nome' => $nomeInfraestrutura, 'principal' => $item->principal ]; } usort($resultadoAgrupado, function ($a, $b) { return strcmp($a['nome_fantasia'], $b['nome_fantasia']); }); return $resultadoAgrupado; } private static function getPaciente($id) { $paciente = DB::table('cadastro_paciente') ->select([ 'cadastro_paciente.id AS paciente_id', 'cadastro_cidadao.nome AS cidadao_nome', 'cadastro_cidadao.cns AS cidadao_cns', 'cadastro_cidadao.cpf AS cidadao_cpf', 'cadastro_sexo.id AS sexo_id', 'cadastro_sexo.descricao AS sexo_descricao', 'cadastro_cidadao.data_nascimento AS cidadao_data_nascimento', 'cadastro_cidadao.nome_mae AS cidadao_nome_mae', DB::raw('LPAD(cadastro_paciente.prontuario,7,0) AS paciente_prontuario'), 'cadastro_unidade.nome_fantasia AS unidade_nome_fantasia', DB::raw('GROUP_CONCAT(DISTINCT cadastro_cidadao_telefone.numero) as cidadao_telefones'), 'cadastro_cidadao.nome_social AS cidadao_nome_social', 'cadastro_cidadao.preferencia_nome_id AS cidadao_preferencia_nome_id', 'cadastro_paciente_classificacao.descricao AS paciente_classificacao_descricao', 'cadastro_paciente_classificacao.id AS paciente_classificacao_id', 'cadastro_raca_cor.descricao as cidadao_raca_cor', 'cadastro_cidadao.id AS cidadao_id', ]) ->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id') ->join('cadastro_sexo', 'cadastro_sexo.id', 'cadastro_cidadao.sexo_id') ->leftJoin('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_paciente.unidade_id') ->leftJoin('cadastro_cidadao_telefone', 'cadastro_cidadao.id', 'cadastro_cidadao_telefone.cidadao_id') ->leftJoin('cadastro_paciente_classificacao', 'cadastro_paciente_classificacao.id', 'cadastro_paciente.classificacao_id') ->leftJoin('cadastro_raca_cor', 'cadastro_raca_cor.id', 'cadastro_cidadao.raca_cor_id') ->whereNull('cadastro_paciente.deleted_at') ->whereNull('cadastro_cidadao_telefone.deleted_at') ->where('cadastro_paciente.id', $id) ->first(); return [ 'paciente_id' => $paciente->paciente_id, 'cidadao_nome' => $paciente->cidadao_nome, 'cidadao_nome_social' => $paciente->cidadao_nome_social, 'cidadao_preferencia_nome_id' => $paciente->cidadao_preferencia_nome_id, 'cidadao_cns' => $paciente->cidadao_cns, 'cidadao_cpf' => $paciente->cidadao_cpf, 'sexo_id' => $paciente->sexo_id, 'sexo_descricao' => $paciente->sexo_descricao, 'cidadao_raca_cor' => $paciente->cidadao_raca_cor ?? 'Não informado', 'cidadao_data_nascimento' => $paciente->cidadao_data_nascimento ? (new Carbon($paciente->cidadao_data_nascimento))->format('d/m/Y') : '', 'cidadao_idade' => Carbon::create($paciente->cidadao_data_nascimento)->diff(Carbon::now())->format('%ya, %mm e %dd'), 'cidadao_idade_anos' => (int) Carbon::create($paciente->cidadao_data_nascimento)->diff(Carbon::now())->format('%y'), 'cidadao_idade_meses' => (int) Carbon::create($paciente->cidadao_data_nascimento)->diff(Carbon::now())->format('%m'), 'cidadao_idade_dias' => (int) Carbon::create($paciente->cidadao_data_nascimento)->diff(Carbon::now())->format('%d'), 'cidadao_nome_mae' => $paciente->cidadao_nome_mae, 'unidade_nome_fantasia' => $paciente->unidade_nome_fantasia, 'paciente_prontuario' => $paciente->paciente_prontuario, 'paciente_classificacao_id' => $paciente->paciente_classificacao_id, 'cidadao_telefones' => self::formatPhone($paciente->cidadao_telefones), 'cidadao_id' => $paciente->cidadao_id, ]; } private static function formatPhone($telefones) { $telefones = explode(',', $telefones); $telefonesComMascara = ''; foreach ($telefones as $telefone) { $telefonesComMascara .= MaskUtil::getPhoneMasked($telefone) . ', '; } $telefonesComMascara = rtrim($telefonesComMascara, ', '); return $telefonesComMascara; } public static function getSupervisor($request) { return [ 'supervisores' => Supervisor::where('usuario_id', $request->supervisor_id) ->get() ->map(fn ($supervisor) => [ 'id' => $supervisor->id, 'usuario_id' => $supervisor->usuario_id, ]), ]; } public static function store(Request $request) { self::validate($request); return self::saveAgendamento($request); } private static function saveAgendamento($request) { foreach ($request->agendamentos_not_save as $params) { if ($params['agendamento_id'] && is_numeric($params['agendamento_id'])) { $agendamento = Agendamento::where('id', $params['agendamento_id'])->first(); $agendamento->agendamento_numero = $params['agendamento_numero']; $retroativo = $agendamento->retroativo; } else { $ultimo_agendamento = Agendamento::orderByDesc('agendamento_numero')->first(); $agendamento_numero = $ultimo_agendamento ? $ultimo_agendamento->agendamento_numero + 1 : 1; $agendamento_numero = $ultimo_agendamento ? $ultimo_agendamento->agendamento_numero + 1 : 1; $retroativo = true; $agendamento = new Agendamento(); $agendamento->agendamento_numero = $agendamento_numero; $agendamento->web_service_laboratorio_cliente_pedido_status_id = PedidoStatus::AGUARDANDO_PROCESSAMENTO; } $agendamento->paciente_id = $params['paciente_id']; $agendamento->jornada_id = $params['jornada_id']; $agendamento->medico_id = $params['medico_id']; $agendamento->data = $params['data']; $agendamento->horario = $params['hora_inicial']; $agendamento->unidade_id = $params['unidade_id']; $agendamento->infraestrutura_id = $params['infraestrutura_id']; $agendamento->coleta_unidade_id = $params['coleta_unidade_id']; $agendamento->coleta_infraestrutura_id = $params['coleta_infraestrutura_id']; $agendamento->laboratorio_unidade_id = $params['laboratorio_id']; $agendamento->laboratorio_infraestrutura_id = $params['laboratorio_infraestrutura_id']; $agendamento->uso_medicamento = $params['medicamentos']; $agendamento->suspeita_clinica = $params['suspeita']; $agendamento->observacao = $params['observacao']; $agendamento->urgente = $params['urgente']; $agendamento->ultima_menstruacao = $params['data_menstruacao']; $agendamento->responsavel = $params['responsavel'] ?? null; $agendamento->gestante = $params['gestante']; $agendamento->retroativo = $retroativo; $agendamento->supervisor_id = $params['supervisor_id']; if (isset($params['regulacao_solicitacao_id'])) { $agendamento->regulacao_solicitacao_id = $params['regulacao_solicitacao_id']; } $unidadeUrgencia = UnidadeSolicitanteExame::where('infraestrutura_id', $params['infraestrutura_id']) ->where('urgencia', true) ->first(); if ($params['impressao'] == true && $params['supervisor_id'] == null && !$unidadeUrgencia) { self::verifyJornada($params); self::getSaldoLaboratorioQuantidade($params); self::getSaldoLaboratorioValor($params); self::getSaldoUnidadeQuantidade($params); self::getSaldoUnidadeValor($params); self::getSaldoExameQuantidade($params); self::getSaldoExameValor($params); self::getSaldoExamePeriodoQuantidade($params); self::getSaldoExamePeriodoValor($params); } $agendamento->save(); self::saveExames($params, $agendamento); if (strlen($params['medicamentos']) > 0) { self::saveHistorico($params, $agendamento); } if ($params['impressao'] == true) { $impressao_agendamento_id = $agendamento->id; } } foreach ($request->agendamentos as $params) { if ($params['agendamento_id'] && is_numeric($params['agendamento_id'])) { $agendamento = Agendamento::where('id', $params['agendamento_id'])->first(); foreach ($params['incluido'] as $param_exame) { $exameAcao = Acao::ALTERACAO; if (isset($param_exame['status_id']) && $param_exame['status_id'] === StatusAgendamento::CANCELADO) { if ($param_exame['id'] && is_numeric($param_exame['id'])) { $exame = AgendamentoExame::where('id', $param_exame['id'])->first(); $exame->status_id = $param_exame['status_id']; $exame->save(); AgendamentoExameHistoricoService::store($exame, $agendamento, $exameAcao); if (!is_null($params['regulacao_solicitacao_id'])) { RegulacaoSolicitacaoService::updateStatus( $params['regulacao_solicitacao_id'], RegulacaoStatusTipoEnum::CANCELADO, ['justificativa' => 'Cancelado automaticamente pela funcionalidade Agendamento de exame'] ); } } } } } } foreach ($request->agendamentos_deletados as $params) { if ($params['agendamento_id'] && is_numeric($params['agendamento_id'])) { AgendamentoHistoricoMedicamento::where('agendamento_id', $params['agendamento_id'])->delete(); AgendamentoExame::where('agendamento_id', $params['agendamento_id'])->delete(); Agendamento::where('id', $params['agendamento_id'])->delete(); } } if (isset($impressao_agendamento_id)) { return self::printProtocolo($impressao_agendamento_id); } } private static function saveExames($params, $agendamento) { $idsExame = []; foreach ($params['incluido'] as $param_exame) { $exame = null; if (!empty($param_exame['id']) && is_numeric($param_exame['id'])) { $exame = AgendamentoExame::find($param_exame['id']); } if (empty($exame)) { $exame = new AgendamentoExame(); } $valor_exame = $param_exame['valor'] ?? null; $status_id = $exame['status_id'] ?? StatusAgendamento::AGENDADO; $exame->agendamento_id = $agendamento->id; $exame->paciente_id = $agendamento->paciente_id; $exame->exame_id = $param_exame['exame_id']; $exame->supervisor_id = $param_exame['supervisor_id']; $exame->status_id = $status_id; $exame->valor = $valor_exame; $exame->procedimento_id = $param_exame['procedimento_id']; $exame->soap_solicitacao_exame_item_id = $param_exame['ambulatorio_atendimento_id'] ?? null; $exame->acompanhamento_oci_id = $param_exame['acompanhamento_oci_id'] ?? null; $exame->quantidade = 1; $exame->save(); $idsExame[] = $exame->id; if (!empty($param_exame['ambulatorio_atendimento_id']) && is_numeric($param_exame['ambulatorio_atendimento_id'])) { AtendimentoSoapSolicitacaoExameItem::findOrFail($param_exame['ambulatorio_atendimento_id'])->update(['agendado_exame_laboratorial' => true]); } } AgendamentoExame::destroy(AgendamentoExame::where('agendamento_id', $agendamento->id) ->whereNotIn('id', $idsExame)->pluck('id')); } public static function saveExameBloqueado() { $exame = new AgendamentoExameBloqueado; $exame->paciente_id = request()->paciente_id; $exame->exame_id = request()->exame_id; $exame->valor = request()->valor; $exame->motivo = request()->motivo; $exame->save(); } private static function saveHistorico($params, $agendamento) { $historico_medicamento = AgendamentoHistoricoMedicamento::where('agendamento_id', $agendamento->id)->first() ?? new AgendamentoHistoricoMedicamento; $historico_medicamento->agendamento_id = $agendamento->id; $historico_medicamento->paciente_id = $agendamento->paciente_id; $historico_medicamento->data = $params['data']; $historico_medicamento->uso_medicamento = $params['medicamentos']; $historico_medicamento->save(); } private static function verifyJornada($params) { $agendamentoCadastrado = Agendamento::where('data', '=', $params['data']) ->whereHas('agendamentoExame', function ($query){ $query->whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, StatusAgendamento::NOVA_COLETA, ]); }) ->where('coleta_infraestrutura_id', $params['coleta_infraestrutura_id']) ->count('id') ?? 0; $jornada = Jornada::where('unidade_id', $params['coleta_unidade_id']) ->where('infraestrutura_id', $params['coleta_infraestrutura_id']) ->where('data', '=', $params['data']) ->selectRaw('SUM(vagas + COALESCE(vagas_app, 0)) as total_vagas') ->value('total_vagas') ?? 0; if ($agendamentoCadastrado > $jornada) { throw new ExceededVagaJornadaException; } } private static function getSaldoLaboratorioQuantidade($params) { $cotaLaboratorio = Cota::where('unidade_id', $params['laboratorio_id']) ->where('infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('inicio', '<=', $params['data']) ->where('fim', '>=', $params['data']) ->first(); if ($cotaLaboratorio) { $totalUnidade = CotaUnidadeSolicitante::where('cota_id', $cotaLaboratorio->id) ->where('unidade_solicitante_id', $params['unidade_id']) ->where('infraestrutura_solicitante_id', $params['infraestrutura_id']) ->sum('cota_quantidade') ?? 0; $saldoEnviado = CotaTransferencia::where('laboratorio_unidade_id', $params['laboratorio_id']) ->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('origem_unidade_id', $params['unidade_id']) ->where('origem_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', $params['data']) ->where('origem_fim', '>=', $params['data']) ->sum('destino_cota_quantidade'); $saldoRecebido = CotaTransferencia::where('laboratorio_unidade_id', $params['laboratorio_id']) ->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('destino_unidade_id', $params['unidade_id']) ->where('destino_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', $params['data']) ->where('origem_fim', '>=', $params['data']) ->sum('destino_cota_quantidade'); if ($totalUnidade == 0) { $totalUnidade = CotaExameUnidadeSolicitante::where('cota_id', $cotaLaboratorio->id) ->where('unidade_solicitante_id', $params['unidade_id']) ->where('infraestrutura_solicitante_id', $params['infraestrutura_id']) ->sum('cota_quantidade') ?? 0; $cotaEnviada = CotaTransferencia::where('laboratorio_unidade_id', $params['laboratorio_id']) ->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('origem_unidade_id', $params['unidade_id']) ->where('origem_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', $params['data']) ->where('origem_fim', '>=', $params['data']) ->get(); foreach ($cotaEnviada as $param_transferencia) { $saldoEnviado = $saldoEnviado + CotaTransferenciaExames::where('cota_transferencia_id', $param_transferencia['id']) ->sum('cota_quantidade_transferido'); } $cotaRecebida = CotaTransferencia::where('laboratorio_unidade_id', $params['laboratorio_id']) ->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('destino_unidade_id', $params['unidade_id']) ->where('destino_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('destino_inicio', '<=', $params['data']) ->where('destino_fim', '>=', $params['data']) ->get(); $saldoEnviado = 0; foreach ($cotaRecebida as $param_recebida) { $saldoRecebido = $saldoRecebido + CotaTransferenciaExames::where('cota_transferencia_id', $param_recebida['id']) ->sum('cota_quantidade_transferido'); } } if ($totalUnidade == 0) { $totalUnidade = $cotaLaboratorio->cota_quantidade; } $cotaUtilizada = Agendamento::where('unidade_id', $params['unidade_id']) ->where('infraestrutura_id', $params['infraestrutura_id']) ->where('laboratorio_unidade_id', $params['laboratorio_id']) ->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('data', '>=', $cotaLaboratorio->inicio) ->where('data', '<=', $cotaLaboratorio->fim) ->count('id') ?? 0; $inicio = Carbon::createFromFormat('Y-m-d', $cotaLaboratorio->inicio)->startOfDay(); $fim = Carbon::createFromFormat('Y-m-d', $cotaLaboratorio->fim)->endOfDay(); $prontoAtendimento = DB::table('pronto_atendimento_pedido_exame_item') ->join('pronto_atendimento_pedido_exame', 'pronto_atendimento_pedido_exame.id', '=', 'pronto_atendimento_pedido_exame_item.pedido_exame_id') ->join('cadastro_lotacao as lotacao_laboratorio', 'lotacao_laboratorio.id', '=', 'pronto_atendimento_pedido_exame.laboratorio_lotacao_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', '=', 'pronto_atendimento_pedido_exame.created_lotacao_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', '=', 'pronto_atendimento_pedido_exame_item.exame_id') ->where('parametrizacao_exame.tipo_id', Tipo::LABORATORIAL) ->where('pronto_atendimento_pedido_exame_item.status_id', Status::REALIZADO) ->whereNull('pronto_atendimento_pedido_exame_item.deleted_at') ->where('cadastro_lotacao.infraestrutura_id', $params['infraestrutura_id']) ->where('lotacao_laboratorio.infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->whereBetween('pronto_atendimento_pedido_exame_item.created_at', [$inicio, $fim]) ->count('pronto_atendimento_pedido_exame_item.id'); $cotaUtilizada = $cotaUtilizada + $prontoAtendimento; if (((($totalUnidade - $saldoEnviado) + $saldoRecebido) - $cotaUtilizada) - 1 < 0) { throw new ExceededCotaAgendamentoException; } } } private static function getSaldoLaboratorioValor($params) { $cotaLaboratorio = Cota::where('unidade_id', $params['laboratorio_id']) ->where('infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('cota_tipo_id', TipoCota::VALOR) ->where('inicio', '<=', $params['data']) ->where('fim', '>=', $params['data']) ->first(); if ($cotaLaboratorio) { $totalUnidade = CotaUnidadeSolicitante::where('cota_id', $cotaLaboratorio->id) ->where('unidade_solicitante_id', $params['unidade_id']) ->where('infraestrutura_solicitante_id', $params['infraestrutura_id']) ->sum('cota_valor') ?? 0; $saldoEnviado = CotaTransferencia::where('laboratorio_unidade_id', $params['laboratorio_id']) ->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('origem_unidade_id', $params['unidade_id']) ->where('origem_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', $params['data']) ->where('origem_fim', '>=', $params['data']) ->sum('destino_cota_valor'); $saldoRecebido = CotaTransferencia::where('laboratorio_unidade_id', $params['laboratorio_id']) ->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('destino_unidade_id', $params['unidade_id']) ->where('destino_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', $params['data']) ->where('origem_fim', '>=', $params['data']) ->sum('destino_cota_valor'); if ($totalUnidade == 0) { $totalUnidade = CotaExameUnidadeSolicitante::where('cota_id', $cotaLaboratorio->id) ->where('unidade_solicitante_id', $params['unidade_id']) ->where('infraestrutura_solicitante_id', $params['infraestrutura_id']) ->sum('cota_valor') ?? 0; $cotaEnviada = CotaTransferencia::where('laboratorio_unidade_id', $params['laboratorio_id']) ->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('origem_unidade_id', $params['unidade_id']) ->where('origem_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', $params['data']) ->where('origem_fim', '>=', $params['data']) ->get(); $saldoEnviado = 0; foreach ($cotaEnviada as $param_transferencia) { $saldoEnviado = $saldoEnviado + CotaTransferenciaExames::where('cota_transferencia_id', $param_transferencia['id']) ->sum('cota_valor_transferido'); } $cotaRecebida = CotaTransferencia::where('laboratorio_unidade_id', $params['laboratorio_id']) ->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('destino_unidade_id', $params['unidade_id']) ->where('destino_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('destino_inicio', '<=', $params['data']) ->where('destino_fim', '>=', $params['data']) ->get(); foreach ($cotaRecebida as $param_recebida) { $saldoRecebido = $saldoRecebido + CotaTransferenciaExames::where('cota_transferencia_id', $param_recebida['id']) ->sum('cota_valor_transferido'); } } if ($totalUnidade == 0) { $totalUnidade = $cotaLaboratorio->cota_valor; } $agendamentoCadastrado = Agendamento::where('unidade_id', $params['unidade_id']) ->where('infraestrutura_id', $params['infraestrutura_id']) ->where('laboratorio_unidade_id', $params['laboratorio_id']) ->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('data', '>=', $cotaLaboratorio->inicio) ->where('data', '<=', $cotaLaboratorio->fim) ->get(); $cotaUtilizada = 0; $agendamentoCotaExames = 0; foreach ($agendamentoCadastrado as $param_utilizada) { $cotaUtilizada = $cotaUtilizada + AgendamentoExame::where('agendamento_id', $param_utilizada->id) ->whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, StatusAgendamento::NOVA_COLETA, ]) ->sum('valor') ?? 0; } $inicio = Carbon::createFromFormat('Y-m-d', $cotaLaboratorio->inicio)->startOfDay(); $fim = Carbon::createFromFormat('Y-m-d', $cotaLaboratorio->fim)->endOfDay(); $prontoAtendimento = DB::table('pronto_atendimento_pedido_exame_item') ->join('pronto_atendimento_pedido_exame', 'pronto_atendimento_pedido_exame.id', '=', 'pronto_atendimento_pedido_exame_item.pedido_exame_id') ->join('cadastro_lotacao as lotacao_laboratorio', 'lotacao_laboratorio.id', '=', 'pronto_atendimento_pedido_exame.laboratorio_lotacao_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', '=', 'pronto_atendimento_pedido_exame.created_lotacao_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', '=', 'pronto_atendimento_pedido_exame_item.exame_id') ->where('parametrizacao_exame.tipo_id', Tipo::LABORATORIAL) ->where('pronto_atendimento_pedido_exame_item.status_id', Status::REALIZADO) ->whereNull('pronto_atendimento_pedido_exame_item.deleted_at') ->where('cadastro_lotacao.infraestrutura_id', $params['infraestrutura_id']) ->where('lotacao_laboratorio.infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->whereBetween('pronto_atendimento_pedido_exame_item.created_at', [$inicio, $fim]) ->selectRaw('FORMAT(SUM(pronto_atendimento_pedido_exame_item.valor_exame), 2, "pt_BR") AS valor') ->value('valor'); $prontoAtendimento = str_replace(',', '.', str_replace('.', '', $prontoAtendimento)); $cotaUtilizada = floatval($cotaUtilizada) + floatval($prontoAtendimento); foreach ($params['incluido'] as $param_exame) { $agendamentoCotaExames = $agendamentoCotaExames + $param_exame['valor']; } if (is_numeric($params['agendamento_id'])) { $cotaUtilizadaAgendameto = AgendamentoExame::where('agendamento_id', $params['agendamento_id']) ->sum('valor') ?? 0; if (((($totalUnidade - $saldoEnviado) + $saldoRecebido) - ($cotaUtilizada - $cotaUtilizadaAgendameto)) - $agendamentoCotaExames < 0) { throw new ExceededCotaAgendamentoException; } } else { if (((($totalUnidade - $saldoEnviado) + $saldoRecebido) - $cotaUtilizada) - $agendamentoCotaExames < 0) { throw new ExceededCotaAgendamentoException; } } } } private static function getSaldoUnidadeQuantidade($params) { $cotaUnidade = Cota::where('unidade_id', $params['unidade_id']) ->where('infraestrutura_id', $params['infraestrutura_id']) ->where('unidade_tipo_id', TipoUnidade::UNIDADE_SOLICITANTE) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('inicio', '<=', $params['data']) ->where('fim', '>=', $params['data']) ->first(); if ($cotaUnidade) { $totalUnidade = $cotaUnidade->cota_quantidade; $saldoEnviado = CotaTransferencia::where('origem_unidade_id', $params['unidade_id']) ->where('origem_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::UNIDADE_SOLICITANTE) ->where('origem_inicio', '<=', $params['data']) ->where('origem_fim', '>=', $params['data']) ->sum('destino_cota_quantidade'); $saldoRecebido = CotaTransferencia::where('destino_unidade_id', $params['unidade_id']) ->where('destino_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::UNIDADE_SOLICITANTE) ->where('origem_inicio', '<=', $params['data']) ->where('origem_fim', '>=', $params['data']) ->sum('destino_cota_quantidade'); $cotaUtilizada = Agendamento::where('unidade_id', $params['unidade_id']) ->where('infraestrutura_id', $params['infraestrutura_id']) ->where('data', '>=', $cotaUnidade->inicio) ->where('data', '<=', $cotaUnidade->fim) ->count('id') ?? 0; $inicio = Carbon::createFromFormat('Y-m-d', $cotaUnidade->inicio)->startOfDay(); $fim = Carbon::createFromFormat('Y-m-d', $cotaUnidade->fim)->endOfDay(); $prontoAtendimento = DB::table('pronto_atendimento_pedido_exame_item') ->join('pronto_atendimento_pedido_exame', 'pronto_atendimento_pedido_exame.id', '=', 'pronto_atendimento_pedido_exame_item.pedido_exame_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', '=', 'pronto_atendimento_pedido_exame.created_lotacao_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', '=', 'pronto_atendimento_pedido_exame_item.exame_id') ->where('parametrizacao_exame.tipo_id', Tipo::LABORATORIAL) ->where('pronto_atendimento_pedido_exame_item.status_id', Status::REALIZADO) ->whereNull('pronto_atendimento_pedido_exame_item.deleted_at') ->where('cadastro_lotacao.infraestrutura_id', $params['infraestrutura_id']) ->whereBetween('pronto_atendimento_pedido_exame_item.created_at', [$inicio, $fim]) ->count('pronto_atendimento_pedido_exame_item.id'); $cotaUtilizada = $cotaUtilizada + $prontoAtendimento; if (((($totalUnidade - $saldoEnviado) + $saldoRecebido) - $cotaUtilizada) - 1 < 0) { throw new ExceededCotaAgendamentoException; } } } private static function getSaldoUnidadeValor($params) { $cotaUnidade = Cota::where('unidade_id', $params['unidade_id']) ->where('infraestrutura_id', $params['infraestrutura_id']) ->where('unidade_tipo_id', TipoUnidade::UNIDADE_SOLICITANTE) ->where('cota_tipo_id', TipoCota::VALOR) ->where('inicio', '<=', $params['data']) ->where('fim', '>=', $params['data']) ->first(); if ($cotaUnidade) { $totalUnidade = $cotaUnidade->cota_valor; $saldoEnviado = CotaTransferencia::where('origem_unidade_id', $params['unidade_id']) ->where('origem_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::UNIDADE_SOLICITANTE) ->where('origem_inicio', '<=', $params['data']) ->where('origem_fim', '>=', $params['data']) ->sum('destino_cota_valor'); $saldoRecebido = CotaTransferencia::where('destino_unidade_id', $params['unidade_id']) ->where('destino_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::UNIDADE_SOLICITANTE) ->where('origem_inicio', '<=', $params['data']) ->where('origem_fim', '>=', $params['data']) ->sum('destino_cota_valor'); $agendamentoCadastrado = Agendamento::where('unidade_id', $params['unidade_id']) ->where('infraestrutura_id', $params['infraestrutura_id']) ->where('laboratorio_unidade_id', $params['laboratorio_id']) ->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('data', '>=', $cotaUnidade->inicio) ->where('data', '<=', $cotaUnidade->fim) ->get(); $cotaUtilizada = 0; $agendamentoCotaExames = 0; foreach ($agendamentoCadastrado as $param_utilizada) { $cotaUtilizada = $cotaUtilizada + AgendamentoExame::where('agendamento_id', $param_utilizada->id) ->sum('valor') ?? 0; } $inicio = Carbon::createFromFormat('Y-m-d', $cotaUnidade->inicio)->startOfDay(); $fim = Carbon::createFromFormat('Y-m-d', $cotaUnidade->fim)->endOfDay(); $prontoAtendimento = DB::table('pronto_atendimento_pedido_exame_item') ->join('pronto_atendimento_pedido_exame', 'pronto_atendimento_pedido_exame.id', '=', 'pronto_atendimento_pedido_exame_item.pedido_exame_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', '=', 'pronto_atendimento_pedido_exame.created_lotacao_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', '=', 'pronto_atendimento_pedido_exame_item.exame_id') ->where('parametrizacao_exame.tipo_id', Tipo::LABORATORIAL) ->where('pronto_atendimento_pedido_exame_item.status_id', Status::REALIZADO) ->whereNull('pronto_atendimento_pedido_exame_item.deleted_at') ->where('cadastro_lotacao.infraestrutura_id', $params['infraestrutura_id']) ->whereBetween('pronto_atendimento_pedido_exame_item.created_at', [$inicio, $fim]) ->selectRaw('FORMAT(SUM(pronto_atendimento_pedido_exame_item.valor_exame), 2, "pt_BR") AS valor') ->value('valor'); $prontoAtendimento = str_replace(',', '.', str_replace('.', '', $prontoAtendimento)); $cotaUtilizada = floatval($cotaUtilizada) + floatval($prontoAtendimento); foreach ($params['incluido'] as $param_exame) { $agendamentoCotaExames = $agendamentoCotaExames + $param_exame['valor']; } if (is_numeric($params['agendamento_id'])) { $cotaUtilizadaAgendameto = AgendamentoExame::where('agendamento_id', $params['agendamento_id']) ->sum('valor') ?? 0; if (((($totalUnidade - $saldoEnviado) + $saldoRecebido) - ($cotaUtilizada - $cotaUtilizadaAgendameto)) - $agendamentoCotaExames < 0) { throw new ExceededCotaAgendamentoException; } } else { if (((($totalUnidade - $saldoEnviado) + $saldoRecebido) - $cotaUtilizada) - $agendamentoCotaExames < 0) { throw new ExceededCotaAgendamentoException; } } } } private static function getSaldoExameQuantidade($params) { $cotaLaboratorio = Cota::where('infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('cota_tipo_id', TipoCota::VALOR) ->where('inicio', '<=', $params['data']) ->where('fim', '>=', $params['data']) ->first(); if ($cotaLaboratorio) { foreach ($params['incluido'] as $param_exame) { $cotaExame = CotaExameUnidadeSolicitante::where('cota_id', $cotaLaboratorio->id) ->where('infraestrutura_solicitante_id', $params['infraestrutura_id']) ->whereHas('cotaExame', function ($query) use ($param_exame) { $query->where('exame_id', $param_exame['exame_id']); }) ->first(); if ($cotaExame) { $saldoEnviado = 0; $saldoRecebido = 0; $totalUnidade = CotaExameUnidadeSolicitante::where('id', $cotaExame->id) ->sum('cota_quantidade') ?? 0; $saldoEnviado = CotaTransferenciaExames::whereHas('cotaTransferencia', function ($query) use ($params) { $query->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('origem_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', $params['data']) ->where('origem_fim', '>=', $params['data']); }) ->whereHas('cotaExame', function ($query) use ($cotaExame) { $query->where('exame_id', $cotaExame->cotaExame->exame_id); }) ->sum('cota_quantidade_transferido'); $saldoRecebido = CotaTransferenciaExames::whereHas('cotaTransferencia', function ($query) use ($params) { $query->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('destino_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', $params['data']) ->where('origem_fim', '>=', $params['data']); }) ->whereHas('cotaExame', function ($query) use ($cotaExame) { $query->where('exame_id', $cotaExame->cotaExame->exame_id); }) ->sum('cota_quantidade_transferido'); $cotaUtilizada = Agendamento::where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('data', '>=', $cotaLaboratorio->inicio) ->where('data', '<=', $cotaLaboratorio->fim) ->whereHas('agendamentoExame', function ($query) use ($cotaExame) { $query->where('exame_id', $cotaExame->cotaExame->exame_id); }) ->count('id') ?? 0; if (is_numeric($params['agendamento_id'])) { $cotaAgendamento = Agendamento::where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('infraestrutura_id', $params['infraestrutura_id']) ->where('id', $params['agendamento_id']) ->where('data', '>=', $cotaLaboratorio->inicio) ->where('data', '<=', $cotaLaboratorio->fim) ->whereHas('agendamentoExame', function ($query) use ($cotaExame) { $query->where('exame_id', $cotaExame->cotaExame->exame_id); }) ->count('id') ?? 0; if ($cotaAgendamento) { $cotaUtilizada = $cotaUtilizada - $cotaAgendamento; } } $inicio = Carbon::createFromFormat('Y-m-d', $cotaLaboratorio->inicio)->startOfDay(); $fim = Carbon::createFromFormat('Y-m-d', $cotaLaboratorio->fim)->endOfDay(); $prontoAtendimento = DB::table('pronto_atendimento_pedido_exame_item') ->join('pronto_atendimento_pedido_exame', 'pronto_atendimento_pedido_exame.id', '=', 'pronto_atendimento_pedido_exame_item.pedido_exame_id') ->join('cadastro_lotacao as lotacao_laboratorio', 'lotacao_laboratorio.id', '=', 'pronto_atendimento_pedido_exame.laboratorio_lotacao_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', '=', 'pronto_atendimento_pedido_exame.created_lotacao_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', '=', 'pronto_atendimento_pedido_exame_item.exame_id') ->where('parametrizacao_exame.tipo_id', Tipo::LABORATORIAL) ->where('pronto_atendimento_pedido_exame_item.status_id', Status::REALIZADO) ->where('pronto_atendimento_pedido_exame_item.exame_id', $cotaExame->cotaExame->exame_id) ->whereNull('pronto_atendimento_pedido_exame_item.deleted_at') ->where('cadastro_lotacao.infraestrutura_id', $params['infraestrutura_id']) ->where('lotacao_laboratorio.infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->whereBetween('pronto_atendimento_pedido_exame_item.created_at', [$inicio, $fim]) ->count('pronto_atendimento_pedido_exame_item.id'); $cotaUtilizada = $cotaUtilizada + $prontoAtendimento; if ((($totalUnidade - $saldoEnviado) + $saldoRecebido) - ($cotaUtilizada + 1) < 0) { throw new ExceededCotaExameException; } } } } } private static function getSaldoExameValor($params) { $cotaLaboratorio = Cota::where('infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('cota_tipo_id', TipoCota::VALOR) ->where('inicio', '<=', $params['data']) ->where('fim', '>=', $params['data']) ->first(); if ($cotaLaboratorio) { foreach ($params['incluido'] as $param_exame) { $cotaExame = CotaExameUnidadeSolicitante::where('cota_id', $cotaLaboratorio->id) ->where('infraestrutura_solicitante_id', $params['infraestrutura_id']) ->whereHas('cotaExame', function ($query) use ($param_exame) { $query->where('exame_id', $param_exame['exame_id']); }) ->first(); if ($cotaExame) { $saldoEnviado = 0; $saldoRecebido = 0; $totalUnidade = CotaExameUnidadeSolicitante::where('id', $cotaExame->id) ->sum('cota_valor') ?? 0; $saldoEnviado = CotaTransferenciaExames::whereHas('cotaTransferencia', function ($query) use ($params) { $query->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('origem_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', $params['data']) ->where('origem_fim', '>=', $params['data']); }) ->whereHas('cotaExame', function ($query) use ($cotaExame) { $query->where('exame_id', $cotaExame->cotaExame->exame_id); }) ->sum('cota_valor_transferido'); $saldoRecebido = CotaTransferenciaExames::whereHas('cotaTransferencia', function ($query) use ($params) { $query->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('destino_infraestrutura_id', $params['infraestrutura_id']) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', $params['data']) ->where('origem_fim', '>=', $params['data']); }) ->whereHas('cotaExame', function ($query) use ($cotaExame) { $query->where('exame_id', $cotaExame->cotaExame->exame_id); }) ->sum('cota_valor_transferido'); $cotaUtilizada = AgendamentoExame::where('exame_id', $cotaExame->cotaExame->exame_id) ->whereHas('Agendamento', function ($query) use ($cotaLaboratorio, $params) { $query->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('data', '>=', $cotaLaboratorio->inicio) ->where('data', '<=', $cotaLaboratorio->fim); }) ->sum('valor') ?? 0; $cotaUtilizada = number_format($cotaUtilizada + $param_exame['valor'], 2); $inicio = Carbon::createFromFormat('Y-m-d', $cotaLaboratorio->inicio)->startOfDay(); $fim = Carbon::createFromFormat('Y-m-d', $cotaLaboratorio->fim)->endOfDay(); $prontoAtendimento = DB::table('pronto_atendimento_pedido_exame_item') ->join('pronto_atendimento_pedido_exame', 'pronto_atendimento_pedido_exame.id', '=', 'pronto_atendimento_pedido_exame_item.pedido_exame_id') ->join('cadastro_lotacao as lotacao_laboratorio', 'lotacao_laboratorio.id', '=', 'pronto_atendimento_pedido_exame.laboratorio_lotacao_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', '=', 'pronto_atendimento_pedido_exame_item.exame_id') ->where('parametrizacao_exame.tipo_id', Tipo::LABORATORIAL) ->where('pronto_atendimento_pedido_exame_item.status_id', Status::REALIZADO) ->whereNull('pronto_atendimento_pedido_exame_item.deleted_at') ->where('pronto_atendimento_pedido_exame_item.exame_id', $cotaExame->cotaExame->exame_id) ->where('lotacao_laboratorio.infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->whereBetween('pronto_atendimento_pedido_exame_item.created_at', [$inicio, $fim]) ->selectRaw('FORMAT(SUM(pronto_atendimento_pedido_exame_item.valor_exame), 2, "pt_BR") AS valor') ->value('valor'); $prontoAtendimento = str_replace(',', '.', str_replace('.', '', $prontoAtendimento)); $cotaUtilizada = floatval($cotaUtilizada) + floatval($prontoAtendimento); if (is_numeric($params['agendamento_id'])) { $cotaAgendamento = AgendamentoExame::where('exame_id', $cotaExame->cotaExame->exame_id) ->whereHas('Agendamento', function ($query) use ($cotaLaboratorio, $params) { $query->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('infraestrutura_id', $params['infraestrutura_id']) ->where('id', $params['agendamento_id']) ->where('data', '>=', $cotaLaboratorio->inicio) ->where('data', '<=', $cotaLaboratorio->fim); }) ->sum('valor') ?? 0; if ($cotaAgendamento) { $cotaUtilizada = number_format($cotaUtilizada - $cotaAgendamento, 2); } } if ((($totalUnidade - $saldoEnviado) + $saldoRecebido) - $cotaUtilizada < 0) { throw new ExceededCotaExameException; } } } } } private static function getSaldoExamePeriodoQuantidade($params) { foreach ($params['incluido'] as $param_exame) { $cotaExame = CotaExamePeriodo::where('infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('exame_id', $param_exame['exame_id']) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('inicio', '<=', $params['data']) ->where('fim', '>=', $params['data']) ->first(); if ($cotaExame) { $quantidadeUtilizada = Agendamento::where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('data', '>=', $cotaExame->inicio) ->where('data', '<=', $cotaExame->fim) ->whereHas('agendamentoExame', function ($query) use ($cotaExame) { $query->where('exame_id', $cotaExame->exame_id); }) ->count('id') ?? 0; if (is_numeric($params['agendamento_id'])) { $quantidadeAgendamento = AgendamentoExame::where('exame_id', $cotaExame->exame_id) ->whereHas('Agendamento', function ($query) use ($cotaExame, $params) { $query->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('infraestrutura_id', $params['infraestrutura_id']) ->where('id', $params['agendamento_id']) ->where('data', '>=', $cotaExame->inicio) ->where('data', '<=', $cotaExame->fim); }) ->count('id') ?? 0; if ($quantidadeAgendamento) { $quantidadeUtilizada = $quantidadeUtilizada - $quantidadeAgendamento; } } $inicio = Carbon::createFromFormat('Y-m-d', $cotaExame->inicio)->startOfDay(); $fim = Carbon::createFromFormat('Y-m-d', $cotaExame->fim)->endOfDay(); $prontoAtendimento = DB::table('pronto_atendimento_pedido_exame_item') ->join('pronto_atendimento_pedido_exame', 'pronto_atendimento_pedido_exame.id', '=', 'pronto_atendimento_pedido_exame_item.pedido_exame_id') ->join('cadastro_lotacao as lotacao_laboratorio', 'lotacao_laboratorio.id', '=', 'pronto_atendimento_pedido_exame.laboratorio_lotacao_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', '=', 'pronto_atendimento_pedido_exame_item.exame_id') ->where('parametrizacao_exame.tipo_id', Tipo::LABORATORIAL) ->where('pronto_atendimento_pedido_exame_item.status_id', Status::REALIZADO) ->where('pronto_atendimento_pedido_exame_item.exame_id', $cotaExame->cotaExame->exame_id) ->whereNull('pronto_atendimento_pedido_exame_item.deleted_at') ->where('lotacao_laboratorio.infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->whereBetween('pronto_atendimento_pedido_exame_item.created_at', [$inicio, $fim]) ->count('pronto_atendimento_pedido_exame_item.id'); $quantidadeUtilizada = $quantidadeUtilizada + $prontoAtendimento; if (($cotaExame->cota_quantidade) - ($quantidadeUtilizada + 1) < 0) { throw new ExceededCotaExameException; } } } } private static function getSaldoExamePeriodoValor($params) { foreach ($params['incluido'] as $param_exame) { $cotaExame = CotaExamePeriodo::where('infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('exame_id', $param_exame['exame_id']) ->where('cota_tipo_id', TipoCota::VALOR) ->where('inicio', '<=', $params['data']) ->where('fim', '>=', $params['data']) ->first(); if ($cotaExame) { $valorUtilizado = AgendamentoExame::where('exame_id', $cotaExame->exame_id) ->whereHas('Agendamento', function ($query) use ($cotaExame, $params) { $query->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('data', '>=', $cotaExame->inicio) ->where('data', '<=', $cotaExame->fim); }) ->sum('valor') ?? 0; $valorUtilizado = number_format($valorUtilizado + $param_exame['valor'], 2); if (is_numeric($params['agendamento_id'])) { $valorAgendamento = AgendamentoExame::where('exame_id', $cotaExame->exame_id) ->whereHas('Agendamento', function ($query) use ($cotaExame, $params) { $query->where('laboratorio_infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->where('infraestrutura_id', $params['infraestrutura_id']) ->where('id', $params['agendamento_id']) ->where('data', '>=', $cotaExame->inicio) ->where('data', '<=', $cotaExame->fim); }) ->sum('valor') ?? 0; if ($valorAgendamento) { $valorUtilizado = number_format($valorUtilizado - $valorAgendamento, 2); } } $inicio = Carbon::createFromFormat('Y-m-d', $cotaExame->inicio)->startOfDay(); $fim = Carbon::createFromFormat('Y-m-d', $cotaExame->fim)->endOfDay(); $prontoAtendimento = DB::table('pronto_atendimento_pedido_exame_item') ->join('pronto_atendimento_pedido_exame', 'pronto_atendimento_pedido_exame.id', '=', 'pronto_atendimento_pedido_exame_item.pedido_exame_id') ->join('cadastro_lotacao as lotacao_laboratorio', 'lotacao_laboratorio.id', '=', 'pronto_atendimento_pedido_exame.laboratorio_lotacao_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', '=', 'pronto_atendimento_pedido_exame_item.exame_id') ->where('parametrizacao_exame.tipo_id', Tipo::LABORATORIAL) ->where('pronto_atendimento_pedido_exame_item.status_id', Status::REALIZADO) ->whereNull('pronto_atendimento_pedido_exame_item.deleted_at') ->where('pronto_atendimento_pedido_exame_item.exame_id', $cotaExame->cotaExame->exame_id) ->where('lotacao_laboratorio.infraestrutura_id', $params['laboratorio_infraestrutura_id']) ->whereBetween('pronto_atendimento_pedido_exame_item.created_at', [$inicio, $fim]) ->selectRaw('FORMAT(SUM(pronto_atendimento_pedido_exame_item.valor_exame), 2, "pt_BR") AS valor') ->value('valor'); $prontoAtendimento = str_replace(',', '.', str_replace('.', '', $prontoAtendimento)); $valorUtilizado = floatval($valorUtilizado) + floatval($prontoAtendimento); if (($cotaExame->cota_quantidade) - ($valorUtilizado) < 0) { throw new ExceededCotaExameException; } } } } public static function getCotas() { return [ 'unidade_solicitante_quantidade' => self::getCotaUnidadeQuantidade(), 'unidade_solicitante_valor' => self::getCotaUnidadeValor(), 'laboratorio_quantidade' => self::getCotaLaboratorioQuantidade(), 'laboratorio_valor' => self::getCotaLaboratorioValor(), 'exame_quantidade' => self::getCotaExameQuantidade(), 'exame_valor' => self::getCotaExameValor(), 'exame_periodo_quantidade' => self::getCotaExamePeriodoQuantidade(), 'exame_periodo_valor' => self::getCotaExamePeriodoValor(), ]; } private static function getCotaLaboratorioQuantidade() { $cotaLaboratorio = Cota::where('infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('inicio', '<=', request()->data) ->where('fim', '>=', request()->data) ->first(); if ($cotaLaboratorio) { $totalUnidade = CotaUnidadeSolicitante::where('cota_id', $cotaLaboratorio->id) ->where('infraestrutura_solicitante_id', request()->infraestrutura_id) ->sum('cota_quantidade') ?? 0; $saldoEnviado = CotaTransferencia::where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('origem_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data) ->sum('destino_cota_quantidade'); $saldoRecebido = CotaTransferencia::where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('destino_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data) ->sum('destino_cota_quantidade'); if ($totalUnidade == 0) { $totalUnidade = CotaExameUnidadeSolicitante::where('cota_id', $cotaLaboratorio->id) ->where('infraestrutura_solicitante_id', request()->infraestrutura_id) ->sum('cota_quantidade') ?? 0; $saldoEnviado = CotaTransferenciaExames::whereHas('cotaTransferencia', function ($query) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('origem_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data); })->sum('cota_quantidade_transferido'); $saldoRecebido = CotaTransferenciaExames::whereHas('cotaTransferencia', function ($query) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('destino_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data); })->sum('cota_quantidade_transferido'); } if ($totalUnidade == 0) { $totalUnidade = $cotaLaboratorio->cota_quantidade; $cotaUtilizada = DB::table('exame_laboratorial_agendamento_exame') ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', '=', 'exame_laboratorial_agendamento_exame.agendamento_id') ->where('exame_laboratorial_agendamento.laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->where('exame_laboratorial_agendamento.data', '>=', $cotaLaboratorio->inicio) ->where('exame_laboratorial_agendamento.data', '<=', $cotaLaboratorio->fim) ->count('exame_laboratorial_agendamento_exame.id') ?? 0; } else { $cotaUtilizada = DB::table('exame_laboratorial_agendamento_exame') ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', '=', 'exame_laboratorial_agendamento_exame.agendamento_id') ->where('exame_laboratorial_agendamento.laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('exame_laboratorial_agendamento.infraestrutura_id', request()->infraestrutura_id) ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->where('exame_laboratorial_agendamento.data', '>=', $cotaLaboratorio->inicio) ->where('exame_laboratorial_agendamento.data', '<=', $cotaLaboratorio->fim) ->count('exame_laboratorial_agendamento_exame.id') ?? 0; } if (request()->agendamento_id) { $cotaAgendamento = DB::table('exame_laboratorial_agendamento_exame') ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', '=', 'exame_laboratorial_agendamento_exame.agendamento_id') ->where('exame_laboratorial_agendamento.laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('exame_laboratorial_agendamento.infraestrutura_id', request()->infraestrutura_id) ->where('exame_laboratorial_agendamento.id', request()->agendamento_id) ->where('exame_laboratorial_agendamento.data', '>=', $cotaLaboratorio->inicio) ->where('exame_laboratorial_agendamento.data', '<=', $cotaLaboratorio->fim) ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->count('exame_laboratorial_agendamento_exame.id') ?? 0; if ($cotaAgendamento) { $cotaUtilizada = $cotaUtilizada - $cotaAgendamento; } } $totalCota = (($totalUnidade - $saldoEnviado) + $saldoRecebido); $percentualRestante = 100 - ($cotaUtilizada / $totalCota * 100); return [ 'cota' => $totalCota, 'utilizada' => $cotaUtilizada, 'saldo' => ($totalCota - $cotaUtilizada), 'percentual_restante' => floor($percentualRestante * 100) / 100 ]; } } private static function getCotaLaboratorioValor() { $cotaLaboratorio = Cota::where('infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('cota_tipo_id', TipoCota::VALOR) ->where('inicio', '<=', request()->data) ->where('fim', '>=', request()->data) ->first(); if ($cotaLaboratorio) { $totalUnidade = CotaUnidadeSolicitante::where('cota_id', $cotaLaboratorio->id) ->where('infraestrutura_solicitante_id', request()->infraestrutura_id) ->sum('cota_valor') ?? 0; $saldoEnviado = CotaTransferencia::where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('origem_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data) ->sum('destino_cota_valor'); $saldoRecebido = CotaTransferencia::where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('destino_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data) ->sum('destino_cota_valor'); if ($totalUnidade == 0) { $totalUnidade = CotaExameUnidadeSolicitante::where('cota_id', $cotaLaboratorio->id) ->where('unidade_solicitante_id', request()->unidade_id) ->where('infraestrutura_solicitante_id', request()->infraestrutura_id) ->sum('cota_valor') ?? 0; $saldoEnviado = CotaTransferenciaExames::whereHas('cotaTransferencia', function ($query) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('origem_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data); })->sum('cota_valor_transferido'); $saldoRecebido = CotaTransferenciaExames::whereHas('cotaTransferencia', function ($query) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('destino_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data); })->sum('cota_valor_transferido'); } if ($totalUnidade == 0) { $totalUnidade = $cotaLaboratorio->cota_valor; $cotaUtilizada = AgendamentoExame::whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereHas('Agendamento', function ($query) use ($cotaLaboratorio) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('data', '>=', $cotaLaboratorio->inicio) ->where('data', '<=', $cotaLaboratorio->fim); }) ->sum('valor') ?? 0; } else { $cotaUtilizada = AgendamentoExame::whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereHas('Agendamento', function ($query) use ($cotaLaboratorio) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('infraestrutura_id', request()->infraestrutura_id) ->where('data', '>=', $cotaLaboratorio->inicio) ->where('data', '<=', $cotaLaboratorio->fim); }) ->sum('valor') ?? 0; } if (request()->agendamento_id) { $cotaAgendamento = AgendamentoExame::whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereHas('Agendamento', function ($query) use ($cotaLaboratorio) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('infraestrutura_id', request()->infraestrutura_id) ->where('id', request()->agendamento_id) ->where('data', '>=', $cotaLaboratorio->inicio) ->where('data', '<=', $cotaLaboratorio->fim); }) ->sum('valor') ?? 0; if ($cotaAgendamento) { $cotaUtilizada = number_format($cotaUtilizada - $cotaAgendamento, 2); } } $totalCota = (($totalUnidade - $saldoEnviado) + $saldoRecebido); if (is_numeric($cotaUtilizada) && is_numeric($totalCota) && $totalCota != 0) { $percentualRestante = 100 - ($cotaUtilizada / $totalCota * 100); } else { $percentualRestante = 0; } if (is_numeric($cotaUtilizada) && is_numeric($totalCota) && $totalCota != 0) { $saldo = ($totalCota - $cotaUtilizada); } else { $saldo = 0; } return [ 'cota' => $totalCota, 'utilizada' => $cotaUtilizada, 'saldo' => $saldo, 'percentual_restante' => floor($percentualRestante * 100) / 100 ]; } } private static function getCotaUnidadeQuantidade() { $cotaUnidade = Cota::where('infraestrutura_id', request()->infraestrutura_id) ->where('unidade_tipo_id', TipoUnidade::UNIDADE_SOLICITANTE) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('inicio', '<=', request()->data) ->where('fim', '>=', request()->data) ->first(); if ($cotaUnidade) { $totalUnidade = $cotaUnidade->cota_quantidade; $saldoEnviado = CotaTransferencia::where('origem_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::UNIDADE_SOLICITANTE) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data) ->sum('destino_cota_quantidade'); $saldoRecebido = CotaTransferencia::where('destino_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::UNIDADE_SOLICITANTE) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data) ->sum('destino_cota_quantidade'); $cotaUtilizada = Agendamento::where('infraestrutura_id', request()->infraestrutura_id) ->whereHas('agendamentoExame', function ($query) { $query->whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]); }) ->where('data', '>=', $cotaUnidade->inicio) ->where('data', '<=', $cotaUnidade->fim) ->count('id') ?? 0; if (request()->agendamento_id) { $cotaAgendamento = Agendamento::where('infraestrutura_id', request()->infraestrutura_id) ->whereHas('agendamentoExame', function ($query) { $query->whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]); }) ->where('id', request()->agendamento_id) ->where('data', '>=', $cotaUnidade->inicio) ->where('data', '<=', $cotaUnidade->fim) ->count('id') ?? 0; if ($cotaAgendamento) { $cotaUtilizada = $cotaUtilizada - $cotaAgendamento; } } $totalCota = (($totalUnidade - $saldoEnviado) + $saldoRecebido); $percentualRestante = 100 - ($cotaUtilizada / $totalCota * 100); return [ 'cota' => $totalCota, 'utilizada' => $cotaUtilizada, 'saldo' => ($totalCota - $cotaUtilizada), 'percentual_restante' => floor($percentualRestante * 100) / 100 ]; } } private static function getCotaUnidadeValor() { $cotaUnidade = Cota::where('infraestrutura_id', request()->infraestrutura_id) ->where('unidade_tipo_id', TipoUnidade::UNIDADE_SOLICITANTE) ->where('cota_tipo_id', TipoCota::VALOR) ->where('inicio', '<=', request()->data) ->where('fim', '>=', request()->data) ->first(); if ($cotaUnidade) { $totalUnidade = $cotaUnidade->cota_valor; $saldoEnviado = CotaTransferencia::where('origem_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::UNIDADE_SOLICITANTE) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data) ->sum('destino_cota_valor'); $saldoRecebido = CotaTransferencia::where('destino_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::UNIDADE_SOLICITANTE) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data) ->sum('destino_cota_valor'); $cotaUtilizada = AgendamentoExame::whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereHas('Agendamento', function ($query) use ($cotaUnidade) { $query->where('infraestrutura_id', request()->infraestrutura_id) ->where('data', '>=', $cotaUnidade->inicio) ->where('data', '<=', $cotaUnidade->fim); }) ->sum('valor') ?? 0; if (request()->agendamento_id) { $cotaAgendamento = AgendamentoExame::whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereHas('Agendamento', function ($query) use ($cotaUnidade) { $query->where('infraestrutura_id', request()->infraestrutura_id) ->where('id', request()->agendamento_id) ->where('data', '>=', $cotaUnidade->inicio) ->where('data', '<=', $cotaUnidade->fim); }) ->sum('valor') ?? 0; if ($cotaAgendamento) { $cotaUtilizada = number_format($cotaUtilizada - $cotaAgendamento, 2); } } $totalCota = (($totalUnidade - $saldoEnviado) + $saldoRecebido); $percentualRestante = 100 - ($cotaUtilizada / $totalCota * 100); return [ 'cota' => $totalCota, 'utilizada' => $cotaUtilizada, 'saldo' => ($totalCota - $cotaUtilizada), 'percentual_restante' => floor($percentualRestante * 100) / 100 ]; } } private static function getCotaExameQuantidade() { $exames = []; $cotaLaboratorio = Cota::where('infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('inicio', '<=', request()->data) ->where('fim', '>=', request()->data) ->first(); if ($cotaLaboratorio) { $cotaExames = CotaExameUnidadeSolicitante::where('cota_id', $cotaLaboratorio->id) ->where('infraestrutura_solicitante_id', request()->infraestrutura_id) ->get(); foreach ($cotaExames as $cotaExame) { $saldoEnviado = 0; $saldoRecebido = 0; $totalUnidade = CotaExameUnidadeSolicitante::where('id', $cotaExame->id) ->sum('cota_quantidade') ?? 0; $saldoEnviado = CotaTransferenciaExames::whereHas('cotaTransferencia', function ($query) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('origem_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data); }) ->sum('cota_quantidade_transferido'); $saldoRecebido = CotaTransferenciaExames::whereHas('cotaTransferencia', function ($query) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('destino_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data); }) ->whereHas('agendamentoExame', function ($query) use ($cotaExame) { $query ->where('exame_id', $cotaExame->cotaExame->exame_id) ->whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]); }) ->sum('cota_quantidade_transferido'); $cotaUtilizada = Agendamento::where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('data', '>=', $cotaLaboratorio->inicio) ->where('data', '<=', $cotaLaboratorio->fim) ->whereHas('agendamentoExame', function ($query) use ($cotaExame) { $query ->where('exame_id', $cotaExame->cotaExame->exame_id) ->whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]); }) ->count('id') ?? 0; if (request()->agendamento_id) { $cotaAgendamento = Agendamento::where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('infraestrutura_id', request()->infraestrutura_id) ->where('id', request()->agendamento_id) ->where('data', '>=', $cotaLaboratorio->inicio) ->where('data', '<=', $cotaLaboratorio->fim) ->whereHas('agendamentoExame', function ($query) use ($cotaExame) { $query ->where('exame_id', $cotaExame->cotaExame->exame_id) ->whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]); }) ->count('id') ?? 0; if ($cotaAgendamento) { $cotaUtilizada = $cotaUtilizada - $cotaAgendamento; } } $exames[] = [ 'exame_id' => $cotaExame->cotaExame->exame_id, 'saldo' => ((($totalUnidade - $saldoEnviado) + $saldoRecebido) - $cotaUtilizada) ]; } } return $exames; } private static function getCotaExameValor() { $exames = []; $cotaLaboratorio = Cota::where('infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('cota_tipo_id', TipoCota::VALOR) ->where('inicio', '<=', request()->data) ->where('fim', '>=', request()->data) ->first(); if ($cotaLaboratorio) { $cotaExames = CotaExameUnidadeSolicitante::where('cota_id', $cotaLaboratorio->id) ->where('infraestrutura_solicitante_id', request()->infraestrutura_id) ->get(); foreach ($cotaExames as $cotaExame) { $saldoEnviado = 0; $saldoRecebido = 0; $totalUnidade = CotaExameUnidadeSolicitante::where('id', $cotaExame->id) ->sum('cota_valor') ?? 0; $saldoEnviado = CotaTransferenciaExames::whereHas('cotaTransferencia', function ($query) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('origem_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data); }) ->whereHas('cotaExame', function ($query) use ($cotaExame) { $query->where('exame_id', $cotaExame->cotaExame->exame_id); }) ->sum('cota_valor_transferido'); $saldoRecebido = CotaTransferenciaExames::whereHas('cotaTransferencia', function ($query) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('destino_infraestrutura_id', request()->infraestrutura_id) ->where('cota_tipo_id', TipoCota::VALOR) ->where('unidade_tipo_id', TipoUnidade::LABORATORIO) ->where('origem_inicio', '<=', request()->data) ->where('origem_fim', '>=', request()->data); }) ->whereHas('cotaExame', function ($query) use ($cotaExame) { $query->where('exame_id', $cotaExame->cotaExame->exame_id); }) ->sum('cota_valor_transferido'); $cotaUtilizada = AgendamentoExame::where('exame_id', $cotaExame->cotaExame->exame_id) ->whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereHas('Agendamento', function ($query) use ($cotaLaboratorio) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('data', '>=', $cotaLaboratorio->inicio) ->where('data', '<=', $cotaLaboratorio->fim); }) ->sum('valor') ?? 0; if (request()->agendamento_id) { $cotaAgendamento = AgendamentoExame::where('exame_id', $cotaExame->cotaExame->exame_id) ->whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereHas('Agendamento', function ($query) use ($cotaLaboratorio) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('infraestrutura_id', request()->infraestrutura_id) ->where('id', request()->agendamento_id) ->where('data', '>=', $cotaLaboratorio->inicio) ->where('data', '<=', $cotaLaboratorio->fim); }) ->sum('valor') ?? 0; if ($cotaAgendamento) { $cotaUtilizada = number_format($cotaUtilizada - $cotaAgendamento, 2); } } $exames[] = [ 'exame_id' => $cotaExame->cotaExame->exame_id, 'saldo' => ((($totalUnidade - $saldoEnviado) + $saldoRecebido) - $cotaUtilizada) ]; } } return $exames; } private static function getCotaExamePeriodoQuantidade() { $exames = []; $cotaExames = CotaExamePeriodo::where('infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('cota_tipo_id', TipoCota::QUANTIDADE) ->where('inicio', '<=', request()->data) ->where('fim', '>=', request()->data) ->get(); foreach ($cotaExames as $cotaExame) { $quantidadeUtilizada = Agendamento::where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('data', '>=', $cotaExame->inicio) ->where('data', '<=', $cotaExame->fim) ->whereHas('agendamentoExame', function ($query) use ($cotaExame) { $query ->where('exame_id', $cotaExame->exame_id) ->whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]); }) ->count('id') ?? 0; if (request()->agendamento_id) { $quantidadeAgendamento = AgendamentoExame::where('exame_id', $cotaExame->exame_id) ->whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereHas('Agendamento', function ($query) use ($cotaExame) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('infraestrutura_id', request()->infraestrutura_id) ->where('id', request()->agendamento_id) ->where('data', '>=', $cotaExame->inicio) ->where('data', '<=', $cotaExame->fim); }) ->count('id') ?? 0; if ($quantidadeAgendamento) { $quantidadeUtilizada = $quantidadeUtilizada - $quantidadeAgendamento; } } $exames[] = [ 'exame_id' => $cotaExame->exame_id, 'saldo' => $cotaExame->cota_quantidade != 0 ? $cotaExame->cota_quantidade - $quantidadeUtilizada : null, ]; } return $exames; } private static function getCotaExamePeriodoValor() { $exames = []; $cotaExames = CotaExamePeriodo::where('infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('cota_tipo_id', TipoCota::VALOR) ->where('inicio', '<=', request()->data) ->where('fim', '>=', request()->data) ->get(); foreach ($cotaExames as $cotaExame) { $valorUtilizado = AgendamentoExame::where('exame_id', $cotaExame->exame_id) ->whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereHas('Agendamento', function ($query) use ($cotaExame) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('data', '>=', $cotaExame->inicio) ->where('data', '<=', $cotaExame->fim); }) ->sum('valor') ?? 0; if (request()->agendamento_id) { $valorAgendamento = AgendamentoExame::where('exame_id', $cotaExame->exame_id) ->whereIn('status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereHas('Agendamento', function ($query) use ($cotaExame) { $query->where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('infraestrutura_id', request()->infraestrutura_id) ->where('id', request()->agendamento_id) ->where('data', '>=', $cotaExame->inicio) ->where('data', '<=', $cotaExame->fim); }) ->sum('valor') ?? 0; if ($valorAgendamento) { $valorUtilizado = number_format($valorUtilizado - $valorAgendamento, 2); } } $saldo = ((float) $cotaExame->cota_valor - (float) $valorUtilizado); $exames[] = [ 'exame_id' => $cotaExame->exame_id, 'saldo' => ($saldo != 0) ? $saldo : null ]; } return $exames; } private static function validate($request) { $validations = [ 'agendamentos_not_save.*.infraestrutura_id' => [ 'required', 'integer', ], 'agendamentos_not_save.*.unidade_id' => [ 'required', 'integer', ], 'agendamentos_not_save.*.coleta_infraestrutura_id' => [ 'required', 'integer', ], 'agendamentos_not_save.*.coleta_unidade_id' => [ 'required', 'integer', ], 'agendamentos_not_save.*.laboratorio_id' => [ 'required', 'integer', ], 'agendamentos_not_save.*.laboratorio_infraestrutura_id' => [ 'required', 'integer', ], 'agendamentos_not_save.*.medico_id' => [ 'required', 'integer', ], 'agendamentos_not_save.*.paciente_id' => [ 'required', 'integer', ], 'agendamentos_not_save.*.jornada_id' => [ 'required', 'integer', ], 'agendamentos_not_save.*.hora_inicial' => [ 'required', ], 'agendamentos_not_save.*.data' => [ 'required', ], 'agendamentos_not_save.*.regulacao_solicitacao_id' => [ 'nullable', 'integer', Rule::exists(RegulacaoSolicitacao::class, 'id'), ], ]; $messages = [ 'agendamentos_not_save.*.infraestrutura_id.required' => 'O local de atendimento da unidade solicitante é obrigatório.', 'agendamentos_not_save.*.unidade_id.required' => 'A unidade solicitante é obrigatória.', 'agendamentos_not_save.*.coleta_infraestrutura_id.required' => 'O local de coleta é obrigatório.', 'agendamentos_not_save.*.coleta_unidade_id.required' => 'O local de atendimento do local de coleta é obrigatório.', 'agendamentos_not_save.*.laboratorio_id.required' => 'O laboratório é obrigatório.', 'agendamentos_not_save.*.laboratorio_infraestrutura_id.required' => 'O local de atendimento do laboratório é obrigatório.', 'agendamentos_not_save.*.medico_id.required' => 'O médico é obrigatório.', 'agendamentos_not_save.*.paciente_id.required' => 'O paciente é obrigatório.', 'agendamentos_not_save.*.jornada_id.required' => 'A data e horário são obrigatórios.', 'agendamentos_not_save.*.data.required' => 'A data é obrigatória.', 'agendamentos_not_save.*.hora_inicial.required' => 'O horário é obrigatório.', ]; return $request->validate($validations, $messages); } private static function getPermissoesAtualizacaoCadastroPaciente() { $parametrizacao = CnsService::getParametrizacao(); if (!is_null($parametrizacao)) { $lotacao = self::getCurrentLotacao(); return DB::table('cadastro_parametrizacao_permissao_usuario') ->select([ 'municipe', 'provisorio', 'outro_municipio', ]) ->where('infraestrutura_id', $lotacao->infraestrutura_id) ->where('usuario_id', $lotacao->usuario_id) ->get() ->first(); } return null; } private static function getCadastroDatasBloqueadas($params) { $datas = collect(); JornadaBloqueio::where('infraestrutura_id', $params->infraestrutura_id) ->where(fn ($q) => $q ->whereDate('inicio', '<', Carbon::today()) ->orWhereDate('fim', '<', Carbon::today()) ) ->get(['inicio', 'fim']) ->each(function ($parametrizacao) use ($datas) { $dataAtual = Carbon::today(); $data = $parametrizacao->inicio; while ($data <= $parametrizacao->fim) { if ($data < $dataAtual) { $datas->push($data->format('d/m/Y')); } $data->addDay(); } }); return $datas; } }