init commit
All checks were successful
build-api-image / build (push) Successful in 51s

This commit is contained in:
Antonio Lopes dos Santos
2026-08-04 16:52:02 -03:00
commit afec302c3e
11594 changed files with 1636728 additions and 0 deletions

View File

@@ -0,0 +1,97 @@
<?php
namespace App\Console\Commands\Farmacia;
use App\Enums\Administracao\Modulo;
use App\Models\PainelSenha\Fila;
use App\Models\PainelSenha\OpcaoEntrada;
use App\Services\Administracao\ModuloService;
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 LimparFilaAtendimentoCommand extends Command
{
protected $signature = 'farmacia:limpar-fila-atendimento';
protected $description = 'Comando para limpeza da fila de atendimento no módulo farmácia.';
public function __construct()
{
parent::__construct();
}
public function handle()
{
try {
$currentDatabase = Config::get('database.default');
$this->getClientes()->each(function($cliente) {
try {
DB::beginTransaction();
Config::set('database.default', $cliente);
Fila::where('finalizado', false)
->where('evadido', false)
->whereIn('opcao_entrada_id', $this->getOpcoesEntrada())
->update([
'finalizado' => true,
'evadido' => true,
]);
Log::channel('farmacia-fila-atendimento')->info('Comando executado com sucesso.', [
'cliente' => $cliente,
'origem' => 'LimparFilaAtendimentoCommand',
]);
DB::commit();
} catch (Exception $error) {
DB::rollBack();
Log::channel('farmacia-fila-atendimento')->error('Erro ao executar o comando', [
'cliente' => $cliente,
'origem' => 'LimparFilaAtendimentoCommand',
'erro' => $error->getMessage(),
]);
if (env('APP_ENV') === 'production') {
TelegramService::send('<strong>Farmácia (' . ($cliente) . '):</strong> (Erro ao executar o comando: LimparFilaAtendimentoCommand).');
}
return;
}
});
Config::set('database.default', $currentDatabase);
} catch (Exception $error) {
Log::channel('farmacia-fila-atendimento')->error('Erro ao executar o comando', [
'origem' => 'LimparFilaAtendimentoCommand',
'erro' => $error->getMessage(),
]);
if (env('APP_ENV') === 'production') {
TelegramService::send('<strong>Farmácia:</strong> (Erro ao executar o comando: LimparFilaAtendimentoCommand).');
}
}
}
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();
}
private function getOpcoesEntrada()
{
return OpcaoEntrada::where('modulo_id', ModuloService::getId(Modulo::FARMACIA))
->pluck('id');
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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;
}
}
}

View 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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View 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();
}
}

View File

@@ -0,0 +1,96 @@
<?php
namespace App\Console\Commands\PainelSenha;
use App\Events\PainelSenha\AvisoEvent;
use App\Models\PainelSenha\AvisoAgendamento;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
class EnvioAvisoAgendadoCommand extends Command
{
protected $signature = 'painel-senha:envio-aviso-agendado';
protected $description = 'Comando para enviar os avisos que estão agendados';
public function __construct()
{
parent::__construct();
}
public function handle()
{
try {
$currentDatabase = Config::get('database.default');
self::getClientes()->each(function($cliente) {
Config::set('database.default', $cliente);
if(!Schema::hasTable('painel_senha_aviso')) {
return;
}
$agora = Carbon::now();
$toleranciaInicio = $agora->copy()->subSeconds(30);
$toleranciaFim = $agora->copy()->addSeconds(30);
$agendamentos = DB::table('painel_senha_aviso_agendamento')
->whereDate('data_hora_agendada', $agora->toDateString())
->whereBetween('data_hora_agendada', [$toleranciaInicio, $toleranciaFim])
->whereNull('data_hora_executada')
->where('painel_senha_aviso.is_ativo', true)
->join('painel_senha_aviso', 'painel_senha_aviso.id', 'painel_senha_aviso_agendamento.aviso_id')
->get();
if($agendamentos->isEmpty()) {
return;
}
$idsAgendamentos = $agendamentos->pluck("id");
$idsAvisos = $agendamentos->pluck("aviso_id");
AvisoAgendamento::whereIn('id', $idsAgendamentos)
->update(['data_hora_executada' => $agora]);
$avisos = DB::table('painel_senha_aviso')
->select(
'painel_senha_aviso.id',
'painel_senha_aviso.mensagem',
DB::raw('GROUP_CONCAT(cadastro_unidade.nome_fantasia) as unidades'),
DB::raw('GROUP_CONCAT(cadastro_unidade.id) as ids_unidade'),
'painel_senha_aviso.is_ativo',
)
->join('painel_senha_aviso_unidade', 'painel_senha_aviso_unidade.aviso_id', 'painel_senha_aviso.id')
->leftJoin('cadastro_unidade', 'cadastro_unidade.id', 'painel_senha_aviso_unidade.unidade_id')
->groupBy('painel_senha_aviso.id', 'painel_senha_aviso.mensagem', 'painel_senha_aviso.is_ativo')
->whereIn('painel_senha_aviso.id', $idsAvisos)
->get();
$avisos->map(function($aviso) {
AvisoEvent::dispatch($aviso->id, $aviso);
});
});
Config::set('database.default', $currentDatabase);
} catch (\Throwable $th) {
Log::info("Não foi possível enviar aviso {$th}");
}
}
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();
}
}

