Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 1060
0.00% covered (danger)
0.00%
0 / 45
CRAP
0.00% covered (danger)
0.00%
0 / 1
Notifications
0.00% covered (danger)
0.00%
0 / 1060
0.00% covered (danger)
0.00%
0 / 45
32580
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
20
 list_notifications
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
20
 update_notifications
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
12
 send_follow_up_notification
0.00% covered (danger)
0.00%
0 / 153
0.00% covered (danger)
0.00%
0 / 1
272
 send_request
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 send_g3w_warning
0.00% covered (danger)
0.00%
0 / 21
0.00% covered (danger)
0.00%
0 / 1
12
 send_request_notification
0.00% covered (danger)
0.00%
0 / 139
0.00% covered (danger)
0.00%
0 / 1
272
 get_cc_bcc
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 delete_cc_bcc
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_cc_bcc
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
 create_cc_bcc
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 isEmailValid
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 delete_notifications
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
6
 list_notification_logs
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 delete_notification_logs
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 get_cc_g3w
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 delete_cc_g3w
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_cc_g3w
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
 create_cc_g3w
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 get_cc_bcc_request
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 delete_cc_bcc_request
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_cc_bcc_request
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
 create_cc_bcc_request
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 send_executive
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
56
 send_executive_report
0.00% covered (danger)
0.00%
0 / 188
0.00% covered (danger)
0.00%
0 / 1
240
 get_executive_reports
