format('Y-m-d'); $lotacao = Lotacao::findOrFail(auth()->payload()->get('lotacao_id')); return [ 'form' => [ 'periodo' => [ 'start' => $currentDate, 'end' => $currentDate, ], 'data_atual' => Carbon::now()->format('d/m/Y'), 'profissional' => [ 'id' => $lotacao->usuario->id, 'nome' => $lotacao->usuario->cidadao->nome, 'cbo' => $lotacao->ocupacao->nome, 'ocupacao_id' => $lotacao->ocupacao->id ?? null, ], 'data_atual' => Carbon::now()->format('d/m/Y'), 'status' => Status::where(function($query) { $query->where('id', StatusAgendamento::REALIZADO) ->orWhere('id', StatusAgendamento::PENDENTE_ASSINATURA) ->orWhere('id', StatusAgendamento::ASSINADO) ->orWhere('id', StatusAgendamento::NAO_REALIZADO) ->orWhere('id', StatusAgendamento::NOVA_COLETA); }) ->orderBy('id') ->get() ->map(fn ($status) => [ 'id' => $status->id, 'descricao' => $status->descricao ]), 'profissionais_assinatura' => ProfissionalAssinatura::all() ->map(fn ($profissional) => [ 'id' => $profissional->usuario_id, 'nome' => $profissional->usuario->cidadao->nome, 'lotacoes' => $profissional->usuario->lotacoes, ]), ], ]; } public static function list(Request $request) { $now = Carbon::now(); $currentDate = $now->format('Y-m-d'); $agendamentos = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento_exame.id AS agendamento_exame_id', 'exame_laboratorial_agendamento.id AS agendamento_id', 'exame_laboratorial_agendamento.agendamento_numero AS agendamento_numero', DB::raw('DATE_FORMAT(exame_laboratorial_agendamento_exame.data_coleta, "%d/%m/%Y") AS data'), DB::raw('TIME_FORMAT(exame_laboratorial_agendamento_exame.data_coleta, "%H:%i") AS hora_inicial'), 'parametrizacao_exame.id AS exame_id', 'parametrizacao_exame.nome AS exame_nome', 'cadastro_grupo.id AS grupo_id', 'cadastro_grupo.nome AS grupo_nome', 'exame_laboratorial_agendamento_exame.status_id AS status_id', 'cadastro_cidadao.nome AS paciente_nome', 'cadastro_cidadao.preferencia_nome_id AS paciente_preferencia_nome_id', 'cadastro_cidadao.nome_social AS paciente_nome_social', DB::raw('LPAD(cadastro_paciente.prontuario,7,0) as paciente_prontuario'), DB::raw('cadastro_unidade.nome_fantasia AS unidade_nome'), DB::raw(" CASE WHEN cadastro_infraestrutura.principal THEN cadastro_unidade.nome_fantasia ELSE cadastro_infraestrutura.nome END AS infraestrutura_nome "), ]) ->leftJoin('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->leftJoin('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->leftJoin('cadastro_grupo', 'cadastro_grupo.id', 'parametrizacao_exame.grupo_tipo_id') ->leftJoin('cadastro_paciente', 'cadastro_paciente.id', 'exame_laboratorial_agendamento.paciente_id') ->leftJoin('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_id') ->leftJoin('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'exame_laboratorial_agendamento.infraestrutura_id') ->leftJoin('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->groupBy([ 'exame_laboratorial_agendamento.id', 'parametrizacao_exame.id', ]); if ($request->periodo) { $agendamentos->where('exame_laboratorial_agendamento.data', '>=', $request->periodo['start']); $agendamentos->where('exame_laboratorial_agendamento.data', '<=', $request->periodo['end']); } else { $agendamentos->where('exame_laboratorial_agendamento.data', $currentDate); } if ($request->paciente_id) { $agendamentos->where('exame_laboratorial_agendamento.paciente_id', $request->paciente_id); } if ($request->agendamento_numero) { $agendamentos->where('exame_laboratorial_agendamento.agendamento_numero', $request->agendamento_numero); } if ($request->prontuario) { $agendamentos->where('cadastro_paciente.prontuario', $request->prontuario); } if ($request->exame_id) { $agendamentos->where('cadastro_grupo.id', $request->exame_id); } if ($request->data_nascimento) { $agendamentos->where('cadastro_cidadao.data_nascimento', $request->data_nascimento); } if ($request->status_id) { $agendamentos->where(function($query) use ($request) { foreach ($request->status_id as $status) { $query->orWhere('status_id', $status); } }); } $agendamentos->whereExists(function($query) { $query->select(DB::raw(1)) ->from('exame_laboratorial_agendamento_exame') ->whereColumn('exame_laboratorial_agendamento_exame.agendamento_id', 'exame_laboratorial_agendamento.id'); $query->where(function($status) { $status->where('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::REALIZADO) ->orWhere('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::PENDENTE_ASSINATURA); }); }); $agendamentos = $agendamentos->orderBy('parametrizacao_exame.posicao_mapa', 'ASC'); $agendamentos = $agendamentos->orderBy('parametrizacao_exame.nome', 'ASC'); $agendamentos = $agendamentos->get()->toArray(); return [ 'model' => [ 'agendamentos' => $agendamentos, 'periodo' => [ 'start' => $currentDate, 'end' => $currentDate, ], ], ]; } public static function getAtendimento() { $id = request()->id; if(is_numeric($id)){ $exame = self::getExame($id); $exames = $exame->exame->mapa_agrupado ? self::getExames($exame->exame->grupo_tipo_id, $exame->agendamento->id) : collect(); } $lotacao = self::getLotacaoLogado(); return [ 'form' => [ 'data_atual' => Carbon::now()->format('d/m/Y'), 'profissional' => [ 'id' => $lotacao->usuario->id, 'nome' => $lotacao->usuario->cidadao->nome, 'cbo' => $lotacao->ocupacao->nome, 'ocupacao_id' => $lotacao->ocupacao->id ?? null, ], 'paciente' => [ 'nome' => $exame->agendamento->paciente->cidadao->nome ?? null, 'nomeSocial' => $exame->agendamento->paciente->cidadao->nome_social, 'prefereNomeSocial' => $exame->agendamento->paciente->cidadao ->preferencia_nome_id === PreferenciaNome::NOME_SOCIAL, 'data_nascimento' => $exame->agendamento->paciente->cidadao->data_nascimento ? $exame->agendamento->paciente->cidadao->data_nascimento->format('d/m/Y') : '', 'idade' => $exame->agendamento->paciente->cidadao->data_nascimento ? "{$exame->agendamento->paciente->cidadao->idade['anos']} ano(s) " . "{$exame->agendamento->paciente->cidadao->idade['meses']} mês(s) " . "{$exame->agendamento->paciente->cidadao->idade['dias']} dia(s) " : '', 'sexo' => $exame->agendamento->paciente->cidadao->sexo ?? '-', 'telefone' => MaskUtil::getPhoneMasked($exame->agendamento->paciente->cidadao->telefone_principal->numero ?? ''), ], 'data_agendamento' => (new Carbon($exame->agendamento->data))->format('d/m/Y'), 'data_coleta' => (new Carbon($exame->data_coleta))->format('d/m/Y'), 'medico' => $exame->agendamento->medico()->withTrashed()->first()->nome, 'uso_medicamento' => $exame->agendamento->uso_medicamento ?? 'Não informado', 'suspeita_clinica' => $exame->agendamento->suspeita_clinica ?? 'Não informada', 'observacao' => $exame->agendamento->observacao ?? 'Não informada', 'motivo' => Motivo::get() ->map(fn($query) => [ 'id' => $query->id ?? null, 'descricao' => $query->descricao ?? null, ]), 'competencia' => Competencia::orderByDesc('valor')->take(4)->get(), ], 'model' => [ 'data_atual' => Carbon::now()->format('d/m/Y'), 'agendamentosNotSave' => null, 'exame_nome' => $exame->exame->nome, 'exame_grupo_nome' => $exame->exame->grupo->nome, 'exame_grupo_tipo_id' => $exame->exame->grupo_tipo_id, 'procedimento_id' => $exame->exame->getProcedimentoAttribute()->id ?? null, 'procedimento_competencia' => $exame->exame->getProcedimentoAttribute()->competencia ?? null, 'competencia' => $exame->exame->procedimento ? self::getCompetencia($exame->agendamento->data->format('Ym'), $exame->exame->procedimento->codigo, $exame->agendamento->laboratorio_infraestrutura_id) : null, 'exame_id' => $exame->exame_id, 'exame_status_id' => $exame->status_id, 'agendamento_id' => $exame->agendamento_id, 'agendamento_exame_id' => $exame->id, 'motivo_id' => $exame->motivo_id ?? null, 'assinatura_profissional_id' => $exame->assinatura_profissional_id ?? null, 'nao_realizado' => $exame->status_id == StatusAgendamento::NAO_REALIZADO ? true : false, 'nova_coleta' => $exame->status_id == StatusAgendamento::NOVA_COLETA ? true : false, 'observacao' => $exame->observacao, 'composicao' => self::getComposicao($exame, $exame->exame_id, $exame->id), 'historico' => self::getHistorico($exame->exame_id, $exame->agendamento_id, $exame->agendamento->paciente->id) ->map(fn ($historico) => [ 'data' => $historico->data, 'exame_nome' => $historico->exame_nome, 'exame_id' => $historico->exame_id, 'observacao' => $historico->observacao, 'composicao' => self::getComposicaoHistorico($exame, $historico->agendamento_exame_id) ]), 'exames' => $exames->map(fn ($exameGrupo) => [ 'exame_nome' => $exameGrupo->exame_nome, 'exame_id' => $exameGrupo->exame_id, 'exame_status_id' => $exameGrupo->status_id, 'procedimento_id' => $exameGrupo->procedimento_id ?? null, 'agendamento_id' => $exameGrupo->agendamento_id, 'agendamento_exame_id' => $exameGrupo->agendamento_exame_id, 'mapa_agrupado' => $exameGrupo->mapa_agrupado, 'motivo_id' => $exameGrupo->motivo_id ?? null, 'competencia' => $exameGrupo->procedimento_codigo ? self::getCompetencia($exameGrupo->data, $exameGrupo->procedimento_codigo, $exame->agendamento->laboratorio_infraestrutura_id) : null, 'assinatura_profissional_id' => $exameGrupo->assinatura_profissional_id ?? null, 'nao_realizado' => $exameGrupo->status_id == StatusAgendamento::NAO_REALIZADO ? true : false, 'nova_coleta' => $exameGrupo->status_id == StatusAgendamento::NOVA_COLETA ? true : false, 'observacao' => $exameGrupo->observacao, 'historico' => self::getHistorico($exameGrupo->exame_id, $exameGrupo->agendamento_id, $exame->agendamento->paciente->id) ->map(fn ($historico) => [ 'data' => $historico->data, 'exame_nome' => $historico->exame_nome, 'exame_id' => $historico->exame_id, 'observacao' => $historico->observacao, 'composicao' => self::getComposicaoHistorico($exame, $historico->agendamento_exame_id) ]), 'composicao' => self::getComposicao($exame, $exameGrupo->exame_id, $exameGrupo->agendamento_exame_id) ]), ], ]; } private static function getComposicao($exame, $exameGrupo, $agendamentoExameId) { return ExameComposicao::where('exame_id', $exameGrupo) ->where(function($query) use ($exame) { $query->where('sexo_id', $exame->agendamento->paciente->cidadao->sexo_id) ->orWhereNull('sexo_id'); }) ->where(function ($query) use ($exame) { $query->whereNull('tipo_idade_id') ->orWhere(function ($idade) use ($exame) { $idade ->where('tipo_idade_id', '!=', null) ->where(function ($idade) use ($exame) { $idade ->where('tipo_idade_id', MedidaTempo::DIAS) ->where( 'idade_inicial', '<=', Carbon::create($exame->agendamento->paciente->cidadao->data_nascimento ->format('d-m-Y'))->diffInDays(Carbon::now())) ->where( 'idade_final', '>=', Carbon::create($exame->agendamento->paciente->cidadao->data_nascimento ->format('d-m-Y'))->diffInDays(Carbon::now())); }) ->orWhere(function ($idade) use ($exame) { $idade ->where('tipo_idade_id', MedidaTempo::MESES) ->where( 'idade_inicial', '<=', Carbon::create($exame->agendamento->paciente->cidadao->data_nascimento ->format('d-m-Y'))->diffInMonths(Carbon::now())) ->where( 'idade_final', '>=', Carbon::create($exame->agendamento->paciente->cidadao->data_nascimento ->format('d-m-Y'))->diffInMonths(Carbon::now())); }) ->orWhere(function ($idade) use ($exame) { $idade ->where('tipo_idade_id', MedidaTempo::ANOS) ->where( 'idade_inicial', '<=', Carbon::create($exame->agendamento->paciente->cidadao->data_nascimento ->format('d-m-Y'))->diffInYears(Carbon::now())) ->where( 'idade_final', '>=', Carbon::create($exame->agendamento->paciente->cidadao->data_nascimento ->format('d-m-Y'))->diffInYears(Carbon::now())); }); }); }) ->get() ->map(function($query) use ($agendamentoExameId) { return [ 'id' => $query->id, 'exame_id' => $query->exame_id, 'descricao' => $query->descricao, 'limite_inferior' => number_format($query->limite_inferior, 2, ',', '.'), 'limite_superior' => number_format($query->limite_superior, 2, ',', '.'), 'unidade_id' => $query->unidade_id, 'unidade' => $query->unidade_id ? $query->unidade->descricao : '', 'referencia' => $query->referencia, 'tipo_idade_id' => $query->tipo_idade_id, 'tipo_idade' => $query->tipo_idade_id ? $query->tipoIdade->descricao : '-', 'idade_inicial' => $query->idade_inicial, 'idade_final' => $query->idade_final, 'sexo_id' => $query->sexo_id, 'sexo' => $query->sexo->descricao ?? 'AMBOS', 'tipo_resultado_id' => $query->tipo_resultado_id, 'tipo_resultado' => $query->tipoResultado->descricao, 'casa_decimal_id' => $query->casa_decimal_id, 'formula_id' => $query->formula_id, 'valor' => ExameComposicaoLista::where('composicao_id', $query->id) ->where('padrao', true) ->first()->id ?? null, 'situacao' => null, 'visivel' => $query->visivel, 'valor_absoluto' => $query->valor_absoluto, 'resultado' => AgendamentoExameResultado::where('agendamento_exame_id', $agendamentoExameId) ->where('composicao_id', $query->id)->first()->valor ?? ExameComposicaoLista::where('composicao_id', $query->id) ->where('padrao', true)->first()->id ?? null, 'referencia_especial' => $query->referencia_especial, 'lista' => ExameComposicaoLista::where('composicao_id', $query->id) ->orderBy('ordem') ->get() ->map(fn ($composicao) => [ 'id' => $composicao->id, 'descricao' => $composicao->descricao, 'ordem' => $composicao->ordem, 'situacao_id' => $composicao->situacao_id, 'situacao' => ucfirst(strtolower($composicao->situacao->descricao)), 'padrao' => $composicao->padrao, ]), 'variavel' => ExameComposicaoVariavel::where('composicao_id', $query->id) ->get() ->map(fn ($variavel) => [ 'id' => $variavel->id, 'ordem' => $variavel->ordem, 'fator_id' => $variavel->fator_id ?? null, 'fator' => $variavel->fator->fator ?? null, ]), 'formula' => FormulaExame::where('id', $query->formula_id) ->get() ->map(fn ($formula) => [ 'id' => $formula->id, 'nome' => $formula->nome, 'fatores' => FormulaExameFator::where('formula_exame_id', $formula->id) ->get() ->map(function($query) { return [ 'id' => $query->id, 'formula_exame_id' => $query->formula_exame_id, 'fator' => $query->fator, 'operacao_id' => $query->operacao_id, 'operacao_descricao' => $query->operacao->descricao, 'tipo' => $query->tipo, 'valor' => $query->valor ? number_format($query->valor, 6, ',', '.') : null, 'exponenciacao' => $query->exponenciacao ? true : false, 'exponenciacao_tipo' => $query->exponenciacao_tipo, 'exponenciacao_valor' => $query->exponenciacao_valor ? number_format($query->exponenciacao_valor, 6, ',', '.') : null, 'ordem' => $query->ordem, ]; })->values(), ]), ]; }); } private static function getComposicaoHistorico($exame, $exameId) { return AgendamentoExameResultado::where('agendamento_exame_id', $exameId) ->whereHas('composicao', function($query) use ($exame) { $query->where('sexo_id', $exame->agendamento->paciente->cidadao->sexo->id) ->orWhereNull('sexo_id'); $query->where(function ($idade) use ($exame) { $idade ->where(function ($idade) use ($exame) { $idade ->where('tipo_idade_id', MedidaTempo::DIAS) ->where( 'idade_inicial', '<=', Carbon::create($exame->agendamento->paciente->cidadao->data_nascimento ->format('d-m-Y'))->diffInDays(Carbon::now())) ->where( 'idade_final', '>=', Carbon::create($exame->agendamento->paciente->cidadao->data_nascimento ->format('d-m-Y'))->diffInDays(Carbon::now())) ->orWhereNull('tipo_idade_id'); }) ->orWhere(function ($idade) use ($exame) { $idade ->where('tipo_idade_id', MedidaTempo::MESES) ->where( 'idade_inicial', '<=', Carbon::create($exame->agendamento->paciente->cidadao->data_nascimento ->format('d-m-Y'))->diffInMonths(Carbon::now())) ->where( 'idade_final', '>=', Carbon::create($exame->agendamento->paciente->cidadao->data_nascimento ->format('d-m-Y'))->diffInMonths(Carbon::now())) ->orWhereNull('tipo_idade_id'); }) ->orWhere(function ($idade) use ($exame) { $idade ->where('tipo_idade_id', MedidaTempo::ANOS) ->where( 'idade_inicial', '<=', Carbon::create($exame->agendamento->paciente->cidadao->data_nascimento ->format('d-m-Y'))->diffInYears(Carbon::now())) ->where( 'idade_final', '>=', Carbon::create($exame->agendamento->paciente->cidadao->data_nascimento ->format('d-m-Y'))->diffInYears(Carbon::now())) ->orWhereNull('tipo_idade_id'); }); }); }) ->get() ->map(function($query) use ($exameId) { return [ 'id' => $query->id, 'descricao' => $query->composicao->descricao, 'tipo_resultado_id' => $query->composicao->tipo_resultado_id, 'resultado' => $query->composicao->tipo_resultado_id == ComposicaoTipo::LISTA ? ExameComposicaoLista::where('id', AgendamentoExameResultado::where('agendamento_exame_id', $exameId) ->where('composicao_id', $query->composicao->id)->first()->valor )->first()->descricao ?? null : AgendamentoExameResultado::where('agendamento_exame_id', $exameId) ->where('composicao_id', $query->composicao->id) ->first()->valor ?? null, ]; }); } private static function getExame($id) { return AgendamentoExame::findOrFail($id); } private static function getCompetencia($data, $codigo, $infraestruturaId) { $competencias = Competencia::orderByDesc('valor')->take(4)->get(); $competencia = $competencias->firstWhere('valor', $data); if (is_null($competencia)) { $competencia = $competencias->first(); }; $procedimentoServiceValidation = new ProcedimentoValidationService( Procedimento::where('codigo', $codigo) ->where('competencia_id', $competencia->id) ->first() ); $lotacao = Lotacao::where('usuario_id', request()->profissional_id) ->where('infraestrutura_id', $infraestruturaId) ->first(); if(is_null($lotacao)){ throw new LotacaoException; } return $procedimentoServiceValidation->isOcupacaoValid($lotacao->ocupacao); } private static function getLotacaoLogado() { return Lotacao::findOrFail(auth()->payload()->get('lotacao_id')); } public static function getExames($id, $agendamentoId) { $agendamentos = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento_exame.id AS agendamento_exame_id', 'exame_laboratorial_agendamento.id AS agendamento_id', DB::raw('DATE_FORMAT(exame_laboratorial_agendamento.data, "%Y%m") AS data'), 'exame_laboratorial_agendamento_exame.motivo_id AS motivo_id', 'exame_laboratorial_agendamento_exame.assinatura_profissional_id AS assinatura_profissional_id', 'exame_laboratorial_agendamento_exame.status_id AS status_id', 'exame_laboratorial_agendamento_exame.observacao AS observacao', 'parametrizacao_exame.id AS exame_id', 'parametrizacao_exame.nome AS exame_nome', 'parametrizacao_exame.mapa_agrupado AS mapa_agrupado', 'cadastro_grupo.id AS grupo_id', 'cadastro_grupo.nome AS grupo_nome', 'sigtap.procedimento.id as procedimento_id', 'sigtap.procedimento.nome as procedimento_nome', 'sigtap.procedimento.codigo as procedimento_codigo', 'sigtap.procedimento.quantidade_maxima_execucao', ]) ->leftJoin('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->leftJoin('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->leftJoin('cadastro_grupo', 'cadastro_grupo.id', 'parametrizacao_exame.grupo_tipo_id') ->leftJoin('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' ) ->groupBy([ 'exame_laboratorial_agendamento.id', 'parametrizacao_exame.id', ]); $agendamentos->where('cadastro_grupo.id', $id); $agendamentos->where('exame_laboratorial_agendamento.id', $agendamentoId); $agendamentos->where('parametrizacao_exame.mapa_agrupado', true); $agendamentos->where('exame_laboratorial_agendamento_exame.status_id', '!=', StatusAgendamento::ASSINADO); $agendamentos = $agendamentos->orderBy('parametrizacao_exame.posicao_mapa', 'ASC'); $agendamentos = $agendamentos->orderBy('parametrizacao_exame.nome', 'ASC'); $agendamentos = $agendamentos->get(); return $agendamentos; } public static function getHistorico($id, $agendamentoId, $pacienteId) { $agendamentos = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento_exame.id AS agendamento_exame_id', 'exame_laboratorial_agendamento.id AS agendamento_id', 'exame_laboratorial_agendamento_exame.observacao AS observacao', DB::raw('DATE_FORMAT(exame_laboratorial_agendamento_exame.data_laudo, "%d/%m/%Y") AS data'), 'parametrizacao_exame.id AS exame_id', 'parametrizacao_exame.nome AS exame_nome', ]) ->leftJoin('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->leftJoin('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->leftJoin('cadastro_paciente', 'cadastro_paciente.id', 'exame_laboratorial_agendamento.paciente_id') ->groupBy([ 'exame_laboratorial_agendamento.id', 'parametrizacao_exame.id', ]); $agendamentos->where('parametrizacao_exame.id', $id); $agendamentos->where('exame_laboratorial_agendamento.id', '!=', $agendamentoId); $agendamentos->where('cadastro_paciente.id', $pacienteId); $agendamentos->whereNotNull('exame_laboratorial_agendamento_exame.data_laudo'); $agendamentos->whereNotIn('exame_laboratorial_agendamento_exame.status_id', [StatusAgendamento::NAO_REALIZADO, StatusAgendamento::NOVA_COLETA]); $agendamentos->where(function ($q) { $q->whereNotIn('exame_laboratorial_agendamento_exame.status_id', [StatusAgendamento::ASSINADO]) ->orWhere(function ($sub) { $sub->where('exame_laboratorial_agendamento_exame.status_id', StatusAgendamento::ASSINADO) ->where('entregue', true); }); }); $agendamentos = $agendamentos->orderBy('parametrizacao_exame.posicao_mapa', 'ASC'); $agendamentos = $agendamentos->orderBy('parametrizacao_exame.nome', 'ASC'); $agendamentos = $agendamentos->get(); return $agendamentos; } public static function loadFields(Request $request) { $now = Carbon::now(); $currentDate = $now->format('Y-m-d'); $grupos = DB::table('parametrizacao_exame') ->select([ 'cadastro_grupo.id AS exame_grupo_id', 'cadastro_grupo.nome AS exame_grupo_nome', ]) ->leftJoin('cadastro_grupo', 'cadastro_grupo.id', 'parametrizacao_exame.grupo_tipo_id') ->whereExists(function ($query) use ($request, $currentDate) { $query->select(DB::raw(1)) ->from('exame_laboratorial_agendamento_exame') ->whereColumn('exame_laboratorial_agendamento_exame.exame_id', 'parametrizacao_exame.id') ->leftJoin('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->where(function($query) use ($request, $currentDate) { if ($request->periodo) { $query->where('exame_laboratorial_agendamento.data', '>=', $request->periodo['start']); $query->where('exame_laboratorial_agendamento.data', '<=', $request->periodo['end']); } else { $query->where('exame_laboratorial_agendamento.data', $currentDate); } }); }) ->where('parametrizacao_exame.tipo_id', Tipo::LABORATORIAL) ->groupBy([ 'cadastro_grupo.id', ]); $grupos = $grupos->get()->toArray(); return [ 'form' => [ 'grupos' => $grupos, ], ]; } public static function store(Request $request) { DB::transaction(function () use ($request) { self::saveStatusExame($request); }); } private static function saveStatusExame($request) { foreach ($request->agendamentos as $params) { $exame = AgendamentoExame::where('agendamento_id', $params['agendamento_id']) ->where('exame_id', $params['exame_id']) ->first(); if ($params['nao_realizado']) { $exame->status_id = StatusAgendamento::NAO_REALIZADO; $exame->motivo_id = $params['motivo_id']; AgendamentoExameResultado::where('agendamento_exame_id', $params['agendamento_exame_id'])->delete(); } if ($params['nova_coleta']) { $exame->status_id = StatusAgendamento::NOVA_COLETA; $exame->motivo_id = $params['motivo_id']; AgendamentoExameResultado::where('agendamento_exame_id', $params['agendamento_exame_id'])->delete(); } if (!$params['nao_realizado'] && !$params['nova_coleta']) { if ($params['exame_status_id'] == StatusAgendamento::ASSINADO) { $exame->status_id = StatusAgendamento::ASSINADO; $exame->assinatura_profissional_id = $params['assinatura_profissional_id']; $exame->data_assinatura = Carbon::now(); } else { $exame->status_id = StatusAgendamento::PENDENTE_ASSINATURA; $exame->data_laudo = Carbon::now(); } } $exame->observacao = $params['observacao']; $exame->save(); if (!$params['nao_realizado'] && !$params['nova_coleta']) { foreach ($params['composicao'] as $paramsComposicao) { if ($paramsComposicao['resultado'] !== null) { $exameComposicao = AgendamentoExameResultado::where('agendamento_exame_id', $params['agendamento_exame_id']) ->where('composicao_id', $paramsComposicao['id']) ->first() ?? new AgendamentoExameResultado; $exameComposicao->agendamento_exame_id = $params['agendamento_exame_id']; $exameComposicao->composicao_id = $paramsComposicao['id']; $exameComposicao->valor = $paramsComposicao['resultado']; $exameComposicao->save(); } } } } } }