Skip to content

Commit d03751d

Browse files
Ataulização em migrations - correção de Erros | criação de Job para limpar tabela de Events
1 parent 3656962 commit d03751d

10 files changed

+157
-39
lines changed

.env.example

+2
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,5 @@ CASHIER_CURRENCY_LOCALE=br
7474
STRIPE_KEY=
7575
STRIPE_SECRET=
7676
STRIPE_WEBHOOK_SECRET=
77+
STRIPE_DEVICE_NAME=
78+

Dockerfile

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ RUN apt-get clean && rm -rf /var/lib/apt/lists/*
2424
# Add Node.js repository and install Node.js & NPM
2525
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
2626
apt-get install -y nodejs && \
27-
npm install -g npm@latest
27+
npm install -g npm@latest
2828

2929
# Install PHP extensions
3030
RUN docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd sockets intl zip
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?php
2+
3+
namespace App\Console\Commands;
4+
5+
use App\Jobs\CleanWebhookEventsJob;
6+
use Illuminate\Console\Command;
7+
8+
class CleanWebhookEvents extends Command
9+
{
10+
protected $signature = 'webhook:clean';
11+
protected $description = 'Limpar registros antigos da tabela webhook_events com base no período de retenção';
12+
13+
public function handle()
14+
{
15+
$retentionPeriod = config('webhook-events.retention_period');
16+
17+
CleanWebhookEventsJob::dispatch($retentionPeriod);
18+
19+
$this->info("Job de limpeza de eventos de webhook enfileirada com sucesso para registros mais antigos que {$retentionPeriod} dias.");
20+
}
21+
}

app/Console/Kernel.php

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
<?php
2+
3+
namespace App\Console;
4+
5+
use App\Console\Commands\CleanWebhookEvents;
6+
use Illuminate\Console\Scheduling\Schedule;
7+
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
8+
9+
class Kernel extends ConsoleKernel
10+
{
11+
protected function schedule(Schedule $schedule)
12+
{
13+
// Carrega as configurações de agendamento
14+
$scheduleConfig = config('webhook-events.schedule');
15+
$time = $scheduleConfig['time'];
16+
17+
// Verifica o tipo de agendamento
18+
switch ($scheduleConfig['type']) {
19+
case 'daily':
20+
// Agendamento diário
21+
$schedule->command(CleanWebhookEvents::class)->dailyAt($time);
22+
break;
23+
24+
case 'weekly_on':
25+
// Agendamento semanal
26+
$schedule->command(CleanWebhookEvents::class)->weeklyOn(
27+
$this->dayOfWeekToInteger($scheduleConfig['weekly_day']), // Chama o método aqui
28+
$time
29+
);
30+
break;
31+
32+
default:
33+
// Caso o tipo de agendamento não seja válido
34+
throw new \InvalidArgumentException("Tipo de agendamento inválido: {$scheduleConfig['type']}");
35+
}
36+
}
37+
38+
/**
39+
* Converte o dia da semana em string para o valor inteiro correspondente.
40+
*
41+
* @param string $day
42+
* @return int
43+
*/
44+
private function dayOfWeekToInteger(string $day): int
45+
{
46+
$days = [
47+
'Sunday' => 0,
48+
'Monday' => 1,
49+
'Tuesday' => 2,
50+
'Wednesday' => 3,
51+
'Thursday' => 4,
52+
'Friday' => 5,
53+
'Saturday' => 6,
54+
];
55+
56+
// Retorna o valor correspondente ou lança uma exceção se o dia for inválido
57+
return $days[$day] ?? throw new \InvalidArgumentException("Dia da semana inválido: {$day}");
58+
}
59+
60+
protected function commands()
61+
{
62+
$this->load(__DIR__ . '/Commands');
63+
}
64+
}