View File

@@ -0,0 +1,95 @@
<?php
namespace App\Console\Commands\PainelSenha;
use App\Enums\Administracao\Modulo;
use App\Models\PainelSenha\Fila;
use App\Models\PainelSenha\OpcaoEntrada;
use App\Services\Administracao\ModuloService;
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 LimparFilaAtendimentoCommand extends Command
{
protected $signature = 'painel-senha:limpar-fila-atendimento';
protected $description = 'Comando para limpesa da fila de atendimento no módulo painel de senha.';
public function __construct()
{
parent::__construct();
}
public function handle()
{
try {
$currentDatabase = Config::get('database.default');
$this->getClientes()->each(function($cliente) {
try {
DB::beginTransaction();
Config::set('database.default', $cliente);
Fila::where('finalizado', false)
->where('evadido', false)
->whereIn('opcao_entrada_id', $this->getOpcoesEntrada())
->update([
'finalizado' => true,
'evadido' => true,
]);
Log::channel('painel-senha-fila-atendimento')->info('Comando executado com sucesso.', [
'cliente' => $cliente,
'origem' => 'LimparFilaAtendimentoCommand',
]);
} catch (Exception $error) {
DB::rollBack();
Log::channel('painel-senha-fila-atendimento')->error('Erro ao executar o comando', [
'cliente' => $cliente,
'origem' => 'LimparFilaAtendimentoCommand',
'erro' => $error->getMessage(),
]);
if (env('APP_ENV') === 'production') {
TelegramService::send('<strong>Farmácia (' . ($cliente) . '):</strong> (Erro ao executar o comando: LimparFilaAtendimentoCommand).');
}
return;
}
});
Config::set('database.default', $currentDatabase);
} catch (Exception $error) {
Log::channel('painel-senha-fila-atendimento')->error('Erro ao executar o comando', [
'origem' => 'LimparFilaAtendimentoCommand',
'erro' => $error->getMessage(),
]);
if (env('APP_ENV') === 'production') {
TelegramService::send('<strong>Painel de senha:</strong> (Erro ao executar o comando: LimparFilaAtendimentoCommand).');
}
}
}
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();
}
private function getOpcoesEntrada()
{
return OpcaoEntrada::where('modulo_id', ModuloService::getId(Modulo::PAINEL_SENHA))
->pluck('id');
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class PublishCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'publish';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Run migrations and seeders';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$this->getCustomers()->each(function ($customer, $i) {
if ($i > 0) {
$this->getOutput()->writeln("\n");
}
$this->getOutput()->writeln("<question>{$customer}</question>");
$this->call('migrate', ['--database' => $customer, '--force' => true]);
$this->call('db:seed', ['--database' => $customer, '--force' => true]);
});
return 0;
}
private function getCustomers()
{
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) => !$this->databaseExists($config['database']))
->map(fn ($config, $customer) => $customer)
->sort()
->values();
}
private function databaseExists($databaseName)
{
return !empty(DB::connection('schema')->select(
"SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = ?",
[$databaseName]
));
}
}

View File

