Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
51.72% covered (warning)
51.72%
15 / 29
60.00% covered (warning)
60.00%
3 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
AbstractSendgridJob
51.72% covered (warning)
51.72%
15 / 29
60.00% covered (warning)
60.00%
3 / 5
24.61
0.00% covered (danger)
0.00%
0 / 1
 middleware
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 buildMail
n/a
0 / 0
n/a
0 / 0
0
 logLabel
n/a
0 / 0
n/a
0 / 0
0
 gateBucket
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 gateCompanyId
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 handle
38.10% covered (danger)
38.10%
8 / 21
0.00% covered (danger)
0.00%
0 / 1
18.62
 failed
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3namespace App\Jobs\Email;
4
5use App\Services\SendgridDispatcher;
6use App\Services\SendgridLogger;
7use Illuminate\Bus\Queueable;
8use Illuminate\Contracts\Queue\ShouldQueue;
9use Illuminate\Foundation\Bus\Dispatchable;
10use Illuminate\Queue\InteractsWithQueue;
11use Illuminate\Queue\Middleware\RateLimited;
12use Illuminate\Queue\SerializesModels;
13use Illuminate\Support\Facades\Log;
14use SendGrid\Mail\Mail;
15
16/**
17 * FIRE-1147: base class for all SendGrid sends that used to run synchronously
18 * inside HTTP request handlers (approve/reject/follow-up email).
19 *
20 * Subclasses implement buildMail() — the same template-construction code that
21 * used to live inline in Quotations.php / Notifications.php — and this base
22 * handles the boilerplate: client instantiation, response logging via
23 * SendgridLogger (preserving the existing tbl_sendgrid_outbound_log audit
24 * trail), retry policy, and dead-letter logging.
25 *
26 * Retries: 5 attempts with exponential backoff. Final failure lands in
27 * `failed_jobs` (Laravel built-in) plus an explicit error log line.
28 *
29 * Rate limit: shared 'sendgrid' bucket across all subclasses so we don't
30 * burst past SendGrid's per-account limit during peak approval traffic.
31 */
32abstract class AbstractSendgridJob implements ShouldQueue
33{
34    use Dispatchable;
35    use InteractsWithQueue;
36    use Queueable;
37    use SerializesModels;
38
39    public int $tries = 5;
40
41    /** Exponential backoff in seconds: 10s, 30s, 1m, 5m, 15m. */
42    public array $backoff = [10, 30, 60, 300, 900];
43
44    public int $timeout = 60;
45
46    public function middleware(): array
47    {
48        return [new RateLimited('sendgrid')];
49    }
50
51    /**
52     * Subclasses build and return the SendGrid Mail message.
53     * Return null to skip the send entirely (e.g. no recipients to notify).
54     */
55    abstract protected function buildMail(): ?Mail;
56
57    /**
58     * A human-readable label included in SendgridLogger entries so the
59     * audit log shows which controller path originally triggered the send.
60     */
61    abstract protected function logLabel(): string;
62
63    /**
64     * FIRE-1930 kill-switch bucket (SendgridDispatcher::BUCKET_*) this job
65     * belongs to, or null for sends outside the four buckets. When set,
66     * the send goes through SendgridDispatcher and is skipped unless the
67     * bucket is enabled for gateCompanyId().
68     */
69    protected function gateBucket(): ?string
70    {
71        return null;
72    }
73
74    protected function gateCompanyId(): ?int
75    {
76        return null;
77    }
78
79    public function handle(): void
80    {
81        $email = $this->buildMail();
82        if ($email === null) {
83            return;
84        }
85
86        $bucket = $this->gateBucket();
87        if ($bucket !== null) {
88            // Gated sends return null and are logged as GATED: by the
89            // dispatcher; SDK exceptions are logged there and rethrown so
90            // the queue retry policy still applies.
91            $response = SendgridDispatcher::send($email, $bucket, $this->gateCompanyId(), $this->logLabel());
92
93            if ($response !== null && $response->statusCode() >= 400) {
94                throw new \RuntimeException(
95                    'SendGrid '.$response->statusCode().': '.$response->body()
96                );
97            }
98
99            return;
100        }
101
102        $sendgrid = new \SendGrid(config('services.sendgrid.api_key'));
103
104        try {
105            $response = $sendgrid->send($email);
106            SendgridLogger::log($email, $response, $this->logLabel());
107
108            // SendGrid 4xx/5xx — let the queue retry per $tries / $backoff.
109            if ($response->statusCode() >= 400) {
110                throw new \RuntimeException(
111                    'SendGrid '.$response->statusCode().': '.$response->body()
112                );
113            }
114        } catch (\Throwable $e) {
115            // Best-effort exception log to tbl_sendgrid_outbound_log so the
116            // retry/exhaustion trail is fully recoverable from the audit table.
117            SendgridLogger::logException($email, $e, $this->logLabel());
118            throw $e;
119        }
120    }
121
122    public function failed(\Throwable $e): void
123    {
124        Log::channel('email_log')->error(static::class.' exhausted retries', [
125            'job' => static::class,
126            'label' => $this->logLabel(),
127            'error' => $e->getMessage(),
128        ]);
129    }
130}