each(function($cliente) { try { $cliente = Cliente::where('link', $cliente) ->where('sistema_id', Sistema::CONECTASUS) ->firstOrFail(); Config::set('database.default', $cliente->link); $parametrizacao = RiaService::getParametrizacao(); if (!is_null($parametrizacao)) { $token = RiaService::getToken($parametrizacao->senha); $expiresAt = Carbon::now()->addMilliseconds($token['expires_in'])->subMinutes(2); DocumentoImunologicoRotinaService::getDocumentosParaExclusao() ->each(function($documento) use ($parametrizacao, &$token, $expiresAt) { if (!app()->environment('production') && !str_contains($documento->identificador_rnds, 'ehr-services-hmg.saude.gov.br')) { return; } if (Carbon::now() >= $expiresAt) { $token = RiaService::getToken($parametrizacao->senha); } $headers = [ 'Authorization' => $parametrizacao->cns_solicitante, 'Content-Type' => 'application/json', 'X-Authorization-Server' => "Bearer " . $token['access_token'], ]; $documento->identificador_solicitante = $parametrizacao->identificador_solicitante; $documento->cns_solicitante = $parametrizacao->cns_solicitante; $documento->data_hora_envio = Carbon::now(); $response = RiaService::destroy($headers, $documento->identificador_rnds); if ($response->status() === 204) { DocumentoImunologicoRotina::destroy($documento->id); } else { $documento->response = $response->json(); DocumentoImunologicoRotinaService::update($documento->id, $documento); } }); Log::channel('integracao-ria')->info('Comando executado com sucesso.', [ 'cliente' => $cliente->link, 'origem' => 'EnviarExclusaoDocumentoCommand', ]); } } catch (Exception $error) { Log::channel('integracao-ria')->error('Erro ao executar o comando', [ 'cliente' => $cliente->link ?? $cliente, 'origem' => 'EnviarExclusaoDocumentoCommand', 'erro' => $error->getMessage(), ]); if (env('APP_ENV') === 'production') { TelegramService::send('Integração RIA (' . ($cliente->link ?? $cliente) . '): (Erro ao executar o comando: EnviarExclusaoDocumentoCommand).'); } return; } }); Config::set('database.default', $currentDatabase); } catch (Exception $error) { Log::channel('integracao-ria')->error('Erro ao executar o comando', [ 'origem' => 'EnviarExclusaoDocumentoCommand', 'erro' => $error->getMessage(), ]); if (env('APP_ENV') === 'production') { TelegramService::send('Integração RIA: (Erro ao executar o comando: EnviarExclusaoDocumentoCommand).'); } } } private function getClientes() { return collect(json_decode(file_get_contents(base_path('connections.json')), true)) ->filter(fn ($config) => isset($config['database']) && Str::startsWith($config['database'], 'conectasus')) ->reject(fn ($config) => empty(DB::connection('schema')->select("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?", [$config['database']]))) ->map(fn ($config, $customer) => $customer) ->sort() ->values(); } }