Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
1.83% covered (danger)
1.83%
2 / 109
20.00% covered (danger)
20.00%
1 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
SendEmailInvoiceNewCreditDays
1.83% covered (danger)
1.83%
2 / 109
20.00% covered (danger)
20.00%
1 / 5
1000.66
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 handle
0.00% covered (danger)
0.00%
0 / 55
0.00% covered (danger)
0.00%
0 / 1
600
 send_email
0.00% covered (danger)
0.00%
0 / 43
0.00% covered (danger)
0.00%
0 / 1
12
 isEmailValid
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 detectDelimiter
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2
3namespace App\Console\Commands;
4
5use App\Models\TblCustomerChangeComms;
6use App\Services\GestionaService;
7use App\Services\SendgridLogger;
8use Illuminate\Console\Command;
9use Illuminate\Support\Facades\File;
10use Illuminate\Support\Facades\Log;
11use SendGrid\Mail\Mail;
12
13class SendEmailInvoiceNewCreditDays extends Command
14{
15    /**
16     * The name and signature of the console command.
17     *
18     * @var string
19     */
20    protected $signature = 'send:invoice-new-credit-days {invoiceDate?}';
21
22    /**
23     * The console command description.
24     *
25     * @var string
26     */
27    protected $description = 'Send email invoice new credit days';
28
29    protected $gestionaService;
30
31    /**
32     * Create a new command instance.
33     *
34     * @return void
35     */
36    public function __construct(GestionaService $gestionaService)
37    {
38        parent::__construct();
39        $this->gestionaService = $gestionaService;
40    }
41
42    /**
43     * Execute the console command.
44     *
45     * @return int
46     */
47    public function handle()
48    {
49        try {
50
51            $invoiceDate = $this->argument('invoiceDate') ?? null;
52
53            if ($invoiceDate != null) {
54                $d = \DateTime::createFromFormat('Y-m-d', $invoiceDate);
55
56                if (! $d || $d->format('Y-m-d') !== $invoiceDate) {
57                    throw new \InvalidArgumentException('Invalid date format. Expected Y-m-d.');
58                }
59            } else {
60                $invoiceDate = date('Y-m-d', strtotime('-1 day'));
61            }
62            $logo = File::get(public_path('fireservicetitan.png'));
63
64            $regions = [
65                'Catalunya',
66                'Madrid',
67                'Andalucía',
68                'Baleares',
69                'Comunidad Valenciana',
70            ];
71
72            foreach ($regions as $region) {
73                $yesterdayInvoices = $this->gestionaService->request('get', 'factura/vence/'.$invoiceDate, $region, []);
74
75                if (! empty($yesterdayInvoices) && ! empty($yesterdayInvoices['facturas'])) {
76
77                    for ($i = 0; $i < count($yesterdayInvoices['facturas']); $i++) {
78
79                        $email = new Mail;
80
81                        $invoiceId = $yesterdayInvoices['facturas'][$i]['ID'];
82                        $dataInvoice = $this->gestionaService->request('get', 'factura/'.$invoiceId, $region, []);
83
84                        if (! empty($dataInvoice) && ! empty($dataInvoice['factura'])) {
85
86                            if (isset($dataInvoice['factura']['cod_cliente'])) {
87
88                                $clientCode = $dataInvoice['factura']['cod_cliente'];
89                                $result = TblCustomerChangeComms::where('client_code', $clientCode)->where('email_sent_at', null)->first();
90
91                                if ($result != null) {
92
93                                    $clientInvoiceResponse = $this->gestionaService->request('get', 'cliente/'.$result->client_code, $result->region, []);
94
95                                    if (! empty($clientInvoiceResponse) && ! empty($clientInvoiceResponse['cliente'])) {
96                                        $addTo = [];
97                                        $toEmail = [];
98
99                                        if (config('services.sendgrid.staging')) {
100                                            $toEmail = ['christian@ibventur.es'];
101                                        } else {
102
103                                            if (isset($clientInvoiceResponse['cliente']['email_facturacion'])) {
104                                                $toEmail = $clientInvoiceResponse['cliente']['email_facturacion'];
105                                            }
106
107                                            if (isset($clientInvoiceResponse['cliente']['email'])) {
108                                                $toEmail = $clientInvoiceResponse['cliente']['email'];
109                                            }
110
111                                        }
112
113                                        if (! empty($toEmail)) {
114                                            // PHP-LARAVEL-27: this block used to appear twice,
115                                            // identically. The first pass turned the delimited
116                                            // string from Gestiona into an array and sent the mail;
117                                            // the second then handed that array to detectDelimiter,
118                                            // where substr_count() raised a TypeError - an Error, so
119                                            // the catch below never saw it and the command aborted
120                                            // mid-run. The duplicate is gone; had it not thrown, it
121                                            // would have sent every client a second copy.
122                                            //
123                                            // Shape-tolerant because the staging override above
124                                            // assigns an array while Gestiona returns a delimited
125                                            // string, and detectDelimiter()/explode() accept only a
126                                            // string - so staging hit the same TypeError.
127                                            if (! is_array($toEmail)) {
128                                                $toEmail = explode($this->detectDelimiter($toEmail), (string) $toEmail);
129                                            }
130
131                                            $toEmail = array_map('trim', $toEmail);
132
133                                            $invalidEmailCount = 0;
134
135                                            foreach ($toEmail as $clientEmail) {
136                                                $isValid = $this->isEmailValid($clientEmail);
137                                                if ($isValid) {
138                                                    if (! in_array($clientEmail, $addTo)) {
139                                                        array_push($addTo, $clientEmail);
140                                                        $email->addTo($clientEmail);
141                                                    }
142                                                } else {
143                                                    $invalidEmailCount++;
144                                                    Log::channel('cron_send_email_invoice_new_credit_days')->error("[$result->client_code]: Invalid email address $clientEmail");
145                                                }
146                                            }
147
148                                            if ($invalidEmailCount != count($toEmail)) {
149                                                $this->send_email($result->id, $result->client_code, $result->client_name, $result->credit_days, $logo, $addTo, $email);
150                                            }
151                                        }
152                                    }
153                                }
154                            }
155                        }
156                    }
157                }
158            }
159
160        } catch (\Exception $e) {
161            Log::channel('cron_send_email_invoice_new_credit_days')->error($e->getMessage());
162
163            return 1;
164        }
165
166        return 0;
167    }
168
169    public function send_email($id, $clientCode, $clientName, $creditDays, $logo, $addTo, $email)
170    {
171
172        $body = "<p>Estimado {$clientName},</p></br>";
173        $body .= "<p>Le informamos de que, como parte de un proceso de revisión y mejora de nuestros procedimientos administrativos y de facturación, a partir del 01/03/2026 el plazo de vencimiento de las facturas emitidas a su nombre pasará a ser de {$creditDays} días, en sustitución del plazo actual.</p></br>";
174        $body .= '<p>Esta modificación tiene como objetivo homogeneizar y optimizar la gestión administrativa, sin que suponga ningún otro cambio al servicio que le ofrecemos habitualmente.</p></br>';
175        $body .= '<p>Muchas gracias.</p></br>';
176        $body .= '<p>Fire Service Titan</p>';
177        $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
178
179        $html = '<!DOCTYPE html>';
180        $html .= '<html>';
181        $html .= '<head>';
182        $html .= '<meta charset="UTF-8">';
183        $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
184        $html .= '</head>';
185        $html .= '<body>';
186        $html .= $body;
187        $html .= '</body>';
188        $html .= '</html>';
189
190        $email->setFrom('fire@fire.es', 'Fire Service Titan');
191        $email->setSubject('Condiciones comerciales Grupo Fire');
192        $email->addContent('text/html', $html);
193        $email->addCc('xavier.lopez@fire.es');
194
195        $email->addAttachment(
196            $logo,
197            'image/png',
198            'fireservicetitan.png',
199            'inline',
200            'fireservicetitan'
201        );
202
203        $sendgrid = new \SendGrid(config('services.sendgrid.api_key'));
204
205        try {
206            $response = $sendgrid->send($email);
207            SendgridLogger::log($email, $response);
208        } catch (\Throwable $sendException) {
209            SendgridLogger::logException($email, $sendException);
210            throw $sendException;
211        }
212
213        if ($response->statusCode() == 202) {
214            $addTo = json_encode($addTo);
215            TblCustomerChangeComms::where('id', $id)
216                ->update([
217                    'email_sent_at' => date('Y-m-d H:i:s'),
218                ]
219                );
220            Log::channel('cron_send_email_invoice_new_credit_days')->info("[SENT-OK] ID:$clientCode - $addTo");
221        } else {
222            $error = $response->body();
223            Log::channel('cron_send_email_invoice_new_credit_days')->error("[ERROR-SG] ID:$clientCode - $addTo - $error");
224        }
225    }
226
227    public function isEmailValid($email)
228    {
229        $pattern = '/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/';
230
231        if (preg_match($pattern, $email)) {
232            return true;
233        } else {
234            return false;
235        }
236    }
237
238    public function detectDelimiter($string)
239    {
240        $delimiters = [',', ';', '|'];
241        $counts = [];
242
243        foreach ($delimiters as $delimiter) {
244            $counts[$delimiter] = substr_count($string, $delimiter);
245        }
246
247        return array_search(max($counts), $counts);
248    }
249}