Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
64.71% covered (warning)
64.71%
11 / 17
50.00% covered (danger)
50.00%
1 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
ProcessNuvemshopWebhookJob
64.71% covered (warning)
64.71%
11 / 17
50.00% covered (danger)
50.00%
1 / 2
9.15
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 handle
62.50% covered (warning)
62.50%
10 / 16
0.00% covered (danger)
0.00%
0 / 1
7.90
1<?php
2
3namespace App\Jobs;
4
5use App\Enums\WebhookStatus;
6use App\Models\StoreIntegration;
7use App\Models\WebhookEvent;
8use App\Services\Nuvemshop\NuvemshopOrderService;
9use Illuminate\Contracts\Queue\ShouldQueue;
10use Illuminate\Foundation\Queue\Queueable;
11use Throwable;
12
13class ProcessNuvemshopWebhookJob implements ShouldQueue
14{
15    use Queueable;
16
17    public int $tries = 3;
18
19    public function __construct(public int $webhookEventId)
20    {
21    }
22
23    public function handle(NuvemshopOrderService $orders): void
24    {
25        $event = WebhookEvent::findOrFail($this->webhookEventId);
26
27        try {
28            $integration = $event->integration ?? StoreIntegration::query()
29                ->whereHas('provider', fn ($q) => $q->where('slug', 'nuvemshop'))
30                ->first();
31
32            if (! $integration) {
33                $event->update(['status' => WebhookStatus::Ignored->value, 'processed_at' => now(), 'error_message' => 'Integração Nuvemshop não encontrada.']);
34                return;
35            }
36
37            $payload = $event->payload ?? [];
38
39            if (str_contains($event->event, 'order') || data_get($payload, 'order') || data_get($payload, 'id')) {
40                $orders->upsertOrderFromPayload($integration, data_get($payload, 'order', $payload));
41                $event->update(['status' => WebhookStatus::Processed->value, 'processed_at' => now()]);
42                return;
43            }
44
45            $event->update(['status' => WebhookStatus::Ignored->value, 'processed_at' => now(), 'error_message' => 'Evento recebido mas ainda não implementado no MVP.']);
46        } catch (Throwable $exception) {
47            $event->update(['status' => WebhookStatus::Failed->value, 'error_message' => $exception->getMessage()]);
48            throw $exception;
49        }
50    }
51}