@@ -0,0 +1,280 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Console\ConfirmableTrait;
use Illuminate\Database\ConnectionResolverInterface as Resolver;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Symfony\Component\Console\Input\InputOption;
class SeedCommand extends Command
{
use ConfirmableTrait;
/**
* The console command name.
*
* @var string
*/
protected $name = 'db:seed';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Seed the database with records';
/**
* The connection resolver instance.
*
* @var \Illuminate\Database\ConnectionResolverInterface
*/
protected $resolver;
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* Create a new database seed command instance.
*
* @param \Illuminate\Database\ConnectionResolverInterface $resolver
* @return void
*/
public function __construct(Resolver $resolver)
{
parent::__construct();
$this->resolver = $resolver;
$this->files = new Filesystem();
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
if (! $this->confirmToProceed()) {
return 1;
}
$previousConnection = $this->resolver->getDefaultConnection();
$this->resolver->setDefaultConnection($this->getDatabase());
Schema::disableForeignKeyConstraints();
self::getSeedersClasses()->each(function ($class) {
Model::unguarded(function () use ($class) {
$this->getOutput()->writeln("<comment>Seeding:</comment> {$class['file_name']}");
$startTime = microtime(true);
$this->getSeeder(class_basename($class['instance']))->__invoke();
$runTime = number_format((microtime(true) - $startTime) * 1000, 2);
$this->getOutput()->writeln("<info>Seeded:</info> {$class['file_name']} ({$runTime}ms)");
DB::connection($this->getDatabase())->table('seeders')->insert(['seeder' => $class['file_name']]);
});
});
Schema::enableForeignKeyConstraints();
if ($previousConnection) {
$this->resolver->setDefaultConnection($previousConnection);
}
$this->info('Database seeding completed successfully.');
return 0;
}
private function getSeedersClasses()
{
$ran = DB::connection($this->getDatabase())->table('seeders')->select('seeder')->pluck('seeder')->all();
$files = $this->getSeederFiles();
$this->requireFiles($seeders = $this->pendingSeeders(
$files, $ran
));
$classes = collect();
foreach ($seeders as $file) {
$fileName = $this->getSeederName($file);
$classes->push([
'file_name' => $fileName,
'instance' => $this->resolve($fileName)
]);
}
return $classes;
}
/**
* Get all of the seeder files.
*
* @return array
*/
public function getSeederFiles()
{
return Collection::make(self::getSeederPaths())->flatMap(function ($path) {
return Str::endsWith($path, '.php') ? [$path] : $this->files->glob($path.'/*_*.php');
})->filter()->values()->keyBy(function ($file) {
return $this->getSeederName($file);
})->sortBy(function ($file, $key) {
return $key;
})->all();
}
/**
* Get seeder path.
*
* @return string
*/
protected function getSeederPaths()
{
$invalidContents = ['.', '..', '.gitkeep', 'base'];
$seedersDir = database_path() . '/seeders/';
return $this->getSeederFilesPaths(
$invalidContents,
$seedersDir
);
}
private function getSeederFilesPaths($invalidContents, $currentDirectory, $paths = [])
{
$contents = opendir($currentDirectory);
while ($content = readdir($contents)) {
if (!in_array($content, $invalidContents)) {
$fullPath = $currentDirectory . $content;
if (is_dir($fullPath)) {
$paths = $this->getSeederFilesPaths(
$invalidContents,
$fullPath . '/',
$paths
);
continue;
}
$paths[] = $fullPath;
}
}
return $paths;
}
/**
* Require in all the seeder files in a given path.
*
* @param array $files
* @return void
*/
public function requireFiles(array $files)
{
foreach ($files as $file) {
$this->files->requireOnce($file);
}
}
/**
* Resolve a seeder instance from a file.
*
* @param string $file
* @return object
*/
public function resolve($file)
{
$fileArr = explode('_', $file);
$class = Str::studly(implode('_', array_slice($fileArr, 4))).'_'.implode(array_slice($fileArr, 0, 4));
return new $class;
}
/**
* Get the name of the seeder.
*
* @param string $path
* @return string
*/
public function getSeederName($path)
{
return str_replace('.php', '', basename($path));
}
/**
* Get the seeder files that have not yet run.
*
* @param array $files
* @param array $ran
* @return array
*/
protected function pendingSeeders($files, $ran)
{
return Collection::make($files)
->reject(function ($file) use ($ran) {
return in_array($this->getSeederName($file), $ran);
})->values()->all();
}
/**
* Get a seeder instance from the container.
* @param string $class
* @return \Illuminate\Database\Seeder
*/
protected function getSeeder($class)
{
return $this->laravel->make($class)
->setContainer($this->laravel)
->setCommand($this);
}
/**
* Get the name of the database connection to use.
*
* @return string
*/
protected function getDatabase()
{
$database = $this->input->getOption('database');
return $database ?: $this->laravel['config']['database.default'];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to seed'],
['force', null, InputOption::VALUE_NONE, 'Force the operation to run when in production'],
];
}
}

View File

