whereHas('registros', function($query) { $query->where('codigo', SigtapRegistro::BPA_INDIVIDUALIZADO); })->get(); } public static function list(Request $request) { $params = (object) $request->except(['origem', 'listar']); switch ($request->origem) { case 'geracao': { switch ($request->listar) { case 'competencias': { return [ 'competencias' => self::getCompetenciasGeracaoExclusao($params), 'cnes' => [], 'unidades' => [], ]; } case 'cnes': { return [ 'cnes' => self::getCnesGeracao($params), 'unidades' => [], ]; } case 'unidades': { return [ 'unidades' => self::getUnidadesGeracao($params), ]; } } break; } case 'exclusao': { switch ($request->listar) { case 'competencias': { return [ 'competencias' => self::getCompetenciasGeracaoExclusao($params), 'cnes' => [], 'unidades' => [], ]; } case 'cnes': { return [ 'cnes' => self::getCnesExclusao($params), 'unidades' => [], ]; } case 'unidades': { return [ 'unidades' => self::getUnidadesExclusao($params), ]; } } break; } } } public static function create() { $form = self::getForm(); return [ 'form' => $form, 'model' => self::getModel($form), ]; } public static function store($request) { $response = null; DB::transaction(function() use ($request, &$response) { switch ($request->get('acao')) { case 'geracao': self::storeProcedimentosAutomaticos($request); break; case 'lancamento': $response = self::storeProcedimentoManual($request); break; case 'exclusao': self::destroyProcedimentosAutomaticos($request); break; } }); return $response; } public static function show($id) { return self::get(Procedimento::class, $id); } public static function edit($id) { $form = self::getForm(); return [ 'form' => $form, 'model' => self::getModel($form, $id), ]; } public static function update($request, $id) { self::validate($request); return Procedimento::findOrFail($id)->update($request->all()); } public static function destroy($id) { DB::transaction(function () use ($id) { AtendimentoProcedimento::where('bpa_procedimento_id', $id)->update(['bpa_procedimento_id' => null]); Faturamento::where('bpa_procedimento_id', $id)->update(['bpa_procedimento_id' => null]); AgendamentoExame::where('bpa_procedimento_id', $id)->update(['bpa_procedimento_id' => null]); FaturamentoTransporte::where('bpa_procedimento_id', $id)->update(['bpa_procedimento_id' => null]); AmbulatorioAtendimentoProcedimento::where('bpa_procedimento_id', $id)->update(['bpa_procedimento_id' => null]); Procedimento::findOrFail($id)->delete(); }); } public static function datatable() { $procedimentos = DB::table('bpa_procedimento') ->select([ 'bpa_procedimento.origem', 'bpa_procedimento.id', 'bpa_procedimento.exportacao_id', 'cadastro_unidade.id AS unidade_id', 'cadastro_unidade.nome_fantasia AS unidade_nome', 'competencia.valor AS competencia', 'cadastro_cidadao_usuario.nome AS usuario_nome', 'cadastro_cidadao_paciente.nome AS paciente_nome', 'procedimento.id AS procedimento_id', 'procedimento.codigo AS procedimento_codigo', 'procedimento.nome AS procedimento_nome', 'registro.id AS registro_id', 'registro.codigo AS registro_codigo', 'ocupacao.id AS ocupacao_id', 'ocupacao.codigo AS ocupacao_codigo', 'ocupacao.nome AS ocupacao_nome', 'bpa_procedimento.idade', 'bpa_procedimento.quantidade', ]) ->join('cadastro_unidade', 'cadastro_unidade.id', 'bpa_procedimento.unidade_id') ->join('sigtap.competencia', 'competencia.id', 'bpa_procedimento.competencia_id') ->join('cadastro_usuario', 'cadastro_usuario.id', 'bpa_procedimento.usuario_id') ->join('cadastro_cidadao AS cadastro_cidadao_usuario', 'cadastro_cidadao_usuario.id', 'cadastro_usuario.cidadao_id') ->join('cadastro_paciente', 'cadastro_paciente.id', 'bpa_procedimento.paciente_id') ->join('cadastro_cidadao AS cadastro_cidadao_paciente', 'cadastro_cidadao_paciente.id', 'cadastro_paciente.cidadao_id') ->join('sigtap.procedimento', 'procedimento.id', 'bpa_procedimento.procedimento_id') ->join('sigtap.ocupacao', 'ocupacao.id', 'bpa_procedimento.ocupacao_id') ->join('sigtap.registro', 'registro.id', 'bpa_procedimento.registro_id') ->whereNull('bpa_procedimento.deleted_at'); return DB::table(DB::raw("({$procedimentos->toSql()}) as x")) ->select([ 'origem', 'id', 'exportacao_id', 'unidade_id', 'unidade_nome', 'usuario_nome', 'paciente_nome', 'competencia', 'procedimento_id', 'procedimento_codigo', 'procedimento_nome', 'ocupacao_id', 'ocupacao_codigo', 'ocupacao_nome', 'quantidade', ]) ->where('registro_codigo', SigtapRegistro::BPA_INDIVIDUALIZADO); } private static function validate($request) { $paciente = Paciente::find($request->paciente_id); $verificaProc = []; if (is_null($request->cid_id) ) { $verificaProc[] = new ProcedimentoRequireCid(); } return $request->validate([ 'unidade_id' => [ 'required', 'integer', 'exists:\App\Models\Cadastro\Estabelecimento\Unidade,id', ], 'competencia_id' => [ new CompetenciaIsValid(), ], 'usuario_id' => [ 'required', 'integer', 'exists:\App\Models\Cadastro\SujeitoAtencao\Usuario,id', ], 'ocupacao_id' => [ new OcupacaoExists(), ], 'paciente_id' => [ 'required', 'integer', 'exists:\App\Models\Cadastro\SujeitoAtencao\Paciente,id', ], 'data_atendimento' => [ new DataAtendimentoIsValid($request->competencia_id), ], 'procedimento_id' => array_merge([ new ProcedimentoIsValidForCompetencia(self::getCompetencias()), new ProcedimentoIsValidForSexo($paciente->cidadao->paciente_sexo), new ProcedimentoExists(), new ProcedimentoIsValidForOcupacao($request->ocupacao_id), new ProcedimentoIsValidForIdade($paciente->cidadao->idade['anos']) ], $verificaProc), 'quantidade' => [ new QuantidadeIsValid(), new QuantidadeIsValidForProcedimento($request->procedimento_id), ], 'servico_id' => [ 'nullable', 'integer', 'exists:\App\Models\Sigtap\Servico,id', ], 'classificacao_id' => [ 'nullable', 'required_with:servico_id', 'integer', 'exists:\App\Models\Sigtap\Classificacao,id', new ClassificacaoIsValidForProcedimento($request->procedimento_id), new ClassificacaoIsValidForServico($request->servico_id), ], 'cid_id' => [ 'nullable', 'integer', 'exists:\App\Models\Sigtap\Cid,id', new CidIsValidForSexo($paciente->cidadao->sexo), ], 'carater_atendimento_id' => [ new CaraterAtendimentoExists(), ], ]); } private static function getUnidades() { return Unidade::orderBy('nome_fantasia') ->where('cnes', '<>', '') ->get() ->map(function($query) { return [ 'id' => $query->id, 'nome_fantasia' => $query->nome_fantasia, ]; }); } private static function getCompetencias() { return Competencia::select('id', 'valor') ->orderBy('valor', 'desc') ->take(4) ->get(); } private static function getCarateresAtendimento() { return CaraterAtendimento::select(['id', 'nome']) ->orderBy('nome') ->get(); } private static function getForm() { $acao = request()->query('acao'); $form = []; switch ($acao) { case 'geracao': case 'exclusao': $anos = self::getAnos(); $form = [ 'anos' => $anos, 'competencias' => $anos->isNotEmpty() ? self::getCompetenciasGeracaoExclusao((object) ['ano' => $anos->first()->value]) : [], 'cnes' => [], 'unidades' => [], ]; break; case 'lancamento': $form = [ 'unidades' => self::getUnidades(), 'competencias' => self::getCompetencias(), 'carateres_atendimento' => self::getCarateresAtendimento(), ]; break; } return $form; } private static function getAnos() { return self::getCompetencias() ->map(function ($competencia) { $ano = substr($competencia->valor, 0, 4); return (object) [ 'value' => $ano, 'text' => $ano, ]; }) ->unique('value') ->values(); } private static function getCompetenciasGeracaoExclusao(object $params) { $competencias = self::getCompetencias() ->map(fn ($competencia) => (object) [ 'id' => $competencia->id, 'ano' => substr($competencia->valor, 0, 4), 'mes' => substr($competencia->valor, 4, 2), ]); return $competencias->where('ano', $params->ano) ->map(fn ($competencia) => (object) [ 'id' => $competencia->id, 'mes' => Str::upper(Carbon::create()->month($competencia->mes)->translatedFormat('F')), ]) ->values(); } private static function getCnesGeracao(object $params) { $configuracao = Configuracao::first(); $competencia = Competencia::findOrFail($params->competencia_id); $valoresCompetencias = Competencia::where('valor', '<=', $competencia->valor) ->orderBy('valor', 'desc') ->take(4) ->get() ->pluck('valor') ->toArray(); return DB::table('cadastro_unidade AS unidade') ->select('unidade.cnes') ->whereNotNull('unidade.cnes') ->where('unidade.cnes', '<>', '') ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('pronto_atendimento_atendimento_procedimento') ->join('cadastro_lotacao', 'cadastro_lotacao.id', 'pronto_atendimento_atendimento_procedimento.lotacao_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_atendimento_procedimento.atendimento_id') ->join('pronto_atendimento_faa', 'pronto_atendimento_faa.id', 'pronto_atendimento_atendimento.faa_id') ->whereColumn('cadastro_infraestrutura.unidade_id', 'unidade.id') ->whereNotNull('pronto_atendimento_faa.desfecho_id') ->whereIn(DB::raw("DATE_FORMAT(pronto_atendimento_atendimento_procedimento.realizado_em, '%Y%m')"), $valoresCompetencias) ->whereNull('pronto_atendimento_atendimento_procedimento.bpa_procedimento_id') ->whereNull('pronto_atendimento_atendimento_procedimento.deleted_at') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'pronto_atendimento_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'pronto_atendimento_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_INDIVIDUALIZADO]) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'pronto_atendimento_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ) ) ->orWhereExists(fn ($q) => $q ->selectRaw(1) ->from('exame_imagem_fechamento_faturamento') ->join('cadastro_lotacao', 'cadastro_lotacao.usuario_id', 'exame_imagem_fechamento_faturamento.usuario_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->join('exame_imagem_agendamento_exame', 'exame_imagem_agendamento_exame.id', 'exame_imagem_fechamento_faturamento.agendamento_exame_id') ->whereColumn('exame_imagem_fechamento_faturamento.unidade_id', 'unidade.id') ->whereIn(DB::raw("DATE_FORMAT(exame_imagem_fechamento_faturamento.data, '%Y%m')"), $valoresCompetencias) ->whereNull('exame_imagem_fechamento_faturamento.bpa_procedimento_id') ->whereNull('exame_imagem_fechamento_faturamento.apac_procedimento_secundario_id') ->where(fn ($q) => $q ->whereNull('exame_imagem_agendamento_exame.acompanhamento_oci_id') ->orWhere(fn ($q) => $q ->whereNotNull('exame_imagem_agendamento_exame.acompanhamento_oci_id') ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_acompanhamento_oci') ->whereColumn('ambulatorio_acompanhamento_oci.id', 'exame_imagem_agendamento_exame.acompanhamento_oci_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereNull('ambulatorio_acompanhamento_oci.finalizado_em') ->whereRaw("CURRENT_DATE <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ->orWhere(fn ($q) => $q ->whereNotNull('ambulatorio_acompanhamento_oci.finalizado_em') ->where('ambulatorio_acompanhamento_oci.etapa_clinica_atual_id', EtapaClinica::ALTA) ->whereRaw("CAST(ambulatorio_acompanhamento_oci.finalizado_em AS DATE) <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ) ) ) ) ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'exame_imagem_fechamento_faturamento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'exame_imagem_fechamento_faturamento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_INDIVIDUALIZADO]) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'exame_imagem_fechamento_faturamento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ) ) ->orWhereExists(fn ($q) => $q ->selectRaw(1) ->from('exame_laboratorial_agendamento_exame') ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', 'exame_laboratorial_agendamento.laboratorio_lotacao_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->whereColumn('exame_laboratorial_agendamento.unidade_id', 'unidade.id') ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereIn(DB::raw("DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m')"), $valoresCompetencias) ->whereNull('exame_laboratorial_agendamento_exame.bpa_procedimento_id') ->whereNull('exame_laboratorial_agendamento_exame.apac_procedimento_secundario_id') ->where(fn ($q) => $q ->whereNull('exame_laboratorial_agendamento_exame.acompanhamento_oci_id') ->orWhere(fn ($q) => $q ->whereNotNull('exame_laboratorial_agendamento_exame.acompanhamento_oci_id') ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_acompanhamento_oci') ->whereColumn('ambulatorio_acompanhamento_oci.id', 'exame_laboratorial_agendamento_exame.acompanhamento_oci_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereNull('ambulatorio_acompanhamento_oci.finalizado_em') ->whereRaw("CURRENT_DATE <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ->orWhere(fn ($q) => $q ->whereNotNull('ambulatorio_acompanhamento_oci.finalizado_em') ->where('ambulatorio_acompanhamento_oci.etapa_clinica_atual_id', EtapaClinica::ALTA) ->whereRaw("CAST(ambulatorio_acompanhamento_oci.finalizado_em AS DATE) <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ) ) ) ) ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'exame_laboratorial_agendamento_exame.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'exame_laboratorial_agendamento_exame.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_INDIVIDUALIZADO]) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'exame_laboratorial_agendamento_exame.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ) ) ->orWhereExists(fn ($q) => $q ->selectRaw(1) ->from('transporte_paciente_faturamento') ->join('transporte_paciente_agendar_transporte', 'transporte_paciente_agendar_transporte.id', 'transporte_paciente_faturamento.agendamento_id') ->leftJoin('cadastro_lotacao', 'cadastro_lotacao.id', 'transporte_paciente_faturamento.lotacao_id') ->leftJoin('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->leftJoin('transporte_paciente_parametrizacao_faturamento', 'transporte_paciente_parametrizacao_faturamento.unidade_id', 'transporte_paciente_agendar_transporte.lotacao_id') ->leftJoin('transporte_paciente_destino', 'transporte_paciente_agendar_transporte.destino_id', 'transporte_paciente_destino.id') ->whereColumn('transporte_paciente_faturamento.lotacao_id', 'unidade.id') ->whereExists(function ($query) { $query->select(DB::raw(1)) ->from('transporte_paciente_parametrizacao') ->where('transporte_paciente_parametrizacao.faturamento', StatusFaturamento::COM_FATURAMENTO); }) ->whereNotNull('transporte_paciente_destino.distancia') ->whereIn(DB::raw("DATE_FORMAT(transporte_paciente_agendar_transporte.data, '%Y%m')"), $valoresCompetencias) ->where('transporte_paciente_agendar_transporte.status_id', EnumStatus::TRANSPORTADO) ->whereNull('transporte_paciente_faturamento.bpa_procedimento_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'transporte_paciente_faturamento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'transporte_paciente_faturamento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_INDIVIDUALIZADO]) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'transporte_paciente_faturamento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ) ) ->orWhereExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_atendimento_procedimento') ->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id') ->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id') ->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->whereColumn('cadastro_infraestrutura.unidade_id', 'unidade.id') ->whereNotNull('ambulatorio_atendimento.finalizado_em') ->whereIn(DB::raw("DATE_FORMAT(ambulatorio_jornada.data, '%Y%m')"), $valoresCompetencias) ->whereNull('ambulatorio_atendimento_procedimento.bpa_procedimento_id') ->whereNull('ambulatorio_atendimento_procedimento.apac_procedimento_secundario_id') ->where(fn ($q) => $q ->whereNull('ambulatorio_atendimento_procedimento.acompanhamento_oci_id') ->orWhere(fn ($q) => $q ->whereNotNull('ambulatorio_atendimento_procedimento.acompanhamento_oci_id') ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_acompanhamento_oci') ->whereColumn('ambulatorio_acompanhamento_oci.id', 'ambulatorio_atendimento_procedimento.acompanhamento_oci_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereNull('ambulatorio_acompanhamento_oci.finalizado_em') ->whereRaw("CURRENT_DATE <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ->orWhere(fn ($q) => $q ->whereNotNull('ambulatorio_acompanhamento_oci.finalizado_em') ->where('ambulatorio_acompanhamento_oci.etapa_clinica_atual_id', EtapaClinica::ALTA) ->whereRaw("CAST(ambulatorio_acompanhamento_oci.finalizado_em AS DATE) <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ) ) ) ) ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'ambulatorio_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'ambulatorio_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_INDIVIDUALIZADO]) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'ambulatorio_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ) ) ->orWhereExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_atendimento_procedimento') ->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id') ->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id') ->join('cadastro_centro_custo', 'cadastro_centro_custo.id', 'ambulatorio_demanda_espontanea.created_centro_custo_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_centro_custo.infraestrutura_id') ->whereColumn('cadastro_infraestrutura.unidade_id', 'unidade.id') ->whereNotNull('ambulatorio_atendimento.finalizado_em') ->whereIn(DB::raw("DATE_FORMAT(ambulatorio_demanda_espontanea.data, '%Y%m')"), $valoresCompetencias) ->whereNull('ambulatorio_atendimento_procedimento.bpa_procedimento_id') ->whereNull('ambulatorio_atendimento_procedimento.apac_procedimento_secundario_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'ambulatorio_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'ambulatorio_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_INDIVIDUALIZADO]) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'ambulatorio_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ) ) ->orWhereExists(fn ($q) => $q ->selectRaw(1) ->from('exame_laboratorial_agendamento_exame') ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', 'exame_laboratorial_agendamento.lotacao_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->whereColumn('exame_laboratorial_agendamento.unidade_id', 'unidade.id') ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::REALIZADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereIn(DB::raw("DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m')"), $valoresCompetencias) ->whereNull('exame_laboratorial_agendamento.bpa_procedimento_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->where('sigtap.procedimento_registro.procedimento_id', self::getProcedimentoPadraoExameLaboratorial()) ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->where('sigtap.procedimento_registro.procedimento_id', self::getProcedimentoPadraoExameLaboratorial()) ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_INDIVIDUALIZADO]) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->where('sigtap.procedimento_registro.procedimento_id', self::getProcedimentoPadraoExameLaboratorial()) ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ) ) ) ->groupBy('unidade.cnes') ->orderBy('unidade.cnes') ->get() ->map(fn ($cnes) => (object) [ 'value' => $cnes->cnes, 'text' => $cnes->cnes, ]); } private static function getCnesExclusao(object $params) { return DB::table('cadastro_unidade AS unidade') ->select('unidade.cnes') ->whereNotNull('unidade.cnes') ->where('unidade.cnes', '<>', '') ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('bpa_procedimento') ->join('sigtap.registro', 'sigtap.registro.id', 'bpa_procedimento.registro_id') ->whereColumn('bpa_procedimento.unidade_id', 'unidade.id') ->where('bpa_procedimento.competencia_id', $params->competencia_id) ->where('bpa_procedimento.origem', '<>', Origem::BPA) ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ->whereNull('bpa_procedimento.exportacao_id') ->whereNull('bpa_procedimento.deleted_at') ) ->groupBy('unidade.cnes') ->orderBy('unidade.cnes') ->get() ->map(fn ($cnes) => (object) [ 'value' => $cnes->cnes, 'text' => $cnes->cnes, ]); } private static function getUnidadesGeracao(object $params) { $configuracao = Configuracao::first(); $competencia = Competencia::findOrFail($params->competencia_id); $valoresCompetencias = Competencia::where('valor', '<=', $competencia->valor) ->orderBy('valor', 'desc') ->take(4) ->get() ->pluck('valor') ->toArray(); return DB::table('cadastro_unidade AS unidade') ->select([ 'unidade.id', 'unidade.nome_fantasia', ]) ->where('unidade.cnes', $params->cnes) ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('pronto_atendimento_atendimento_procedimento') ->join('cadastro_lotacao', 'cadastro_lotacao.id', 'pronto_atendimento_atendimento_procedimento.lotacao_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_atendimento_procedimento.atendimento_id') ->join('pronto_atendimento_faa', 'pronto_atendimento_faa.id', 'pronto_atendimento_atendimento.faa_id') ->whereColumn('cadastro_infraestrutura.unidade_id', 'unidade.id') ->whereNotNull('pronto_atendimento_faa.desfecho_id') ->whereIn(DB::raw("DATE_FORMAT(pronto_atendimento_atendimento_procedimento.realizado_em, '%Y%m')"), $valoresCompetencias) ->whereNull('pronto_atendimento_atendimento_procedimento.bpa_procedimento_id') ->whereNull('pronto_atendimento_atendimento_procedimento.deleted_at') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'pronto_atendimento_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'pronto_atendimento_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_INDIVIDUALIZADO]) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'pronto_atendimento_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ) ) ->orWhereExists(fn ($q) => $q ->selectRaw(1) ->from('exame_imagem_fechamento_faturamento') ->join('cadastro_lotacao', 'cadastro_lotacao.usuario_id', 'exame_imagem_fechamento_faturamento.usuario_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->join('exame_imagem_agendamento_exame', 'exame_imagem_agendamento_exame.id', 'exame_imagem_fechamento_faturamento.agendamento_exame_id') ->whereColumn('exame_imagem_fechamento_faturamento.unidade_id', 'unidade.id') ->whereIn(DB::raw("DATE_FORMAT(exame_imagem_fechamento_faturamento.data, '%Y%m')"), $valoresCompetencias) ->whereNull('exame_imagem_fechamento_faturamento.bpa_procedimento_id') ->whereNull('exame_imagem_fechamento_faturamento.apac_procedimento_secundario_id') ->where(fn ($q) => $q ->whereNull('exame_imagem_agendamento_exame.acompanhamento_oci_id') ->orWhere(fn ($q) => $q ->whereNotNull('exame_imagem_agendamento_exame.acompanhamento_oci_id') ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_acompanhamento_oci') ->whereColumn('ambulatorio_acompanhamento_oci.id', 'exame_imagem_agendamento_exame.acompanhamento_oci_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereNull('ambulatorio_acompanhamento_oci.finalizado_em') ->whereRaw("CURRENT_DATE <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ->orWhere(fn ($q) => $q ->whereNotNull('ambulatorio_acompanhamento_oci.finalizado_em') ->where('ambulatorio_acompanhamento_oci.etapa_clinica_atual_id', EtapaClinica::ALTA) ->whereRaw("CAST(ambulatorio_acompanhamento_oci.finalizado_em AS DATE) <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ) ) ) ) ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'exame_imagem_fechamento_faturamento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'exame_imagem_fechamento_faturamento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_INDIVIDUALIZADO]) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'exame_imagem_fechamento_faturamento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ) ) ->orWhereExists(fn ($q) => $q ->selectRaw(1) ->from('exame_laboratorial_agendamento_exame') ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', 'exame_laboratorial_agendamento.laboratorio_lotacao_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->whereColumn('exame_laboratorial_agendamento.unidade_id', 'unidade.id') ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereIn(DB::raw("DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m')"), $valoresCompetencias) ->whereNull('exame_laboratorial_agendamento_exame.bpa_procedimento_id') ->whereNull('exame_laboratorial_agendamento_exame.apac_procedimento_secundario_id') ->where(fn ($q) => $q ->whereNull('exame_laboratorial_agendamento_exame.acompanhamento_oci_id') ->orWhere(fn ($q) => $q ->whereNotNull('exame_laboratorial_agendamento_exame.acompanhamento_oci_id') ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_acompanhamento_oci') ->whereColumn('ambulatorio_acompanhamento_oci.id', 'exame_laboratorial_agendamento_exame.acompanhamento_oci_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereNull('ambulatorio_acompanhamento_oci.finalizado_em') ->whereRaw("CURRENT_DATE <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ->orWhere(fn ($q) => $q ->whereNotNull('ambulatorio_acompanhamento_oci.finalizado_em') ->where('ambulatorio_acompanhamento_oci.etapa_clinica_atual_id', EtapaClinica::ALTA) ->whereRaw("CAST(ambulatorio_acompanhamento_oci.finalizado_em AS DATE) <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ) ) ) ) ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'exame_laboratorial_agendamento_exame.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'exame_laboratorial_agendamento_exame.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_INDIVIDUALIZADO]) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'exame_laboratorial_agendamento_exame.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ) ) ->orWhereExists(fn ($q) => $q ->selectRaw(1) ->from('transporte_paciente_faturamento') ->join('transporte_paciente_agendar_transporte', 'transporte_paciente_agendar_transporte.id', 'transporte_paciente_faturamento.agendamento_id') ->leftJoin('cadastro_lotacao', 'cadastro_lotacao.id', 'transporte_paciente_faturamento.lotacao_id') ->leftJoin('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->leftJoin('transporte_paciente_parametrizacao_faturamento', 'transporte_paciente_parametrizacao_faturamento.unidade_id', 'transporte_paciente_agendar_transporte.lotacao_id') ->leftJoin('transporte_paciente_destino', 'transporte_paciente_agendar_transporte.destino_id', 'transporte_paciente_destino.id') ->whereColumn('transporte_paciente_faturamento.lotacao_id', 'unidade.id') ->whereExists(function ($query) { $query->select(DB::raw(1)) ->from('transporte_paciente_parametrizacao') ->where('transporte_paciente_parametrizacao.faturamento', StatusFaturamento::COM_FATURAMENTO); }) ->whereNotNull('transporte_paciente_destino.distancia') ->whereIn(DB::raw("DATE_FORMAT(transporte_paciente_agendar_transporte.data, '%Y%m')"), $valoresCompetencias) ->where('transporte_paciente_agendar_transporte.status_id', EnumStatus::TRANSPORTADO) ->whereNull('transporte_paciente_faturamento.bpa_procedimento_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'transporte_paciente_faturamento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'transporte_paciente_faturamento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_INDIVIDUALIZADO]) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'transporte_paciente_faturamento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ) ) ->orWhereExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_atendimento_procedimento') ->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id') ->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id') ->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->whereColumn('cadastro_infraestrutura.unidade_id', 'unidade.id') ->whereNotNull('ambulatorio_atendimento.finalizado_em') ->whereIn(DB::raw("DATE_FORMAT(ambulatorio_jornada.data, '%Y%m')"), $valoresCompetencias) ->whereNull('ambulatorio_atendimento_procedimento.bpa_procedimento_id') ->whereNull('ambulatorio_atendimento_procedimento.apac_procedimento_secundario_id') ->where(fn ($q) => $q ->whereNull('ambulatorio_atendimento_procedimento.acompanhamento_oci_id') ->orWhere(fn ($q) => $q ->whereNotNull('ambulatorio_atendimento_procedimento.acompanhamento_oci_id') ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_acompanhamento_oci') ->whereColumn('ambulatorio_acompanhamento_oci.id', 'ambulatorio_atendimento_procedimento.acompanhamento_oci_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereNull('ambulatorio_acompanhamento_oci.finalizado_em') ->whereRaw("CURRENT_DATE <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ->orWhere(fn ($q) => $q ->whereNotNull('ambulatorio_acompanhamento_oci.finalizado_em') ->where('ambulatorio_acompanhamento_oci.etapa_clinica_atual_id', EtapaClinica::ALTA) ->whereRaw("CAST(ambulatorio_acompanhamento_oci.finalizado_em AS DATE) <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ) ) ) ) ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'ambulatorio_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'ambulatorio_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_INDIVIDUALIZADO]) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'ambulatorio_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ) ) ->orWhereExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_atendimento_procedimento') ->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id') ->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id') ->join('cadastro_centro_custo', 'cadastro_centro_custo.id', 'ambulatorio_demanda_espontanea.created_centro_custo_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_centro_custo.infraestrutura_id') ->whereColumn('cadastro_infraestrutura.unidade_id', 'unidade.id') ->whereNotNull('ambulatorio_atendimento.finalizado_em') ->whereIn(DB::raw("DATE_FORMAT(ambulatorio_demanda_espontanea.data, '%Y%m')"), $valoresCompetencias) ->whereNull('ambulatorio_atendimento_procedimento.bpa_procedimento_id') ->whereNull('ambulatorio_atendimento_procedimento.apac_procedimento_secundario_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'ambulatorio_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'ambulatorio_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_INDIVIDUALIZADO]) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->whereColumn('sigtap.procedimento_registro.procedimento_id', 'ambulatorio_atendimento_procedimento.procedimento_id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ) ) ->orWhereExists(fn ($q) => $q ->selectRaw(1) ->from('exame_laboratorial_agendamento_exame') ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', 'exame_laboratorial_agendamento.lotacao_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->whereColumn('exame_laboratorial_agendamento.unidade_id', 'unidade.id') ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::REALIZADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereIn(DB::raw("DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m')"), $valoresCompetencias) ->whereNull('exame_laboratorial_agendamento.bpa_procedimento_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->where('sigtap.procedimento_registro.procedimento_id', self::getProcedimentoPadraoExameLaboratorial()) ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->where('sigtap.procedimento_registro.procedimento_id', self::getProcedimentoPadraoExameLaboratorial()) ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_INDIVIDUALIZADO]) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('sigtap.procedimento_registro') ->join('sigtap.registro', 'sigtap.registro.id', 'sigtap.procedimento_registro.registro_id') ->where('sigtap.procedimento_registro.procedimento_id', self::getProcedimentoPadraoExameLaboratorial()) ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ) ) ) ->orderBy('unidade.nome_fantasia') ->get(); } private static function getUnidadesExclusao(object $params) { return DB::table('cadastro_unidade AS unidade') ->select([ 'unidade.id', 'unidade.nome_fantasia', ]) ->where('unidade.cnes', $params->cnes) ->whereExists(fn ($q) => $q ->selectRaw(1) ->from('bpa_procedimento') ->join('sigtap.registro', 'sigtap.registro.id', 'bpa_procedimento.registro_id') ->whereColumn('bpa_procedimento.unidade_id', 'unidade.id') ->where('bpa_procedimento.competencia_id', $params->competencia_id) ->where('bpa_procedimento.origem', '<>', Origem::BPA) ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ->whereNull('bpa_procedimento.exportacao_id') ->whereNull('bpa_procedimento.deleted_at') ) ->orderBy('unidade.nome_fantasia') ->get(); } private static function getModel($form, $id = null) { $acao = request()->query('acao'); $procedimento = null; $model = []; if (is_numeric($id)) { $procedimento = self::show($id); } switch ($acao) { case 'geracao': case 'exclusao': $model = [ 'acao' => $acao, 'ano' => $form['anos']->first()->value ?? null, 'competencia_id' => null, 'cnes' => null, 'unidade_id' => null, ]; break; case 'lancamento': $model = [ 'data_atual' => Carbon::now()->format('d/m/Y'), 'acao' => $acao, 'unidade_id' => $procedimento['unidade_id'] ?? null, 'competencia_id' => $procedimento['competencia_id'] ?? null, 'usuario' => $procedimento ? [ 'id' => $procedimento['usuario']['id'] ?? null, 'cidadao_cns' => $procedimento['usuario']['cidadao']['cns'] ?? null, 'cidadao_nome' => $procedimento['usuario']['cidadao']['nome'] ?? null, ] : null, 'ocupacao' => $procedimento ? [ 'id' => $procedimento['ocupacao']['id'] ?? null, 'codigo' => $procedimento['ocupacao']['codigo'] ?? null, 'nome' => $procedimento['ocupacao']['nome'] ?? null, ] : null, 'paciente' => $procedimento ? [ 'cidadao' => [ 'cns' => $procedimento['paciente']['cidadao']['cns'] ?? null, 'data_nascimento' => $procedimento['paciente']['cidadao']['data_nascimento'] ?? null, 'domicilio' => [ 'endereco' => [ 'complemento' => $procedimento['paciente']['cidadao']['domicilio']['endereco']['complemento'] ?? null, 'logradouro' => [ 'bairro' => [ 'nome' => $procedimento['paciente']['cidadao']['domicilio']['endereco']['logradouro']['bairro']['nome'] ?? null, ], 'cep' => $procedimento['paciente']['cidadao']['domicilio']['endereco']['logradouro']['cep'] ?? null, 'municipio' => [ 'nome' => $procedimento['paciente']['cidadao']['domicilio']['endereco']['logradouro']['municipio']['nome'] ?? null, ], 'nome' => $procedimento['paciente']['cidadao']['domicilio']['endereco']['logradouro']['nome'] ?? null, 'tipo' => [ 'descricao' => $procedimento['paciente']['cidadao']['domicilio']['endereco']['logradouro']['tipo']['descricao'] ?? null, ], ], 'numero' => $procedimento['paciente']['cidadao']['domicilio']['endereco']['numero'] ?? null, ], ], 'etnia_indigena' => [ 'descricao' => $procedimento['paciente']['cidadao']['etnia_indigena']['descricao'] ?? null, ], 'nacionalidade' => [ 'descricao' => $procedimento['paciente']['cidadao']['nacionalidade']['descricao'] ?? null, ], 'nome' => $procedimento['paciente']['cidadao']['nome'] ?? null, 'raca_cor' => [ 'descricao' => $procedimento['paciente']['cidadao']['racaCor']['descricao'] ?? null, ], 'sexo' => [ 'descricao' => $procedimento['paciente']['cidadao']['sexo']['descricao'] ?? null, ], 'telefone_principal' => [ 'numero' => $procedimento['paciente']['cidadao']['telefonePrincipal']['numero'] ?? null, ], ], 'email' => $procedimento['paciente']['email'] ?? null, 'id' => $procedimento['paciente']['id'] ?? null, ] : null, 'data_atendimento' => $procedimento['data_atendimento'] ?? null, 'procedimento' => $procedimento ? [ 'has_cid_principal' => $procedimento['procedimento']['has_cid_principal'] ?? false, 'id' => $procedimento['procedimento']['id'] ?? null, 'codigo' => $procedimento['procedimento']['codigo'] ?? null, 'nome' => $procedimento['procedimento']['nome'] ?? null, 'quantidade_maxima_execucao' => $procedimento['procedimento']['quantidade_maxima_execucao'] ?? null, ] : null, 'quantidade' => $procedimento['quantidade'] ?? null, 'servico' => $procedimento && $procedimento['servico'] ? [ 'id' => $procedimento['servico']['id'] ?? null, 'codigo' => $procedimento['servico']['codigo'] ?? null, 'nome' => $procedimento['servico']['nome'] ?? null, ] : null, 'classificacao' => $procedimento && $procedimento['classificacao'] ? [ 'id' => $procedimento['classificacao']['id'] ?? null, 'codigo' => $procedimento['classificacao']['codigo'] ?? null, 'nome' => $procedimento['classificacao']['nome'] ?? null, ] : null, 'cid' => $procedimento && $procedimento['cid'] ? [ 'id' => $procedimento['cid']['id'] ?? null, 'codigo' => $procedimento['cid']['codigo'] ?? null, 'nome' => $procedimento['cid']['nome'] ?? null, ] : null, 'carater_atendimento_id' => $procedimento['carater_atendimento_id'] ?? null, ]; break; } return $model; } private static function storeProcedimentoManual($request) { self::validate($request); $registro = Registro::where('codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ->whereHas('procedimentos', function($query) use ($request) { $query->where('procedimento.id', $request->procedimento_id); }) ->firstOrFail(); return Procedimento::create([ 'unidade_id' => $request->unidade_id, 'competencia_id' => $request->competencia_id, 'usuario_id' => $request->usuario_id, 'ocupacao_id' => $request->ocupacao_id, 'paciente_id' => $request->paciente_id, 'procedimento_id' => $request->procedimento_id, 'registro_id' => $registro->id, 'servico_id' => $request->servico_id, 'classificacao_id' => $request->classificacao_id, 'cid_id' => $request->cid_id, 'carater_atendimento_id' => $request->carater_atendimento_id, 'origem' => Origem::BPA, 'data_atendimento' => $request->data_atendimento, 'quantidade' => $request->quantidade, ]); } private static function storeProcedimentosAutomaticos($request) { $configuracao = Configuracao::first(); $competencia = Competencia::findOrFail($request->competencia_id); $valoresCompetencias = Competencia::where('valor', '<=', $competencia->valor) ->orderBy('valor', 'desc') ->take(4) ->get() ->pluck('valor') ->toArray(); $valoresCompetenciasId = Competencia::where('valor', '<=', $competencia->valor) ->orderBy('valor', 'desc') ->take(4) ->get() ->pluck('id') ->toArray(); $prontoAtendimentoAtendimentoProcedimento = DB::table('pronto_atendimento_atendimento_procedimento') ->select([ 'pronto_atendimento_atendimento_procedimento.id', 'cadastro_infraestrutura.unidade_id', 'cadastro_lotacao.usuario_id', 'cadastro_lotacao.ocupacao_id', 'pronto_atendimento_faa.paciente_id', 'pronto_atendimento_atendimento_procedimento.procedimento_id', 'pronto_atendimento_atendimento_procedimento.cid_principal_id', DB::raw("'" . Origem::PRONTO_ATENDIMENTO . "' AS origem"), DB::raw("DATE_FORMAT(pronto_atendimento_atendimento_procedimento.realizado_em, '%Y%m%d') AS data_atendimento"), 'pronto_atendimento_atendimento_procedimento.quantidade', ]) ->join('cadastro_lotacao', 'cadastro_lotacao.id', 'pronto_atendimento_atendimento_procedimento.lotacao_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->join('pronto_atendimento_atendimento', 'pronto_atendimento_atendimento.id', 'pronto_atendimento_atendimento_procedimento.atendimento_id') ->join('pronto_atendimento_faa', 'pronto_atendimento_faa.id', 'pronto_atendimento_atendimento.faa_id') ->whereNotNull('pronto_atendimento_faa.desfecho_id') ->when(is_null($request->unidade_id), fn ($q) => $q->where('cadastro_unidade.cnes', $request->cnes), fn ($q) => $q->where('cadastro_infraestrutura.unidade_id', $request->unidade_id) ) ->whereIn(DB::raw("DATE_FORMAT(pronto_atendimento_atendimento_procedimento.realizado_em, '%Y%m')"), $valoresCompetencias) ->whereNull('pronto_atendimento_atendimento_procedimento.bpa_procedimento_id') ->whereNull('pronto_atendimento_atendimento_procedimento.deleted_at'); $exameImagem = DB::table('exame_imagem_fechamento_faturamento') ->select([ 'exame_imagem_fechamento_faturamento.id', 'exame_imagem_fechamento_faturamento.unidade_id', 'cadastro_lotacao.usuario_id', 'exame_imagem_fechamento_faturamento.ocupacao_id', 'exame_imagem_fechamento_faturamento.paciente_id', 'exame_imagem_fechamento_faturamento.procedimento_id', 'exame_imagem_fechamento_faturamento.cid_principal_id', DB::raw("'" . Origem::EXAME_IMAGEM . "' AS origem"), DB::raw("DATE_FORMAT(exame_imagem_fechamento_faturamento.data, '%Y%m%d') AS data_atendimento"), 'exame_imagem_fechamento_faturamento.quantidade', ]) ->join('cadastro_lotacao', 'cadastro_lotacao.usuario_id', 'exame_imagem_fechamento_faturamento.usuario_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->join('cadastro_unidade', 'cadastro_unidade.id', 'exame_imagem_fechamento_faturamento.unidade_id') ->join('exame_imagem_agendamento_exame', 'exame_imagem_agendamento_exame.id', 'exame_imagem_fechamento_faturamento.agendamento_exame_id') ->when(is_null($request->unidade_id), fn ($q) => $q->where('cadastro_unidade.cnes', $request->cnes), fn ($q) => $q->where('exame_imagem_fechamento_faturamento.unidade_id', $request->unidade_id) ) ->whereIn(DB::raw("DATE_FORMAT(exame_imagem_fechamento_faturamento.data, '%Y%m')"), $valoresCompetencias) ->whereNull('exame_imagem_fechamento_faturamento.bpa_procedimento_id') ->whereNull('exame_imagem_fechamento_faturamento.apac_procedimento_secundario_id') ->where(fn ($q) => $q ->whereNull('exame_imagem_agendamento_exame.acompanhamento_oci_id') ->orWhere(fn ($q) => $q ->whereNotNull('exame_imagem_agendamento_exame.acompanhamento_oci_id') ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_acompanhamento_oci') ->whereColumn('ambulatorio_acompanhamento_oci.id', 'exame_imagem_agendamento_exame.acompanhamento_oci_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereNull('ambulatorio_acompanhamento_oci.finalizado_em') ->whereRaw("CURRENT_DATE <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ->orWhere(fn ($q) => $q ->whereNotNull('ambulatorio_acompanhamento_oci.finalizado_em') ->where('ambulatorio_acompanhamento_oci.etapa_clinica_atual_id', EtapaClinica::ALTA) ->whereRaw("CAST(ambulatorio_acompanhamento_oci.finalizado_em AS DATE) <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ) ) ) ); $exameLaboratorial = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento_exame.id', 'cadastro_infraestrutura.unidade_id', 'exame_laboratorial_agendamento.laboratorio_usuario_id AS usuario_id', 'exame_laboratorial_agendamento.laboratorio_ocupacao_id AS ocupacao_id', 'exame_laboratorial_agendamento_exame.paciente_id', 'sigtap.procedimento.id as procedimento_id', 'exame_laboratorial_agendamento_exame.cid_principal_id', DB::raw("'" . Origem::EXAME_LABORATORIAL . "' AS origem"), DB::raw("DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m%d') AS data_atendimento"), 'exame_laboratorial_agendamento_exame.quantidade', ]) ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', 'exame_laboratorial_agendamento.laboratorio_lotacao_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->join('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->join('sigtap.procedimento', function ($join) use ($valoresCompetenciasId) { $join->on('sigtap.procedimento.codigo', '=', 'parametrizacao_exame.codigo') ->whereRaw(" sigtap.procedimento.competencia_id = ( SELECT p2.competencia_id FROM sigtap.procedimento p2 INNER JOIN sigtap.competencia c2 ON c2.id = p2.competencia_id WHERE p2.codigo = parametrizacao_exame.codigo AND p2.competencia_id IN (" . implode(',', $valoresCompetenciasId) . ") AND c2.valor <= DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m') ORDER BY c2.valor DESC LIMIT 1 ) "); }) ->when(is_null($request->unidade_id), fn ($q) => $q->where('cadastro_unidade.cnes', $request->cnes), fn ($q) => $q->where('cadastro_unidade.id', $request->unidade_id) ) ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereIn(DB::raw("DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m')"), $valoresCompetencias) ->whereNull('exame_laboratorial_agendamento_exame.bpa_procedimento_id') ->whereNull('exame_laboratorial_agendamento_exame.apac_procedimento_secundario_id') ->where(fn ($q) => $q ->whereNull('exame_laboratorial_agendamento_exame.acompanhamento_oci_id') ->orWhere(fn ($q) => $q ->whereNotNull('exame_laboratorial_agendamento_exame.acompanhamento_oci_id') ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_acompanhamento_oci') ->whereColumn('ambulatorio_acompanhamento_oci.id', 'exame_laboratorial_agendamento_exame.acompanhamento_oci_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereNull('ambulatorio_acompanhamento_oci.finalizado_em') ->whereRaw("CURRENT_DATE <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ->orWhere(fn ($q) => $q ->whereNotNull('ambulatorio_acompanhamento_oci.finalizado_em') ->where('ambulatorio_acompanhamento_oci.etapa_clinica_atual_id', EtapaClinica::ALTA) ->whereRaw("CAST(ambulatorio_acompanhamento_oci.finalizado_em AS DATE) <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ) ) ) ); $transportePaciente = DB::table('transporte_paciente_faturamento') ->select([ 'transporte_paciente_faturamento.id', 'transporte_paciente_faturamento.lotacao_id as unidade_id', 'transporte_paciente_faturamento.usuario_id', 'transporte_paciente_faturamento.ocupacao_id', 'transporte_paciente_faturamento.paciente_id', 'transporte_paciente_faturamento.procedimento_id', 'transporte_paciente_faturamento.cid_principal_id', DB::raw("'" . Origem::TRANSPORTE_PACIENTE . "' AS origem"), DB::raw("DATE_FORMAT(transporte_paciente_agendar_transporte.data, '%Y%m%d') AS data_atendimento"), 'transporte_paciente_faturamento.quantidade', ]) ->join('transporte_paciente_agendar_transporte', 'transporte_paciente_agendar_transporte.id', 'transporte_paciente_faturamento.agendamento_id') ->join('cadastro_unidade', 'cadastro_unidade.id', 'transporte_paciente_faturamento.lotacao_id') ->leftJoin('cadastro_lotacao', 'cadastro_lotacao.id', 'transporte_paciente_faturamento.lotacao_id') ->leftJoin('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->leftJoin('transporte_paciente_parametrizacao_faturamento', 'transporte_paciente_parametrizacao_faturamento.unidade_id', 'transporte_paciente_agendar_transporte.lotacao_id') ->leftJoin('transporte_paciente_destino', 'transporte_paciente_agendar_transporte.destino_id', 'transporte_paciente_destino.id') ->whereExists(function ($query) { $query->select(DB::raw(1)) ->from('transporte_paciente_parametrizacao') ->where('transporte_paciente_parametrizacao.faturamento', StatusFaturamento::COM_FATURAMENTO); }) ->whereNotNull('transporte_paciente_destino.distancia') ->whereIn(DB::raw("DATE_FORMAT(transporte_paciente_agendar_transporte.data, '%Y%m')"), $valoresCompetencias) ->when(is_null($request->unidade_id), fn ($q) => $q->where('cadastro_unidade.cnes', $request->cnes), fn ($q) => $q->where('transporte_paciente_faturamento.lotacao_id', $request->unidade_id) ) ->where('transporte_paciente_agendar_transporte.status_id', EnumStatus::TRANSPORTADO) ->whereNull('transporte_paciente_faturamento.bpa_procedimento_id'); $ambulatorioAtendimentoAgendadoProcedimento = DB::table('ambulatorio_atendimento_procedimento') ->select([ 'ambulatorio_atendimento_procedimento.id', 'cadastro_infraestrutura.unidade_id', 'ambulatorio_atendimento_procedimento.usuario_id', 'ambulatorio_atendimento_procedimento.ocupacao_id', 'ambulatorio_agendamento.paciente_id', 'ambulatorio_atendimento_procedimento.procedimento_id', 'ambulatorio_atendimento_procedimento.cid_id as cid_principal_id', DB::raw("'" . Origem::AMBULATORIO . "' AS origem"), DB::raw("DATE_FORMAT(ambulatorio_jornada.data, '%Y%m%d') AS data_atendimento"), 'ambulatorio_atendimento_procedimento.quantidade', ]) ->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id') ->join('ambulatorio_agendamento', 'ambulatorio_agendamento.id', 'ambulatorio_atendimento.agendamento_id') ->join('ambulatorio_jornada', 'ambulatorio_jornada.id', 'ambulatorio_agendamento.jornada_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', 'ambulatorio_jornada.lotacao_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->whereNotNull('ambulatorio_atendimento.finalizado_em') ->when(is_null($request->unidade_id), fn ($q) => $q->where('cadastro_unidade.cnes', $request->cnes), fn ($q) => $q->where('cadastro_infraestrutura.unidade_id', $request->unidade_id) ) ->whereIn(DB::raw("DATE_FORMAT(ambulatorio_jornada.data, '%Y%m')"), $valoresCompetencias) ->whereNull('ambulatorio_atendimento_procedimento.bpa_procedimento_id') ->whereNull('ambulatorio_atendimento_procedimento.apac_procedimento_secundario_id') ->where(fn ($q) => $q ->whereNull('ambulatorio_atendimento_procedimento.acompanhamento_oci_id') ->orWhere(fn ($q) => $q ->whereNotNull('ambulatorio_atendimento_procedimento.acompanhamento_oci_id') ->whereNotExists(fn ($q) => $q ->selectRaw(1) ->from('ambulatorio_acompanhamento_oci') ->whereColumn('ambulatorio_acompanhamento_oci.id', 'ambulatorio_atendimento_procedimento.acompanhamento_oci_id') ->where(fn ($q) => $q ->where(fn ($q) => $q ->whereNull('ambulatorio_acompanhamento_oci.finalizado_em') ->whereRaw("CURRENT_DATE <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ->orWhere(fn ($q) => $q ->whereNotNull('ambulatorio_acompanhamento_oci.finalizado_em') ->where('ambulatorio_acompanhamento_oci.etapa_clinica_atual_id', EtapaClinica::ALTA) ->whereRaw("CAST(ambulatorio_acompanhamento_oci.finalizado_em AS DATE) <= LAST_DAY(DATE_ADD(CAST(ambulatorio_acompanhamento_oci.iniciado_em AS DATE), INTERVAL 1 MONTH))") ) ) ) ) ); $ambulatorioAtendimentoDemandaEspontaneaProcedimento = DB::table('ambulatorio_atendimento_procedimento') ->select([ 'ambulatorio_atendimento_procedimento.id', 'cadastro_infraestrutura.unidade_id', 'ambulatorio_atendimento_procedimento.usuario_id', 'ambulatorio_atendimento_procedimento.ocupacao_id', 'ambulatorio_demanda_espontanea.paciente_id', 'ambulatorio_atendimento_procedimento.procedimento_id', 'ambulatorio_atendimento_procedimento.cid_id as cid_principal_id', DB::raw("'" . Origem::AMBULATORIO . "' AS origem"), DB::raw("DATE_FORMAT(ambulatorio_demanda_espontanea.data, '%Y%m%d') AS data_atendimento"), 'ambulatorio_atendimento_procedimento.quantidade', ]) ->join('ambulatorio_atendimento', 'ambulatorio_atendimento.id', 'ambulatorio_atendimento_procedimento.atendimento_id') ->join('ambulatorio_demanda_espontanea', 'ambulatorio_demanda_espontanea.id', 'ambulatorio_atendimento.demanda_espontanea_id') ->join('cadastro_centro_custo', 'cadastro_centro_custo.id', 'ambulatorio_demanda_espontanea.created_centro_custo_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_centro_custo.infraestrutura_id') ->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->whereNotNull('ambulatorio_atendimento.finalizado_em') ->when(is_null($request->unidade_id), fn ($q) => $q->where('cadastro_unidade.cnes', $request->cnes), fn ($q) => $q->where('cadastro_infraestrutura.unidade_id', $request->unidade_id) ) ->whereIn(DB::raw("DATE_FORMAT(ambulatorio_demanda_espontanea.data, '%Y%m')"), $valoresCompetencias) ->whereNull('ambulatorio_atendimento_procedimento.bpa_procedimento_id') ->whereNull('ambulatorio_atendimento_procedimento.apac_procedimento_secundario_id'); $prontoAtendimentoAtendimentoProcedimento ->union($exameImagem) ->union($exameLaboratorial) ->union($transportePaciente) ->union($ambulatorioAtendimentoAgendadoProcedimento) ->union($ambulatorioAtendimentoDemandaEspontaneaProcedimento) ->get() ->map(function($query) use ($request, $configuracao) { $registros = DB::table('sigtap.procedimento_registro') ->select([ 'registro.id AS registro_id', 'registro.codigo AS registro_codigo' ]) ->join('sigtap.registro', 'registro.id', 'procedimento_registro.registro_id') ->where('procedimento_registro.procedimento_id', $query->procedimento_id) ->get(); if ( ( $registros->contains('registro_codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) && $registros->contains('registro_codigo', SigtapRegistro::BPA_CONSOLIDADO) === false ) || ( $configuracao->bpa_intrumento_registro_padrao === SigtapRegistro::BPA_INDIVIDUALIZADO && $registros->contains('registro_codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) { $origemFuncionalidade = $query->origem; if ($origemFuncionalidade == Origem::PRONTO_ATENDIMENTO){ $caraterAtendimento = '2'; } else { $caraterAtendimento = '1'; } $competenciaValor= substr($query->data_atendimento, 0, 6); $competencia = Competencia::where('valor', $competenciaValor)->first(); $procedimento = Procedimento::create([ 'unidade_id' => $query->unidade_id, 'competencia_id' => $competencia->id, 'usuario_id' => $query->usuario_id, 'ocupacao_id' => $query->ocupacao_id, 'paciente_id' => $query->paciente_id, 'procedimento_id' => $query->procedimento_id, 'registro_id' => $registros->firstWhere('registro_codigo', SigtapRegistro::BPA_INDIVIDUALIZADO)->registro_id, 'cid_id' => $query->cid_principal_id, 'carater_atendimento_id' => $caraterAtendimento, 'origem' => $query->origem, 'data_atendimento' => $query->data_atendimento, 'quantidade' => $query->quantidade, ]); switch ($query->origem) { case Origem::PRONTO_ATENDIMENTO: AtendimentoProcedimento::findOrFail($query->id)->update(['bpa_procedimento_id' => $procedimento->id]); break; case Origem::EXAME_IMAGEM: Faturamento::findOrFail($query->id)->update(['bpa_procedimento_id' => $procedimento->id]); break; case Origem::EXAME_LABORATORIAL: AgendamentoExame::findOrFail($query->id)->update(['bpa_procedimento_id' => $procedimento->id]); break; case Origem::TRANSPORTE_PACIENTE: FaturamentoTransporte::findOrFail($query->id)->update(['bpa_procedimento_id' => $procedimento->id]); break; case Origem::AMBULATORIO: AmbulatorioAtendimentoProcedimento::findOrFail($query->id)->update(['bpa_procedimento_id' => $procedimento->id]); break; } } }); DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento.id', 'cadastro_infraestrutura.unidade_id', 'exame_laboratorial_agendamento.usuario_id AS usuario_id', 'exame_laboratorial_agendamento.ocupacao_id AS ocupacao_id', 'exame_laboratorial_agendamento_exame.paciente_id', DB::raw(" ( SELECT sigtap.procedimento.id FROM sigtap.procedimento INNER JOIN sigtap.competencia ON sigtap.competencia.id = sigtap.procedimento.competencia_id WHERE sigtap.procedimento.codigo = '" . ProcedimentoEnum::COLETA_DE_MATERIAL_PARA_EXAME_LABORATORIAL . "' AND sigtap.competencia.valor <= DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m') ORDER BY sigtap.competencia.id DESC LIMIT 1 ) AS procedimento_id "), DB::raw("DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m%d') AS data_atendimento"), 'exame_laboratorial_agendamento_exame.quantidade', ]) ->join('exame_laboratorial_agendamento', 'exame_laboratorial_agendamento.id', 'exame_laboratorial_agendamento_exame.agendamento_id') ->join('cadastro_lotacao', 'cadastro_lotacao.id', 'exame_laboratorial_agendamento.lotacao_id') ->join('cadastro_infraestrutura', 'cadastro_infraestrutura.id', 'cadastro_lotacao.infraestrutura_id') ->join('cadastro_unidade', 'cadastro_unidade.id', 'cadastro_infraestrutura.unidade_id') ->when(is_null($request->unidade_id), fn ($q) => $q->where('cadastro_unidade.cnes', $request->cnes), fn ($q) => $q->where('cadastro_unidade.id', $request->unidade_id) ) ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::REALIZADO, StatusAgendamento::NOVA_COLETA, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereIn(DB::raw("DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m')"), $valoresCompetencias) ->whereNull('exame_laboratorial_agendamento.bpa_procedimento_id') ->groupBy('exame_laboratorial_agendamento.id') ->get() ->map(function($query) use ($configuracao) { $registros = DB::table('sigtap.procedimento_registro') ->select([ 'registro.id AS registro_id', 'registro.codigo AS registro_codigo' ]) ->join('sigtap.registro', 'registro.id', 'procedimento_registro.registro_id') ->where('procedimento_registro.procedimento_id', $query->procedimento_id) ->get(); if ( ( $registros->contains('registro_codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) && $registros->contains('registro_codigo', SigtapRegistro::BPA_CONSOLIDADO) === false ) || ( $configuracao->bpa_intrumento_registro_padrao === SigtapRegistro::BPA_INDIVIDUALIZADO && $registros->contains('registro_codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) { $caraterAtendimento = '1'; $competenciaValor= substr($query->data_atendimento, 0, 6); $competencia = Competencia::where('valor', $competenciaValor)->first(); $procedimento = Procedimento::create([ 'unidade_id' => $query->unidade_id, 'competencia_id' => $competencia->id, 'usuario_id' => $query->usuario_id, 'ocupacao_id' => $query->ocupacao_id, 'paciente_id' => $query->paciente_id, 'procedimento_id' => $query->procedimento_id, 'registro_id' => $registros->firstWhere('registro_codigo', SigtapRegistro::BPA_INDIVIDUALIZADO)->registro_id, 'cid_id' => null, 'carater_atendimento_id' => $caraterAtendimento, 'origem' => Origem::EXAME_LABORATORIAL, 'data_atendimento' => $query->data_atendimento, 'quantidade' => $query->quantidade, ]); Agendamento::findOrFail($query->id)->update(['bpa_procedimento_id' => $procedimento->id]); } }); } private function getProcedimentoPadraoExameLaboratorial() { return DB::raw(" ( SELECT sigtap.procedimento.id FROM sigtap.procedimento INNER JOIN sigtap.competencia ON sigtap.competencia.id = sigtap.procedimento.competencia_id WHERE sigtap.procedimento.codigo = '" . ProcedimentoEnum::COLETA_DE_MATERIAL_PARA_EXAME_LABORATORIAL . "' AND sigtap.competencia.valor <= DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m') ORDER BY sigtap.competencia.id DESC LIMIT 1 ) "); } private static function destroyProcedimentosAutomaticos($request) { DB::table('bpa_procedimento') ->select([ 'bpa_procedimento.id', 'bpa_procedimento.origem' ]) ->join('sigtap.registro', 'registro.id', 'bpa_procedimento.registro_id') ->join('cadastro_unidade', 'cadastro_unidade.id', 'bpa_procedimento.unidade_id') ->when(is_null($request->unidade_id), fn ($q) => $q->where('cadastro_unidade.cnes', $request->cnes), fn ($q) => $q->where('bpa_procedimento.unidade_id', $request->unidade_id) ) ->where('bpa_procedimento.competencia_id', $request->competencia_id) ->where('bpa_procedimento.origem', '<>', Origem::BPA) ->where('registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ->whereNull('bpa_procedimento.exportacao_id') ->whereNull('bpa_procedimento.deleted_at') ->get() ->map(function($query) { switch ($query->origem) { case Origem::PRONTO_ATENDIMENTO: AtendimentoProcedimento::where('bpa_procedimento_id', $query->id)->update(['bpa_procedimento_id' => null]); break; case Origem::EXAME_IMAGEM: Faturamento::where('bpa_procedimento_id', $query->id)->update(['bpa_procedimento_id' => null]); break; case Origem::EXAME_LABORATORIAL: AgendamentoExame::where('bpa_procedimento_id', $query->id)->update(['bpa_procedimento_id' => null]); Agendamento::where('bpa_procedimento_id', $query->id)->update(['bpa_procedimento_id' => null]); break; case Origem::TRANSPORTE_PACIENTE: FaturamentoTransporte::where('bpa_procedimento_id', $query->id)->update(['bpa_procedimento_id' => null]); break; case Origem::AMBULATORIO: AmbulatorioAtendimentoProcedimento::where('bpa_procedimento_id', $query->id)->update(['bpa_procedimento_id' => null]); break; } Procedimento::findOrFail($query->id)->delete(); }); } }