app/Jobs/CleanWebhookEventsJob.php

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
<?php
2+
3+
namespace App\Jobs;
4+
5+
use Carbon\Carbon;
6+
use App\Models\WebhookEvent;
7+
use Illuminate\Support\Facades\DB;
8+
use Illuminate\Support\Facades\Log;
9+
use Illuminate\Queue\SerializesModels;
10+
use Illuminate\Queue\InteractsWithQueue;
11+
use Illuminate\Foundation\Queue\Queueable;
12+
use Illuminate\Contracts\Queue\ShouldQueue;
13+
use Illuminate\Foundation\Bus\Dispatchable;
14+
15+
class CleanWebhookEventsJob implements ShouldQueue
16+
{
17+
use Queueable, InteractsWithQueue, SerializesModels, Dispatchable;
18+
19+
private int $retentionPeriod;
20+
21+
/**
22+
* Create a new job instance.
23+
*
24+
* @param int $retentionPeriod
25+
*/
26+
public function __construct(int $retentionPeriod)
27+
{
28+
$this->retentionPeriod = $retentionPeriod;
29+
}
30+
31+
/**
32+
* Execute the job.
33+
*/
34+
public function handle()
35+
{
36+
Log::info("CleanWebhookEventsJob iniciado.");
37+
38+
// Calcula a data limite com base no período de retenção
39+
$dateLimit = Carbon::now()->subDays($this->retentionPeriod);
40+
41+
// Exclui os eventos mais antigos que a data limite
42+
$deletedCount = WebhookEvent::where('created_at', '<', $dateLimit)->delete();
43+
44+
Log::info("{$deletedCount} registros excluídos.");
45+
46+
// Log para auditoria (opcional)
47+
Log::info("{$deletedCount} registros de webhook mais antigos que {$this->retentionPeriod} dias foram excluídos.");
48+
}
49+
}

app/Models/WebhookEvent.php

+1
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ class WebhookEvent extends Model
1414
'payload',
1515
'status',
1616
'received_at',
17+
'created_at',
1718
];
1819

1920

config/webhook-events.php

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
<?php
2+
3+
return [
4+
// Período de retenção para limpar registros de webhook
5+
'retention_period' => 1, // Em dias, por exemplo 2 dias
6+
7+
// Configuração de agendamento para o comando de limpeza
8+
'schedule' => [
9+
'type' => 'daily', // Tipo de agendamento: 'daily' ou 'weekly_on'
10+
'time' => '15:33', // Hora específica para o agendamento diário
11+
// Para o agendamento semanal, você pode adicionar o dia da semana
12+
// 'weekly_day' => 'Sunday', // Exemplo para agendar no domingo
13+
],
14+
];

database/migrations/2025_01_08_144505_create_subscriptions_table.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ public function up(): void
4646

4747
Schema::create('subscription_refunds', function (Blueprint $table) {
4848
$table->id();
49-
$table->foreignId(Organization::class)->constrained()->cascadeOnDelete();
49+
$table->foreignIdFor(Organization::class)->constrained()->cascadeOnDelete();
5050
$table->foreignIdFor(Subscription::class);
5151
$table->string('object')->default('refund');
5252
$table->string('refund_id')->nullable();
@@ -57,7 +57,7 @@ public function up(): void
5757
$table->string('reason');
5858
$table->timestamps();
5959

60-
$table->index(['organization_id', 'subscription_id', 'refund_id']);
60+
$table->index(['organization_id', 'subscription_id']);
6161
});
6262

6363
Schema::create('subscription_cancellations', function (Blueprint $table) {
@@ -69,7 +69,7 @@ public function up(): void
6969
$table->string('rating')->default('other');
7070
$table->timestamps();
7171

72-
$table->index(['organization_id', 'stripe_id', 'reason']);
72+
$table->index(['organization_id', 'stripe_id']);
7373
});
7474

7575
}

database/migrations/2025_01_16_142454_create_subscription_cancellations_table.php

-33
This file was deleted.

docker-compose.yml

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,11 @@ services:
2525
uid: ${UID:-1000}
2626
dockerfile: Dockerfile
2727
restart: always
28-
command: "php artisan queue:work"
28+
command: ["php", "artisan", "queue:work", "--sleep=3", "--tries=3"]
2929
volumes:
3030
- ./:/var/www
3131
depends_on:
32-
- redis
32+
- mysql
3333
networks:
3434
- tenant
3535

0 commit comments

Comments
 (0)