@@ -0,0 +1,119 @@
<?php
namespace App\Console\Commands;
use Database\Seeders\Base\Funcionalidade;
use Database\Seeders\Base\FuncionalidadeSub;
use Database\Seeders\Base\Menu;
use Database\Seeders\Base\Modulo;
use Database\Seeders\Base\Permissao;
use Illuminate\Console\Command;
use Illuminate\Database\ConnectionResolverInterface as Resolver;
use Symfony\Component\Console\Input\InputOption;
class SeedPermissionsCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'dev:seed-permissions';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Seed the database with permissions records';
/**
* The connection resolver instance.
*
* @var \Illuminate\Database\ConnectionResolverInterface
*/
protected $resolver;
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* Create a new database seed command instance.
*
* @param \Illuminate\Database\ConnectionResolverInterface $resolver
* @return void
*/
public function __construct(Resolver $resolver)
{
parent::__construct();
$this->resolver = $resolver;
}
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$previousConnection = $this->resolver->getDefaultConnection();
$this->resolver->setDefaultConnection($this->getDatabase());
collect([
Modulo::class,
Funcionalidade::class,
FuncionalidadeSub::class,
Menu::class,
Permissao::class,
])->each(function ($model) {
$this->getOutput()->writeln("<comment>Seeding:</comment> {$model}");
$startTime = microtime(true);
$model::run();
$runTime = number_format((microtime(true) - $startTime) * 1000, 2);
$this->getOutput()->writeln("<info>Seeded:</info> {$model} ({$runTime}ms)");
});
if ($previousConnection) {
$this->resolver->setDefaultConnection($previousConnection);
}
$this->info('Permissions seeding completed successfully.');
return 0;
}
/**
* Get the name of the database connection to use.
*
* @return string
*/
protected function getDatabase()
{
$database = $this->input->getOption('database');
return $database ?: $this->laravel['config']['database.default'];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['database', null, InputOption::VALUE_OPTIONAL, 'The database connection to seed'],
];
}
}

View File

@@ -0,0 +1,211 @@
<?php
namespace App\Console\Commands;
use DateTime;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Composer;
use Illuminate\Support\Str;
use InvalidArgumentException;
class SeederMakeCommand extends Command
{
/**
* The console command signature.
*
* @var string
*/
protected $signature = 'make:seeder {name : The name of the seeder}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new seeder file';
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* The Composer instance.
*
* @var \Illuminate\Support\Composer
*/
protected $composer;
/**
* Create a new seeder make command instance.
*
* @param \Illuminate\Filesystem\Filesystem $files
* @param \Illuminate\Support\Composer $composer
* @return void
*/
public function __construct(Filesystem $files, Composer $composer)
{
parent::__construct();
$this->files = $files;
$this->composer = $composer;
}
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
$name = Str::snake(trim($this->input->getArgument('name')));
$this->writeSeeder($name);
$this->composer->dumpAutoloads();
}
/**
* Write the seeder file to disk.
*
* @param string $name
* @return string
*/
protected function writeSeeder($name)
{
$file = $this->create(
$name, $this->getSeederPath()
);
$file = pathinfo($file, PATHINFO_FILENAME);
$this->line("<info>Created Seeder:</info> {$file}");
}
/**
* Get seeder path.
*
* @return string
*/
protected function getSeederPath()
{
return $this->laravel->databasePath().DIRECTORY_SEPARATOR.'seeders';
}
/**
* Create a new seeder at the given path.
*
* @param string $name
* @param string $path
* @return string
*
* @throws \Exception
*/
public function create($name, $path)
{
$dateTime = new DateTime();
$className = $this->getClassName($dateTime, $name);
$this->ensureSeederDoesntAlreadyExist($className, $path);
$stub = $this->getStub();
$path = $this->getPath($dateTime, $name, $path);
$this->files->ensureDirectoryExists(dirname($path));
$this->files->put(
$path, $this->populateStub($className, $stub)
);
return $path;
}
/**
* Ensure that a seeder with the given name doesn't already exist.
*
* @param string $name
* @param string $seederPath
* @return void
*
* @throws \InvalidArgumentException
*/
protected function ensureSeederDoesntAlreadyExist($className, $seederPath = null)
{
if (! empty($seederPath)) {
$seederFiles = $this->files->glob($seederPath.'/*.php');
foreach ($seederFiles as $seederFile) {
$this->files->requireOnce($seederFile);
}
}
if (class_exists($className)) {
throw new InvalidArgumentException("A {$className} class already exists.");
}
}
/**
* Get the seeder stub file.
*
* @return string
*/
protected function getStub()
{
$stub = $this->stubPath().'/seeder.stub';
return $this->files->get($stub);
}
/**
* Populate the place-holders in the seeder stub.
*
* @param string $className
* @param string $stub
* @return string
*/
protected function populateStub($className, $stub)
{
$stub = str_replace(
['DummyClass', '{{ class }}', '{{class}}'],
$className, $stub
);
return $stub;
}
/**
* Get the class name of a seeder name.
*
* @param string $name
* @return string
*/
protected function getClassName($dateTime, $name)
{
return Str::studly($name).'_'.$dateTime->format('YmdHis');
}
/**
* Get the full path to the seeder.
*
* @param string $name
* @param string $path
* @return string
*/
protected function getPath($dateTime, $name, $path)
{
return $path.'/'.$dateTime->format('Y_m_d_His').'_'.$name.'.php';
}
/**
* Get the path to the stubs.
*
* @return string
*/
public function stubPath()
{
return $this->laravel->basePath().'/stubs';
}
}