This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Bnafar;
|
||||
|
||||
use App\Enums\Intranet\Sistema;
|
||||
use App\Models\Intranet\Cliente;
|
||||
use App\Services\Integracao\BnafarService;
|
||||
use App\Services\Integracao\Bnafar\PosicaoEstoqueService;
|
||||
use App\Services\Telegram\TelegramService;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EnviarPosicaoEstoqueCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:bnafar-enviar-posicao-estoque';
|
||||
protected $description = 'Comando para envio de posição de estoque ao BNAFAR.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
try {
|
||||
$currentDatabase = Config::get('database.default');
|
||||
|
||||
self::getClientes()->each(function($cliente) {
|
||||
try {
|
||||
DB::beginTransaction();
|
||||
|
||||
$cliente = Cliente::where('link', $cliente)
|
||||
->where('sistema_id', Sistema::CONECTASUS)
|
||||
->firstOrFail();
|
||||
|
||||
$ibge = substr($cliente->municipio->ibge, 0, 6);
|
||||
|
||||
Config::set('database.default', $cliente->link);
|
||||
|
||||
$parametrizacao = BnafarService::getParametrizacao();
|
||||
|
||||
if (!is_null($parametrizacao)) {
|
||||
$token = BnafarService::getToken($parametrizacao->usuario, $parametrizacao->senha);
|
||||
|
||||
if (!is_null($token)) {
|
||||
$token = $token['access_token'];
|
||||
|
||||
PosicaoEstoqueService::store();
|
||||
PosicaoEstoqueService::post($cliente->link, $token, $ibge);
|
||||
|
||||
Log::channel('integracao-bnafar')->info('Comando executado com sucesso.', [
|
||||
'cliente' => $cliente->link,
|
||||
'origem' => 'EnviarPosicaoEstoqueCommand',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
} catch (Exception $error) {
|
||||
DB::rollBack();
|
||||
|
||||
Log::channel('integracao-bnafar')->error('Erro ao executar o comando', [
|
||||
'cliente' => $cliente->link ?? $cliente,
|
||||
'origem' => 'EnviarPosicaoEstoqueCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração BNAFAR (' . ($cliente->link ?? $cliente) . '):</strong> (Erro ao executar o comando: EnviarPosicaoEstoqueCommand).');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
Config::set('database.default', $currentDatabase);
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-bnafar')->error('Erro ao executar o comando', [
|
||||
'origem' => 'EnviarPosicaoEstoqueCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração BNAFAR:</strong> (Erro ao executar o comando: EnviarPosicaoEstoqueCommand).');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Bnafar;
|
||||
|
||||
use App\Enums\Intranet\Sistema;
|
||||
use App\Models\Intranet\Cliente;
|
||||
use App\Services\Integracao\Bnafar\SaidaService;
|
||||
use App\Services\Integracao\BnafarService;
|
||||
use App\Services\Telegram\TelegramService;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EnviarSaidaCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:bnafar-enviar-saida';
|
||||
protected $description = 'Comando para envio de saida ao BNAFAR.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
try {
|
||||
$currentDatabase = Config::get('database.default');
|
||||
|
||||
self::getClientes()->each(function($cliente) {
|
||||
DB::beginTransaction();
|
||||
|
||||
try {
|
||||
$cliente = Cliente::where('link', $cliente)
|
||||
->where('sistema_id', Sistema::CONECTASUS)
|
||||
->firstOrFail();
|
||||
|
||||
$ibge = substr($cliente->municipio->ibge, 0, 6);
|
||||
|
||||
Config::set('database.default', $cliente->link);
|
||||
|
||||
$parametrizacao = BnafarService::getParametrizacao();
|
||||
|
||||
if (!is_null($parametrizacao)) {
|
||||
$token = BnafarService::getToken($parametrizacao->usuario, $parametrizacao->senha);
|
||||
|
||||
if (!is_null($token)) {
|
||||
$token = $token['access_token'];
|
||||
|
||||
SaidaService::store();
|
||||
SaidaService::post($cliente->link, $token, $ibge);
|
||||
|
||||
Log::channel('integracao-bnafar')->info('Comando executado com sucesso.', [
|
||||
'cliente' => $cliente->link,
|
||||
'origem' => 'EnviarSaidaCommand',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
} catch (Exception $error) {
|
||||
DB::rollBack();
|
||||
|
||||
Log::channel('integracao-bnafar')->error('Erro ao executar o comando', [
|
||||
'cliente' => $cliente->link ?? $cliente,
|
||||
'origem' => 'EnviarSaidaCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração BNAFAR (' . ($cliente->link ?? $cliente) . '):</strong> (Erro ao executar o comando: EnviarSaidaCommand).');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
Config::set('database.default', $currentDatabase);
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-bnafar')->error('Erro ao executar o comando', [
|
||||
'origem' => 'EnviarSaidaCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração BNAFAR:</strong> (Erro ao executar o comando: EnviarSaidaCommand).');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Bnafar;
|
||||
|
||||
use App\Enums\Intranet\Sistema;
|
||||
use App\Models\Intranet\Cliente;
|
||||
use App\Services\Integracao\Bnafar\PosicaoEstoqueService;
|
||||
use App\Services\Integracao\BnafarService;
|
||||
use App\Services\Telegram\TelegramService;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class VerificarPosicaoEstoqueCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:bnafar-verificar-posicao-estoque';
|
||||
protected $description = 'Comando para verificação de posição de estoque enviada ao BNAFAR.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
try {
|
||||
$currentDatabase = Config::get('database.default');
|
||||
|
||||
self::getClientes()->each(function($cliente) {
|
||||
DB::beginTransaction();
|
||||
|
||||
try {
|
||||
$cliente = Cliente::where('link', $cliente)
|
||||
->where('sistema_id', Sistema::CONECTASUS)
|
||||
->firstOrFail();
|
||||
|
||||
$ibge = substr($cliente->municipio->ibge, 0, 6);
|
||||
|
||||
Config::set('database.default', $cliente->link);
|
||||
|
||||
$parametrizacao = BnafarService::getParametrizacao();
|
||||
|
||||
if (!is_null($parametrizacao)) {
|
||||
$token = BnafarService::getToken($parametrizacao->usuario, $parametrizacao->senha);
|
||||
|
||||
if (!is_null($token)) {
|
||||
$token = $token['access_token'];
|
||||
|
||||
PosicaoEstoqueService::check($cliente->link, $token, $ibge);
|
||||
|
||||
Log::channel('integracao-bnafar')->info('Comando executado com sucesso.', [
|
||||
'cliente' => $cliente->link,
|
||||
'origem' => 'VerificarPosicaoEstoqueCommand',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
} catch (Exception $error) {
|
||||
DB::rollBack();
|
||||
|
||||
Log::channel('integracao-bnafar')->error('Erro ao executar o comando', [
|
||||
'cliente' => $cliente->link ?? $cliente,
|
||||
'origem' => 'VerificarPosicaoEstoqueCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração BNAFAR (' . ($cliente->link ?? $cliente) . '):</strong> (Erro ao executar o comando: VerificarPosicaoEstoqueCommand).');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
Config::set('database.default', $currentDatabase);
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-bnafar')->error('Erro ao executar o comando', [
|
||||
'origem' => 'VerificarPosicaoEstoqueCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração BNAFAR:</strong> (Erro ao executar o comando: VerificarPosicaoEstoqueCommand).');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Bnafar;
|
||||
|
||||
use App\Enums\Intranet\Sistema;
|
||||
use App\Models\Intranet\Cliente;
|
||||
use App\Services\Integracao\Bnafar\SaidaService;
|
||||
use App\Services\Integracao\BnafarService;
|
||||
use App\Services\Telegram\TelegramService;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class VerificarSaidaCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:bnafar-verificar-saida';
|
||||
protected $description = 'Comando para verificação de saida enviada ao BNAFAR.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
try {
|
||||
$currentDatabase = Config::get('database.default');
|
||||
|
||||
self::getClientes()->each(function($cliente) {
|
||||
DB::beginTransaction();
|
||||
|
||||
try {
|
||||
$cliente = Cliente::where('link', $cliente)
|
||||
->where('sistema_id', Sistema::CONECTASUS)
|
||||
->firstOrFail();
|
||||
|
||||
$ibge = substr($cliente->municipio->ibge, 0, 6);
|
||||
|
||||
Config::set('database.default', $cliente->link);
|
||||
|
||||
$parametrizacao = BnafarService::getParametrizacao();
|
||||
|
||||
if (!is_null($parametrizacao)) {
|
||||
$token = BnafarService::getToken($parametrizacao->usuario, $parametrizacao->senha);
|
||||
|
||||
if (!is_null($token)) {
|
||||
$token = $token['access_token'];
|
||||
|
||||
SaidaService::check($cliente->link, $token, $ibge);
|
||||
|
||||
Log::channel('integracao-bnafar')->info('Comando executado com sucesso.', [
|
||||
'cliente' => $cliente->link,
|
||||
'origem' => 'VerificarSaidaCommand',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
DB::commit();
|
||||
} catch (Exception $error) {
|
||||
DB::rollBack();
|
||||
|
||||
Log::channel('integracao-bnafar')->error('Erro ao executar o comando', [
|
||||
'cliente' => $cliente->link ?? $cliente,
|
||||
'origem' => 'VerificarSaidaCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração BNAFAR (' . ($cliente->link ?? $cliente) . '):</strong> (Erro ao executar o comando: VerificarSaidaCommand).');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
Config::set('database.default', $currentDatabase);
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-bnafar')->error('Erro ao executar o comando', [
|
||||
'origem' => 'VerificarSaidaCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração BNAFAR:</strong> (Erro ao executar o comando: VerificarSaidaCommand).');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Erpsaude;
|
||||
|
||||
use App\Enums\Intranet\Sistema;
|
||||
use App\Models\Integracao\Erpsaude\Atendimento as ErpsaudeAtendimento;
|
||||
use App\Models\Integracao\Erpsaude\Exame as ErpsaudeExame;
|
||||
use App\Models\Integracao\Erpsaude\Medicamento;
|
||||
use App\Models\Integracao\Erpsaude\Paciente as ErpsaudePaciente;
|
||||
use App\Models\Integracao\Erpsaude\Reavaliacao;
|
||||
use App\Models\Integracao\Erpsaude\TipoAlta;
|
||||
use App\Models\Integracao\Erpsaude\TipoAtendimento as ErpsaudeTipoAtendimento;
|
||||
use App\Models\Integracao\Erpsaude\UnidadeAtendimento;
|
||||
use App\Models\Integracao\Erpsaude\UnidadeEncaminhadora;
|
||||
use App\Models\Intranet\Cliente;
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
|
||||
class BuscarAtendimentosHospitalSantaCasaCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:erpsaude-buscar-atendimentos-hospital-santa-casa';
|
||||
protected $description = 'Comando para buscar os atendimentos realizados no hospital santa casa.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
|
||||
try {
|
||||
$cliente = Cliente::where('link', 'santarita')
|
||||
->where('sistema_id', Sistema::CONECTASUS)
|
||||
->firstOrFail();
|
||||
|
||||
Config::set('database.default', $cliente->link);
|
||||
|
||||
$token = env('ERPSAUDE_ACCESS_TOKEN');
|
||||
$url = env('ERPSAUDE_ENDPOINT_URL') . "DadosPaciente";
|
||||
|
||||
$response = Http::withHeaders([
|
||||
'Authorization' => "Bearer $token"
|
||||
])->get($url);
|
||||
|
||||
$dados = $response->json();
|
||||
|
||||
if (!is_array($dados)) {
|
||||
Log::channel('integracao-erpsaude')->error('A resposta da API não retornou um array válido', [
|
||||
'cliente' => $cliente->link,
|
||||
'origem' => 'BuscarAtendimentosHospitalSantaCasaCommand',
|
||||
'dados' => $dados,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
if ($response->successful()) {
|
||||
foreach ($dados as $item) {
|
||||
|
||||
$cpf = isset($item['cpf']) ? substr(preg_replace('/\D/', '', $item['cpf']), 0, 11) : null;
|
||||
$dataNascimento = Carbon::createFromFormat('d/m/Y', $item['dataNascimento'])->format('Y-m-d');
|
||||
$cns = $item['cartaoNacionalSaude'];
|
||||
$nome = $item['paciente'];
|
||||
|
||||
$paciente = null;
|
||||
|
||||
if ($cpf) {
|
||||
$paciente = ErpsaudePaciente::where('cpf', $cpf)
|
||||
->where('nome', $nome)
|
||||
->where('data_nascimento', $dataNascimento)
|
||||
->first();
|
||||
}
|
||||
|
||||
if (!$paciente) {
|
||||
$paciente = ErpsaudePaciente::where('cns', $cns)
|
||||
->where('nome', $nome)
|
||||
->where('data_nascimento', $dataNascimento)
|
||||
->first();
|
||||
}
|
||||
|
||||
if (!$paciente) {
|
||||
$paciente = ErpsaudePaciente::create([
|
||||
'nome' => $nome,
|
||||
'cpf' => $cpf,
|
||||
'cns' => $cns,
|
||||
'data_nascimento' => $dataNascimento,
|
||||
'sexo' => $item['sexo'],
|
||||
'cep' => isset($item['cep']) ? preg_replace('/\D/', '', $item['cep']) : null,
|
||||
]);
|
||||
} else {
|
||||
|
||||
$paciente->update([
|
||||
'nome' => $nome,
|
||||
'cpf' => $cpf,
|
||||
'cns' => $cns,
|
||||
'data_nascimento' => $dataNascimento,
|
||||
'sexo' => $item['sexo'],
|
||||
'cep' => isset($item['cep']) ? preg_replace('/\D/', '', $item['cep']) : null,
|
||||
]);
|
||||
}
|
||||
|
||||
$tipoAlta = TipoAlta::where('codigo', $item['codTipoAlta'])->first();
|
||||
$tipoAtendimento = ErpsaudeTipoAtendimento::where('codigo', (int) $item['codTipoAtendimento'])->first();
|
||||
$unidadeEncaminhadora = UnidadeEncaminhadora::where('codigo', (int) $item['codUnEncaminhadora'])->first();
|
||||
$unidadeAtendimento = UnidadeAtendimento::where('codigo', (int) $item['codUnAtendimento'])->first();
|
||||
|
||||
$atendimento = ErpsaudeAtendimento::create([
|
||||
'paciente_id' => $paciente->id,
|
||||
'registro_paciente' => $item['registroPaciente'],
|
||||
'data' => Carbon::createFromFormat('d/m/Y', $item['data'])->format('Y-m-d'),
|
||||
'hora' => $item['hora'],
|
||||
'suspeita_maus_tratos' => $item['suspeitaMausTratos'],
|
||||
'hipotese_diagnostica' => $item['hipoteseDiagnostica'],
|
||||
'cid10' => $item['cid10'],
|
||||
'descricao_procedimento' => $item['descricaoProcedimento'],
|
||||
'descricao_exame_clinico' => $item['descricaoExameClinico'],
|
||||
'conduta_medica' => $item['condutaMedica'],
|
||||
'codigo_conta_prof' => $item['codigoContaProf'],
|
||||
'profissional' => $item['profissional'],
|
||||
'conselho' => $item['conselho'],
|
||||
'uf_conselho' => $item['ufConselho'],
|
||||
'convenio' => $item['convenio'],
|
||||
'registro_ans' => $item['registroAns'],
|
||||
'cod_convenio' => $item['codConvenio'],
|
||||
'nome_setor' => $item['nomeSetor'],
|
||||
'codigo_setor' => $item['codigoSetor'],
|
||||
'cod_tipo_encaminhamento' => $item['codTipoEncaminhamento'],
|
||||
'tipo_atendimento_id' => $tipoAtendimento ? $tipoAtendimento->id : null,
|
||||
'cod_grupo_atendimento' => $item['codGrupoAtendimento'],
|
||||
'unidade_encaminhadora_id' => $unidadeEncaminhadora ? $unidadeEncaminhadora->id : null,
|
||||
'unidade_atendimento_id' => $unidadeAtendimento ? $unidadeAtendimento->id : null,
|
||||
'data_atendimento' => Carbon::createFromFormat('d/m/Y', $item['dataAtendimento'])->format('Y-m-d'),
|
||||
'data_alta' => !empty($item['dataAlta']) && preg_match('/^\d{2}\/\d{2}\/\d{4}$/', $item['dataAlta'])
|
||||
? Carbon::createFromFormat('d/m/Y', $item['dataAlta'])->format('Y-m-d')
|
||||
: null,
|
||||
'horario_atendimento' => $item['horarioAtendimento'],
|
||||
'hora_alta' => isset($item['horaAlta']) && trim($item['horaAlta']) !== '' ? $item['horaAlta'] : null,
|
||||
'tipo_alta_id' => $tipoAlta ? $tipoAlta->id : null,
|
||||
'unidade_atendimento' => $item['unAtendimento'],
|
||||
'cnes_un_atendimento' => $item['cnesUnAtendimento'],
|
||||
]);
|
||||
|
||||
if (!empty($item['reavaliacoes'])) {
|
||||
foreach ($item['reavaliacoes'] as $reavaliacao) {
|
||||
|
||||
Reavaliacao::create([
|
||||
'atendimento_id' => $atendimento->id,
|
||||
'reavaliacao' => $reavaliacao['reavalicao'],
|
||||
'profissional' => $reavaliacao['profissional'],
|
||||
'numero_conselho' => $reavaliacao['numConselho'],
|
||||
'uf_conselho' => $reavaliacao['ufConselho'],
|
||||
'data' => Carbon::createFromFormat('d/m/Y', $reavaliacao['dataReavaliacao'])->format('Y-m-d'),
|
||||
'hora' => $reavaliacao['horaReavaliacao'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($item['medicamentos'])) {
|
||||
foreach ($item['medicamentos'] as $med) {
|
||||
|
||||
Medicamento::create([
|
||||
'atendimento_id' => $atendimento->id,
|
||||
'medicamento' => $med['medicamento'],
|
||||
'quantidade' => str_replace(',', '.', $med['qtdePresc']),
|
||||
'unidade_medida' => $med['uniMedPresc'],
|
||||
'medicamento_id' => $med['idMedicamento'],
|
||||
'tipo' => $med['tipo'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($item['exames'])) {
|
||||
foreach ($item['exames'] as $exame) {
|
||||
|
||||
ErpsaudeExame::create([
|
||||
'atendimento_id' => $atendimento->id,
|
||||
'exame' => $exame['descricao'] ?? '',
|
||||
'tipo' => $exame['tipo'] ?? '',
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Log::channel('integracao-erpsaude')->info('Comando executado com sucesso.', [
|
||||
'cliente' => $cliente->link,
|
||||
'origem' => 'BuscarAtendimentosHospitalSantaCasaCommand'
|
||||
]);
|
||||
}
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-erpsaude')->error('Erro ao executar o comando', [
|
||||
'cliente' => $cliente->link ?? $cliente,
|
||||
'origem' => 'BuscarAtendimentosHospitalSantaCasaCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
151
api/app/Console/Commands/Integracao/Esus/EnviarCommand.php
Normal file
151
api/app/Console/Commands/Integracao/Esus/EnviarCommand.php
Normal file
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Esus;
|
||||
|
||||
use App\Models\Integracao\Esus\Parametrizacao;
|
||||
use App\Services\AtencaoBasica\Exportacao\ExportacaoService;
|
||||
use App\Services\Integracao\EsusService;
|
||||
use App\Services\Telegram\TelegramService;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EnviarCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:esus-enviar';
|
||||
protected $description = 'Comando para envio de fichas ao e-SUS.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
$currentDatabase = Config::get('database.default');
|
||||
$mesAnoInicial = '072025';
|
||||
|
||||
try {
|
||||
|
||||
self::getClientes()->each(function($cliente) use($mesAnoInicial) {
|
||||
try {
|
||||
|
||||
Config::set('database.default', $cliente);
|
||||
|
||||
$parametrizacao = Parametrizacao::first();
|
||||
|
||||
if (!($parametrizacao->ativo ?? false)) {
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$parametrizacao->url_instalacao = trim($parametrizacao->url_instalacao, '/');
|
||||
|
||||
try {
|
||||
|
||||
EsusService::getAuthorizationCookie($parametrizacao);
|
||||
|
||||
} catch (Exception $e) {
|
||||
|
||||
Log::channel('integracao-esus')->error('Falha na conexão.', [
|
||||
'cliente' => $cliente,
|
||||
'origem' => 'EnviarCommand',
|
||||
'erro' => 'Exportação não realizada (falha no cookie inicial)',
|
||||
]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (ExportacaoService::gerarExportacoes($mesAnoInicial) as $nomeFicha => $fichas) {
|
||||
|
||||
$parametrizacao->cookie = EsusService::getAuthorizationCookie($parametrizacao);
|
||||
|
||||
try {
|
||||
|
||||
EsusService::deleteInconsistencias($cliente, $nomeFicha);
|
||||
|
||||
foreach ($fichas as $ficha) {
|
||||
|
||||
try {
|
||||
|
||||
EsusService::sendFicha($cliente, $parametrizacao, $nomeFicha, $ficha);
|
||||
}
|
||||
catch (Exception $error) {
|
||||
|
||||
Log::channel('integracao-esus')->error('Erro ao executar o comando', [
|
||||
'cliente' => $cliente,
|
||||
'origem' => 'EnviarCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração ESUS (' . $cliente . '):</strong> (Erro ao executar o comando: EnviarCommand).');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception $error) {
|
||||
|
||||
Log::channel('integracao-esus')->error('Erro ao executar o comando', [
|
||||
'cliente' => $cliente,
|
||||
'origem' => 'EnviarCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração ESUS (' . $cliente . '):</strong> (Erro ao executar o comando: EnviarCommand).');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Log::channel('integracao-esus')->info('Comando executado com sucesso.', [
|
||||
'cliente' => $cliente,
|
||||
'origem' => 'EnviarCommand'
|
||||
]);
|
||||
}
|
||||
catch (Exception $error) {
|
||||
|
||||
Log::channel('integracao-esus')->error('Erro ao executar o comando', [
|
||||
'cliente' => $cliente,
|
||||
'origem' => 'EnviarCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração ESUS (' . $cliente . '):</strong> (Erro ao executar o comando: EnviarCommand).');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception $error) {
|
||||
|
||||
Log::channel('integracao-esus')->error('Erro ao executar o comando', [
|
||||
'origem' => 'EnviarCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração ESUS:</strong> (Erro ao executar o comando: EnviarCommand).');
|
||||
}
|
||||
}
|
||||
|
||||
Config::set('database.default', $currentDatabase);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Ria;
|
||||
|
||||
use App\Enums\Intranet\Sistema;
|
||||
use App\Models\Integracao\Ria\DocumentoImunologicoRotina;
|
||||
use App\Models\Intranet\Cliente;
|
||||
use App\Services\Integracao\Ria\DocumentoImunologicoRotinaService;
|
||||
use App\Services\Integracao\RiaService;
|
||||
use App\Services\Telegram\TelegramService;
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EnviarDocumentoAlteradoCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:ria-enviar-documento-alterado';
|
||||
protected $description = 'Comando para envio de documentos alterados ao RIA.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
try {
|
||||
$currentDatabase = Config::get('database.default');
|
||||
|
||||
self::getClientes()->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($cliente, $parametrizacao, $parametrizacao->senha);
|
||||
$expiresAt = Carbon::now()->addMilliseconds($token['expires_in'])->subMinutes(2);
|
||||
|
||||
DocumentoImunologicoRotinaService::getDocumentosAlterados()
|
||||
->each(function($documentoAlterado) 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'],
|
||||
];
|
||||
|
||||
$documentoAlterado->identificador_solicitante = $parametrizacao->identificador_solicitante;
|
||||
$documentoAlterado->cns_solicitante = $parametrizacao->cns_solicitante;
|
||||
$documentoAlterado->data_hora_envio = Carbon::now();
|
||||
|
||||
$response = RiaService::sendDocumentoImunologicoRotina($headers, $documentoAlterado, $cliente->municipio->estado->uf);
|
||||
|
||||
if ($response->status() === 201) {
|
||||
$documentoAlterado->identificador_rnds = $response->header('Location') ? $response->header('Location') : null;
|
||||
$documentoAlterado->response = $response->json();
|
||||
$documentoAlterado->alterar = false;
|
||||
$documentoAlterado->atualizado = true;
|
||||
|
||||
DocumentoImunologicoRotinaService::update($documentoAlterado->documento_imunologico_rotina_id, $documentoAlterado);
|
||||
}
|
||||
else {
|
||||
DocumentoImunologicoRotina::where('id', $documentoAlterado->documento_imunologico_rotina_id)->update([
|
||||
'tentou_substituir' => true,
|
||||
]);
|
||||
|
||||
DocumentoImunologicoRotinaService::updateInconsistencias($documentoAlterado->documento_imunologico_rotina_id, $response->json());
|
||||
}
|
||||
});
|
||||
|
||||
Log::channel('integracao-ria')->info('Comando executado com sucesso.', [
|
||||
'cliente' => $cliente->link,
|
||||
'origem' => 'EnviarDocumentoAlteradoCommand'
|
||||
]);
|
||||
}
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-ria')->error('Erro ao executar o comando', [
|
||||
'cliente' => $cliente->link ?? $cliente,
|
||||
'origem' => 'EnviarDocumentoAlteradoCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração RIA (' . ($cliente->link ?? $cliente) . '):</strong> (Erro ao executar o comando: EnviarDocumentoAlteradoCommand).');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
Config::set('database.default', $currentDatabase);
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-ria')->error('Erro ao executar o comando', [
|
||||
'origem' => 'EnviarDocumentoAlteradoCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração RIA:</strong> (Erro ao executar o comando: EnviarDocumentoAlteradoCommand).');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Ria;
|
||||
|
||||
use App\Enums\Intranet\Sistema;
|
||||
use App\Models\Intranet\Cliente;
|
||||
use App\Services\Integracao\RiaService;
|
||||
use App\Services\Integracao\Ria\DocumentoImunologicoRotinaService;
|
||||
use App\Services\Telegram\TelegramService;
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EnviarDocumentoComInconsistenciaCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:ria-enviar-documento-com-inconsistencia';
|
||||
protected $description = 'Comando para envio de documentos com inconsistencia ao RIA.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
try {
|
||||
$currentDatabase = Config::get('database.default');
|
||||
|
||||
self::getClientes()->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($cliente, $parametrizacao, $parametrizacao->senha);
|
||||
$expiresAt = Carbon::now()->addMilliseconds($token['expires_in'])->subMinutes(2);
|
||||
|
||||
DocumentoImunologicoRotinaService::getDocumentosComInconsistencia()
|
||||
->each(function($documentoComInconsistencia) 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'],
|
||||
];
|
||||
|
||||
$documentoComInconsistencia->identificador_solicitante = $parametrizacao->identificador_solicitante;
|
||||
$documentoComInconsistencia->cns_solicitante = $parametrizacao->cns_solicitante;
|
||||
$documentoComInconsistencia->data_hora_envio = Carbon::now();
|
||||
|
||||
$response = RiaService::sendDocumentoImunologicoRotina($headers, $documentoComInconsistencia, $cliente->municipio->estado->uf);
|
||||
|
||||
$documentoComInconsistencia->identificador_rnds = $response->header('Location') ? $response->header('Location') : null;
|
||||
$documentoComInconsistencia->response = $response->json();
|
||||
|
||||
DocumentoImunologicoRotinaService::update($documentoComInconsistencia->documento_imunologico_rotina_id, $documentoComInconsistencia);
|
||||
});
|
||||
|
||||
Log::channel('integracao-ria')->info('Comando executado com sucesso.', [
|
||||
'cliente' => $cliente->link,
|
||||
'origem' => 'EnviarDocumentoComInconsistenciaCommand'
|
||||
]);
|
||||
}
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-ria')->error('Erro ao executar o comando', [
|
||||
'cliente' => $cliente->link ?? $cliente,
|
||||
'origem' => 'EnviarDocumentoComInconsistenciaCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração RIA (' . ($cliente->link ?? $cliente) . '):</strong> (Erro ao executar o comando: EnviarDocumentoComInconsistenciaCommand).');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
Config::set('database.default', $currentDatabase);
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-ria')->error('Erro ao executar o comando', [
|
||||
'origem' => 'EnviarDocumentoComInconsistenciaCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração RIA:</strong> (Erro ao executar o comando: EnviarDocumentoComInconsistenciaCommand).');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Ria;
|
||||
|
||||
use App\Enums\Intranet\Sistema;
|
||||
use App\Models\Intranet\Cliente;
|
||||
use App\Services\Integracao\RiaService;
|
||||
use App\Services\Integracao\Ria\DocumentoImunologicoRotinaService;
|
||||
use App\Services\Telegram\TelegramService;
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EnviarDocumentoComInconsistenciaRetroativoCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:ria-enviar-documento-com-inconsistencia-retroativo';
|
||||
protected $description = 'Comando para envio de documentos com inconsistencia retroativos ao RIA.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
try {
|
||||
$currentDatabase = Config::get('database.default');
|
||||
|
||||
self::getClientes()->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::getDocumentosComInconsistenciaRetroativos()
|
||||
->each(function($documentoComInconsistenciaRetroativo) 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'],
|
||||
];
|
||||
|
||||
$documentoComInconsistenciaRetroativo->identificador_solicitante = $parametrizacao->identificador_solicitante;
|
||||
$documentoComInconsistenciaRetroativo->cns_solicitante = $parametrizacao->cns_solicitante;
|
||||
$documentoComInconsistenciaRetroativo->data_hora_envio = Carbon::now();
|
||||
|
||||
$response = RiaService::sendDocumentoImunologicoRotina($headers, $documentoComInconsistenciaRetroativo, $cliente->municipio->estado->uf);
|
||||
|
||||
$documentoComInconsistenciaRetroativo->identificador_rnds = $response->header('Location') ? $response->header('Location') : null;
|
||||
$documentoComInconsistenciaRetroativo->response = $response->json();
|
||||
|
||||
DocumentoImunologicoRotinaService::update($documentoComInconsistenciaRetroativo->documento_imunologico_rotina_id, $documentoComInconsistenciaRetroativo);
|
||||
});
|
||||
|
||||
Log::channel('integracao-ria')->info('Comando executado com sucesso.', [
|
||||
'cliente' => $cliente->link,
|
||||
'origem' => 'EnviarDocumentoComInconsistenciaRetroativoCommand'
|
||||
]);
|
||||
}
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-ria')->error('Erro ao executar o comando', [
|
||||
'cliente' => $cliente->link ?? $cliente,
|
||||
'origem' => 'EnviarDocumentoComInconsistenciaRetroativoCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração RIA (' . ($cliente->link ?? $cliente) . '):</strong> (Erro ao executar o comando: EnviarDocumentoComInconsistenciaRetroativoCommand).');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
Config::set('database.default', $currentDatabase);
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-ria')->error('Erro ao executar o comando', [
|
||||
'origem' => 'EnviarDocumentoComInconsistenciaRetroativoCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração RIA:</strong> (Erro ao executar o comando: EnviarDocumentoComInconsistenciaRetroativoCommand).');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Ria;
|
||||
|
||||
use App\Enums\Intranet\Sistema;
|
||||
use App\Models\Integracao\Ria\DocumentoImunologicoRotina;
|
||||
use App\Models\Intranet\Cliente;
|
||||
use App\Services\Integracao\RiaService;
|
||||
use App\Services\Integracao\Ria\DocumentoImunologicoRotinaService;
|
||||
use App\Services\Telegram\TelegramService;
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EnviarExclusaoDocumentoCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:ria-enviar-exclusao-documento';
|
||||
protected $description = 'Comando para envio de exclusão de documentos ao RIA.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
try {
|
||||
$currentDatabase = Config::get('database.default');
|
||||
|
||||
self::getClientes()->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('<strong>Integração RIA (' . ($cliente->link ?? $cliente) . '):</strong> (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('<strong>Integração RIA:</strong> (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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Ria;
|
||||
|
||||
use App\Enums\Intranet\Sistema;
|
||||
use App\Models\Intranet\Cliente;
|
||||
use App\Services\Integracao\RiaService;
|
||||
use App\Services\Integracao\Ria\DocumentoImunologicoRotinaService;
|
||||
use App\Services\Telegram\TelegramService;
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EnviarRegistroAplicacaoCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:ria-enviar-registro-aplicacao';
|
||||
protected $description = 'Comando para envio de novos registros de aplicação ao RIA.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
try {
|
||||
$currentDatabase = Config::get('database.default');
|
||||
|
||||
self::getClientes()->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::getRegistrosAplicacao()
|
||||
->each(function($registroAplicacao) 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'],
|
||||
];
|
||||
|
||||
$registroAplicacao->identificador_solicitante = $parametrizacao->identificador_solicitante;
|
||||
$registroAplicacao->cns_solicitante = $parametrizacao->cns_solicitante;
|
||||
$registroAplicacao->data_hora_envio = Carbon::now();
|
||||
|
||||
$response = RiaService::sendDocumentoImunologicoRotina($headers, $registroAplicacao, $cliente->municipio->estado->uf);
|
||||
|
||||
$registroAplicacao->identificador_rnds = $response->header('Location') ? $response->header('Location') : null;
|
||||
$registroAplicacao->response = $response->json();
|
||||
|
||||
DocumentoImunologicoRotinaService::store($registroAplicacao);
|
||||
});
|
||||
|
||||
Log::channel('integracao-ria')->info('Comando executado com sucesso.', [
|
||||
'cliente' => $cliente->link,
|
||||
'origem' => 'EnviarRegistroAplicacaoCommand',
|
||||
]);
|
||||
}
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-ria')->error('Erro ao executar o comando', [
|
||||
'cliente' => $cliente->link ?? $cliente,
|
||||
'origem' => 'EnviarRegistroAplicacaoCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração RIA (' . ($cliente->link ?? $cliente) . '):</strong> (Erro ao executar o comando: EnviarRegistroAplicacaoCommand).');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
Config::set('database.default', $currentDatabase);
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-ria')->error('Erro ao executar o comando', [
|
||||
'origem' => 'EnviarRegistroAplicacaoCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração RIA:</strong> (Erro ao executar o comando: EnviarRegistroAplicacaoCommand).');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Ria;
|
||||
|
||||
use App\Enums\Intranet\Sistema;
|
||||
use App\Models\Intranet\Cliente;
|
||||
use App\Services\Integracao\RiaService;
|
||||
use App\Services\Integracao\Ria\DocumentoImunologicoRotinaService;
|
||||
use App\Services\Telegram\TelegramService;
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EnviarRegistroAplicacaoRetroativoCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:ria-enviar-registro-aplicacao-retroativo';
|
||||
protected $description = 'Comando para envio de registros de aplicação retroativos ao RIA.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
try {
|
||||
$currentDatabase = Config::get('database.default');
|
||||
|
||||
self::getClientes()->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::getRegistrosAplicacaoRetroativos()
|
||||
->each(function($registroAplicacaoRetroativo) 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'],
|
||||
];
|
||||
|
||||
$registroAplicacaoRetroativo->identificador_solicitante = $parametrizacao->identificador_solicitante;
|
||||
$registroAplicacaoRetroativo->cns_solicitante = $parametrizacao->cns_solicitante;
|
||||
$registroAplicacaoRetroativo->data_hora_envio = Carbon::now();
|
||||
|
||||
$response = RiaService::sendDocumentoImunologicoRotina($headers, $registroAplicacaoRetroativo, $cliente->municipio->estado->uf);
|
||||
|
||||
$registroAplicacaoRetroativo->identificador_rnds = $response->header('Location') ? $response->header('Location') : null;
|
||||
$registroAplicacaoRetroativo->response = $response->json();
|
||||
|
||||
DocumentoImunologicoRotinaService::store($registroAplicacaoRetroativo);
|
||||
});
|
||||
|
||||
Log::channel('integracao-ria')->info('Comando executado com sucesso.', [
|
||||
'cliente' => $cliente->link,
|
||||
'origem' => 'EnviarRegistroAplicacaoRetroativoCommand'
|
||||
]);
|
||||
}
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-ria')->error('Erro ao executar o comando', [
|
||||
'cliente' => $cliente->link ?? $cliente,
|
||||
'origem' => 'EnviarRegistroAplicacaoRetroativoCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração RIA (' . ($cliente->link ?? $cliente) . '):</strong> (Erro ao executar o comando: EnviarRegistroAplicacaoRetroativoCommand).');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
Config::set('database.default', $currentDatabase);
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-ria')->error('Erro ao executar o comando', [
|
||||
'origem' => 'EnviarRegistroAplicacaoRetroativoCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração RIA:</strong> (Erro ao executar o comando: EnviarRegistroAplicacaoRetroativoCommand).');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Ria;
|
||||
|
||||
use App\Enums\Intranet\Sistema;
|
||||
use App\Models\Intranet\Cliente;
|
||||
use App\Services\Integracao\RiaService;
|
||||
use App\Services\Integracao\Ria\DocumentoImunologicoRotinaService;
|
||||
use App\Services\Telegram\TelegramService;
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EnviarRegistroAtualizacaoCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:ria-enviar-registro-atualizacao';
|
||||
protected $description = 'Comando para envio de novos registros de atulaização ao RIA.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
try {
|
||||
$currentDatabase = Config::get('database.default');
|
||||
|
||||
self::getClientes()->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('<strong>Integração RIA (' . ($cliente->link ?? $cliente) . '):</strong> (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('<strong>Integração RIA:</strong> (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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Ria;
|
||||
|
||||
use App\Enums\Intranet\Sistema;
|
||||
use App\Models\Intranet\Cliente;
|
||||
use App\Services\Integracao\RiaService;
|
||||
use App\Services\Integracao\Ria\DocumentoImunologicoRotinaService;
|
||||
use App\Services\Telegram\TelegramService;
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EnviarRegistroAtualizacaoRetroativoCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:ria-enviar-registro-atualizacao-retroativo';
|
||||
protected $description = 'Comando para envio de registros de atualização retroativos ao RIA.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
try {
|
||||
$currentDatabase = Config::get('database.default');
|
||||
|
||||
self::getClientes()->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::getRegistrosAtualizacaoRetroativos()
|
||||
->each(function($registroAtualizacaoRetroativo) 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'],
|
||||
];
|
||||
|
||||
$registroAtualizacaoRetroativo->identificador_solicitante = $parametrizacao->identificador_solicitante;
|
||||
$registroAtualizacaoRetroativo->cns_solicitante = $parametrizacao->cns_solicitante;
|
||||
$registroAtualizacaoRetroativo->data_hora_envio = Carbon::now();
|
||||
|
||||
$response = RiaService::sendDocumentoImunologicoRotina($headers, $registroAtualizacaoRetroativo, $cliente->municipio->estado->uf);
|
||||
|
||||
$registroAtualizacaoRetroativo->identificador_rnds = $response->header('Location') ? $response->header('Location') : null;
|
||||
$registroAtualizacaoRetroativo->response = $response->json();
|
||||
|
||||
DocumentoImunologicoRotinaService::store($registroAtualizacaoRetroativo);
|
||||
});
|
||||
|
||||
Log::channel('integracao-ria')->info('Comando executado com sucesso.', [
|
||||
'cliente' => $cliente->link,
|
||||
'origem' => 'EnviarRegistroAtualizacaoRetroativoCommand'
|
||||
]);
|
||||
}
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-ria')->error('Erro ao executar o comando', [
|
||||
'cliente' => $cliente->link ?? $cliente,
|
||||
'origem' => 'EnviarRegistroAtualizacaoRetroativoCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração RIA (' . ($cliente->link ?? $cliente) . '):</strong> (Erro ao executar o comando: EnviarRegistroAtualizacaoRetroativoCommand).');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
Config::set('database.default', $currentDatabase);
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-ria')->error('Erro ao executar o comando', [
|
||||
'origem' => 'EnviarRegistroAtualizacaoRetroativoCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração RIA:</strong> (Erro ao executar o comando: EnviarRegistroAtualizacaoRetroativoCommand).');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
107
api/app/Console/Commands/Integracao/Rira/EnviarCommand.php
Normal file
107
api/app/Console/Commands/Integracao/Rira/EnviarCommand.php
Normal file
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands\Integracao\Rira;
|
||||
|
||||
use App\Models\Intranet\Cliente;
|
||||
use App\Services\Integracao\Rira\DocumentoService;
|
||||
use App\Services\Integracao\RiraService;
|
||||
use App\Services\Telegram\TelegramService;
|
||||
use Carbon\Carbon;
|
||||
use Exception;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Config;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EnviarCommand extends Command
|
||||
{
|
||||
protected $signature = 'integracao:rira-enviar';
|
||||
protected $description = 'Comando para envio de solicitações ao RIRA.';
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct();
|
||||
}
|
||||
|
||||
public function handle()
|
||||
{
|
||||
$currentDatabase = Config::get('database.default');
|
||||
|
||||
try {
|
||||
self::getClientes()->each(function($cliente) {
|
||||
Config::set('database.default', $cliente);
|
||||
|
||||
$clienteModel = Cliente::where('link', $cliente)->where('sistema_id', 1)->firstOrFail();
|
||||
$parametrizacao = RiraService::getParametrizacao();
|
||||
|
||||
if (!is_null($parametrizacao)) {
|
||||
$token = RiraService::getToken($parametrizacao, $parametrizacao->senha);
|
||||
$expiresAt = Carbon::now()->addMilliseconds($token['expires_in'])->subMinutes(2);
|
||||
|
||||
DocumentoService::getSolicitacoes()
|
||||
->each(function($solicitacao) use ($parametrizacao, &$token, $expiresAt, $clienteModel) {
|
||||
if (Carbon::now() >= $expiresAt) {
|
||||
$token = RiraService::getToken($parametrizacao->senha);
|
||||
}
|
||||
|
||||
$headers = [
|
||||
'Authorization' => $parametrizacao->cns_solicitante,
|
||||
'Content-Type' => 'application/json',
|
||||
'X-Authorization-Server' => "Bearer " . $token['access_token'],
|
||||
];
|
||||
|
||||
$solicitacao->identificador_solicitante = $parametrizacao->identificador_solicitante;
|
||||
$solicitacao->cns_solicitante = $parametrizacao->cns_solicitante;
|
||||
$solicitacao->data_hora_envio = Carbon::now();
|
||||
|
||||
$response = RiraService::send($clienteModel, $headers, $solicitacao);
|
||||
|
||||
$urlRnds = null;
|
||||
$identificadorRnds = null;
|
||||
|
||||
if (!empty($response->header('Location'))) {
|
||||
$urlRnds = $response->header('Location');
|
||||
$urlRndsExploded = explode('/', $urlRnds);
|
||||
$identificadorRnds = $urlRndsExploded[count($urlRndsExploded) - 1];
|
||||
}
|
||||
|
||||
$solicitacao->url_rnds = $urlRnds;
|
||||
$solicitacao->identificador_rnds = $identificadorRnds;
|
||||
$solicitacao->response = $response->json();
|
||||
|
||||
DocumentoService::save($solicitacao);
|
||||
});
|
||||
|
||||
Log::channel('integracao-rira')->info('Comando executado com sucesso.', [
|
||||
'cliente' => $cliente,
|
||||
'origem' => 'EnviarCommand'
|
||||
]);
|
||||
}
|
||||
});
|
||||
} catch (Exception $error) {
|
||||
Log::channel('integracao-rira')->error('Erro ao executar o comando', [
|
||||
'origem' => 'EnviarCommand',
|
||||
'erro' => $error->getMessage(),
|
||||
]);
|
||||
|
||||
if (env('APP_ENV') === 'production') {
|
||||
TelegramService::send('<strong>Integração RIRA:</strong> (Erro ao executar o comando: EnviarCommand).');
|
||||
}
|
||||
}
|
||||
|
||||
Config::set('database.default', $currentDatabase);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user