where($where)->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]); AmbulatorioAtendimentoProcedimento::where('bpa_procedimento_id', $id)->update(['bpa_procedimento_id' => null]); Procedimento::findOrFail($id)->delete(); }); } public static function datatable() { $procedimentos = DB::table('bpa_procedimento') ->join('cadastro_unidade', 'cadastro_unidade.id', 'bpa_procedimento.unidade_id') ->join('sigtap.competencia', 'competencia.id', 'bpa_procedimento.competencia_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') ->select([ 'bpa_procedimento.origem', 'cadastro_unidade.id AS unidade_id', 'cadastro_unidade.nome_fantasia AS unidade_nome', 'competencia.valor AS competencia', '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', DB::raw('SUM(bpa_procedimento.quantidade) AS quantidade'), ]) ->whereNull('bpa_procedimento.deleted_at') ->groupBy( 'bpa_procedimento.origem', 'cadastro_unidade.id', 'competencia.valor', 'procedimento.codigo', 'registro.codigo', 'ocupacao.codigo', 'bpa_procedimento.idade' ); return DB::table(DB::raw("({$procedimentos->toSql()}) as x")) ->select([ 'origem', 'unidade_id', 'unidade_nome', 'competencia', 'procedimento_id', 'procedimento_codigo', 'procedimento_nome', 'registro_id', 'registro_codigo', 'ocupacao_id', 'ocupacao_codigo', 'ocupacao_nome', 'idade', 'quantidade', ]) ->where('registro_codigo', SigtapRegistro::BPA_CONSOLIDADO); } private static function validate($request) { return $request->validate([ 'unidade_id' => [ 'required', 'integer', 'exists:\App\Models\Cadastro\Estabelecimento\Unidade,id', ], 'competencia_id' => [ new CompetenciaIsValid(), ], 'procedimento_id' => [ 'required', 'integer', new ProcedimentoIsValidForCompetencia(self::getCompetencias()), new ProcedimentoExists(), new ProcedimentoIsValidForOcupacao($request->ocupacao_id), ], 'ocupacao_id' => [ new OcupacaoExists(), ], 'quantidade' => [ 'integer', new QuantidadeIsValid(), ], ]); } 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 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; default: $form = [ 'unidades' => self::getUnidades(), 'competencias' => self::getCompetencias(), ]; } 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_CONSOLIDADO) ) ->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_INDIVIDUALIZADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_CONSOLIDADO]) ->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_CONSOLIDADO) ) ) ) ) ->orWhereExists(fn ($q) => $q ->selectRaw(1) ->from('exame_imagem_fechamento_faturamento') ->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') ->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_CONSOLIDADO) ) ->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_INDIVIDUALIZADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_CONSOLIDADO]) ->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_CONSOLIDADO) ) ) ) ) ->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') ->join('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->join('sigtap.procedimento', function($join) use ($competencia) { $join->on('sigtap.procedimento.codigo', 'parametrizacao_exame.codigo') ->where('sigtap.procedimento.competencia_id', $competencia->id); }) ->whereColumn('cadastro_infraestrutura.unidade_id', 'unidade.id') ->whereIn(DB::raw("DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m')"), $valoresCompetencias) ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereNull('exame_laboratorial_agendamento_exame.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', 'sigtap.procedimento.id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ->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', 'sigtap.procedimento.id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_CONSOLIDADO]) ->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', 'sigtap.procedimento.id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ) ) ->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') ->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_CONSOLIDADO) ) ->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_INDIVIDUALIZADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_CONSOLIDADO]) ->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_CONSOLIDADO) ) ) ) ) ->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') ->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_CONSOLIDADO) ) ->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_INDIVIDUALIZADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_CONSOLIDADO]) ->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_CONSOLIDADO) ) ) ) ) ->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('cadastro_infraestrutura.unidade_id', 'unidade.id') ->whereIn(DB::raw("DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m')"), $valoresCompetencias) ->whereNull('exame_laboratorial_agendamento.bpa_procedimento_id') ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->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_CONSOLIDADO) ) ->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_INDIVIDUALIZADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_CONSOLIDADO]) ->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_CONSOLIDADO) ) ) ) ) ) ->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_CONSOLIDADO) ->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_CONSOLIDADO) ) ->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_INDIVIDUALIZADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_CONSOLIDADO]) ->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_CONSOLIDADO) ) ) ) ) ->orWhereExists(fn ($q) => $q ->selectRaw(1) ->from('exame_imagem_fechamento_faturamento') ->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') ->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_CONSOLIDADO) ) ->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_INDIVIDUALIZADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_CONSOLIDADO]) ->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_CONSOLIDADO) ) ) ) ) ->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') ->join('parametrizacao_exame', 'parametrizacao_exame.id', 'exame_laboratorial_agendamento_exame.exame_id') ->join('sigtap.procedimento', function($join) use ($competencia) { $join->on('sigtap.procedimento.codigo', 'parametrizacao_exame.codigo') ->where('sigtap.procedimento.competencia_id', $competencia->id); }) ->whereColumn('cadastro_infraestrutura.unidade_id', 'unidade.id') ->whereIn(DB::raw("DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m')"), $valoresCompetencias) ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereNull('exame_laboratorial_agendamento_exame.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', 'sigtap.procedimento.id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ->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', 'sigtap.procedimento.id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_CONSOLIDADO]) ->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', 'sigtap.procedimento.id') ->where('sigtap.registro.codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) ) ) ->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') ->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_CONSOLIDADO) ) ->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_INDIVIDUALIZADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_CONSOLIDADO]) ->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_CONSOLIDADO) ) ) ) ) ->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') ->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_CONSOLIDADO) ) ->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_INDIVIDUALIZADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_CONSOLIDADO]) ->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_CONSOLIDADO) ) ) ) ) ->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('cadastro_infraestrutura.unidade_id', 'unidade.id') ->whereIn(DB::raw("DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m')"), $valoresCompetencias) ->whereNull('exame_laboratorial_agendamento.bpa_procedimento_id') ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->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_CONSOLIDADO) ) ->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_INDIVIDUALIZADO) ) ) ->orWhere(fn ($q) => $q ->whereRaw("'{$configuracao->bpa_intrumento_registro_padrao}' = ?", [SigtapRegistro::BPA_CONSOLIDADO]) ->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_CONSOLIDADO) ) ) ) ) ) ->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_CONSOLIDADO) ->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 = [ 'acao' => $acao, 'unidade_id' => $procedimento['unidade_id'] ?? null, 'competencia_id' => $procedimento['competencia_id'] ?? null, 'procedimento' => $procedimento ? [ 'id' => $procedimento['procedimento']['id'] ?? null, 'codigo' => $procedimento['procedimento']['codigo'] ?? null, 'nome' => $procedimento['procedimento']['nome'] ?? null, ] : null, 'ocupacao' => $procedimento ? [ 'id' => $procedimento['ocupacao']['id'] ?? null, 'codigo' => $procedimento['ocupacao']['codigo'] ?? null, 'nome' => $procedimento['ocupacao']['nome'] ?? null, ] : null, 'quantidade' => $procedimento['quantidade'] ?? null, 'idade' => $procedimento['idade'] ?? null, ]; break; } return $model; } private static function storeProcedimentoManual($request) { self::validate($request); $registro = Registro::where('codigo', SigtapRegistro::BPA_CONSOLIDADO) ->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, 'procedimento_id' => $request->procedimento_id, 'registro_id' => $registro->id, 'ocupacao_id' => $request->ocupacao_id, 'origem' => Origem::BPA, 'quantidade' => $request->quantidade, 'idade' => $request->idade, ]); } 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.ocupacao_id', 'pronto_atendimento_atendimento_procedimento.procedimento_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', DB::raw('TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, NOW()) AS idade'), ]) ->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') ->join('cadastro_paciente', 'cadastro_paciente.id', 'pronto_atendimento_faa.paciente_id') ->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_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', 'exame_imagem_fechamento_faturamento.ocupacao_id', 'exame_imagem_fechamento_faturamento.procedimento_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', DB::raw('TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, NOW()) AS idade'), ]) ->join('cadastro_unidade', 'cadastro_unidade.id', 'exame_imagem_fechamento_faturamento.unidade_id') ->join('cadastro_paciente', 'cadastro_paciente.id', 'exame_imagem_fechamento_faturamento.paciente_id') ->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_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'); $exameLaboratorial = DB::table('exame_laboratorial_agendamento_exame') ->select([ 'exame_laboratorial_agendamento_exame.id', 'cadastro_infraestrutura.unidade_id', 'exame_laboratorial_agendamento.laboratorio_ocupacao_id', 'sigtap.procedimento.id as procedimento_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', DB::raw('TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, NOW()) AS idade'), ]) ->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('cadastro_paciente', 'cadastro_paciente.id', 'exame_laboratorial_agendamento_exame.paciente_id') ->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_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(DB::raw("DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m')"), $valoresCompetencias) ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->whereNull('exame_laboratorial_agendamento_exame.bpa_procedimento_id'); $ambulatorioAtendimentoAgendadoProcedimento = DB::table('ambulatorio_atendimento_procedimento') ->select([ 'ambulatorio_atendimento_procedimento.id', 'cadastro_infraestrutura.unidade_id', 'ambulatorio_atendimento_procedimento.ocupacao_id', 'ambulatorio_atendimento_procedimento.procedimento_id', DB::raw("'" . Origem::AMBULATORIO . "' AS origem"), DB::raw("DATE_FORMAT(ambulatorio_jornada.data, '%Y%m%d') AS data_atendimento"), 'ambulatorio_atendimento_procedimento.quantidade', DB::raw('TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, NOW()) AS idade'), ]) ->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') ->join('cadastro_paciente', 'cadastro_paciente.id', 'ambulatorio_agendamento.paciente_id') ->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_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'); $ambulatorioAtendimentoDemandaEspontaneaProcedimento = DB::table('ambulatorio_atendimento_procedimento') ->select([ 'ambulatorio_atendimento_procedimento.id', 'cadastro_infraestrutura.unidade_id', 'ambulatorio_atendimento_procedimento.ocupacao_id', 'ambulatorio_atendimento_procedimento.procedimento_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', DB::raw('TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, NOW()) AS idade'), ]) ->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') ->join('cadastro_paciente', 'cadastro_paciente.id', 'ambulatorio_demanda_espontanea.paciente_id') ->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_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'); $prontoAtendimentoAtendimentoProcedimento ->union($exameImagem) ->union($exameLaboratorial) ->union($ambulatorioAtendimentoAgendadoProcedimento) ->union($ambulatorioAtendimentoDemandaEspontaneaProcedimento) ->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_CONSOLIDADO) && $registros->contains('registro_codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) === false ) || ( $configuracao->bpa_intrumento_registro_padrao === SigtapRegistro::BPA_CONSOLIDADO && $registros->contains('registro_codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) { $detalhe = DB::table('sigtap.procedimento_detalhe') ->join('sigtap.procedimento', 'procedimento.id', 'procedimento_detalhe.procedimento_id') ->join('sigtap.detalhe', 'detalhe.id', 'procedimento_detalhe.detalhe_id') ->where('detalhe.codigo', '012') ->where('procedimento.id', $query->procedimento_id) ->exists(); $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, 'ocupacao_id' => $query->ocupacao_id, 'procedimento_id' => $query->procedimento_id, 'registro_id' => $registros->firstWhere('registro_codigo', SigtapRegistro::BPA_CONSOLIDADO)->registro_id, 'origem' => $query->origem, 'data_atendimento' => $query->data_atendimento, 'quantidade' => $query->quantidade, 'idade' => $detalhe ? $query->idade : null, ]); 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::AMBULATORIO: AmbulatorioAtendimentoProcedimento::findOrFail($query->id)->update(['bpa_procedimento_id' => $procedimento->id]); break; } } }); DB::table('exame_laboratorial_agendamento_exame') ->select([ 'cadastro_infraestrutura.unidade_id', 'exame_laboratorial_agendamento.ocupacao_id', 'exame_laboratorial_agendamento.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', DB::raw('TIMESTAMPDIFF(YEAR, cadastro_cidadao.data_nascimento, NOW()) AS idade'), ]) ->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') ->join('cadastro_paciente', 'cadastro_paciente.id', 'exame_laboratorial_agendamento_exame.paciente_id') ->join('cadastro_cidadao', 'cadastro_cidadao.id', 'cadastro_paciente.cidadao_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(DB::raw("DATE_FORMAT(exame_laboratorial_agendamento.data, '%Y%m')"), $valoresCompetencias) ->whereNull('exame_laboratorial_agendamento.bpa_procedimento_id') ->whereIn('exame_laboratorial_agendamento_exame.status_id', [ StatusAgendamento::REALIZADO, StatusAgendamento::PENDENTE_ASSINATURA, StatusAgendamento::ASSINADO, StatusAgendamento::PENDENTE_ENTREGA, StatusAgendamento::ENTREGUE, ]) ->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_CONSOLIDADO) && $registros->contains('registro_codigo', SigtapRegistro::BPA_INDIVIDUALIZADO) === false ) || ( $configuracao->bpa_intrumento_registro_padrao === SigtapRegistro::BPA_CONSOLIDADO && $registros->contains('registro_codigo', SigtapRegistro::BPA_CONSOLIDADO) ) ) { $detalhe = DB::table('sigtap.procedimento_detalhe') ->join('sigtap.procedimento', 'procedimento.id', 'procedimento_detalhe.procedimento_id') ->join('sigtap.detalhe', 'detalhe.id', 'procedimento_detalhe.detalhe_id') ->where('detalhe.codigo', '012') ->where('procedimento.id', $query->procedimento_id) ->exists(); $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, 'ocupacao_id' => $query->ocupacao_id, 'procedimento_id' => $query->procedimento_id, 'registro_id' => $registros->firstWhere('registro_codigo', SigtapRegistro::BPA_CONSOLIDADO)->registro_id, 'origem' => Origem::EXAME_LABORATORIAL, 'data_atendimento' => $query->data_atendimento, 'quantidade' => $query->quantidade, 'idade' => $detalhe ? $query->idade : null, ]); 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_CONSOLIDADO) ->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::AMBULATORIO: AmbulatorioAtendimentoProcedimento::where('bpa_procedimento_id', $query->id)->update(['bpa_procedimento_id' => null]); break; } Procedimento::findOrFail($query->id)->delete(); }); } }