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, 'laboratorio_padrao' => Unidade::with('laboratorioPadraoInfraestrutura')->get() ?? null, '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') ->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()->withTrashed()->first()->nome, 'medico_solicitante' => [ 'id' => $agendamento->medico_id, 'cidadao_nome' => $agendamento->medico()->withTrashed()->first()->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 getHistoricoExame($idAgendamento) { return DB::table('exame_laboratorial_agendamento_exame_historico') ->select([ 'parametrizacao_exame.nome AS exame', DB::raw("COALESCE(usuario_responsavel.usuario, CONCAT(ws_usuario_alteracao.nome, ' (Web service)')) AS usuario_cadastro"), DB::raw("COALESCE(usuario_responsavel.usuario, CONCAT(ws_usuario_alteracao.nome, ' (Web service)')) AS usuario_alteracao"), DB::raw("DATE_FORMAT(exame_laboratorial_agendamento_exame_historico.created_at, '%d/%m/%Y %H:%i:%s') AS data_hora_modificacao"), 'acao.descricao AS acao', 'status.descricao AS status', 'exame_laboratorial_agendamento_exame_historico.justificativa AS justificativa', 'cadastro_unidade_coleta.nome_fantasia AS unidade_coleta_nome', DB::raw('CASE WHEN cadastro_infraestrutura_coleta.principal THEN cadastro_unidade_coleta.nome_fantasia ELSE cadastro_infraestrutura_coleta.nome END AS coleta_infraestrutura_nome'), 'cadastro_unidade_laboratorio.nome_fantasia AS laboratorio_nome', DB::raw('CASE WHEN cadastro_infraestrutura_laboratorio.principal THEN cadastro_unidade_laboratorio.nome_fantasia ELSE cadastro_infraestrutura_laboratorio.nome END AS laboratorio_infraestrutura_nome'), DB::raw('CASE WHEN infraestrutura_responsavel.principal THEN unidade_responsavel.nome_fantasia ELSE infraestrutura_responsavel.nome END AS unidade_responsavel'), DB::raw("DATE_FORMAT( COALESCE(CONCAT(exame_laboratorial_agendamento_exame_historico.data, ' ', exame_laboratorial_agendamento_exame_historico.horario), NOW()), '%d/%m/%Y %H:%i:%s' ) as data_horario_agendamento") ]) ->where('agendamento_id', $idAgendamento) ->join('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame_historico.exame_id') ->join('exame_laboratorial_agendamento as agendamento', 'agendamento.id', 'exame_laboratorial_agendamento_exame_historico.agendamento_id') ->join('exame_laboratorial_agendamento_exame_historico_acao as acao', 'acao.id', 'exame_laboratorial_agendamento_exame_historico.acao_id') ->join('exame_laboratorial_agendamento_exame_status as status', 'status.id', 'exame_laboratorial_agendamento_exame_historico.status_id') ->leftJoin('cadastro_lotacao as lotacao_responsavel', 'lotacao_responsavel.id', 'exame_laboratorial_agendamento_exame_historico.created_lotacao_id') ->leftJoin('cadastro_usuario as usuario_responsavel', 'usuario_responsavel.id', 'lotacao_responsavel.usuario_id') ->leftJoin('cadastro_infraestrutura as infraestrutura_responsavel', 'infraestrutura_responsavel.id', 'lotacao_responsavel.infraestrutura_id') ->leftJoin('cadastro_unidade as unidade_responsavel', 'unidade_responsavel.id', 'infraestrutura_responsavel.unidade_id') ->leftJoin('cadastro_infraestrutura as cadastro_infraestrutura_coleta', 'cadastro_infraestrutura_coleta.id', 'agendamento.coleta_infraestrutura_id') ->leftJoin('cadastro_unidade as cadastro_unidade_coleta', 'cadastro_unidade_coleta.id', 'cadastro_infraestrutura_coleta.unidade_id') ->leftJoin('cadastro_infraestrutura as cadastro_infraestrutura_laboratorio', 'cadastro_infraestrutura_laboratorio.id', 'agendamento.laboratorio_infraestrutura_id') ->leftJoin('cadastro_unidade as cadastro_unidade_laboratorio', 'cadastro_unidade_laboratorio.id', 'cadastro_infraestrutura_laboratorio.unidade_id') ->leftJoin('web_service_usuario as ws_usuario_alteracao', 'ws_usuario_alteracao.id', 'exame_laboratorial_agendamento_exame_historico.externo_created_usuario_id') ->latest('exame_laboratorial_agendamento_exame_historico.created_at') ->get(); } public static function getDetalhamento($id) { $agendamento = Agendamento::findOrFail($id); $integracaoAtiva = WebService::whereNotNull('tipo_id')->exists(); $statusIntegracao = null; $dataHoraStatusIntegracao = null; if ($integracaoAtiva) { $statusIntegracao = optional($agendamento->webServiceLaboratorioClientePedidoStatus)->nome ?? 'Sem status'; $dataHoraStatusIntegracao = $agendamento->updated_at ? $agendamento->updated_at->format('d/m/Y H:i:s') : null; } 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, 'integracao_ativa' => $integracaoAtiva, 'status_integracao' => $statusIntegracao, 'status_integracao_data_hora' => $dataHoraStatusIntegracao, ]; } 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, 'mapa_agrupado' => $query->exame->mapa_agrupado ?? null, 'grupo_id' => $query->exame->grupo_tipo_id ?? null, 'valor' => $query->valor, 'status_id' => $query->status_id, 'supervisor_id' => $query->supervisor_id ?? null, 'prazo_entrega' => $query->exame->prazo_entrega ?? null, 'validade' => $query->exame->validade ?? null, 'permite_repeticao' => $query->exame->permite_repeticao ?? null, 'observacao' => $query->exame->observacao ?? null, 'observacao_coleta' => $query->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, 'regulacao_mensagem_comprovante_agendamento' => RegulacaoParametrizacao::first() ->mensagem_comprovante_agendamento ?? null ]; } public static function getJornadas($request) { return [ 'agendamentos' => DB::table('exame_laboratorial_agendamento') ->join('exame_laboratorial_agendamento_exame','exame_laboratorial_agendamento_exame.agendamento_id','exame_laboratorial_agendamento.id') ->where('exame_laboratorial_agendamento.coleta_unidade_id', $request->unidade_id) ->where('exame_laboratorial_agendamento.coleta_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, ]) ->select('exame_laboratorial_agendamento.*') ->groupBy('exame_laboratorial_agendamento.id') ->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' => $agendamento->data ? (new Carbon($agendamento->data))->format('d/m/Y') : null, 'hora_inicial' => $agendamento->horario ? (new Carbon($agendamento->horario))->format('H:i') : null, ]) ->sortBy('data') ->values(), 'jornadas' => DB::table('exame_laboratorial_jornada') ->where('unidade_id', $request->unidade_id) ->where('infraestrutura_id', $request->infraestrutura_id) ->whereNull('deleted_at') ->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, '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), ]; } public static function getKits($request) { return 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( 'parametrizacao_kit_exame', 'parametrizacao_kit_exame.id', 'parametrizacao_kit_exame_item.kit_exame_id' ) ->join( 'exame_laboratorial_parametrizacao_unidade_solicitante_exame_item', 'exame_laboratorial_parametrizacao_unidade_solicitante_exame_item.exame_id', 'parametrizacao_kit_exame_item.exame_id' ) ->join( 'exame_laboratorial_parametrizacao_unidade_solicitante_exame', 'exame_laboratorial_parametrizacao_unidade_solicitante_exame.id', 'exame_laboratorial_parametrizacao_unidade_solicitante_exame_item.unidade_solicitante_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') ->where('parametrizacao_kit_exame_item.kit_exame_id', $kit->id) ->where('exame_laboratorial_parametrizacao_unidade_solicitante_exame.infraestrutura_id', $request->infraestrutura_id) ->where('parametrizacao_kit_exame.tipo_id', Tipo::LABORATORIAL) ->whereNull('parametrizacao_exame.regulacao_tipo_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(); } 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('exame_laboratorial_parametrizacao_unidade.deleted_at') ->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']; $alterouData = Carbon::parse($agendamento->data)->toDateString() != Carbon::parse($params['data'])->toDateString(); } else { $ultimo_agendamento = Agendamento::orderByDesc('agendamento_numero')->first(); $agendamento_numero = $ultimo_agendamento ? $ultimo_agendamento->agendamento_numero + 1 : 1; $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->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 && empty($params['reagendar']) && !$unidadeUrgencia) { if($params['agendamento_id'] && (!is_numeric($params['agendamento_id']) || $alterouData)){ 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,$params['justificativa_cancelamento'] ?? null); if (!empty($exame->soap_solicitacao_exame_item_id)) { AtendimentoSoapSolicitacaoExameItem::where('id', $exame->soap_solicitacao_exame_item_id) ->update([ 'agendado_exame_laboratorial' => false, 'descartado_exame_laboratorial' => false, ]); } 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'])) { $agendamento = Agendamento::where('id', $params['agendamento_id'])->first(); if ($agendamento) { self::cancelAgendamentoExames($agendamento, $params['justificativa_cancelamento'] ?? null); } } } if (isset($impressao_agendamento_id)) { return self::printProtocolo($impressao_agendamento_id); } } private static function saveExames($params, $agendamento) { $examesUnicos = []; foreach ($params['incluido'] as $item) { $exameId = $item['exame_id']; if (!isset($examesUnicos[$exameId])) { $examesUnicos[$exameId] = $item; } else { $storedHasId = isset($examesUnicos[$exameId]['id']) && is_numeric($examesUnicos[$exameId]['id']); $currentHasId = isset($item['id']) && is_numeric($item['id']); if ($currentHasId && !$storedHasId) { $examesUnicos[$exameId] = $item; } } } $params['incluido'] = array_values($examesUnicos); $idsExame = []; foreach ($params['incluido'] as $param_exame) { $exameAcao = Acao::INSERCAO; if ($param_exame['id'] && is_numeric($param_exame['id'])) { $exame = AgendamentoExame::where('id', $param_exame['id']) ->where('agendamento_id', $agendamento->id) ->first(); if (!$exame) { $exame = new AgendamentoExame(); $exameAcao = Acao::INSERCAO; } else { $exameAcao = Acao::ALTERACAO; } } else { $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->status_id = $status_id; $exame->valor = $valor_exame; $exame->procedimento_id = $param_exame['procedimento_id']; $exame->supervisor_id = $param_exame['supervisor_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(); 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]); } AgendamentoExameHistoricoService::store($exame, $agendamento, $exameAcao); $idsExame[] = $exame->id; self::updateExameBloqueado($agendamento->paciente_id, $param_exame['supervisor_id'], $param_exame['exame_id']); } $examesRemovidos = AgendamentoExame::where('agendamento_id', $agendamento->id) ->whereNotIn('id', $idsExame)->pluck('id'); $examesRemovidos->map(function($item) use($exame, $agendamento) { $exame = AgendamentoExame::where('id', $item)->first(); AgendamentoExameHistoricoService::store($exame, $agendamento, Acao::EXCLUSAO); }); AgendamentoExame::destroy($examesRemovidos); } private static function cancelAgendamentoExames(Agendamento $agendamento, ?string $justificativa = null): void { $exames = AgendamentoExame::where('agendamento_id', $agendamento->id)->get(); foreach ($exames as $exame) { if ($exame->status_id === StatusAgendamento::CANCELADO) { continue; } $exame->status_id = StatusAgendamento::CANCELADO; $exame->save(); AgendamentoExameHistoricoService::store($exame, $agendamento, Acao::EXCLUSAO, $justificativa); if (!empty($exame->soap_solicitacao_exame_item_id)) { AtendimentoSoapSolicitacaoExameItem::where('id', $exame->soap_solicitacao_exame_item_id) ->update([ 'agendado_exame_laboratorial' => false, 'descartado_exame_laboratorial' => false, ]); } } } public static function descartarExameAmbulatorioAtendimento() { if (request()->multiple == true) { $examesIds = array_column(request()->exames, 'exame_item_id'); AtendimentoSoapSolicitacaoExameItem::whereIn('id', $examesIds)->update(['descartado_exame_laboratorial' => true]); return true; } else { return AtendimentoSoapSolicitacaoExameItem::findOrFail(request()->ambulatorio_atendimento_id)->update(['descartado_exame_laboratorial' => true]); } } public static function cancel($id, string $justificativa) { $agendamento = Agendamento::findOrFail($id); self::cancelAgendamentoExames($agendamento, $justificativa); return [ 'success' => true, ]; } private static function updateExameBloqueado($paciente_id, $supervisor_id, $exame_id) { if ($supervisor_id) { $exame_bloqueado = AgendamentoExameBloqueado::where('paciente_id', $paciente_id) ->where('exame_id', $exame_id) ->where('created_lotacao_id', auth()->payload()->get('lotacao_id')) ->whereDate('created_at', Carbon::now()->toDateString()) ->whereNull('supervisor_id') ->first(); if ($exame_bloqueado) { $exame_bloqueado->update(['supervisor_id' => $supervisor_id]); } } } public static function saveExameBloqueado() { $exame = AgendamentoExameBloqueado::where('paciente_id', request()->paciente_id) ->where('exame_id', request()->exame_id) ->where('created_lotacao_id', auth()->payload()->get('lotacao_id')) ->whereDate('created_at', Carbon::now()->toDateString()) ->whereNull('supervisor_id') ->first() ?? new AgendamentoExameBloqueado; $exame->paciente_id = request()->paciente_id; $exame->exame_id = request()->exame_id; $exame->valor = request()->valor; $exame->motivo_id = request()->motivo_id; $exame->save(); return $exame; } 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('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) ->whereNotIn('status_id', [ StatusAgendamento::CANCELADO, StatusAgendamento::FALTOU ]) ->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->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); $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 (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); } } 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) ->where(function ($query) { $query->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->orWhereNull('status_id'); }) ->where('exame_laboratorial_agendamento.data', '>=', $cotaLaboratorio->inicio) ->where('exame_laboratorial_agendamento.data', '<=', $cotaLaboratorio->fim) ->count('exame_laboratorial_agendamento_exame.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('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('lotacao_laboratorio.infraestrutura_id', request()->laboratorio_infraestrutura_id) ->whereBetween('pronto_atendimento_pedido_exame_item.created_at', [$inicio, $fim]) ->count('pronto_atendimento_pedido_exame_item.id'); $cotaUtilizada = $cotaUtilizada + $prontoAtendimento; } 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(function ($query) { $query->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::AGENDADO, StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->orWhereNull('status_id'); }) ->where('exame_laboratorial_agendamento.data', '>=', $cotaLaboratorio->inicio) ->where('exame_laboratorial_agendamento.data', '<=', $cotaLaboratorio->fim) ->where('exame_laboratorial_agendamento.infraestrutura_id', request()->infraestrutura_id) ->count('exame_laboratorial_agendamento_exame.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', request()->infraestrutura_id) ->where('lotacao_laboratorio.infraestrutura_id', request()->laboratorio_infraestrutura_id) ->whereBetween('pronto_atendimento_pedido_exame_item.created_at', [$inicio, $fim]) ->count('pronto_atendimento_pedido_exame_item.id'); $cotaUtilizada = $cotaUtilizada + $prontoAtendimento; } 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 ]; } } public static function getExameAmbulatorioAtendimento() { return DB::table('ambulatorio_atendimento_soap_solicitacao_exame_item') ->select( 'ambulatorio_atendimento_soap_solicitacao_exame_item.id as exame_item_id', 'parametrizacao_exame.nome as exame_nome', 'parametrizacao_exame.id as exame_id', 'parametrizacao_exame.codigo as exame_codigo', 'parametrizacao_exame.observacao as exame_observacao', 'parametrizacao_exame.prazo_entrega as exame_prazo_entrega', 'parametrizacao_exame.validade as validade', 'parametrizacao_exame.senha_supervisor as exame_senha_supervisor', 'parametrizacao_exame.sigla_exame as exame_sigla_exame', 'parametrizacao_exame.grupo_tipo_id as exame_grupo_tipo_id', 'parametrizacao_exame.quantidade_maxima as exame_quantidade_maxima', 'sigtap.procedimento.quantidade_maxima_execucao as exame_quantidade_maxima_execucao', 'parametrizacao_exame.permite_repeticao as exame_permite_repeticao', 'sigtap.procedimento.id as exame_procedimento_id', 'parametrizacao_exame.valor as exame_valor', 'parametrizacao_exame.valor_sigtap as exame_valor_sigtap', 'sigtap.procedimento.valor_servico_ambilatorial as exame_valor_servico_ambilatorial', 'painel_senha_fila.paciente_id', DB::raw('false AS selecionado'), 'cadastro_cidadao.nome as profissional_nome', 'profissional.id as profissional_id', 'unidade.nome_fantasia as unidade', 'unidade.id as unidade_id', 'infraestrutura.id as infraestrutura_id', DB::raw('IF(infraestrutura.nome IS NULL, unidade.nome_fantasia, infraestrutura.nome) as infraestrutura'), DB::raw("DATE_FORMAT(ambulatorio_atendimento_soap_solicitacao_exame.created_at, '%d/%m/%Y') AS data"), DB::raw("IF(ambulatorio_atendimento_soap_solicitacao_exame_item.faz_parte_oci = 1, ambulatorio_atendimento_soap.acompanhamento_oci_id, NULL) as acompanhamento_oci_id") ) ->join('ambulatorio_atendimento_soap_solicitacao_exame', 'ambulatorio_atendimento_soap_solicitacao_exame.id', '=', 'ambulatorio_atendimento_soap_solicitacao_exame_item.solicitacao_exame_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', '=', 'ambulatorio_atendimento_soap_solicitacao_exame_item.exame_id') ->join('ambulatorio_atendimento_soap', 'ambulatorio_atendimento_soap.id', '=', 'ambulatorio_atendimento_soap_solicitacao_exame.soap_id') ->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', '=', 'ambulatorio_atendimento_soap.atendimento_id') ->join('painel_senha_fila', 'painel_senha_fila.id', '=', 'ambulatorio_atendimento.fila_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_atendimento_soap_solicitacao_exame.created_lotacao_id') ->join('cadastro_usuario as profissional', 'profissional.id', 'cadastro_lotacao.usuario_id') ->join('cadastro_cidadao', 'cadastro_cidadao.id', 'profissional.cidadao_id') ->join('cadastro_infraestrutura as infraestrutura', 'infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->join('cadastro_unidade as unidade', 'unidade.id', 'infraestrutura.unidade_id') ->leftJoin('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' ) ->where('parametrizacao_exame.tipo_id', Tipo::LABORATORIAL) ->whereNull('parametrizacao_exame.regulacao_tipo_id') ->where('ambulatorio_atendimento_soap_solicitacao_exame_item.descartado_exame_laboratorial', '!=', true) ->where('ambulatorio_atendimento_soap_solicitacao_exame_item.agendado_exame_laboratorial', '!=', true) ->where('painel_senha_fila.paciente_id', request()->paciente_id) ->where('ambulatorio_atendimento_soap.is_rascunho', false) ->get(); } 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; $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('lotacao_laboratorio.infraestrutura_id', request()->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); } 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; $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', request()->infraestrutura_id) ->where('lotacao_laboratorio.infraestrutura_id', request()->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 (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 = $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 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; $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', request()->infraestrutura_id) ->whereBetween('pronto_atendimento_pedido_exame_item.created_at', [$inicio, $fim]) ->count('pronto_atendimento_pedido_exame_item.id'); $cotaUtilizada = $cotaUtilizada + $prontoAtendimento; 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; $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', request()->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'); if ($prontoAtendimento) { $prontoAtendimento = str_replace('.', '', $prontoAtendimento); $prontoAtendimento = str_replace(',', '.', $prontoAtendimento); $prontoAtendimento = floatval($prontoAtendimento); } else { $prontoAtendimento = 0; } $cotaUtilizada = floatval($cotaUtilizada) + $prontoAtendimento; 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 = round($cotaUtilizada - $cotaAgendamento, 2); } } $totalCota = (($totalUnidade - $saldoEnviado) + $saldoRecebido); if ($totalCota > 0) { $percentualRestante = 100 - ($cotaUtilizada / $totalCota * 100); } else { $percentualRestante = 0; } 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); }) ->whereHas('cotaExame', function ($query) use ($cotaExame) { $query->where('exame_id', $cotaExame->cotaExame->exame_id); }) ->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('cotaExame', function ($query) use ($cotaExame) { $query->where('exame_id', $cotaExame->cotaExame->exame_id); }) ->sum('cota_quantidade_transferido'); $cotaUtilizada = Agendamento::where('laboratorio_infraestrutura_id', request()->laboratorio_infraestrutura_id) ->where('infraestrutura_id', request()->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; $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('pronto_atendimento_pedido_exame_item.exame_id', $cotaExame->cotaExame->exame_id) ->where('cadastro_lotacao.infraestrutura_id', request()->infraestrutura_id) ->where('lotacao_laboratorio.infraestrutura_id', request()->laboratorio_infraestrutura_id) ->whereBetween('pronto_atendimento_pedido_exame_item.created_at', [$inicio, $fim]) ->count('pronto_atendimento_pedido_exame_item.id'); $cotaUtilizada = $cotaUtilizada + $prontoAtendimento; 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('infraestrutura_id', request()->infraestrutura_id) ->where('data', '>=', $cotaLaboratorio->inicio) ->where('data', '<=', $cotaLaboratorio->fim); }) ->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('pronto_atendimento_pedido_exame_item.exame_id', $cotaExame->cotaExame->exame_id) ->where('cadastro_lotacao.infraestrutura_id', request()->infraestrutura_id) ->where('lotacao_laboratorio.infraestrutura_id', request()->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 (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; $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->exame_id) ->where('lotacao_laboratorio.infraestrutura_id', request()->laboratorio_infraestrutura_id) ->whereBetween('pronto_atendimento_pedido_exame_item.created_at', [$inicio, $fim]) ->count('pronto_atendimento_pedido_exame_item.id'); $quantidadeUtilizada = $quantidadeUtilizada + $prontoAtendimento; 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; $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->exame_id) ->where('lotacao_laboratorio.infraestrutura_id', request()->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 (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); } } $exames[] = [ 'exame_id' => $cotaExame->exame_id, 'saldo' => $cotaExame->cota_valor - $valorUtilizado != 0 ? $cotaExame->cota_valor - $valorUtilizado : 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; } }