Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 256
0.00% covered (danger)
0.00%
0 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
ResendEmails
0.00% covered (danger)
0.00%
0 / 256
0.00% covered (danger)
0.00%
0 / 4
3422
0.00% covered (danger)
0.00%
0 / 1
 handle
0.00% covered (danger)
0.00%
0 / 155
0.00% covered (danger)
0.00%
0 / 1
1482
 isEmailValid
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getEmailBody
0.00% covered (danger)
0.00%
0 / 78
0.00% covered (danger)
0.00%
0 / 1
132
 calculateEmailRequestSize
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
56
1<?php
2
3namespace App\Console\Commands;
4
5use App\Models\TblBlockedDomains;
6use App\Models\TblCcBcc;
7use App\Models\TblCompanyEmails;
8use App\Models\TblEmailConfiguration;
9use App\Models\TblEmailFiles;
10use App\Models\TblFiles;
11use App\Models\TblQuotations;
12use App\Models\TblResendEmails;
13use App\Models\TblSendgridWebhook;
14use App\Services\SendgridDispatcher;
15use App\Services\SendgridLogger;
16use Illuminate\Console\Command;
17use Illuminate\Support\Facades\DB;
18use Illuminate\Support\Facades\Log;
19use Illuminate\Support\Facades\Storage;
20use SendGrid\Mail\Attachment;
21use SendGrid\Mail\Mail;
22
23class ResendEmails extends Command
24{
25    /**
26     * The name and signature of the console command.
27     *
28     * @var string
29     */
30    protected $signature = 'command:resend-emails {id?} {type?}';
31
32    private ?Mail $email = null;
33
34    /**
35     * The console command description.
36     *
37     * @var string
38     */
39    protected $description = 'Command description';
40
41    /**
42     * Execute the console command.
43     */
44    public function handle(): void
45    {
46
47        try {
48
49            $this->email = new Mail;
50
51            $id = $this->argument('id') ?? null;
52            $typeId = (int) ($this->argument('type') ?? 0);
53
54            $type = 'followUps';
55
56            if ($typeId == 1) {
57                $type = 'sendToClient';
58            }
59
60            if ($id !== null) {
61
62                $result = TblQuotations::where('id', $id)->first();
63
64                $emailTemplate = TblEmailConfiguration::where('type', $type)->where('is_default', 1)->get()->keyBy('company_id');
65
66                if ($result) {
67
68                    $budgetTypeId = $result->budget_type_id;
69                    $quoteId = $result->id;
70                    $commercialUser = $result->commercial;
71                    $companyId = $result->company_id;
72
73                    // FIRE-1930: retries against a region whose client
74                    // email bucket is off would defeat the kill switch.
75                    // The row stays in tbl_resend_emails so once the
76                    // switch is flipped back on the next cron picks it up.
77                    if (! SendgridDispatcher::isAllowed(
78                        SendgridDispatcher::BUCKET_CLIENT,
79                        (int) $companyId,
80                    )) {
81                        Log::channel('resend_emails')->info("ID:{$quoteId}: skipped by FIRE-1930 kill switch (company {$companyId})");
82
83                        return;
84                    }
85
86                    $emailContent = $this->getEmailBody(
87                        $emailTemplate[$companyId]->getAttribute('html'),
88                        $emailTemplate[$companyId]->getAttribute('subject'),
89                        $emailTemplate[$companyId]->getAttribute('email_template_id'),
90                        $result
91                    );
92
93                    $html = $emailContent[0];
94                    $subject = $emailContent[1];
95
96                    $blockedDomains = TblBlockedDomains::where('company_id', $result->company_id)->pluck('domain')->toArray();
97
98                    if (config('services.sendgrid.staging')) {
99                        $toEmail = 'christian@ibventur.es';
100                    } else {
101                        $toEmail = $result->email;
102                    }
103
104                    if ($toEmail != null) {
105
106                        $toEmail = explode(',', (string) $toEmail);
107                        $toEmail = array_map(trim(...), $toEmail);
108
109                        $companyEmail = null;
110
111                        $queryUsers = "SELECT 
112                                            sender_email AS from_email, 
113                                            `name` AS from_name 
114                                        FROM tbl_users
115                                        WHERE 
116                                            sender_enabled = 1 
117                                        AND response_id IS NOT NULL 
118                                        AND verified = 1 
119                                        AND `name` = '{$commercialUser}'";
120
121                        $commercialEmail = DB::select($queryUsers);
122
123                        if (count($commercialEmail) > 0) {
124                            $companyEmail = $commercialEmail[0];
125                        } else {
126                            if ($emailTemplate[$companyId]->getAttribute('from_id') != null) {
127                                $companyEmail = TblCompanyEmails::where('id', $emailTemplate[$companyId]->getAttribute('from_id'))->first();
128                            } else {
129                                $companyEmail = TblCompanyEmails::where('is_active', 1)->where('verified', 1)->where('company_id', $result->company_id)->first();
130                            }
131                        }
132
133                        if (! $companyEmail) {
134                            $error = __('language.no_active_verified_sender');
135                            Log::channel('resend_emails')->error("ID:{$quoteId}: {$error}");
136                        }
137
138                        $ccBcc = TblCcBcc::where('company_id', $result->company_id)->get();
139
140                        $this->email->setFrom($companyEmail->from_email, $companyEmail->from_name);
141                        $this->email->setSubject($subject);
142
143                        $s = 0;
144                        $addTo = [];
145                        foreach ($toEmail as $clientEmail) {
146                            $isValid = $this->isEmailValid($clientEmail);
147
148                            if ($isValid) {
149                                $domain = substr($clientEmail, strpos($clientEmail, '@') + 1);
150
151                                if (! in_array($domain, $blockedDomains)) {
152                                    $this->email->addTo($clientEmail);
153                                    array_push($addTo, $clientEmail);
154                                    $s++;
155                                }
156                            } else {
157                                Log::channel('resend_emails')->error("ID:{$quoteId}: Invalid email {$clientEmail}");
158                            }
159                        }
160
161                        if ($s == 0) {
162                            $toEmail = json_encode($toEmail);
163                            Log::channel('resend_emails')->error("[NO-VALID-EMAILS:{$s}] ID:{$quoteId}: {$toEmail}}");
164                        }
165
166                        if (! config('services.sendgrid.staging')) {
167                            if (count($ccBcc) > 0) {
168                                foreach ($ccBcc as $data) {
169                                    if (! in_array($data->email, $toEmail)) {
170                                        $this->email->addBcc($data->email);
171                                    }
172                                }
173                            }
174                        }
175
176                        $this->email->addContent('text/html', $html);
177
178                        $sendgrid = new \SendGrid(config('services.sendgrid.api_key'));
179
180                        $files = TblFiles::where('quotation_id', $result->id)->where('is_internal', null)->get();
181                        $requestSize = $this->calculateEmailRequestSize($this->email);
182
183                        foreach ($files as $key => $value) {
184                            if ($files[$key]->filename && Storage::disk('s3')->exists('uploads/'.$files[$key]->filename)) {
185
186                                $fileContent = Storage::disk('s3')->get('uploads/'.$files[$key]->filename);
187                                $fileSize = strlen((string) $fileContent) / 1048576;
188                                $fileSize = (int) ceil($fileSize);
189
190                                $originalName = $files[$key]->original_name ?: basename((string) $files[$key]->filename);
191                            } elseif ($files[$key]->file) {
192                                $fileContent = $files[$key]->file;
193
194                                if (is_string($fileContent) && base64_decode($fileContent, true)) {
195                                    $fileContent = base64_decode($fileContent);
196                                }
197
198                                $fileSize = strlen((string) $fileContent) / 1048576;
199                                $fileSize = (int) ceil($fileSize);
200
201                                $originalName = $files[$key]->original_name ?: ($files[$key]->getAttribute('file_name') ?: 'file');
202                            } else {
203                                continue;
204                            }
205
206                            if ($fileSize > 0) {
207                                if ($requestSize + $fileSize < 25) {
208                                    $attachment = new Attachment;
209                                    $attachment->setFilename($originalName);
210                                    $attachment->setDisposition('attachment');
211
212                                    $attachment->setContent(base64_encode((string) $fileContent));
213
214                                    if ($files[$key]->mime_type) {
215                                        $attachment->setType($files[$key]->mime_type);
216                                    }
217
218                                    $this->email->addAttachment($attachment);
219                                    $requestSize = $this->calculateEmailRequestSize($this->email);
220                                } else {
221                                    Log::channel('resend_emails')->error('File omitted due to size limit: '.$originalName);
222                                }
223                            }
224                        }
225
226                        $sentWithBackup = false;
227
228                        try {
229                            $response = $sendgrid->send($this->email);
230                            SendgridLogger::log($this->email, $response);
231                        } catch (\Throwable $sendException) {
232                            SendgridLogger::logException($this->email, $sendException);
233                            throw $sendException;
234                        }
235
236                        if ($response->statusCode() == 202) {
237
238                            $messageId = null;
239
240                            foreach ($response->headers() as $header) {
241                                if (str_starts_with(strtolower((string) $header), 'x-message-id:')) {
242                                    $messageId = trim(substr((string) $header, strpos((string) $header, ':') + 1));
243                                    break;
244                                }
245                            }
246
247                            $typeArray = [
248                                'y_message_id' => $messageId,
249                                'y_status' => 'Processing',
250                            ];
251
252                            if ($type == 'sendToClient') {
253                                $typeArray = [
254                                    'x_message_id' => $messageId,
255                                    'x_status' => 'Processing',
256                                ];
257                            }
258
259                            TblQuotations::where('id', $result->id)->update($typeArray);
260
261                            $jsonBody = [];
262
263                            foreach ($toEmail as $clientEmail) {
264                                $isValid = $this->isEmailValid($clientEmail);
265                                $eventStatus = 'processed';
266                                $eventResponse = '';
267                                if (! $isValid) {
268                                    $eventStatus = 'invalid';
269                                    $eventResponse = 'Invalid email address';
270                                }
271
272                                array_push(
273                                    $jsonBody,
274                                    [
275                                        'email' => $clientEmail,
276                                        'event' => $eventStatus,
277                                        'sg_message_id' => $messageId,
278                                        'smtp-id' => $messageId,
279                                        'timestamp' => strtotime(date('Y-m-d H:i:s')),
280                                        'response' => $eventResponse,
281                                    ]
282                                );
283                            }
284
285                            TblSendgridWebhook::create(
286                                [
287                                    'quotation_id' => $result->id,
288                                    'type' => $type,
289                                    'json_body' => json_encode($jsonBody),
290                                    'x_message_id' => $messageId,
291                                ]
292                            );
293
294                            TblResendEmails::where('quotation_id', $quoteId)->where('type', $typeId)->delete();
295
296                            $toEmail = json_encode($toEmail);
297                            Log::channel('resend_emails')->error("[SENT-OK] ID:{$quoteId}: {$toEmail}}");
298                        } else {
299                            Log::channel('resend_emails')->error('[ERROR-SG] ID:'.$result->id.' - '.$response->body());
300                        }
301                    }
302                } else {
303                    Log::channel('resend_emails')->error('[ERROR-ID] ID does not exist');
304                }
305            } else {
306                Log::channel('resend_emails')->error('[ERROR-ID] Missing ID');
307            }
308
309        } catch (\Exception $e) {
310            Log::channel('resend_emails')->error($e);
311        }
312    }
313
314    public function isEmailValid($email): bool
315    {
316        // Regular expression pattern for email validation
317        $pattern = '/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/';
318
319        // Check if the email matches the pattern
320        if (preg_match($pattern, (string) $email)) {
321            return true; // Valid email
322        } else {
323            return false; // Invalid email
324        }
325    }
326
327    public function getEmailBody($body, $subject, $emailTemplateId, $result): array
328    {
329
330        $availableParameters = [
331            'quote_id',
332            'company_id',
333            'client',
334            'client_type',
335            'phone_number',
336            'email',
337            'issue_date',
338            'request_date',
339            'duration',
340            'invoice_number',
341            'type',
342            'acceptance_date',
343            'status',
344            'source',
345            'amount',
346            'reason_for_not_following_up',
347            'last_follow_up_date',
348            'last_follow_up_comment',
349            'reason_for_rejection_id',
350            'reason_for_rejection',
351            'commercial',
352            'created_at',
353            'created_by',
354            'updated_at',
355            'updated_by',
356        ];
357
358        $dateParameters = [
359            'issue_date',
360            'request_date',
361            'acceptance_date',
362            'last_follow_up_date',
363            'created_at',
364            'updated_at',
365        ];
366
367        preg_match_all('/{{(.*?)}}/', (string) $body, $matches);
368
369        $parameters = $matches[1];
370
371        foreach ($parameters as $parameter) {
372
373            if (in_array($parameter, $dateParameters)) {
374                if ($result->{$parameter}) {
375                    $result->{$parameter} = iconv('ISO-8859-2', 'UTF-8', strftime('%A, %B %d, %Y', strtotime((string) $result->{$parameter})));
376                }
377            }
378
379            if (in_array($parameter, $availableParameters)) {
380                $body = str_replace('{{'.$parameter.'}}', $result->{$parameter}, $body);
381            }
382        }
383
384        preg_match_all('/{{(.*?)}}/', (string) $subject, $matches);
385
386        $parameters = $matches[1];
387
388        foreach ($parameters as $parameter) {
389
390            if (in_array($parameter, $dateParameters)) {
391                if ($result->{$parameter}) {
392                    $result->{$parameter} = iconv('ISO-8859-2', 'UTF-8', strftime('%A, %B %d, %Y', strtotime((string) $result->{$parameter})));
393                }
394            }
395
396            if (in_array($parameter, $availableParameters)) {
397                $subject = str_replace('{{'.$parameter.'}}', $result->{$parameter}, $subject);
398            }
399        }
400
401        $templateFiles = TblEmailFiles::where('email_template_id', $emailTemplateId)->orderBy('order', 'asc')->get();
402
403        foreach ($templateFiles as $item) {
404            $f = storage_path('app/public/uploads/'.$item->filename);
405
406            if (file_exists($f)) {
407                $imgpath = file_get_contents($f);
408                $base64 = 'data:image/png;base64,'.base64_encode($imgpath);
409                $mimeType = mime_content_type($f);
410
411                $this->email->addAttachment(
412                    $imgpath,
413                    $mimeType,
414                    str_replace(' ', '', $item->original_name),
415                    'inline',
416                    str_replace(' ', '', $item->original_name),
417                );
418
419                $body .= "<img src='cid:{$item->original_name}' style='height: 45px; padding-right: 6px' />";
420            } else {
421                Log::channel('resend_emails')->error("[{$result->id}] File not found: ".$f);
422            }
423        }
424
425        $html = '<!DOCTYPE html>';
426        $html .= '<html>';
427        $html .= '<head>';
428        $html .= '<meta charset="UTF-8">';
429        $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
430        $html .= '</head>';
431        $html .= '<body>';
432        $html .= $body;
433        $html .= '</body>';
434        $html .= '</html>';
435
436        return [$html, $subject];
437    }
438
439    public function calculateEmailRequestSize(Mail $email): int
440    {
441
442        $size = 0;
443
444        // Add size of 'from', 'to', 'subject', 'content'
445        $from = $email->getFrom();
446        $size += strlen(json_encode([
447            'from' => $from->getEmail().' '.$from->getName(),
448            'subject' => $email->getSubject(),
449        ]));
450
451        // Add size of 'to' (recipients)
452        $personalizations = $email->getPersonalizations() ?? [];
453        foreach ($personalizations as $personalization) {
454            foreach ($personalization->getTos() as $to) {
455                $size += strlen($to->getEmail().' '.$to->getName());
456            }
457        }
458
459        // Add size of content
460        foreach ($email->getContents() as $content) {
461            $size += strlen((string) $content->getValue());
462        }
463
464        // Add size of attachments (if any)
465
466        if ($email->getAttachments() != null && $email->getAttachments() != '') {
467            foreach ($email->getAttachments() as $attachment) {
468                $size += strlen($attachment->getContent()); // Base64 encoded size
469                $size += strlen($attachment->getFilename());
470                $size += strlen($attachment->getType());
471            }
472        }
473
474        $sizeInMegabytes = $size / 1048576; // 1 MB = 1,048,576 bytes
475
476        return (int) ceil($sizeInMegabytes);
477    }
478}