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::getRegistrosAtualizacao()
->each(function($registroAtualizacao) use ($cliente, $parametrizacao, &$token, $expiresAt) {
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'],
];
$registroAtualizacao->identificador_solicitante = $parametrizacao->identificador_solicitante;
$registroAtualizacao->cns_solicitante = $parametrizacao->cns_solicitante;
$registroAtualizacao->data_hora_envio = Carbon::now();
$response = RiaService::sendDocumentoImunologicoRotina($headers, $registroAtualizacao, $cliente->municipio->estado->uf);
$registroAtualizacao->identificador_rnds = $response->header('Location') ? $response->header('Location') : null;
$registroAtualizacao->response = $response->json();
DocumentoImunologicoRotinaService::store($registroAtualizacao);
});
Log::channel('integracao-ria')->info('Comando executado com sucesso.', [
'cliente' => $cliente->link,
'origem' => 'EnviarRegistroAtualizacaoCommand',
]);
}
} catch (Exception $error) {
Log::channel('integracao-ria')->error('Erro ao executar o comando', [
'cliente' => $cliente->link ?? $cliente,
'origem' => 'EnviarRegistroAtualizacaoCommand',
'erro' => $error->getMessage(),
]);
if (env('APP_ENV') === 'production') {
TelegramService::send('Integração RIA (' . ($cliente->link ?? $cliente) . '): (Erro ao executar o comando: EnviarRegistroAtualizacaoCommand).');
}
return;
}
});
Config::set('database.default', $currentDatabase);
} catch (Exception $error) {
Log::channel('integracao-ria')->error('Erro ao executar o comando', [
'origem' => 'EnviarRegistroAtualizacaoCommand',
'erro' => $error->getMessage(),
]);
if (env('APP_ENV') === 'production') {
TelegramService::send('Integração RIA: (Erro ao executar o comando: EnviarRegistroAtualizacaoCommand).');
}
}
}
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();
}
}