Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
35.56% covered (danger)
35.56%
64 / 180
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
SendG3WEmailReminders
35.56% covered (danger)
35.56%
64 / 180
0.00% covered (danger)
0.00%
0 / 2
362.86
0.00% covered (danger)
0.00%
0 / 1
 quoteList
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
56
 handle
39.51% covered (danger)
39.51%
64 / 162
0.00% covered (danger)
0.00%
0 / 1
201.56
1<?php
2
3namespace App\Console\Commands;
4
5use App\Models\TblCcG3WEmailReminders;
6use App\Models\TblNotificationLogs;
7use App\Services\SendgridDispatcher;
8use App\Services\SendgridLogger;
9use Illuminate\Console\Command;
10use Illuminate\Support\Facades\DB;
11use Illuminate\Support\Facades\Log;
12use SendGrid\Mail\Mail;
13
14class SendG3WEmailReminders extends Command
15{
16    /**
17     * The name and signature of the console command.
18     *
19     * @var string
20     */
21    protected $signature = 'send:g3w-email-reminders {sent_by?} {email?} {company_id?}
22        {--dry-run : List who would get which quotes, send nothing}';
23
24    /**
25     * The console command description.
26     *
27     * @var string
28     */
29    protected $description = 'Send g3w warning email reminders';
30
31    /**
32     * The one rule for every section of the email: the quote is still pending
33     * to be sent (status NULL or one of these) and is sent by email
34     * (send_channel 'email', or NULL for legacy rows). Pending statuses:
35     * Nuevo, Solicitud, Visita, Listo para enviar, En proceso, Sin estado en
36     * G3W, Estado no reconocido, En proceso - IA. Everything else is already
37     * sent (Enviado, Enviado - IA) or final (Aceptado, Rechazado*, Anulado,
38     * Gestión Recuperación Baja, correo erróneo) and never appears; nor do
39     * WhatsApp or correo ordinario quotes (FIRE KO 13/10: the rule was applied
40     * to "falta el email" only, so accepted and WhatsApp quotes kept coming in
41     * the other sections).
42     */
43    private const PENDING_TO_SEND_STATUSES = [1, 6, 8, 11, 12, 13, 14, 16];
44
45    /**
46     * Accounts that are not sales reps: "Ifex" is the IFEX integration
47     * (ifex@ifex.es, an outside mailbox). It got ~1,340 quotes a day, three
48     * quarters of all warnings, with the Valencia CC list copied (FIRE KO 13/10).
49     */
50    private const NOT_A_SALES_REP = ['Ifex'];
51
52    /** Quotes listed per section; the count and the "see all" link cover the rest. */
53    private const MAX_LISTED = 50;
54
55    /**
56     * "N presupuestos (número en Titan):" + one line per quote with its
57     * Gestiona number. The count used to read "#N de orden interno:", which
58     * reps took as "the internal order number is missing". The count links to
59     * exactly these quotes.
60     *
61     * @param  array<int,object>  $items
62     */
63    private function quoteList(array $items, array &$companyCcIds): string
64    {
65        $ids = implode(',', array_map(fn ($item) => (int) $item->id, $items));
66        $listUrl = config('app.frontend_url')."orders?order_ids={$ids}";
67        $count = count($items);
68        $label = $count === 1 ? 'presupuesto' : 'presupuestos';
69
70        $html = "<p><b><a href='{$listUrl}'>{$count} {$label}</a> (número en Titan):</b></p><ul>";
71        foreach ($items as $i => $item) {
72            if (! in_array($item->company_id, $companyCcIds)) {
73                $companyCcIds[] = $item->company_id;
74            }
75            if ($i >= self::MAX_LISTED) {
76                continue;     // still collect CC companies, but keep the email readable
77            }
78            $url = config('app.frontend_url')."orders/{$item->id}?company_id={$item->company_id}";
79            $g3w = ! empty($item->internal_quote_id) ? " <span style='color:#666'>(G3W: {$item->internal_quote_id})</span>" : '';
80            $html .= "<li><a href='{$url}'>{$item->quote_id}</a>{$g3w}</li>";
81        }
82        $html .= '</ul>';
83
84        if ($count > self::MAX_LISTED) {
85            $more = $count - self::MAX_LISTED;
86            $html .= "<p>… y {$more} más. <a href='{$listUrl}'>Verlos todos en Titan</a>.</p>";
87        }
88
89        return $html;
90    }
91
92    /**
93     * Execute the console command.
94     */
95    public function handle(): void
96    {
97
98        try {
99
100            $sentByArg = $this->argument('sent_by') ?? 'System';
101            $toEmailArg = $this->argument('email') ?? null;
102            $companyIdArg = (int) ($this->argument('company_id') ?? 0);
103
104            $where = '';
105
106            if ($companyIdArg != 0) {
107                $where = " AND a.company_id = {$companyIdArg} ";
108            }
109
110            // FIRE-1930: one digest mixes several companies, so the
111            // commercial kill switch filters rows instead of skipping a send.
112            // No enabled company -> IN (0), which matches nothing.
113            $enabledCompanyIds = SendgridDispatcher::allowedCompanyIds(SendgridDispatcher::BUCKET_COMMERCIAL) ?: [0];
114            $where .= ' AND a.company_id IN ('.implode(', ', $enabledCompanyIds).') ';
115
116            $notSalesReps = "AND a.commercial NOT IN ('".implode("', '", self::NOT_A_SALES_REP)."')";
117
118            // The quote lists are built with GROUP_CONCAT, which MySQL cuts at
119            // 1,024 characters by default: for a rep with many quotes the JSON
120            // came back truncated, json_decode() gave null and that section of
121            // the email silently disappeared.
122            DB::statement('SET SESSION group_concat_max_len = 1000000');
123
124            // Pending to be sent, by email: see PENDING_TO_SEND_STATUSES.
125            $pendingByEmail = '(a.budget_status_id IS NULL OR a.budget_status_id IN ('.implode(', ', self::PENDING_TO_SEND_STATUSES).'))'
126                ." AND COALESCE(a.send_channel, 'email') = 'email'";
127
128            $sectionQuery = fn (string $condition, string $column) => "SELECT
129                        b.id,
130                        COUNT(a.commercial) total,
131                        a.commercial,
132                        b.email,
133                        CONCAT('[', GROUP_CONCAT(JSON_OBJECT('id', a.id, 'quote_id', a.quote_id, 'internal_quote_id', a.internal_quote_id, 'company_id', a.company_id)), ']') {$column}
134                    FROM tbl_quotations a
135                    LEFT JOIN tbl_users b ON a.commercial = b.name
136                    WHERE a.sync_import = 1
137                        AND a.deleted_at IS NULL
138                        AND {$condition}
139                        AND {$pendingByEmail}
140                        AND a.commercial IS NOT NULL
141                        AND b.email IS NOT NULL
142                        {$notSalesReps}
143                        {$where}
144                    GROUP BY 1
145                    ORDER BY a.commercial ASC";
146
147            $json_ids_no_budget_types = DB::select($sectionQuery(
148                '(a.budget_type_id IS NULL OR a.budget_type_id = 16)',
149                'json_ids_no_budget_types'
150            ));
151
152            $json_ids_missing_email = DB::select($sectionQuery(
153                "(a.email IS NULL OR TRIM(a.email) = '')",
154                'json_ids'
155            ));
156
157            $json_ids_missing_name = DB::select($sectionQuery(
158                "(a.client IS NULL OR TRIM(a.client) = '')",
159                'json_ids'
160            ));
161
162            // One entry per sales rep, with a list per section.
163            $combined = [];
164            $sections = [
165                'json_ids_no_budget_types' => [$json_ids_no_budget_types, 'json_ids_no_budget_types'],
166                'json_ids_missing_email' => [$json_ids_missing_email, 'json_ids'],
167                'json_ids_missing_name' => [$json_ids_missing_name, 'json_ids'],
168            ];
169            foreach ($sections as $section => [$rows, $column]) {
170                foreach ($rows as $item) {
171                    $email = $item->email;
172                    if (! isset($combined[$email])) {
173                        $combined[$email] = (object) [
174                            'id' => $item->id,
175                            'commercial' => $item->commercial,
176                            'email' => $email,
177                            'total' => 0,
178                            'json_ids_no_budget_types' => [],
179                            'json_ids_missing_email' => [],
180                            'json_ids_missing_name' => [],
181                        ];
182                    }
183                    $combined[$email]->total += $item->total;
184                    $combined[$email]->{$section} = json_decode((string) $item->{$column}) ?: [];
185                }
186            }
187
188            $result = array_values($combined);
189
190            if ($this->option('dry-run')) {
191                $rows = [];
192                $total = 0;
193                foreach ($result as $r) {
194                    $codes = fn ($list) => implode(', ', array_map(fn ($q) => $q->quote_id, $list));
195                    $rows[] = [$r->commercial, count($r->json_ids_no_budget_types), count($r->json_ids_missing_email), count($r->json_ids_missing_name),
196                        mb_strimwidth($codes($r->json_ids_missing_email), 0, 60, '…')];
197                    $total += $r->total;
198                }
199                $this->table(['Sales rep', 'No type', 'No client email', 'No client name', 'Missing-email quotes'], $rows);
200                $this->info(sprintf('DRY RUN: %d emails, %d quotes in total. Nothing sent.', count($result), $total));
201
202                return;
203            }
204
205            if (count($result) > 0) {
206
207                $today = date('d/m/Y');
208
209                for ($i = 0; $i < count($result); $i++) {
210                    $body = '';
211                    $companyCcIds = [];
212                    $jsonIdsNoBudgetTypes = $result[$i]->json_ids_no_budget_types;
213                    $jsonIdsMissingEmail = $result[$i]->json_ids_missing_email;
214                    $jsonIdsMissingName = $result[$i]->json_ids_missing_name;
215                    $commercial = $result[$i]->commercial;
216
217                    $subject = "Revisión de warnings en G3W – Acción necesaria en presupuestos {$today} for {$commercial}";
218
219                    $isStaging = (bool) config('services.sendgrid.staging');
220                    if ($isStaging) {
221                        // Staging: SENDGRID_TO_EMAIL only (no CC), never the real
222                        // reps. Empty = nothing is sent.
223                        $toEmail = config('services.sendgrid.to_email') ?: null;
224                    } elseif ($toEmailArg != null) {
225                        $toEmail = $toEmailArg;
226                    } else {
227                        $toEmail = $result[$i]->email;
228                    }
229
230                    $body .= "<p>Hola <b>{$commercial}</b>,</p>";
231                    $body .= '<p>Te escribo porque he estado revisando tus <i>warnings</i> en G3W desde la integración con TITAN, y he detectado algunos puntos que necesitan tu atención:</p>';
232
233                    if ($result[$i]->total > 0) {
234
235                        if ($jsonIdsNoBudgetTypes) {
236                            $body .= '<p><b>PRESUPUESTOS SIN TIPO DE PRESUPUESTO</b><p>';
237                            $body .= '<p>Los siguientes presupuestos en G3W no tienen el tipo de cliente asignado en TITAN, por lo tanto <b>no se contabilizan en los datos:</b></p>';
238                            $body .= $this->quoteList($jsonIdsNoBudgetTypes, $companyCcIds);
239
240                            $body .= '<p>Para solucionarlo:</p>';
241                            $body .= '<ol>';
242                            $body .= '<li>Accede a G3W</li>';
243                            $body .= '<li>Revisa cada presupuesto indicado.</li>';
244                            $body .= '<li>Añade el campo <b>"ORIGEN DE PRESUPUESTO"</b>.</li>';
245                            $body .= '</ol>';
246
247                            $body .= '<p>Si tienes dudas sobre qué origen asignar, puedes consultarlo en el siguiente enlace:</p>';
248                            $url = config('app.frontend_url').'normalize-g3w';
249                            $body .= "<p><a href='{$url}'><b>Apartado de normalización</b></a></p>";
250                        }
251
252                        if ($jsonIdsMissingEmail) {
253                            $body .= '<p><b>FALTA EL EMAIL DEL CLIENTE</b><p>';
254                            $body .= '<p>Estos presupuestos se envían por email y todavía no se han enviado, pero no tienen el email del cliente (no llegó desde G3W, por ser un cliente nuevo o por falta de información en G3W).</p>';
255                            $body .= '<p>Por favor, <b>añade el email del cliente EN TITAN</b> en cada uno:</p>';
256                            $body .= $this->quoteList($jsonIdsMissingEmail, $companyCcIds);
257                        }
258
259                        if ($jsonIdsMissingName) {
260                            $body .= '<p><b>FALTA EL NOMBRE DEL CLIENTE</b><p>';
261                            $body .= '<p>Estos presupuestos se envían por email y todavía no se han enviado, pero no tienen el nombre del cliente.</p>';
262                            $body .= '<p>Por favor, <b>añade el nombre del cliente EN TITAN</b> en cada uno:</p>';
263                            $body .= $this->quoteList($jsonIdsMissingName, $companyCcIds);
264                        }
265
266                        $body .= '<p>Si tienes cualquier duda sobre esta operativa o necesitas ayuda con alguno de los <i>warnings</i>, no dudes en escribirme.</p>';
267                        $body .= '<p>Gracias por tu atención y colaboración.</p>';
268                        $body .= '<p>Un saludo,</p>';
269
270                        $imgpath = file_get_contents(public_path('fireservicetitan.png'));
271                        $body .= '<br><p>Fire Service Titan</p>';
272                        $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
273
274                        $html = '<!DOCTYPE html>';
275                        $html .= '<html>';
276                        $html .= '<head>';
277                        $html .= '<meta charset="UTF-8">';
278                        $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
279                        $html .= '</head>';
280                        $html .= '<body>';
281                        $html .= $body;
282                        $html .= '</body>';
283                        $html .= '</html>';
284
285                        if ($toEmail != null) {
286                            $email = new Mail;
287
288                            if ($toEmailArg == null && ! $isStaging) {
289                                $companyCcIds = array_values(array_unique($companyCcIds));
290                                $ccBcc = TblCcG3WEmailReminders::whereIn('company_id', $companyCcIds)->get();
291
292                                $inCc = [];
293
294                                if (count($ccBcc) > 0) {
295                                    foreach ($ccBcc as $data) {
296                                        if ($data->email != $toEmail && ! in_array($data->email, $inCc)) {
297                                            $email->addCc($data->email);
298                                            array_push($inCc, $data->email);
299                                        }
300                                    }
301                                }
302                            }
303
304                            $email->setFrom('fire@fire.es', 'Fire Service Titan');
305                            $email->setSubject($subject);
306                            $email->addTo($toEmail);
307                            $email->addContent('text/html', $html);
308
309                            $email->addAttachment(
310                                $imgpath,
311                                'image/png',
312                                'fireservicetitan.png',
313                                'inline',
314                                'fireservicetitan'
315                            );
316
317                            $sendgrid = new \SendGrid(config('services.sendgrid.api_key'));
318
319                            try {
320                                $response = $sendgrid->send($email);
321                                SendgridLogger::log($email, $response);
322                            } catch (\Throwable $sendException) {
323                                SendgridLogger::logException($email, $sendException);
324                                throw $sendException;
325                            }
326
327                            if ($response->statusCode() != 202) {
328                                Log::channel('cron_send_g3w_email_reminders')->error('ID: '.$toEmail.' - '.$response->body());
329                            } else {
330                                TblNotificationLogs::create(
331                                    [
332                                        'company_id' => $companyIdArg,
333                                        'commercial' => $commercial,
334                                        'total_g3w_warning' => $result[$i]->total,
335                                        'created_by' => $sentByArg,
336                                    ]
337                                );
338                            }
339                        }
340                    }
341                }
342            }
343
344        } catch (\Exception $e) {
345            Log::channel('cron_send_g3w_email_reminders')->error($e->getMessage());
346        }
347
348    }
349}