0.00% covered (danger)
0.00%
0 / 65
0.00% covered (danger)
0.00%
0 / 1
30
 currency
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 get_cc_bcc_executive
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 delete_cc_bcc_executive
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_cc_bcc_executive
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
 create_cc_bcc_executive
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 update_notification_settings
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 get_notification_settings
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 send_report_logs
0.00% covered (danger)
0.00%
0 / 38
0.00% covered (danger)
0.00%
0 / 1
12
 get_emails_acceptance_notifications
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 create_to_email_acceptance
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 delete_to_email_acceptance
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_to_email_acceptance
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
30
 create_cc_email_acceptance
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 delete_cc_email_acceptance
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 update_cc_email_acceptance
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
30
 list_last_follow_up_date
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 update_last_follow_up_date_working_days
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 update_last_follow_up_date
0.00% covered (danger)
0.00%
0 / 37
0.00% covered (danger)
0.00%
0 / 1
30
 delete_last_follow_up_date
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Models\TblNotifications;
6use App\Models\TblCompanies;
7use App\Models\TblCompanyUsers;
8use App\Models\TblUsers;
9use App\Models\TblCcBccNotifications;
10use App\Models\TblNotificationLogs;
11use App\Models\TblCcBccRequestNotifications;
12use App\Models\TblCcG3WEmailReminders;
13use App\Models\TblCcBccExecutiveNotifications;
14use App\Models\TblNotificationSettings;
15use App\Models\TblToAcceptanceNotifications;
16use App\Models\TblCcAcceptanceNotifications;
17use App\Models\TblLastFollowUpDate;
18use Illuminate\Http\Request;
19use Illuminate\Support\Facades\DB;
20use Illuminate\Support\Facades\App;
21use Illuminate\Support\Facades\Storage;
22use Illuminate\Support\Facades\Log;
23use Illuminate\Support\Facades\Artisan;
24use SendGrid\Mail\Mail;
25
26class Notifications extends Controller
27{
28    public function __construct(){
29        $this->locale = @getallheaders()['Locale-ID'];
30        $this->userId = @getallheaders()['User-ID'];
31        $this->region = @getallheaders()['Region'];
32        
33        App::setLocale($this->locale);
34
35        $this->companyIds = array();
36
37        if($this->region != null && $this->region != "" && $this->region != "All"){
38            $this->region = urldecode($this->region);
39
40            $query = "SELECT 
41                        b.company_id
42                    FROM 
43                        tbl_company_users a 
44                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id 
45                    WHERE 
46                        a.user_id = {$this->userId}
47                        AND b.region = '{$this->region}'";
48            
49            $this->companyIds = DB::select($query);
50
51            $this->companyIds = collect($this->companyIds)->pluck('company_id')->toArray();
52        }else{
53            $this->companyIds = TblCompanyUsers::where('user_id', $this->userId)->pluck('company_id')->all();
54        }
55        
56        $this->companyId = implode(',', $this->companyIds);
57    }
58
59    function list_notifications(Request $request){
60
61        try {
62            
63            $data = $request->all();
64            $userId = addslashes($data['user_id']);
65
66            $query = "SELECT
67                        notification_id,
68                        user_id,
69                        REPLACE(content, '<br>', '') content,
70                        link,
71                        is_open,
72                        created_by,
73                        created_at,
74                        updated_by,
75                        updated_at,
76                        CASE
77                            WHEN TIMESTAMPDIFF(SECOND, created_at, NOW()) < 60 THEN
78                                CASE
79                                    WHEN TIMESTAMPDIFF(SECOND, created_at, NOW()) = 1 THEN '1 second ago'
80                                    ELSE CONCAT(TIMESTAMPDIFF(SECOND, created_at, NOW()), ' seconds ago')
81                                END
82                            WHEN TIMESTAMPDIFF(MINUTE, created_at, NOW()) < 60 THEN
83                                CASE
84                                    WHEN TIMESTAMPDIFF(MINUTE, created_at, NOW()) = 1 THEN '1 minute ago'
85                                    ELSE CONCAT(TIMESTAMPDIFF(MINUTE, created_at, NOW()), ' minutes ago')
86                                END
87                            WHEN TIMESTAMPDIFF(HOUR, created_at, NOW()) < 24 THEN
88                                CASE
89                                    WHEN TIMESTAMPDIFF(HOUR, created_at, NOW()) = 1 THEN '1 hour ago'
90                                    ELSE CONCAT(TIMESTAMPDIFF(HOUR, created_at, NOW()), ' hours ago')
91                                END
92                            WHEN TIMESTAMPDIFF(DAY, created_at, NOW()) < 7 THEN
93                                CASE
94                                    WHEN TIMESTAMPDIFF(DAY, created_at, NOW()) = 1 THEN '1 day ago'
95                                    ELSE CONCAT(TIMESTAMPDIFF(DAY, created_at, NOW()), ' days ago')
96                                END
97                            WHEN TIMESTAMPDIFF(WEEK, created_at, NOW()) < 4 THEN
98                                CASE
99                                    WHEN TIMESTAMPDIFF(WEEK, created_at, NOW()) = 1 THEN '1 week ago'
100                                    ELSE CONCAT(TIMESTAMPDIFF(WEEK, created_at, NOW()), ' weeks ago')
101                                END
102                            WHEN TIMESTAMPDIFF(MONTH, created_at, NOW()) < 12 THEN
103                                CASE
104                                    WHEN TIMESTAMPDIFF(MONTH, created_at, NOW()) = 1 THEN '1 month ago'
105                                    ELSE CONCAT(TIMESTAMPDIFF(MONTH, created_at, NOW()), ' months ago')
106                                END
107                            ELSE
108                                CASE
109                                    WHEN TIMESTAMPDIFF(YEAR, created_at, NOW()) = 1 THEN '1 year ago'
110                                    ELSE CONCAT(TIMESTAMPDIFF(YEAR, created_at, NOW()), ' years ago')
111                                END
112                        END AS formatted_created_at
113                    FROM
114                        tbl_notifications
115                    WHERE user_id = {$userId}
116                    ORDER BY
117                        created_at DESC";
118
119            $result = DB::select($query);
120
121            $totalOpenNotification = 0;
122            foreach ($result as $item) {
123                if($item->is_open > 0){
124                    $totalOpenNotification++;
125                }
126            }
127            
128            return response([
129                'message' => 'OK', 
130                'data' => $result,
131                'total' => $totalOpenNotification
132            ]);
133
134        } catch (\Exception $e) {
135            /** @disregard P1014 */
136            $e->exceptionCode = 'LIST_NOTIFICATIONS_EXCEPTION'; 
137            report($e);
138            return response(['message' => 'KO', 'error' => $e->getMessage()]);
139        }
140
141
142    }
143
144    function update_notifications(Request $request, $notificationId){
145
146        try {
147            
148            $data = $request->all();
149
150            if($notificationId == 999999999){
151                TblNotifications::where('user_id', $data['user_id'])->update(array(
152                    'is_open' => null
153                ));   
154            }else{
155                TblNotifications::where('notification_id', $notificationId)->update(array(
156                    'is_open' => null,
157                    'updated_at' => date('Y-m-d H:i:s'),
158                    'updated_by' => $data['updated_by']
159                ));
160            }
161
162            $r = new Request([
163                'user_id' => $data['user_id']
164            ]);
165
166            $result = $this->list_notifications($r);
167            
168            return $result;
169
170        } catch (\Exception $e) {
171            /** @disregard P1014 */
172            $e->exceptionCode = 'UPDATE_NOTIFICATION_EXCEPTION'; 
173            report($e);
174            return response(['message' => 'KO', 'error' => $e->getMessage()]);
175        }
176    }
177
178    function send_follow_up_notification($userId = null){
179
180        try {
181
182            if($userId != null){
183                $this->userId = $userId;
184                $this->locale = 'es';
185                App::setLocale($this->locale);
186            }
187
188            $users = TblUsers::get();
189            $body = "";
190            $allTotalFollowUps = 0;
191            $totalOrders = 0;
192            $totalCompanies = 0;
193            foreach ($users as $user) {
194                $userCompanies = TblCompanyUsers::where('user_id', $user->id)->get();
195
196                $body .= __('language.send_follow_up_notification.body_hello');
197                $body = str_replace('{{username}}', $user->name, $body);
198                
199                $body .= __('language.send_follow_up_notification.body_message');
200                
201                $hasFollowUp = false;
202                $companyCcIds = array();
203                foreach ($userCompanies as $userCompany) {
204                    
205                    $companyId = $userCompany->company_id;
206                    $company = TblCompanies::where('company_id', $companyId)->first();
207
208                    if($company->is_send_follow_up > 0){
209                        $toEmail = $user->email;
210        
211                        $query = "SELECT 
212                                    id,
213                                    quote_id,
214                                    amount,
215                                    DATE_FORMAT(last_follow_up_date, '%d/%m/%Y') last_follow_up_date,
216                                    commercial 
217                                FROM 
218                                    tbl_quotations 
219                                WHERE 
220                                    last_follow_up_date < NOW() 
221                                    AND email IS NOT NULL 
222                                    AND email <> ''
223                                    AND NOT EXISTS (
224                                    SELECT 
225                                        1 
226                                    FROM 
227                                        tbl_blocked_domains bd 
228                                    WHERE 
229                                        email LIKE CONCAT('%', bd.domain, '%') 
230                                        AND bd.company_id = company_id
231                                    )
232                                    AND last_follow_up_date IS NOT NULL
233                                    AND reason_for_not_following_up_id IS NULL
234                                    AND last_follow_up_date > 0
235                                    AND last_follow_up_date < NOW()
236                                    AND total_sent < 3
237                                    AND for_add = 0
238                                    AND company_id = {$companyId}
239                                    AND commercial IS NOT NULL 
240                                    AND commercial = '{$user->name}'
241                                    AND budget_status_id = 2
242                                ORDER BY last_follow_up_date ASC, CAST(amount AS DOUBLE) DESC";
243    
244                        $result = DB::select($query);
245    
246                        $totalFolloUps = count($result);
247    
248                        if($totalFolloUps > 0){
249                            $allTotalFollowUps = $allTotalFollowUps + $totalFolloUps;
250                            array_push($companyCcIds, $companyId);
251
252                            $hasFollowUp = true;
253                            $body .= __('language.send_follow_up_notification.body_company_message');
254                            $body = str_replace('{{total}}', $totalFolloUps, $body);
255                            $body = str_replace('{{company}}', $company->name, $body);
256    
257                            $clickhRef = env('URL') . "orders?commercial={$user->name}&status=Enviado&last_follow_up_date=1&company_id={$companyId}";
258                            $body = str_replace('{{click}}', $clickhRef, $body);
259    
260                            $ul = "<ul>";
261    
262                            $list = "";
263                            $totalAmount = 0;
264                            for ($i = 0; $i < $totalFolloUps; $i++) { 
265                                $li = __('language.send_follow_up_notification.body_due');
266    
267                                $id = $result[$i]->id;
268                                $date = $result[$i]->last_follow_up_date;
269                                $quoteId = $result[$i]->quote_id;
270                                $totalAmount = $totalAmount + $result[$i]->amount;
271                                $amount = $this->currency($result[$i]->amount, 1);
272    
273                                $url = env('URL') . "orders/{$id}?company_id={$companyId}";
274                                $href = "<a href='{$url}'>{$quoteId}</a>";
275    
276                                $li = str_replace('{{quote_id}}', $href, $li);
277                                $li = str_replace('{{amount}}', $amount, $li);
278                                $list .= str_replace('{{date}}', $date, $li);
279                            }
280                            $ul .= $list;
281                            $ul .= "</ul>";
282    
283                            $totalAmount = $this->currency($totalAmount, 1);
284                            $body = str_replace('{{amount}}', $totalAmount, $body);
285    
286                            $content = $body . $ul;
287    
288                            $body .= $ul;
289
290                        }else{
291                            continue;
292                        }
293                    }else{
294                        continue;
295                    }
296                }
297                
298                if($hasFollowUp){
299
300                    $body = str_replace('{{totalOrders}}', $allTotalFollowUps, $body);
301                    $body = str_replace('{{totalCompanies}}', count($companyCcIds), $body);
302
303                    $clickhRef = env('URL') . "orders?commercial={$user->name}&status=Enviado&last_follow_up_date=1&company_id=0";
304                    $body = str_replace('{{clickAll}}', $clickhRef, $body);
305
306                    $imgpathS = \File::get(public_path('sendfollowups.png'));
307                    $img = "<br><img src='cid:sendfollowups' />";
308                    $body .= $img;
309
310                    $imgpath = \File::get(public_path('fireservicetitan.png'));
311                    $body .= "<br><p>Fire Service Titan</p>";
312                    $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
313                    
314                    $html = '<!DOCTYPE html>';
315                    $html .= '<html>';
316                    $html .= '<head>';
317                    $html .= '<meta charset="UTF-8">';
318                    $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
319                    $html .= '</head>';
320                    $html .= '<body>';
321                    $html .= $body;
322                    $html .= '</body>';
323                    $html .= '</html>';
324
325                    $dateNow = date_create(date('Y-m-d'));
326                    $dateNow = date_format($dateNow,"d/m/Y");
327
328                    $subject = __('language.send_follow_up_notification.subject');
329                    $subject = str_replace('{{dateNow}}', $dateNow, $subject);
330
331                    if($toEmail != null){
332                        $email = new \SendGrid\Mail\Mail(); 
333                        $sentBy = 'System';
334
335                        $email->setFrom('fire@fire.es', 'Fire Service Titan');
336                        $email->setSubject($subject);
337
338                        $userAdmin = TblUsers::where('id', $this->userId)->first();
339                        $sentBy = $userAdmin->name;
340
341                        if(env('SENDGRID_STAGING')){
342                            $toEmail = $userAdmin->email;
343                            $sentBy = $userAdmin->name;
344                            $user->id = $this->userId;
345                        }else{
346                            $companyCcIds = array_values(array_unique($companyCcIds));
347                            $ccBcc = TblCcBccNotifications::whereIn('company_id', $companyCcIds)->get();                            
348
349                            $inCc = array();
350
351                            if(count($ccBcc) > 0){
352                                foreach ($ccBcc as $data) {
353                                    if($data->email != $toEmail && !in_array($data->email, $inCc)){
354                                        $email->addCc($data->email);
355                                        array_push($inCc, $data->email);
356                                    }
357                                }
358                            }
359                        }
360
361                        $email->addTo($toEmail);
362                        $email->addContent("text/html", $html);
363
364                        $email->addAttachment(
365                            $imgpath,
366                            "image/png",
367                            "fireservicetitan.png",
368                            "inline",
369                            "fireservicetitan"
370                        );
371
372                        $email->addAttachment(
373                            $imgpathS,
374                            "image/png",
375                            "sendfollowups.png",
376                            "inline",
377                            "sendfollowups"
378                        );
379
380                        $sendgrid = new \SendGrid(env('SENDGRID_API_KEY','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'));
381
382                        $response = $sendgrid->send($email);
383                        if ($response->statusCode() == 202) {
384                            Log::channel('email_log')->info('ID: '. $toEmail .' - TO FOLLOW UP EMAIL NOTIFICATION SENT');
385                            
386                            TblNotifications::create(
387                                array(
388                                    'user_id' => $user->id,
389                                    'content' => $content,
390                                    'is_open' => 1,
391                                    'created_by' => 'System',
392                                )
393                            );
394
395                            TblNotificationLogs::create(
396                                array(
397                                    'commercial' => $user->name,
398                                    'total_follow_ups' => $allTotalFollowUps,
399                                    'created_by' => $sentBy
400                                )
401                            );
402                            
403                        } else {
404                            $error = true;
405                            Log::channel('email_log')->error('ID: '. $toEmail .' - ' . $response->body());
406                        }
407
408                        $body = "";
409                        $content = "";
410                    }
411                }
412
413                $hasFollowUp = false;
414                $body = "";
415                $content = "";
416                $allTotalFollowUps = 0;
417            }
418
419            return response([
420                'message' => 'OK'
421            ]);
422
423        } catch (\Exception $e) {
424            /** @disregard P1014 */
425            $e->exceptionCode = 'SEND_FOLLOW_UP_NOTIFICATION_EXCEPTION'; 
426            report($e);
427            return response(['message' => 'KO', 'error' => $e->getMessage()]);
428        }
429    }
430
431    function send_request($companyId){
432
433        try {
434
435            $companyId = addslashes($companyId);
436
437            $user = array('commercial');
438            
439            foreach ($user as $col) {
440                $this->send_request_notification($companyId, $col);
441            }
442
443            return response([
444                'message' => 'OK'
445            ]);
446            
447        } catch (\Exception $e) {
448            /** @disregard P1014 */
449            $e->exceptionCode = 'SEND_REQUEST_EXCEPTION'; 
450            report($e);
451            return response(['message' => 'KO', 'error' => $e->getMessage()]);
452        }
453
454    }
455
456    function send_g3w_warning($companyId){
457
458        try {
459
460            $companyId = addslashes($companyId);
461            
462            $userAdmin = TblUsers::where('id', $this->userId)->first();
463
464            if(env('SENDGRID_STAGING')){                
465                Artisan::call('send:g3w-email-reminders', [
466                    'sent_by' => $userAdmin->name,
467                    'email' => $userAdmin->email,
468                    'company_id' => $companyId
469                ]);
470            }else{
471                Artisan::call('send:g3w-email-reminders', [
472                    'sent_by' => $userAdmin->name,
473                    'email' => null,
474                    'company_id' => $companyId
475                ]);
476            }
477            
478            $output = Artisan::output();
479        
480            return response([
481                'message' => 'OK'
482            ]);
483
484        } catch (\Exception $e) {
485            /** @disregard P1014 */
486            $e->exceptionCode = 'SEND_G3W_WARNING_EXCEPTION'; 
487            report($e);
488            return response(['message' => 'KO', 'error' => $e->getMessage()]);
489        }
490
491    }
492
493    function send_request_notification($userId = null){
494
495        try {
496
497            if($userId != null){
498                $this->userId = $userId;
499                $this->locale = 'es';
500                App::setLocale($this->locale);
501            }
502
503            $users = TblUsers::get();
504            $body = "";
505            $allTotalRequest = 0;
506            
507            foreach ($users as $user) {
508                $userCompanies = TblCompanyUsers::where('user_id', $user->id)->get();
509
510                $body .= __('language.send_request_notification.body_hello');
511                $body = str_replace('{{username}}', $user->name, $body);
512                $body .= __('language.send_request_notification.body_intro');
513
514                $hasRequest = false;
515                $companyCcIds = array();
516                foreach ($userCompanies as $userCompany) {
517                    
518                    $companyId = $userCompany->company_id;
519                    $company = TblCompanies::where('company_id', $companyId)->first();
520
521                    if($company->is_send_request > 0){
522                        $toEmail = $user->email;
523        
524                        $query = "SELECT 
525                                    id,
526                                    quote_id,
527                                    DATE_FORMAT(created_at, '%d/%m/%Y') created_at,
528                                    commercial,
529                                    created_by
530                                FROM 
531                                    tbl_quotations 
532                                WHERE 
533                                    company_id = {$companyId}
534                                    AND budget_status_id IN (6)
535                                    AND commercial = '{$user->name}'";
536    
537                        $result = DB::select($query);
538    
539                        $totalRequest = count($result);
540    
541                        if($totalRequest > 0){
542                            $allTotalRequest = $allTotalRequest + $totalRequest;
543                            $hasRequest = true;
544                            array_push($companyCcIds, $companyId);
545
546                            $body .= __('language.send_request_notification.body_message_commercial');
547                            $body = str_replace('{{total}}', $totalRequest, $body);
548                            $body = str_replace('{{company}}', $company->name, $body);
549    
550                            $clickhRef = env('URL') . "orders?commercial={$user->name}&status=Solicitud&company_id={$companyId}";
551                            $body = str_replace('{{click}}', $clickhRef, $body);
552    
553                            $ul = "<ul>";
554    
555                            $list = "";
556                            $totalAmount = 0;
557                            for ($i = 0; $i < $totalRequest; $i++) { 
558                                $li = __('language.send_request_notification.body_due');
559
560                                $id = $result[$i]->id;
561                                $date = $result[$i]->created_at;
562                                $quoteId = $result[$i]->quote_id;
563
564                                $url = env('URL') . "orders/{$id}?company_id={$companyId}";
565                                $href = "<a href='{$url}'>{$quoteId}</a>";
566
567                                $li = str_replace('{{quote_id}}', $href, $li);
568                                $list .= str_replace('{{date}}', $date, $li);
569                            }
570                            $ul .= $list;
571                            $ul .= "</ul>";
572    
573                            $totalAmount = $this->currency($totalAmount, 1);
574                            $body = str_replace('{{amount}}', $totalAmount, $body);
575    
576                            $content = $body . $ul;
577    
578                            $body .= $ul;
579
580                        }else{
581                            continue;
582                        }
583                    }else{
584                        continue;
585                    }
586                }
587
588                if($hasRequest){
589
590                    $body = str_replace('{{totalOrders}}', $allTotalRequest, $body);
591                    $body = str_replace('{{totalCompanies}}', count($companyCcIds), $body);
592
593                    $clickhRef = env('URL') . "orders?commercial={$user->name}&status=Solicitud&company_id=0";
594                    $body = str_replace('{{clickAll}}', $clickhRef, $body);
595
596                    $imgpath = \File::get(public_path('fireservicetitan.png'));
597
598                    $body .= "<br><p>Fire Service Titan</p>";
599                    $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
600                    
601                    $html = '<!DOCTYPE html>';
602                    $html .= '<html>';
603                    $html .= '<head>';
604                    $html .= '<meta charset="UTF-8">';
605                    $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
606                    $html .= '</head>';
607                    $html .= '<body>';
608                    $html .= $body;
609                    $html .= '</body>';
610                    $html .= '</html>';
611
612                    $dateNow = date_create(date('Y-m-d'));
613                    $dateNow = date_format($dateNow,"d/m/Y");
614
615                    $subject = __('language.send_request_notification.subject');
616                    $subject = str_replace('{{dateNow}}', $dateNow, $subject);
617                    $subject = str_replace('{{total}}', $allTotalRequest, $subject);
618
619                    if($toEmail != null){
620                        $email = new \SendGrid\Mail\Mail(); 
621                        $sentBy = 'System';
622
623                        $email->setFrom('fire@fire.es', 'Fire Service Titan');
624                        $email->setSubject($subject);
625
626                        $userAdmin = TblUsers::where('id', $this->userId)->first();
627                        $sentBy = $userAdmin->name;
628
629                        if(env('SENDGRID_STAGING')){
630                            $toEmail = $userAdmin->email;
631                            $sentBy = $userAdmin->name;
632                            $user->id = $this->userId;
633                        }else{
634                            $companyCcIds = array_values(array_unique($companyCcIds));
635                            $ccBcc = TblCcBccRequestNotifications::whereIn('company_id', $companyCcIds)->get();
636
637                            $inCc = array();
638
639                            if(count($ccBcc) > 0){
640                                foreach ($ccBcc as $data) {
641                                    if($data->email != $toEmail && !in_array($data->email, $inCc)){
642                                        $email->addCc($data->email);
643                                        array_push($inCc, $data->email);
644                                    }
645                                }
646                            }
647                        }
648
649                        $email->addTo($toEmail);
650                        $email->addContent("text/html", $html);
651
652                        $email->addAttachment(
653                            $imgpath,
654                            "image/png",
655                            "fireservicetitan.png",
656                            "inline",
657                            "fireservicetitan"
658                        );
659
660                        $sendgrid = new \SendGrid(env('SENDGRID_API_KEY','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'));
661
662                        $response = $sendgrid->send($email);
663                        if ($response->statusCode() == 202) {
664                            Log::channel('email_log')->info('ID:' . $toEmail .' - REQUEST EMAIL NOTIFICATION SENT');
665                            
666                            TblNotifications::create(
667                                array(
668                                    'user_id' => $user->id,
669                                    'content' => $content,
670                                    'is_open' => 1,
671                                    'created_by' => 'System',
672                                )
673                            );
674
675                            TblNotificationLogs::create(
676                                array(
677                                    'company_id' => $companyId,
678                                    'commercial' => $user->name,
679                                    'total_request' => $allTotalRequest,
680                                    'created_by' => $sentBy
681                                )
682                            );
683                            
684                        } else {
685                            $error = true;
686                            Log::channel('email_log')->error('ID:' . $toEmail .' - ' . $response->body());
687                        }
688
689                        $body = "";
690                        $content = "";
691                    }
692                }
693
694                $hasRequest = false;
695                $body = "";
696                $content = "";
697                $allTotalRequest = 0;
698            }
699
700            return response([
701                'message' => 'OK'
702            ]);
703
704
705        } catch (\Exception $e) {
706            /** @disregard P1014 */
707            $e->exceptionCode = 'SEND_REQUEST_EXCEPTION'; 
708            report($e);
709            return response(['message' => 'KO', 'error' => $e->getMessage()]);
710        }
711    }
712
713    function get_cc_bcc($id){
714
715        try {
716            
717            $companyId = addslashes($id);
718
719            $result = TblCcBccNotifications::where('company_id', $companyId)->get();
720
721            return response(['message' => 'OK', 'data' => $result]);
722
723        } catch (\Exception $e) {
724            /** @disregard P1014 */
725            $e->exceptionCode = 'GET_CC_BCC_EXCEPTION'; 
726            report($e);
727            return response(['message' => 'KO', 'error' => $e->getMessage()]);
728        }
729    }
730
731    function delete_cc_bcc($id){
732
733        try {
734            
735            $id = addslashes($id);
736
737            TblCcBccNotifications::where('id', $id)->delete();
738
739            return response(['message' => 'OK']);
740
741        } catch (\Exception $e) {
742            /** @disregard P1014 */
743            $e->exceptionCode = 'DELETE_CC_BCC_EXCEPTION'; 
744            report($e);
745            return response(['message' => 'KO', 'error' => $e->getMessage()]);
746        }
747    }
748
749    function update_cc_bcc(Request $request, $id){
750
751        try {
752
753            $data = $request->all();
754            $id = addslashes($id);
755
756            $x = $this->isEmailValid($data['email']);
757
758            if($x){
759                $result = TblCcBccNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
760
761                if($result > 0){
762                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
763                }else{
764                    $data['updated_at'] = date('Y-m-d H:i:s');
765                    TblCcBccNotifications::where('id', $id)->update($data);
766                }
767            }else{
768                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
769            }
770
771            return response(['message' => 'OK']);
772
773        } catch (\Exception $e) {
774            /** @disregard P1014 */
775            $e->exceptionCode = 'UPDATE_CC_BCC_EXCEPTION'; 
776            report($e);
777            return response(['message' => 'KO', 'error' => $e->getMessage()]);
778        }
779    }
780
781    function create_cc_bcc(Request $request){
782
783        try {
784            
785            $data = $request->all();
786
787            $x = $this->isEmailValid($data['email']);
788
789            if($x){
790                $result = TblCcBccNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
791
792                if($result > 0){
793                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
794                }else{
795                    TblCcBccNotifications::create($data);
796                }
797            }else{
798                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
799            }
800            
801            return response(['message' => 'OK']);
802
803        } catch (\Exception $e) {
804            /** @disregard P1014 */
805            $e->exceptionCode = 'CREATE_CC_BCC_EXCEPTION'; 
806            report($e);
807            return response(['message' => 'KO', 'error' => $e->getMessage()]);
808        }
809    }
810
811    function isEmailValid($email) {
812        // Regular expression pattern for email validation
813        $pattern = '/^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/';
814        
815        // Check if the email matches the pattern
816        if (preg_match($pattern, $email)) {
817            return true; // Valid email
818        } else {
819            return false; // Invalid email
820        }
821    }
822
823    function delete_notifications($userId){
824
825        try {
826            
827            $userId = addslashes($userId);
828
829            TblNotifications::where('user_id', $userId)->delete();
830
831            $r = new Request([
832                'user_id' => $userId
833            ]);
834
835            $result = $this->list_notifications($r);
836            
837            return $result;
838
839        } catch (\Exception $e) {
840            /** @disregard P1014 */
841            $e->exceptionCode = 'DELETE_NOTIFICATIONS_EXCEPTION'; 
842            report($e);
843            return response(['message' => 'KO', 'error' => $e->getMessage()]);
844        }
845
846    }
847
848    function list_notification_logs($companyId){
849
850        try {
851            
852            $companyId = addslashes($companyId);
853
854            if($companyId != 0){
855                $where = " company_id = {$companyId} ";
856            }else{
857                $where = " company_id IN ({$this->companyId}";
858            }
859
860            $query = "SELECT
861                        id,
862                        commercial,
863                        total_follow_ups,
864                        total_request,
865                        total_executive_report,
866                        total_g3w_warning,
867                        CASE 
868                            WHEN total_follow_ups IS NOT NULL THEN total_follow_ups
869                            WHEN total_request IS NOT NULL THEN total_request
870                            WHEN total_executive_report IS NOT NULL THEN total_executive_report
871                            WHEN total_g3w_warning IS NOT NULL THEN total_g3w_warning
872                        END totals,
873                        created_by,
874                        created_at
875                    FROM `tbl_notification_logs` 
876                    WHERE {$where}
877                    OR company_id IS NULL
878                    ORDER BY created_at DESC";
879
880            $result = DB::select($query);
881            
882            return response(['message' => 'OK', 'data' => $result]);
883
884        } catch (\Exception $e) {
885            /** @disregard P1014 */
886            $e->exceptionCode = 'LIST_NOTIFICATION_LOGS_EXCEPTION'; 
887            report($e);
888            return response(['message' => 'KO', 'error' => $e->getMessage()]);
889        }
890
891    }
892
893    function delete_notification_logs($companyId){
894
895        try {
896            
897            $companyId = addslashes($companyId);
898
899            TblNotificationLogs::where('company_id', $companyId)->orWhere('company_id', null)->delete();
900            
901            return response(['message' => 'OK']);
902
903        } catch (\Exception $e) {
904            /** @disregard P1014 */
905            $e->exceptionCode = 'DELETE_NOTIFICATION_LOGS_EXCEPTION'; 
906            report($e);
907            return response(['message' => 'KO', 'error' => $e->getMessage()]);
908        }
909    }
910
911    function get_cc_g3w($id){
912
913        try {
914            
915            $companyId = addslashes($id);
916
917            $result = TblCcG3WEmailReminders::where('company_id', $companyId)->get();
918
919            return response(['message' => 'OK', 'data' => $result]);
920
921        } catch (\Exception $e) {
922            /** @disregard P1014 */
923            $e->exceptionCode = 'GET_CC_G3W_EXCEPTION'; 
924            report($e);
925            return response(['message' => 'KO', 'error' => $e->getMessage()]);
926        }
927    }
928
929    function delete_cc_g3w($id){
930
931        try {
932            
933            $id = addslashes($id);
934
935            TblCcG3WEmailReminders::where('id', $id)->delete();
936
937            return response(['message' => 'OK']);
938
939        } catch (\Exception $e) {
940            /** @disregard P1014 */
941            $e->exceptionCode = 'DELETE_CC_G3W_EXCEPTION'; 
942            report($e);
943            return response(['message' => 'KO', 'error' => $e->getMessage()]);
944        }
945    }
946
947    function update_cc_g3w(Request $request, $id){
948
949        try {
950
951            $data = $request->all();
952            $id = addslashes($id);
953
954            $x = $this->isEmailValid($data['email']);
955
956            if($x){
957                $result = TblCcG3WEmailReminders::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
958
959                if($result > 0){
960                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
961                }else{
962                    $data['updated_at'] = date('Y-m-d H:i:s');
963                    TblCcG3WEmailReminders::where('id', $id)->update($data);
964                }
965            }else{
966                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
967            }
968
969            return response(['message' => 'OK']);
970
971        } catch (\Exception $e) {
972            /** @disregard P1014 */
973            $e->exceptionCode = 'UPDATE_CC_G3W_EXCEPTION'; 
974            report($e);
975            return response(['message' => 'KO', 'error' => $e->getMessage()]);
976        }
977    }
978
979    function create_cc_g3w(Request $request){
980
981        try {
982            
983            $data = $request->all();
984
985            $x = $this->isEmailValid($data['email']);
986
987            if($x){
988                $result = TblCcG3WEmailReminders::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
989
990                if($result > 0){
991                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
992                }else{
993                    TblCcG3WEmailReminders::create($data);
994                }
995            }else{
996                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
997            }
998            
999            return response(['message' => 'OK']);
1000
1001        } catch (\Exception $e) {
1002            /** @disregard P1014 */
1003            $e->exceptionCode = 'CREATE_CC_G3W_EXCEPTION'; 
1004            report($e);
1005            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1006        }
1007    }
1008
1009    function get_cc_bcc_request($id){
1010
1011        try {
1012            
1013            $companyId = addslashes($id);
1014
1015            $result = TblCcBccRequestNotifications::where('company_id', $companyId)->get();
1016
1017            return response(['message' => 'OK', 'data' => $result]);
1018
1019        } catch (\Exception $e) {
1020            /** @disregard P1014 */
1021            $e->exceptionCode = 'GET_CC_BCC_REQUEST_EXCEPTION'; 
1022            report($e);
1023            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1024        }
1025    }
1026
1027    function delete_cc_bcc_request($id){
1028
1029        try {
1030            
1031            $id = addslashes($id);
1032
1033            TblCcBccRequestNotifications::where('id', $id)->delete();
1034
1035            return response(['message' => 'OK']);
1036
1037        } catch (\Exception $e) {
1038            /** @disregard P1014 */
1039            $e->exceptionCode = 'DELETE_CC_BCC_REQUEST_EXCEPTION'; 
1040            report($e);
1041            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1042        }
1043    }
1044
1045    function update_cc_bcc_request(Request $request, $id){
1046
1047        try {
1048
1049            $data = $request->all();
1050            $id = addslashes($id);
1051
1052            $x = $this->isEmailValid($data['email']);
1053
1054            if($x){
1055                $result = TblCcBccRequestNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1056
1057                if($result > 0){
1058                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1059                }else{
1060                    $data['updated_at'] = date('Y-m-d H:i:s');
1061                    TblCcBccRequestNotifications::where('id', $id)->update($data);
1062                }
1063            }else{
1064                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1065            }
1066
1067            return response(['message' => 'OK']);
1068
1069        } catch (\Exception $e) {
1070            /** @disregard P1014 */
1071            $e->exceptionCode = 'UPDATE_CC_BCC_REQUEST_EXCEPTION'; 
1072            report($e);
1073            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1074        }
1075    }
1076
1077    function create_cc_bcc_request(Request $request){
1078
1079        try {
1080            
1081            $data = $request->all();
1082
1083            $x = $this->isEmailValid($data['email']);
1084
1085            if($x){
1086                $result = TblCcBccRequestNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1087
1088                if($result > 0){
1089                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1090                }else{
1091                    TblCcBccRequestNotifications::create($data);
1092                }
1093            }else{
1094                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1095            }
1096            
1097            return response(['message' => 'OK']);
1098
1099        } catch (\Exception $e) {
1100            /** @disregard P1014 */
1101            $e->exceptionCode = 'CREATE_CC_BCC_REQUEST_EXCEPTION'; 
1102            report($e);
1103            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1104        }
1105    }
1106
1107    function send_executive(Request $request){
1108
1109        try {
1110            
1111            $data = $request->all();
1112
1113            $executiveEmails = TblCcBccExecutiveNotifications::get();
1114
1115            if(isset($data['User-ID'])){
1116                $this->userId = $data['User-ID'];
1117            }
1118            
1119            if(isset($data['self']) && $data['self'] == 1){
1120                $user = TblUsers::where('id', $this->userId)->first();
1121                $this->send_executive_report($user->email, $user->name, $user->id, $data['processed_by']);   
1122            }else{
1123                foreach ($executiveEmails as $item) {
1124                    $user = TblUsers::where('email', $item->email)->first();
1125                    if($user){                    
1126                        $this->send_executive_report($item->email, $user->name, $user->id, $data['processed_by']);   
1127                    }
1128                }
1129            }
1130
1131            return response([
1132                'message' => 'OK'
1133            ]);
1134            
1135        } catch (\Exception $e) {
1136            /** @disregard P1014 */
1137            $e->exceptionCode = 'SEND_EXECUTIVE_EXCEPTION'; 
1138            report($e);
1139            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1140        }
1141
1142    }
1143
1144    function send_executive_report($toEmail, $toName, $toUserId, $sentBy = 'System'){
1145
1146        try{
1147
1148            $result = TblNotificationSettings::where('id', 1)->first();
1149
1150            $currentYear = date('Y');
1151            $previousYear = date('Y', strtotime('-1 year', strtotime(date('Y-m-d'))));
1152
1153            if($toEmail != null && $result->is_auto_send_executive == 1){
1154
1155                if(env('SENDGRID_STAGING')){
1156                    $user = TblUsers::where('id', $this->userId)->first();
1157                    $toEmail = $user->email;
1158                }
1159                
1160                $result = (object) $this->get_executive_reports();
1161
1162                $weekNumber = $result->weekNumber;
1163                $monday = $result->monday;
1164                $totalBudgets = number_format($result->totalBudgets, 0, ',', '.');
1165                $totalAmountApproved = $result->totalAmountApproved;
1166                $totalAmount = $result->totalAmount;
1167                $dividendMaintenance = $result->dividendMaintenance;
1168                $dividendCorrectives = $result->dividendCorrectives;
1169                $percentageMoreThanLastWeek = $result->percentageMoreThanLastWeek;
1170                $approvalRate = $result->approvalRate;
1171    
1172                $subject = "FST executive report week $weekNumber (starting on monday - $monday) - Automated";
1173
1174                $body = "<p>Hello {$toName},</p>";
1175
1176                $url = env('URL') . "analytics?week={$weekNumber}";
1177                $body .= "<p>Find a summary of the commercial activity across <b>Grupo Fire</b> (see the <a href='{$url}'>report on FST here</a>) for week {$weekNumber} (starting on monday - {$monday})</p>";
1178                $body .= "<p><b>{$totalBudgets} budget(s)</b> ({$percentageMoreThanLastWeek}% compared to last week) created for a total of <b>{$totalAmount}</b> ({$dividendMaintenance}% “Mantenimiento”, {$dividendCorrectives}% “Correctivos”) - ";
1179                $body .= "this week across all companies - <i>we have an approval rate of <b>{$approvalRate}%</b> for the month <b>(<span style='color: blue;'>{$totalAmountApproved} approved</span>)</b></i></p>";
1180    
1181                $query = "SELECT 
1182                            a.company_id, 
1183                            a.name,
1184                            (
1185                            SELECT 
1186                                COUNT(created_at) 
1187                            FROM 
1188                                tbl_quotations 
1189                            WHERE 
1190                                company_id = a.company_id
1191                                AND for_add = 0 
1192                                AND created_at IS NOT NULL 
1193                                AND issue_date IS NOT NULL
1194                                AND YEAR(created_at) = YEAR(issue_date)
1195                            ) total 
1196                        FROM 
1197                            tbl_companies a 
1198                            WHERE is_send_executive = 1
1199                            -- AND company_id IN ({$this->companyId})
1200                        ORDER BY 
1201                            3 DESC
1202                        ";
1203                
1204                $companies = DB::select($query);
1205                
1206                $li = array();
1207    
1208                foreach ($companies as $company) {
1209                    $result = (object) $this->get_executive_reports($company->company_id);
1210                    $result->name = $company->name;
1211                    array_push($li, $result);
1212                }
1213    
1214                usort($li, function ($a, $b) {
1215                    return $b->totalBudgets - $a->totalBudgets;
1216                });
1217                
1218                $body .= "<ul>";
1219                foreach ($li as $result) {
1220                    $totalBudgets = number_format($result->totalBudgets, 0, ',', '.');
1221                    $totalAmount = $result->totalAmount;
1222                    $dividendMaintenance = $result->dividendMaintenance;
1223                    $dividendCorrectives = $result->dividendCorrectives;
1224                    $percentageMoreThanLastWeek = $result->percentageMoreThanLastWeek;
1225                    $approvalRate = $result->approvalRate;
1226    
1227                    $body .= "<li>{$totalBudgets} order(s) in “<b>{$result->name}</b>” ({$dividendMaintenance}% “Mantenimiento”, {$dividendCorrectives}% “Correctivos”) for total of <b>{$totalAmount}</b></li>";
1228                }
1229                $body .= "</ul>";
1230    
1231                
1232                $result = (object) $this->get_executive_reports(null, true, $currentYear);
1233                
1234                $totalBudgets = number_format($result->totalBudgets, 0, ',', '.');
1235                $totalAmountApproved = $result->totalAmountApproved;
1236                $totalAmount = $result->totalAmount;
1237                $dividendMaintenance = $result->dividendMaintenance;
1238                $dividendCorrectives = $result->dividendCorrectives;
1239                $percentageMoreThanLastWeek = $result->percentageMoreThanLastWeek;
1240                $approvalRate = $result->approvalRate;
1241                $totalDaysFromStartOfYear = date('z') + 1;
1242                $totalDaysOfCurrentYear = date('z', mktime(0, 0, 0, 12, 31,date('Y'))) + 1;
1243                $expected = 0;
1244
1245                $totalGoalForTheYear = 0;
1246                if($result->totalGoalForTheYear > 0){
1247                    $totalGoalForTheYear = number_format(($result->totalBudgets / $result->totalGoalForTheYear) * 100, 0, ',', '.');
1248                    $expected = number_format(($totalDaysFromStartOfYear / $totalDaysOfCurrentYear) * 100, 0, ',', '.');
1249                }
1250    
1251                $body .= "<p><b>For {$currentYear}</b> as a whole, <b><span style='color: blue;'>{$totalBudgets}</span> budgets (<span style='color: blue;'>{$totalGoalForTheYear}% of the goal for the year accomplished</span> vs {$expected}% expected) for a total of <span style='color: blue;'>{$totalAmount}</span></b> ({$dividendMaintenance}% “Mantenimientos”, {$dividendCorrectives}% “Correctivos”) ";
1252                $body .= "were created across all companies - <i>we have an approval rate of <b>{$approvalRate}%</b> for the year <b>(<span style='color: blue;'>{$totalAmountApproved} approved</span>)</b></i></p>";                            
1253
1254                $query = "SELECT 
1255                            a.company_id, 
1256                            a.name,
1257                            (
1258                            SELECT 
1259                                COUNT(created_at) 
1260                            FROM 
1261                                tbl_quotations 
1262                            WHERE 
1263                                company_id = a.company_id
1264                                AND for_add != 1
1265                                AND amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1266                                AND created_at IS NOT NULL 
1267                                AND YEAR(created_at) = {$currentYear}                                
1268                            ) total 
1269                        FROM 
1270                            tbl_companies a 
1271                            WHERE is_send_executive = 1
1272                            -- AND company_id IN ({$this->companyId})
1273                        ORDER BY 
1274                            3 DESC
1275                        ";
1276                
1277                $companies = DB::select($query);
1278
1279                $li = array();
1280    
1281                foreach ($companies as $company) {
1282                    $result = (object) $this->get_executive_reports($company->company_id, true, $currentYear);
1283                    $result->name = $company->name;
1284                    array_push($li, $result);
1285                }
1286    
1287                usort($li, function ($a, $b) {
1288                    return $b->totalBudgets - $a->totalBudgets;
1289                });
1290
1291                $body .= "<ul>";
1292                foreach ($li as $result) {
1293                    
1294                    $totalBudgets = number_format($result->totalBudgets, 0, ',', '.');
1295                    $totalAmountApproved = $result->totalAmountApproved;
1296                    $totalAmount = $result->totalAmount;
1297                    $dividendMaintenance = $result->dividendMaintenance;
1298                    $dividendCorrectives = $result->dividendCorrectives;
1299                    $percentageMoreThanLastWeek = $result->percentageMoreThanLastWeek;
1300                    $approvalRate = $result->approvalRate;
1301                    $goalForTheYear = number_format($result->totalGoalForTheYear, 0, ',', '.');
1302                    $totalDaysFromStartOfYear = date('z') + 1;
1303                    $totalDaysOfCurrentYear = date('z', mktime(0, 0, 0, 12, 31,date('Y'))) + 1;
1304                    $expected = 0;
1305
1306                    $totalGoalForTheYear = 0;
1307                    $style = "style='color: green'";
1308                    if($result->totalGoalForTheYear > 0){
1309                        $totalGoalForTheYear = number_format(($result->totalBudgets / $result->totalGoalForTheYear) * 100, 0, ',', '.');
1310                        $expected = number_format(($totalDaysFromStartOfYear / $totalDaysOfCurrentYear) * 100, 0, ',', '.');
1311
1312                        if($totalGoalForTheYear < $expected){
1313                            $style = "style='color: red'";
1314                        }
1315                    }
1316    
1317                    $body .= "<li>{$totalBudgets} order(s) in “<b>{$result->name}</b>” ({$dividendMaintenance}% “Mantenimiento”, {$dividendCorrectives}% “Correctivos”) for total of <b>{$totalAmount}</b></li>";
1318                    $body .= "<ul>";
1319                    $body .= "<li><i><b>{$goalForTheYear} goal</b> for the year. <b {$style}>{$totalGoalForTheYear}%</b> accomplished to date vs <b>{$expected}% expected</b></i></li>";
1320                    $body .= "<li><i>Approval rate of <b>{$approvalRate}%</b> (<span style='color: blue;'>{$totalAmountApproved} approved</span>)</i></li>";
1321                    $body .= "</ul>";
1322                }
1323
1324                $body .= "</ul>";
1325    
1326                
1327                $result = (object) $this->get_executive_reports(null, true, $previousYear);
1328                
1329                $totalBudgets = number_format($result->totalBudgets, 0, ',', '.');
1330                $totalAmount = $result->totalAmount;
1331                $dividendMaintenance = $result->dividendMaintenance;
1332                $dividendCorrectives = $result->dividendCorrectives;
1333                $percentageMoreThanLastWeek = $result->percentageMoreThanLastWeek;
1334                $approvalRate = $result->approvalRate;
1335    
1336                $body .= "<p>For your reference, in <b>{$previousYear}</b>, <b>{$totalBudgets} budgets for a total of {$totalAmount}</b> ({$dividendMaintenance}% “Mantenimientos”, {$dividendCorrectives}% “Correctivos”) ";
1337                $body .= "were created across all companies - <i>we have an approval rate of <b>{$approvalRate}%</b> for the year</i></p>";                            
1338
1339                $query = "SELECT 
1340                            a.company_id, 
1341                            a.name,
1342                            (
1343                            SELECT 
1344                                COUNT(created_at) 
1345                            FROM 
1346                                tbl_quotations 
1347                            WHERE 
1348                                company_id = a.company_id
1349                                AND for_add != 1
1350                                AND amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1351                                AND created_at IS NOT NULL 
1352                                AND YEAR(created_at) = {$currentYear}
1353                            ) total 
1354                        FROM 
1355                            tbl_companies a 
1356                            WHERE is_send_executive = 1
1357                            -- AND company_id IN ({$this->companyId})
1358                        ORDER BY 
1359                            3 DESC
1360                        ";
1361                
1362                $companies = DB::select($query);
1363
1364                $li = array();
1365    
1366                foreach ($companies as $company) {
1367                    $result = (object) $this->get_executive_reports($company->company_id, true, $previousYear);
1368                    $result->name = $company->name;
1369                    array_push($li, $result);
1370                }
1371    
1372                usort($li, function ($a, $b) {
1373                    return $b->totalBudgets - $a->totalBudgets;
1374                });
1375
1376                $body .= "<ul>";
1377
1378                foreach ($li as $result) {
1379                    $totalBudgets = number_format($result->totalBudgets, 0, ',', '.');
1380                    $totalAmount = $result->totalAmount;
1381                    $dividendMaintenance = $result->dividendMaintenance;
1382                    $dividendCorrectives = $result->dividendCorrectives;
1383                    $percentageMoreThanLastWeek = $result->percentageMoreThanLastWeek;
1384                    $approvalRate = $result->approvalRate;
1385    
1386                    $body .= "<li>{$totalBudgets} order(s) in “<b>{$result->name}</b>” ({$dividendMaintenance}% “Mantenimiento”, {$dividendCorrectives}% “Correctivos”) for total of <b>{$totalAmount}</b> <i> - approval rate of <b>{$approvalRate}%</b></i></li>";
1387                }
1388
1389                $body .= "</ul><br><br>";
1390    
1391                $imgpath = \File::get(public_path('fireservicetitan.png'));
1392                
1393                $content = $body;                                
1394
1395                $body .= "<br><p>Fire Service Titan</p>";
1396                $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
1397                
1398                $html = '<!DOCTYPE html>';
1399                $html .= '<html>';
1400                $html .= '<head>';
1401                $html .= '<meta charset="UTF-8">';
1402                $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
1403                $html .= '</head>';
1404                $html .= '<body>';
1405                $html .= $body;
1406                $html .= '</body>';
1407                $html .= '</html>';
1408    
1409                $email = new \SendGrid\Mail\Mail(); 
1410    
1411                $email->setFrom('fire@fire.es', 'Fire Service Titan');
1412                $email->setSubject($subject);
1413    
1414                $email->addTo($toEmail);
1415                $email->addContent("text/html", $html);
1416    
1417                $email->addAttachment(
1418                    $imgpath,
1419                    "image/png",
1420                    "fireservicetitan.png",
1421                    "inline",
1422                    "fireservicetitan"
1423                );
1424    
1425                $sendgrid = new \SendGrid(env('SENDGRID_API_KEY','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'));
1426    
1427                $response = $sendgrid->send($email);
1428                if ($response->statusCode() == 202) {
1429                    Log::channel('email_log')->info('ID:' . $toEmail .' - EXECUTIVE REPORT EMAIL NOTIFICATION SENT');
1430                    
1431                    TblNotifications::create(
1432                        array(
1433                            'user_id' => $toUserId,
1434                            'content' => $content,
1435                            'is_open' => 1,
1436                            'created_by' => 'System',
1437                        )
1438                    );
1439
1440                    TblNotificationLogs::create(
1441                        array(
1442                            'commercial' => $toName,
1443                            'total_executive_report' => 1,
1444                            'created_by' => $sentBy
1445                        )
1446                    );
1447                } else {
1448                    $error = true;
1449                    Log::channel('email_log')->error('ID:' . $toEmail .' - ' . $response->body());
1450                }
1451    
1452                $body = "";
1453    
1454                return response([
1455                    'message' => 'OK'
1456                ]);
1457            }
1458            
1459        } catch (\Exception $e) {
1460            /** @disregard P1014 */
1461            $e->exceptionCode = 'SEND_EXECUTIVE_REPORT_EXCEPTION'; 
1462            report($e);
1463            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1464        }
1465
1466    }
1467
1468    function get_executive_reports($companyId = null, $wholeYear = false, $year = null){
1469
1470        $where = "";
1471        $whereYear = "";
1472        $whereMonth = "DATE_FORMAT(q.created_at, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m') ";
1473
1474        if($companyId != null){
1475            $where = " AND company_id = {$companyId} ";
1476        }
1477
1478        $now = date('Y-m-d');
1479        $weekNumber = date('W', strtotime($now));
1480        $monday = date('F j, Y', strtotime($now . " - " . (date('N', strtotime($now)) - 1) . " days"));
1481
1482        $mondayDate = date('Y-m-d', strtotime($now . " - " . (date('N', strtotime($now)) - 1) . " days"));
1483        $sundayDate = date('Y-m-d', strtotime($mondayDate . " + 6 days"));
1484
1485        $mondayLastWeekDate = date('Y-m-d', strtotime($mondayDate . " - 1 week"));
1486        $sundayLastWeekDate = date('Y-m-d', strtotime($mondayLastWeekDate . " + 6 days"));
1487
1488        $whereAccMonth = "";
1489        if($wholeYear == false){
1490            $whereYear = " AND DATE_FORMAT(q.created_at, '%Y-%m-%d') BETWEEN '{$mondayDate}' AND '{$sundayDate}";
1491            $whereMonth = " AND DATE_FORMAT(q.created_at, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m') ";
1492            $whereAccMonth = " AND DATE_FORMAT(q.acceptance_date, '%Y-%m') = DATE_FORMAT(NOW(), '%Y-%m') ";
1493        }else{
1494            $whereYear = " AND YEAR(q.created_at) = {$year} ";
1495            $whereMonth = " AND YEAR(q.created_at) = {$year} ";
1496            $whereAccMonth = " AND YEAR(q.acceptance_date) = {$year} ";
1497        }
1498
1499        $query = "SELECT 
1500                    COUNT(q.created_at) totalBudgets, 
1501                    SUM(q.amount) totalAmount, 
1502                    COALESCE(
1503                        SUM(CASE WHEN bt.budget_type_group_id = 3 THEN 1 END)
1504                        , 0
1505                    ) / 
1506                    COUNT(q.created_at) * 100 dividendMaintenance, 
1507                    COALESCE(
1508                        SUM(CASE WHEN bt.budget_type_group_id = 5 THEN 1 END)
1509                        , 0
1510                    ) / 
1511                    COUNT(q.created_at) * 100 dividendCorrectives 
1512                FROM 
1513                    tbl_quotations q 
1514                    LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id 
1515                WHERE 
1516                    q.for_add != 1
1517                    AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1518                    AND q.created_at IS NOT NULL 
1519                    AND q.company_id IN (SELECT company_id FROM tbl_companies WHERE is_send_executive = 1 {$where})
1520                    AND q.budget_type_id != 7
1521                    AND YEAR(q.created_at) = YEAR(q.issue_date)
1522                    {$whereYear}
1523                    ";
1524
1525        $result = DB::select($query)[0];
1526
1527        $totalBudgets = $result->totalBudgets;
1528        $totalAmount = $this->currency($result->totalAmount, 1, 0);
1529        $totalAmountC = $result->totalAmount;
1530        $dividendMaintenance = number_format($result->dividendMaintenance, 0);
1531        $dividendCorrectives = number_format($result->dividendCorrectives, 0);
1532
1533        $query = "SELECT 
1534                        COUNT(q.created_at) totalBudgetLastWeek 
1535                    FROM tbl_quotations q WHERE 
1536                    DATE_FORMAT(q.created_at, '%Y-%m-%d') BETWEEN '{$mondayLastWeekDate}
1537                    AND '{$sundayLastWeekDate}
1538                    AND q.for_add != 1
1539                    AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1540                    AND q.created_at IS NOT NULL 
1541                    AND q.budget_type_id != 7
1542                    AND q.budget_type_id IS NOT NULL 
1543                    AND YEAR(q.created_at) = YEAR(q.issue_date)
1544                    AND q.company_id IN (SELECT company_id FROM tbl_companies WHERE is_send_executive = 1 {$where})";
1545        
1546        $result = DB::select($query)[0];
1547
1548        $percentageMoreThanLastWeek = 0;
1549
1550        if($result->totalBudgetLastWeek > 0){
1551            $percentageMoreThanLastWeek = number_format($totalBudgets / $result->totalBudgetLastWeek * 100, 2);
1552        }
1553
1554        $query = "SELECT 
1555                    SUM(q.amount) totalAmount
1556                FROM tbl_quotations q WHERE 
1557                q.for_add != 1
1558                AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1559                AND q.created_at IS NOT NULL 
1560                AND q.budget_type_id != 7
1561                AND q.budget_type_id IS NOT NULL 
1562                AND YEAR(q.created_at) = YEAR(q.issue_date)
1563                AND q.company_id IN (SELECT company_id FROM tbl_companies WHERE is_send_executive = 1 {$where})
1564                {$whereMonth}";
1565        
1566        $result = DB::select($query)[0];
1567
1568        $totalAmountCC = $result->totalAmount;
1569
1570        $query = "SELECT 
1571                COUNT(CASE WHEN q.created_at IS NOT NULL THEN 1 END) totalBudgets,
1572                COUNT(CASE WHEN q.acceptance_date IS NOT NULL AND q.budget_status_id = 3 THEN 1 END) totalAcceptance,
1573                SUM(CASE WHEN q.acceptance_date IS NOT NULL AND q.budget_status_id = 3 THEN q.amount END) totalAmountApproved
1574            FROM tbl_quotations q WHERE 
1575            q.for_add != 1
1576            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1577            AND q.created_at IS NOT NULL 
1578            AND q.budget_type_id != 7
1579            AND q.budget_type_id IS NOT NULL 
1580            AND YEAR(q.created_at) = YEAR(q.issue_date)
1581            AND q.company_id IN (SELECT company_id FROM tbl_companies WHERE is_send_executive = 1 {$where})
1582            {$whereAccMonth}";
1583
1584        $result = DB::select($query)[0];
1585
1586        $approvalRate = 0; 
1587        $totalAmountApproved = $result->totalAmountApproved;
1588        if($totalAmountCC > 0){
1589            $approvalRate = number_format(($totalAmountApproved / $totalAmountCC) * 100, 0);
1590        }
1591
1592        $query = "SELECT SUM(goal_for_the_year) goalForTheYear FROM tbl_companies WHERE is_send_executive = 1 {$where}";
1593        $result = DB::select($query)[0];
1594
1595        return array(
1596            'weekNumber' => $weekNumber,
1597            'monday' => $monday,
1598            'totalBudgets' => $totalBudgets,
1599            'totalAmount' => $totalAmount,
1600            'totalAmountApproved' => $this->currency($totalAmountApproved, 1, 0),
1601            'dividendMaintenance' => $dividendMaintenance,
1602            'dividendCorrectives' => $dividendCorrectives,
1603            'percentageMoreThanLastWeek' => $percentageMoreThanLastWeek,
1604            'approvalRate' => $approvalRate,
1605            'totalGoalForTheYear' => $result->goalForTheYear
1606        );
1607
1608    }
1609
1610    function currency($amount, $withEuro = null, $n = 2){
1611
1612        if($withEuro != null){
1613            $withEuro = ' €';
1614        }
1615
1616        return number_format($amount, $n, ',', '.') . $withEuro;
1617    }
1618
1619    function get_cc_bcc_executive(){
1620
1621        try {
1622
1623            $result = TblCcBccExecutiveNotifications::get();
1624
1625            return response(['message' => 'OK', 'data' => $result]);
1626
1627        } catch (\Exception $e) {
1628            /** @disregard P1014 */
1629            $e->exceptionCode = 'GET_CC_BCC_EXECUTIVE_EXCEPTION'; 
1630            report($e);
1631            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1632        }
1633    }
1634
1635    function delete_cc_bcc_executive($id){
1636
1637        try {
1638            
1639            $id = addslashes($id);
1640
1641            TblCcBccExecutiveNotifications::where('id', $id)->delete();
1642
1643            return response(['message' => 'OK']);
1644
1645        } catch (\Exception $e) {
1646            /** @disregard P1014 */
1647            $e->exceptionCode = 'DELETE_CC_BCC_EXECUTIVE_EXCEPTION'; 
1648            report($e);
1649            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1650        }
1651    }
1652
1653    function update_cc_bcc_executive(Request $request, $id){
1654
1655        try {
1656
1657            $data = $request->all();
1658            $id = addslashes($id);
1659
1660            $x = $this->isEmailValid($data['email']);
1661
1662            if($x){
1663                $result = TblCcBccExecutiveNotifications::where('email', strtolower($data['email']))->count();
1664
1665                if($result > 0){
1666                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1667                }else{
1668                    $data['updated_at'] = date('Y-m-d H:i:s');
1669                    TblCcBccExecutiveNotifications::where('id', $id)->update($data);
1670                }
1671            }else{
1672                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1673            }
1674
1675            return response(['message' => 'OK']);
1676
1677        } catch (\Exception $e) {
1678            /** @disregard P1014 */
1679            $e->exceptionCode = 'UPDATE_CC_BCC_EXECUTIVE_EXCEPTION'; 
1680            report($e);
1681            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1682        }
1683    }
1684
1685    function create_cc_bcc_executive(Request $request){
1686
1687        try {
1688            
1689            $data = $request->all();
1690
1691            $x = $this->isEmailValid($data['email']);
1692
1693            if($x){
1694                $result = TblCcBccExecutiveNotifications::where('email', strtolower($data['email']))->count();
1695
1696                if($result > 0){
1697                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1698                }else{
1699                    TblCcBccExecutiveNotifications::create($data);
1700                }
1701            }else{
1702                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1703            }
1704            
1705            return response(['message' => 'OK']);
1706
1707        } catch (\Exception $e) {
1708            /** @disregard P1014 */
1709            $e->exceptionCode = 'CREATE_CC_BCC_EXECUTIVE_EXCEPTION'; 
1710            report($e);
1711            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1712        }
1713    }
1714
1715    function update_notification_settings(Request $request){
1716
1717        try {
1718            
1719            $data = $request->all();
1720
1721            $data['updated_at'] = date('Y-m-d H:i:s');
1722            TblNotificationSettings::where('id', 1)->update($data);
1723
1724            return response(['message' => 'OK']);
1725
1726        } catch (\Exception $e) {
1727            /** @disregard P1014 */
1728            $e->exceptionCode = 'UPDATE_NOTIFICATION_SETTINGS_EXCEPTION'; 
1729            report($e);
1730            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1731        }
1732
1733    }
1734
1735    function get_notification_settings(){
1736
1737        try {
1738            
1739            $result = TblNotificationSettings::where('id', 1)->first();
1740
1741            return response(['message' => 'OK', 'data' => $result]);
1742
1743        } catch (\Exception $e) {
1744            /** @disregard P1014 */
1745            $e->exceptionCode = 'GET_NOTIFICATION_SETTINGS_EXCEPTION'; 
1746            report($e);
1747            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1748        }
1749    }
1750
1751    function send_report_logs(Request $request){
1752
1753        try {
1754
1755            $data = $request->all();
1756
1757            $toEmail = env('SENDGRID_TO_EMAIL');
1758
1759            $imgpath = \File::get('fireservicetitan.png');
1760
1761            $body = $data['logs'];
1762
1763            $body .= "<br><br><p>Fire Service Titan</p>";
1764            $body .= "<img src='cid:fireservicetitan' style='height: 45px;' />";
1765            
1766            $html = '<!DOCTYPE html>';
1767            $html .= '<html>';
1768            $html .= '<head>';
1769            $html .= '<meta charset="UTF-8">';
1770            $html .= '<meta name="viewport" content="width=device-width, initial-scale=1.0">';
1771            $html .= '</head>';
1772            $html .= '<body>';
1773            $html .= $body;
1774            $html .= '</body>';
1775            $html .= '</html>';
1776
1777            $email = new \SendGrid\Mail\Mail(); 
1778            $subject = "FST Error report " . date('Y-m-d H:i:s');
1779    
1780            $email->setFrom('fire@fire.es', 'Fire Service Titan');
1781            $email->setSubject($subject);
1782
1783            $email->addTo($toEmail);
1784            $email->addContent("text/html", $html);
1785
1786            $email->addAttachment(
1787                $imgpath,
1788                "image/png",
1789                "fireservicetitan.png",
1790                "inline",
1791                "fireservicetitan"
1792            );
1793
1794            $sendgrid = new \SendGrid(env('SENDGRID_API_KEY','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'));
1795
1796            $response = $sendgrid->send($email);
1797            if ($response->statusCode() == 202) {
1798                Log::channel('email_log')->info('ID:' . $toEmail .' - REPORT LOG EMAIL SENT');
1799            }
1800
1801            return response(['message' => 'OK']);
1802
1803        } catch (\Exception $e) {
1804            /** @disregard P1014 */
1805            $e->exceptionCode = 'SEND_REPORT_LOGS_EXCEPTION'; 
1806            report($e);
1807            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1808        }
1809    }
1810
1811    function get_emails_acceptance_notifications($companyId){
1812
1813        try {
1814
1815            $companyId = addslashes($companyId);
1816
1817            $cc = TblCcAcceptanceNotifications::where('company_id', $companyId)->get();
1818            $to = TblToAcceptanceNotifications::where('company_id', $companyId)->get();
1819
1820            return response(['message' => 'OK', 'cc' => $cc, 'to' => $to]);
1821
1822        } catch (\Exception $e) {
1823            /** @disregard P1014 */
1824            $e->exceptionCode = 'GET_EMAILS_ACCEPTANCE_NOTIFICATIONS_EXCEPTION'; 
1825            report($e);
1826            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1827        }
1828    }
1829
1830    function create_to_email_acceptance(Request $request){
1831
1832        try {
1833            
1834            $data = $request->all();
1835
1836            $x = $this->isEmailValid($data['email']);
1837
1838            if($x){
1839                $result = TblToAcceptanceNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1840
1841                if($result > 0){
1842                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1843                }else{
1844                    TblToAcceptanceNotifications::create($data);
1845                }
1846            }else{
1847                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1848            }
1849            
1850            return response(['message' => 'OK']);
1851
1852        } catch (\Exception $e) {
1853            /** @disregard P1014 */
1854            $e->exceptionCode = 'CREATE_TO_EMAIL_ACCEPTANCE_EXCEPTION'; 
1855            report($e);
1856            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1857        }
1858    }
1859
1860    function delete_to_email_acceptance($id){
1861
1862        try {
1863            
1864            $id = addslashes($id);
1865
1866            TblToAcceptanceNotifications::where('id', $id)->delete();
1867
1868            return response(['message' => 'OK']);
1869
1870        } catch (\Exception $e) {
1871            /** @disregard P1014 */
1872            $e->exceptionCode = 'DELETE_TO_EMAIL_ACCEPTANCE_EXCEPTION'; 
1873            report($e);
1874            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1875        }
1876    }
1877
1878    function update_to_email_acceptance(Request $request, $id){
1879
1880        try {
1881
1882            $data = $request->all();
1883            $id = addslashes($id);
1884
1885            $x = $this->isEmailValid($data['email']);
1886
1887            if($x){
1888                $to = TblToAcceptanceNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1889                $cc = TblCcAcceptanceNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1890
1891                if($to > 0 || $cc > 0){
1892                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1893                }else{
1894                    $data['updated_at'] = date('Y-m-d H:i:s');
1895                    TblToAcceptanceNotifications::where('id', $id)->update($data);
1896                }
1897            }else{
1898                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1899            }
1900
1901            return response(['message' => 'OK']);
1902
1903        } catch (\Exception $e) {
1904            /** @disregard P1014 */
1905            $e->exceptionCode = 'UPDATE_TO_EMAIL_ACCEPTANCE_EXCEPTION'; 
1906            report($e);
1907            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1908        }
1909    }
1910
1911    function create_cc_email_acceptance(Request $request){
1912
1913        try {
1914            
1915            $data = $request->all();
1916
1917            $x = $this->isEmailValid($data['email']);
1918
1919            if($x){
1920                $result = TblCcAcceptanceNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1921
1922                if($result > 0){
1923                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1924                }else{
1925                    TblCcAcceptanceNotifications::create($data);
1926                }
1927            }else{
1928                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1929            }
1930            
1931            return response(['message' => 'OK']);
1932
1933        } catch (\Exception $e) {
1934            /** @disregard P1014 */
1935            $e->exceptionCode = 'CREATE_CC_EMAIL_ACCEPTANCE_EXCEPTION'; 
1936            report($e);
1937            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1938        }
1939    }
1940
1941    function delete_cc_email_acceptance($id){
1942
1943        try {
1944            
1945            $id = addslashes($id);
1946
1947            TblCcAcceptanceNotifications::where('id', $id)->delete();
1948
1949            return response(['message' => 'OK']);
1950
1951        } catch (\Exception $e) {
1952            /** @disregard P1014 */
1953            $e->exceptionCode = 'DELETE_CC_EMAIL_ACCEPTANCE_EXCEPTION'; 
1954            report($e);
1955            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1956        }
1957    }
1958
1959    function update_cc_email_acceptance(Request $request, $id){
1960
1961        try {
1962
1963            $data = $request->all();
1964            $id = addslashes($id);
1965
1966            $x = $this->isEmailValid($data['email']);
1967
1968            if($x){
1969                $cc = TblCcAcceptanceNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1970                $to = TblToAcceptanceNotifications::where('company_id', $data['company_id'])->where('email', strtolower($data['email']))->count();
1971
1972                if($cc > 0 || $to > 0){
1973                    return response(['message' => 'KO', 'error' => __('language.email_exists')]);
1974                }else{
1975                    $data['updated_at'] = date('Y-m-d H:i:s');
1976                    TblCcAcceptanceNotifications::where('id', $id)->update($data);
1977                }
1978            }else{
1979                return response(['message' => 'KO', 'error' => __('language.email_invalid')]);
1980            }
1981
1982            return response(['message' => 'OK']);
1983
1984        } catch (\Exception $e) {
1985            /** @disregard P1014 */
1986            $e->exceptionCode = 'UPDATE_CC_EMAIL_ACCEPTANCE_EXCEPTION'; 
1987            report($e);
1988            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1989        }
1990    }
1991
1992    function list_last_follow_up_date($companyId){
1993
1994        try {
1995            
1996            $companyId = addslashes($companyId);
1997
1998            $result = TblLastFollowUpDate::where('company_id', $companyId)->orderBy('row_id', 'ASC')->get();
1999
2000            $data = array();
2001
2002            for ($i = 0; $i < count($result); $i++) { 
2003                $data[$result[$i]->row_id]['row_id'] = $result[$i]->row_id;
2004                $data[$result[$i]->row_id]['last_follow_up_date'] = $result[$i]->last_follow_up_date;
2005                if($result[$i]->budget_type_id != null){
2006                    $data[$result[$i]->row_id]['budget_types'][] = $result[$i]->budget_type_id;
2007                }
2008            }
2009
2010            return response(['message' => 'OK', 'data' => array_values($data)]);
2011
2012        } catch (\Exception $e) {
2013            /** @disregard P1014 */
2014            $e->exceptionCode = 'LIST_LAST_FOLLOW_UP_DATE_EXCEPTION'; 
2015            report($e);
2016            return response(['message' => 'KO', 'error' => $e->getMessage()]);
2017        }
2018
2019    }
2020
2021    function update_last_follow_up_date_working_days(Request $request){
2022
2023        try {
2024            
2025            $data = $request->all();
2026            $companyId = addslashes($data['company_id']);
2027            $rowId = addslashes($data['row_id']);
2028
2029            unset($data['company_id']);
2030            unset($data['row_id']);
2031
2032            $data['updated_at'] = date('Y-m-d H:i:s');
2033
2034            TblLastFollowUpDate::where('company_id', $companyId)->where('row_id', $rowId)->update($data);
2035
2036            return $this->list_last_follow_up_date($companyId);
2037
2038        } catch (\Exception $e) {
2039            /** @disregard P1014 */
2040            $e->exceptionCode = 'UPDATE_LAST_FOLLOW_UP_DATE_WORKING_DAYS_EXCEPTION'; 
2041            report($e);
2042            return response(['message' => 'KO', 'error' => $e->getMessage()]);
2043        }
2044
2045    }
2046
2047
2048    function update_last_follow_up_date(Request $request){
2049
2050        try {
2051            
2052            $data = $request->all();
2053            $companyId = addslashes($data['company_id']);
2054            $rowId = addslashes($data['row_id']);
2055            unset($data['company_id']);
2056            unset($data['row_id']);
2057
2058            $previousData = TblLastFollowUpDate::where('company_id', $companyId)->where('row_id', $rowId)->first();
2059
2060            $lastBudgetTypeId = end($data['budget_type_id']);
2061            $lastFollowUpDate = TblLastFollowUpDate::where('company_id', $companyId)->where('budget_type_id', $lastBudgetTypeId)->first();
2062
2063            TblLastFollowUpDate::where('company_id', $companyId)->whereIn('budget_type_id', $data['budget_type_id'])->delete();
2064            TblLastFollowUpDate::where('company_id', $companyId)->where('row_id', $rowId)->delete();
2065
2066            foreach ($data['budget_type_id'] as $budgetTypeId) {
2067                TblLastFollowUpDate::create(
2068                    array(
2069                        'company_id' => $companyId,
2070                        'row_id' => $rowId,                        
2071                        'budget_type_id' => $budgetTypeId,                        
2072                        'last_follow_up_date' => $previousData->last_follow_up_date,
2073                        'updated_by' => $data['updated_by'],
2074                        'updated_at' => date('Y-m-d H:i:s')
2075                    )
2076                );
2077            }
2078
2079            if($lastFollowUpDate != null){
2080                if($lastFollowUpDate->budget_type_id != null){
2081                    TblLastFollowUpDate::create(
2082                        array(
2083                            'company_id' => $companyId,
2084                            'row_id' => $lastFollowUpDate->row_id,
2085                            'budget_type_id' => null,
2086                            'last_follow_up_date' => $lastFollowUpDate->last_follow_up_date,
2087                            'created_by' => $data['updated_by']
2088                        )
2089                    );
2090                }
2091            }
2092
2093            return $this->list_last_follow_up_date($companyId);
2094
2095        } catch (\Exception $e) {
2096            /** @disregard P1014 */
2097            $e->exceptionCode = 'UPDATE_LAST_FOLLOW_UP_DATE_EXCEPTION'; 
2098            report($e);
2099            return response(['message' => 'KO', 'error' => $e->getMessage()]);
2100        }
2101
2102    }
2103
2104    function delete_last_follow_up_date(Request $request){
2105
2106        try {
2107            
2108            $data = $request->all();
2109            $companyId = addslashes($data['company_id']);
2110            $rowId = addslashes($data['row_id']);
2111            unset($data['company_id']);
2112            unset($data['row_id']);
2113
2114            $count = TblLastFollowUpDate::where('company_id', $companyId)->where('row_id', $rowId)->count();
2115
2116            if($count > 1){
2117                TblLastFollowUpDate::where('company_id', $companyId)->where('budget_type_id', $data['budget_type_id'])->delete();
2118            }else{
2119                TblLastFollowUpDate::where('company_id', $companyId)->where('row_id', $rowId)->update(array('budget_type_id' => null));
2120            }
2121
2122            return $this->list_last_follow_up_date($companyId);
2123
2124        } catch (\Exception $e) {
2125            /** @disregard P1014 */
2126            $e->exceptionCode = 'DELETE_LAST_FOLLOW_UP_DATE_EXCEPTION'; 
2127            report($e);
2128            return response(['message' => 'KO', 'error' => $e->getMessage()]);
2129        }
2130
2131    }
2132}