Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
1.90% covered (danger)
1.90%
2 / 105
20.00% covered (danger)
20.00%
1 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
SendEmailInvoiceNewCreditDays
1.90% covered (danger)
1.90%
2 / 105
20.00% covered (danger)
20.00%
1 / 5
879.54
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
552
 send_email
0.00% covered (danger)
0.00%
0 / 39
0.00% covered (danger)
0.00%
0 / 1
6
 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 Illuminate\Console\Command;
8use Illuminate\Support\Facades\File;
9use Illuminate\Support\Facades\Log;
10
11class SendEmailInvoiceNewCreditDays extends Command
12{
13    /**
14     * The name and signature of the console command.
15     *
16     * @var string
17     */
18    protected $signature = 'send:invoice-new-credit-days {invoiceDate?}';
19
20    /**
21     * The console command description.
22     *
23     * @var string
24     */
25    protected $description = 'Send email invoice new credit days';
26
27    protected $gestionaService;
28
29    /**
30     * Create a new command instance.
31     *
32     * @return void
33     */
34    public function __construct(GestionaService $gestionaService)
35    {
36        parent::__construct();
37        $this->gestionaService = $gestionaService;
38    }
39
40    /**
41     * Execute the console command.
42     *
43     * @return int
44     */
45    public function handle()
46    {
47        try {
48
49            $invoiceDate = $this->argument('invoiceDate') ?? null;
50
51            if ($invoiceDate != null) {
52                $d = \DateTime::createFromFormat('Y-m-d', $invoiceDate);
53
54                if (! $d || $d->format('Y-m-d') !== $invoiceDate) {
55                    throw new \InvalidArgumentException('Invalid date format. Expected Y-m-d.');
56                }
57            } else {
58                $invoiceDate = date('Y-m-d', strtotime('-1 day'));
59            }
60
61            $logo = File::get(public_path('fireservicetitan.png'));
62
63            $regions = [
64                'Catalunya',
65                'Madrid',
66                'Andalucía',
67                'Baleares',
68                'Comunidad Valenciana',
69            ];
70
71            foreach ($regions as $region) {
72                $yesterdayInvoices = $this->gestionaService->request('get', 'factura/vence/'.$invoiceDate, $region, []);
73
74                if (! empty($yesterdayInvoices) && ! empty($yesterdayInvoices['facturas'])) {
75
76                    for ($i = 0; $i < count($yesterdayInvoices['facturas']); $i++) {
77
78                        $email = new \SendGrid\Mail\Mail;
79
80                        $invoiceId = $yesterdayInvoices['facturas'][$i]['ID'];
81                        $dataInvoice = $this->gestionaService->request('get', 'factura/'.$invoiceId, $region, []);
82
83                        if (! empty($dataInvoice) && ! empty($dataInvoice['factura'])) {
84
85                            if (isset($dataInvoice['factura']['cod_cliente'])) {
86
87                                $clientCode = $dataInvoice['factura']['cod_cliente'];
88                                $result = TblCustomerChangeComms::where('client_code', $clientCode)->where('email_sent_at', null)->first();
89
90                                if ($result != null) {
91
92                                    $clientInvoiceResponse = $this->gestionaService->request('get', 'cliente/'.$result->client_code, $result->region, []);
93
94                                    if (! empty($clientInvoiceResponse) && ! empty($clientInvoiceResponse['cliente'])) {
95                                        $addTo = [];
96                                        $toEmail = [];
97
98                                        if (config('services.sendgrid.staging')) {
99                                            $toEmail = ['christian@ibventur.es'];
100                                        } else {
101
102                                            if (isset($clientInvoiceResponse['cliente']['email_facturacion'])) {
103                                                $toEmail = $clientInvoiceResponse['cliente']['email_facturacion'];
104                                            }
105
106                                            if (isset($clientInvoiceResponse['cliente']['email'])) {
107                                                $toEmail = $clientInvoiceResponse['cliente']['email'];
108                                            }
109
110                                        }
111
112                                        if (! empty($toEmail)) {
113                                            $delimiter = $this->detectDelimiter($toEmail);
114                                            $toEmail = explode($delimiter, $toEmail);
115                                            $toEmail = array_map('trim', $toEmail);
116
117                                            $invalidEmailCount = 0;
118
119                                            foreach ($toEmail as $clientEmail) {
120                                                $isValid = $this->isEmailValid($clientEmail);
121                                                if ($isValid) {
122                                                    if (! in_array($clientEmail, $addTo)) {
123                                                        array_push($addTo, $clientEmail);
124                                                        $email->addTo($clientEmail);
125                                                    }
126                                                } else {
127                                                    $invalidEmailCount++;
128                                                    Log::channel('cron_send_email_invoice_new_credit_days')->error("[$result->client_code]: Invalid email address $clientEmail");
129                                                }
130                                            }
131
132                                            if ($invalidEmailCount != count($toEmail)) {
133                                                $this->send_email($result->id, $result->client_code, $result->client_name, $result->credit_days, $logo, $addTo, $email);
134                                            }
135                                        }
136                                    }
137                                }
138                            }
139                        }
140                    }
141                }
142            }
143
144        } catch (\Exception $e) {
145            Log::channel('cron_send_email_invoice_new_credit_days')->error($e->getMessage());
146
147            return 1;
148        }
149
150        return 0;
151    }
152
153    public function send_email($id, $clientCode, $clientName, $creditDays, $logo, $addTo, $email)
154    {
155
156        $body = "<p>Estimado {$clientName},</p></br>";
157        $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>";
158        $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>';
159        $body .= '<p>Muchas gracias.</p></br>';
160        $body .= '<p>Fire Service Titan</p>';
161        $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
162
163        $html = '<!DOCTYPE html>';
164        $html .= '<html>';
165        $html .= '<head>';
166        $html .= '<meta charset="UTF-8">';
167        $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
168        $html .= '</head>';
169        $html .= '<body>';
170        $html .= $body;
171        $html .= '</body>';
172        $html .= '</html>';
173
174        $email->setFrom('fire@fire.es', 'Fire Service Titan');
175        $email->setSubject('Condiciones comerciales Grupo Fire');
176        $email->addContent('text/html', $html);
177        $email->addCc('xavier.lopez@fire.es');
178
179        $email->addAttachment(
180            $logo,
181            'image/png',
182            'fireservicetitan.png',
183            'inline',
184            'fireservicetitan'
185        );
186
187        $sendgrid = new \SendGrid(config('services.sendgrid.api_key'));
188        $response = $sendgrid->send($email);
189
190        if ($response->statusCode() == 202) {
191            $addTo = json_encode($addTo);
192            TblCustomerChangeComms::where('id', $id)
193                ->update([
194                    'email_sent_at' => date('Y-m-d H:i:s'),
195                ]
196                );
197            Log::channel('cron_send_email_invoice_new_credit_days')->info("[SENT-OK] ID:$clientCode - $addTo");
198        } else {
199            $error = $response->body();
200            Log::channel('cron_send_email_invoice_new_credit_days')->error("[ERROR-SG] ID:$clientCode - $addTo - $error");
201        }
202    }
203
204    public function isEmailValid($email)
205    {
206        $pattern = '/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/';
207
208        if (preg_match($pattern, $email)) {
209            return true;
210        } else {
211            return false;
212        }
213    }
214
215    public function detectDelimiter($string)
216    {
217        $delimiters = [',', ';', '|'];
218        $counts = [];
219
220        foreach ($delimiters as $delimiter) {
221            $counts[$delimiter] = substr_count($string, $delimiter);
222        }
223
224        return array_search(max($counts), $counts);
225    }
226}