Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 146
0.00% covered (danger)
0.00%
0 / 2
CRAP
0.00% covered (danger)
0.00%
0 / 1
SendG3WEmailReminders
0.00% covered (danger)
0.00%
0 / 146
0.00% covered (danger)
0.00%
0 / 2
600
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 handle
0.00% covered (danger)
0.00%
0 / 145
0.00% covered (danger)
0.00%
0 / 1
552
1<?php
2
3namespace App\Console\Commands;
4
5use App\Models\TblCcG3WEmailReminders;
6use App\Models\TblNotificationLogs;
7use Illuminate\Console\Command;
8use Illuminate\Support\Facades\DB;
9use Illuminate\Support\Facades\Log;
10
11class SendG3WEmailReminders extends Command
12{
13    /**
14     * The name and signature of the console command.
15     *
16     * @var string
17     */
18    protected $signature = 'send:g3w-email-reminders {sent_by?} {email?} {company_id?}';
19
20    /**
21     * The console command description.
22     *
23     * @var string
24     */
25    protected $description = 'Send g3w warning email reminders';
26
27    /**
28     * Create a new command instance.
29     *
30     * @return void
31     */
32    public function __construct()
33    {
34        parent::__construct();
35    }
36
37    /**
38     * Execute the console command.
39     *
40     * @return int
41     */
42    public function handle()
43    {
44
45        try {
46
47            $sentByArg = $this->argument('sent_by') ?? 'System';
48            $toEmailArg = $this->argument('email') ?? null;
49            $companyIdArg = (int) ($this->argument('company_id') ?? 0);
50
51            $where = '';
52
53            if ($companyIdArg != 0) {
54                $where = " AND a.company_id = {$companyIdArg} ";
55            }
56
57            $query = "SELECT 
58                        b.id,
59                        COUNT(a.commercial) total,
60                        a.commercial,
61                        b.email,
62                        CONCAT('[', GROUP_CONCAT(JSON_OBJECT('id', a.id, 'quote_id', a.quote_id, 'company_id', a.company_id)), ']') json_ids_no_budget_types
63                    FROM tbl_quotations a
64                    LEFT JOIN tbl_users b ON a.commercial = b.name
65                    WHERE a.sync_import = 1
66                        AND (a.budget_type_id IS NULL
67                            OR a.budget_type_id=16)
68                        AND a.commercial IS NOT NULL
69                        AND b.email IS NOT NULL     
70                        {$where}
71                    GROUP BY 1
72                    ORDER BY a.commercial ASC";
73
74            $json_ids_no_budget_types = DB::select($query);
75
76            $query = "SELECT 
77                        b.id,
78                        COUNT(a.commercial) total,
79                        a.commercial,
80                        b.email,
81                        CONCAT('[', GROUP_CONCAT(JSON_OBJECT('id', a.id, 'quote_id', a.quote_id, 'company_id', a.company_id)), ']') json_ids_incomplete_data
82                    FROM tbl_quotations a
83                    LEFT JOIN tbl_users b ON a.commercial = b.name
84                    WHERE a.sync_import = 1
85                        AND ((a.client IS NULL OR TRIM(a.client) = '')
86                            OR (a.email IS NULL
87                            OR TRIM(a.email) = ''))
88                        AND a.commercial IS NOT NULL
89                        AND b.email IS NOT NULL     
90                        {$where}
91                    GROUP BY 1
92                    ORDER BY a.commercial ASC";
93
94            $json_ids_incomplete_data = DB::select($query);
95
96            $combined = [];
97
98            foreach ($json_ids_no_budget_types as $item) {
99                $email = $item->email;
100
101                $combined[$email] = (object) [
102                    'id' => $item->id,
103                    'commercial' => $item->commercial,
104                    'email' => $email,
105                    'total' => $item->total,
106                    'json_ids_no_budget_types' => json_decode($item->json_ids_no_budget_types),
107                    'json_ids_incomplete_data' => [],
108                ];
109            }
110
111            foreach ($json_ids_incomplete_data as $item) {
112                $email = $item->email;
113
114                if (! isset($combined[$email])) {
115                    $combined[$email] = (object) [
116                        'id' => $item->id,
117                        'commercial' => $item->commercial,
118                        'email' => $email,
119                        'total' => $item->total,
120                        'json_ids_no_budget_types' => [],
121                        'json_ids_incomplete_data' => json_decode($item->json_ids_incomplete_data),
122                    ];
123                } else {
124                    $combined[$email]->total += $item->total;
125                    $combined[$email]->json_ids_incomplete_data = json_decode($item->json_ids_incomplete_data);
126                }
127            }
128
129            $result = array_values($combined);
130
131            if (count($result) > 0) {
132
133                $today = date('d/m/Y');
134
135                for ($i = 0; $i < count($result); $i++) {
136                    $body = '';
137                    $companyCcIds = [];
138                    $jsonIdsNoBudgetTypes = $result[$i]->json_ids_no_budget_types;
139                    $jsonIdsIncompleteData = $result[$i]->json_ids_incomplete_data;
140                    $commercial = $result[$i]->commercial;
141
142                    $subject = "Revisión de warnings en G3W – Acción necesaria en presupuestos {$today} for {$commercial}";
143
144                    if ($toEmailArg != null) {
145                        $toEmail = $toEmailArg;
146                    } else {
147                        $toEmail = $result[$i]->email;
148                    }
149
150                    $body .= "<p>Hola <b>{$commercial}</b>,</p>";
151                    $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>';
152
153                    if ($result[$i]->total > 0) {
154
155                        if ($jsonIdsNoBudgetTypes) {
156                            $totalIdsNoBudgetTypes = count($jsonIdsNoBudgetTypes);
157                            $urlIdsNoBudgetTypes = env('URL')."orders?commercial={$commercial}&g3w_warning=si&g3w_warning_fields=Tipo&company_id={$companyIdArg}";
158                            $body .= '<p><b>PRESUPUESTOS SIN TIPO DE PRESUPUESTO</b><p>';
159                            $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>';
160                            $body .= "<p><b>#<a href='{$urlIdsNoBudgetTypes}'>{$totalIdsNoBudgetTypes}</a> IDs EN G3W:</b></p>";
161                            $body .= '<ul>';
162                            foreach ($jsonIdsNoBudgetTypes as $item) {
163                                $url = env('URL')."orders/{$item->id}?company_id={$item->company_id}";
164                                $href = "<li><a href='{$url}'>{$item->quote_id}</a></li>";
165                                $body .= $href;
166
167                                if (! in_array($item->company_id, $companyCcIds)) {
168                                    array_push($companyCcIds, $item->company_id);
169                                }
170                            }
171
172                            $body .= '</ul>';
173
174                            $body .= '<p>Para solucionarlo:</p>';
175                            $body .= '<ol>';
176                            $body .= '<li>Accede a G3W</li>';
177                            $body .= '<li>Revisa cada presupuesto indicado.</li>';
178                            $body .= '<li>Añade el campo <b>"ORIGEN DE PRESUPUESTO"</b>.</li>';
179                            $body .= '</ol>';
180
181                            $body .= '<p>Si tienes dudas sobre qué origen asignar, puedes consultarlo en el siguiente enlace:</p>';
182                            $url = env('URL').'normalize-g3w';
183                            $body .= "<p><a href='{$url}'><b>Apartado de normalización</b></a></p>";
184                        }
185
186                        if ($jsonIdsIncompleteData) {
187                            $totalIdsIncompleteData = count($jsonIdsIncompleteData);
188                            $urlIdsIncompleteData = env('URL')."orders?commercial={$commercial}&g3w_warning=si&g3w_warning_fields=Email,Datos cliente&company_id={$companyIdArg}";
189                            $body .= '<p><b>DATOS DE CLIENTE INCOMPLETOS</b><p>';
190                            $body .= '<p>En algunos casos, durante el volcado desde G3W, los datos del cliente pueden no haberse trasladado correctamente (por ser un cliente nuevo o por falta de información en G3W).</p>';
191                            $body .= '<p>Por favor, <b>rellena los datos manualmente EN TITAN</b> para los siguientes presupuestos:</p>';
192                            $body .= "<p><b>#<a href='{$urlIdsIncompleteData}'>{$totalIdsIncompleteData}</a> de orden interno:</b></p>";
193                            $body .= '<ul>';
194                            foreach ($jsonIdsIncompleteData as $item) {
195                                $url = env('URL')."orders/{$item->id}?company_id={$item->company_id}";
196                                $href = "<li><a href='{$url}'>{$item->quote_id}</a></li>";
197                                $body .= $href;
198
199                                if (! in_array($item->company_id, $companyCcIds)) {
200                                    array_push($companyCcIds, $item->company_id);
201                                }
202                            }
203                            $body .= '</ul>';
204                        }
205
206                        $body .= '<p>Si tienes cualquier duda sobre esta operativa o necesitas ayuda con alguno de los <i>warnings</i>, no dudes en escribirme.</p>';
207                        $body .= '<p>Gracias por tu atención y colaboración.</p>';
208                        $body .= '<p>Un saludo,</p>';
209
210                        $imgpath = \File::get(public_path('fireservicetitan.png'));
211                        $body .= '<br><p>Fire Service Titan</p>';
212                        $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
213
214                        $html = '<!DOCTYPE html>';
215                        $html .= '<html>';
216                        $html .= '<head>';
217                        $html .= '<meta charset="UTF-8">';
218                        $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
219                        $html .= '</head>';
220                        $html .= '<body>';
221                        $html .= $body;
222                        $html .= '</body>';
223                        $html .= '</html>';
224
225                        if ($toEmail != null) {
226                            $email = new \SendGrid\Mail\Mail;
227
228                            if ($toEmailArg == null) {
229                                $companyCcIds = array_values(array_unique($companyCcIds));
230                                $ccBcc = TblCcG3WEmailReminders::whereIn('company_id', $companyCcIds)->get();
231
232                                $inCc = [];
233
234                                if (count($ccBcc) > 0) {
235                                    foreach ($ccBcc as $data) {
236                                        if ($data->email != $toEmail && ! in_array($data->email, $inCc)) {
237                                            $email->addCc($data->email);
238                                            array_push($inCc, $data->email);
239                                        }
240                                    }
241                                }
242                            }
243
244                            $email->setFrom('fire@fire.es', 'Fire Service Titan');
245                            $email->setSubject($subject);
246                            $email->addTo($toEmail);
247                            $email->addContent('text/html', $html);
248
249                            $email->addAttachment(
250                                $imgpath,
251                                'image/png',
252                                'fireservicetitan.png',
253                                'inline',
254                                'fireservicetitan'
255                            );
256
257                            $sendgrid = new \SendGrid(env('SENDGRID_API_KEY'));
258
259                            $response = $sendgrid->send($email);
260                            if ($response->statusCode() != 202) {
261                                Log::channel('cron_send_g3w_email_reminders')->error('ID: '.$toEmail.' - '.$response->body());
262                            } else {
263                                TblNotificationLogs::create(
264                                    [
265                                        'company_id' => $companyIdArg,
266                                        'commercial' => $commercial,
267                                        'total_g3w_warning' => $result[$i]->total,
268                                        'created_by' => $sentByArg,
269                                    ]
270                                );
271                            }
272                        }
273                    }
274                }
275            }
276
277        } catch (\Exception $e) {
278            Log::channel('cron_send_g3w_email_reminders')->error($e->getMessage());
279        }
280
281        return 0;
282    }
283}