Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 409
0.00% covered (danger)
0.00%
0 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
Pipelines
0.00% covered (danger)
0.00%
0 / 409
0.00% covered (danger)
0.00%
0 / 10
9702
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 list_pipelines
0.00% covered (danger)
0.00%
0 / 238
0.00% covered (danger)
0.00%
0 / 1
4970
 create_pipeline
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 update_pipeline
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
6
 delete_pipelines
0.00% covered (danger)
0.00%
0 / 26
0.00% covered (danger)
0.00%
0 / 1
20
 get_dates
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 get_all_users
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
12
 get_pipeline
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 get_distincts
0.00% covered (danger)
0.00%
0 / 37
0.00% covered (danger)
0.00%
0 / 1
12
 get_past_added_pipelines
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
30
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Models\TblCompanyUsers;
6use App\Models\TblPipelines;
7use Illuminate\Http\Request;
8use Illuminate\Support\Facades\App;
9use Illuminate\Support\Facades\Cache;
10use Illuminate\Support\Facades\DB;
11
12class Pipelines extends Controller
13{
14    private $locale;
15
16    private $userId;
17
18    private $region;
19
20    private $companyIds;
21
22    private $companyId;
23
24    public function __construct()
25    {
26        $this->locale = @getallheaders()['Locale-ID'];
27        $this->userId = @getallheaders()['User-ID'];
28        $this->region = @getallheaders()['Region'];
29
30        App::setLocale($this->locale);
31
32        $this->companyIds = [];
33
34        if ($this->region != null && $this->region != '' && $this->region != 'All') {
35            $this->region = urldecode($this->region);
36
37            $query = 'SELECT 
38                        b.company_id
39                    FROM 
40                        tbl_company_users a 
41                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id 
42                    WHERE 
43                        a.user_id = ?
44                        AND b.region = ?';
45
46            $this->companyIds = DB::select($query, [intval($this->userId), $this->region]);
47
48            $this->companyIds = collect($this->companyIds)->pluck('company_id')->toArray();
49        } else {
50            $this->companyIds = TblCompanyUsers::where('user_id', $this->userId)->pluck('company_id')->all();
51        }
52
53        $this->companyId = implode(',', $this->companyIds);
54    }
55
56    public function list_pipelines(Request $request)
57    {
58
59        try {
60
61            $data = $request->all();
62            $companyId = intval($data['company_id']);
63            $userId = intval($data['user_id']);
64            $filter = $data['filterModel'];
65            $sort = $data['sortModel'];
66            $result = [];
67            $subquery = '';
68            $where = '';
69            $having = '';
70            $orderBy = '';
71            $start = intval($data['start']);
72            $end = intval($data['end']);
73            $totalRowCount = 0;
74            $withFilters = '';
75
76            $filterType = [
77                'contains' => "LIKE '%[value]%'",
78                'notContains' => "NOT LIKE '%[value]%'",
79                'equals' => "= '[value]'",
80                'notEqual' => "<> '[value]'",
81                'startsWith' => "LIKE '[value]%'",
82                'endsWith' => "LIKE '%[value]'",
83                'blank' => 'IS NULL',
84                'notBlank' => 'IS NOT NULL',
85                'lessThan' => '< [value]',
86                'lessThanOrEqual' => '<= [value]',
87                'greaterThan' => '> [value]',
88                'greaterThanOrEqual' => '>= [value]',
89                'inRange' => 'BETWEEN [value1] AND [value2]',
90            ];
91
92            if (isset($data['ids']) && count($data['ids']) > 0) {
93                $ids = implode(',', $data['ids']);
94                $where = " AND a.id IN ({$ids}";
95            }
96
97            if (isset($data['ids_not_in']) && count($data['ids_not_in']) > 0) {
98                $ids = implode(',', $data['ids_not_in']);
99                $where = " AND a.id NOT IN ({$ids}";
100            }
101
102            if ($companyId != 0) {
103                $where .= " AND a.company_id = {$companyId} ";
104            } else {
105                $where .= " AND a.company_id IN ({$this->companyId}";
106            }
107
108            $matchScoreCol = '';
109            $matchScoreOrderBy = '';
110
111            if (isset($data['searchText']) && $data['searchText'] != null) {
112
113                $availableParameters = [
114                    'a.client_name',
115                    'a.client_type',
116                    'a.commercial',
117                    'a.location',
118                    'a.visit_type_id',
119                    'a.visit_date',
120                    'a.opportunity_type',
121                    'a.comments',
122                    'a.visit_call',
123                    'a.created_by',
124                    'a.created_at',
125                    'a.updated_by',
126                    'a.updated_at',
127                ];
128
129                $searchText = addslashes($data['searchText']);
130                $searchTextArray = explode(' ', $searchText);
131
132                $searchArray = [];
133                $splitSearchArray = [];
134                $matchScoreArray = [];
135                $sc = 1;
136                foreach ($availableParameters as $field) {
137                    if ($field == 'a.client_name' || $field == 'a.created_at') {
138                        $sc = 3;
139                    } elseif ($field == 'a.visit_date') {
140                        $sc = 2;
141                    } else {
142                        $sc = 1;
143                    }
144
145                    $l = "{$field} LIKE '%{$searchText}%'";
146
147                    $d = "IFNULL((LENGTH(LOWER({$field})) - LENGTH(REPLACE(LOWER({$field}), LOWER('{$searchText}'), ''))) / LENGTH(LOWER('{$searchText}')), 0) * {$sc}";
148
149                    if (count($searchTextArray) > 1) {
150                        foreach ($searchTextArray as $word) {
151                            if (! is_numeric($word)) {
152                                $d .= " + IFNULL((LENGTH(LOWER({$field})) - LENGTH(REPLACE(LOWER({$field}), LOWER('{$word}'), ''))) / LENGTH(LOWER('{$word}')), 0) * {$sc}";
153                            }
154                        }
155                    }
156
157                    array_push($matchScoreArray, $d);
158
159                    if (is_numeric($searchText)) {
160                        array_push($searchArray, "({$l} OR {$field} = CAST('{$searchText}' AS UNSIGNED))");
161                    } else {
162                        array_push($searchArray, "({$l} OR DATE_FORMAT({$field}, '%d/%m/%Y') = DATE_FORMAT(STR_TO_DATE('{$searchText}', '%d/%m/%Y'), '%d/%m/%Y'))");
163                    }
164
165                    if (count($searchTextArray) > 1) {
166                        foreach ($searchTextArray as $word) {
167
168                            $l = "{$field} LIKE '%{$word}%'";
169
170                            if (is_numeric($word)) {
171                                array_push($splitSearchArray, "{$l} OR {$field} = CAST('{$word}' AS UNSIGNED)");
172                            } else {
173                                array_push($splitSearchArray, "{$l} OR DATE_FORMAT({$field}, '%d/%m/%Y') = DATE_FORMAT(STR_TO_DATE('{$word}', '%d/%m/%Y'), '%d/%m/%Y')");
174                            }
175                        }
176                    }
177
178                    $sc = 1;
179                }
180
181                if (count($splitSearchArray) > 0) {
182                    $splitSearchArray = implode(' OR ', $splitSearchArray);
183                    $splitSearchArray = " OR ({$splitSearchArray}";
184                } else {
185                    $splitSearchArray = '';
186                }
187
188                $searchArray = implode(' OR ', $searchArray);
189                $matchScoreArray = implode(',', $matchScoreArray);
190                $matchScoreCol = ", GREATEST({$matchScoreArray}) match_score";
191                $matchScoreOrderBy = 'match_score DESC,';
192                $where .= " AND ({$searchArray} {$splitSearchArray})";
193            }
194
195            if (count($sort) > 0) {
196                $field = $sort[0]['colId'];
197                $sortBy = $sort[0]['sort'];
198
199                if (strpos($field, 'translate') !== false) {
200                    $field = str_replace('_translate', '', $field);
201                }
202
203                if ($matchScoreOrderBy) {
204                    $matchScoreOrderBy = ', match_score DESC';
205                }
206
207                $orderBy = " ORDER BY {$field} {$sortBy} {$matchScoreOrderBy}";
208            } else {
209                $orderBy = " ORDER BY {$matchScoreOrderBy} a.id DESC";
210            }
211
212            foreach ($filter as $key => $data) {
213                if (strpos($key, 'translate') !== false) {
214
215                    $field = str_replace('_translate', '', $key);
216
217                    if ($field == 'created_at') {
218                        $field = 'a.created_at';
219                    } elseif ($field == 'updated_at') {
220                        $field = 'a.updated_at';
221                    } elseif ($field == 'visit_date') {
222                        $field = 'a.visit_date';
223                    }
224
225                    $whereDates = '';
226                    $z = 0;
227
228                    if (isset($data['filters']) && ! empty($data['filters'])) {
229                        foreach ($data['filters'] as $yearKey => $yearData) {
230                            $yearsMonths = [];
231                            $yearsWeeks = [];
232
233                            if ($z > 0) {
234                                $whereDates .= " OR (YEAR($field) = {$yearKey} ";
235                            } else {
236                                $whereDates .= " (YEAR($field) = {$yearKey} ";
237                            }
238
239                            for ($i = 0; $i < count($yearData['months']); $i++) {
240                                if ($yearData['months'][$i]['isChecked']) {
241                                    array_push($yearsMonths, $yearData['months'][$i]['value']);
242                                }
243                            }
244
245                            $yearsMonths = implode("','", $yearsMonths);
246                            $whereDates .= " AND (MONTH({$field}) IN ('{$yearsMonths}')";
247
248                            for ($i = 0; $i < count($yearData['weeks']); $i++) {
249                                if ($yearData['weeks'][$i]['isChecked']) {
250                                    array_push($yearsWeeks, $yearData['weeks'][$i]['value']);
251                                }
252                            }
253
254                            $yearsWeeks = implode("','", $yearsWeeks);
255                            if ($yearsWeeks != '') {
256                                $whereDates .= " OR WEEK({$field}) IN ('{$yearsWeeks}') ";
257                            }
258
259                            $whereDates .= ')) ';
260                            $z++;
261                        }
262                    }
263
264                    $whereBlanks = '';
265                    if (isset($data['isBlanks'])) {
266                        if ($data['isBlanks']) {
267                            $conj = 'OR';
268                            if ($whereDates == '') {
269                                $conj = '';
270                            }
271                            $whereBlanks .= " {$conj} {$field} IS NULL ";
272                        } else {
273                            $conj = 'AND';
274                            if ($whereDates == '') {
275                                $conj = '';
276                            }
277                            $whereBlanks .= " {$conj} {$field} IS NOT NULL ";
278                        }
279                    }
280
281                    $where .= " AND ({$whereDates} {$whereBlanks}";
282                } else {
283                    if ($data['filterType'] == 'number') {
284                        if (array_key_exists('operator', $data)) {
285                            if ($data['condition1']['type'] != 'blank' && $data['condition2']['type'] != 'notBlank') {
286                                $data['condition1']['filter'] = addslashes($data['condition1']['filter']);
287                                $data['condition2']['filter'] = addslashes($data['condition2']['filter']);
288
289                                if ($data['condition1']['type'] == 'inRange') {
290                                    $data['condition1']['filterTo'] = addslashes($data['condition1']['filterTo']);
291                                    $inRange = str_replace('[value1]', $data['condition1']['filter'], $filterType['inRange']);
292                                    $val1 = str_replace('[value2]', $data['condition1']['filterTo'], $inRange);
293                                } else {
294                                    $val1 = str_replace('[value]', $data['condition1']['filter'], $filterType[$data['condition1']['type']]);
295                                }
296
297                                if ($data['condition2']['type'] == 'inRange') {
298                                    $data['condition2']['filterTo'] = addslashes($data['condition2']['filterTo']);
299                                    $inRange = str_replace('[value1]', $data['condition2']['filter'], $filterType['inRange']);
300                                    $val2 = str_replace('[value2]', $data['condition2']['filterTo'], $inRange);
301                                } else {
302                                    $val2 = str_replace('[value]', $data['condition2']['filter'], $filterType[$data['condition2']['type']]);
303                                }
304
305                            } else {
306                                $val1 = $filterType[$data['condition1']['type']];
307                                $val2 = $filterType[$data['condition2']['type']];
308                            }
309
310                            $where .= " AND a.{$key} {$val1} {$data['operator']} a.{$key} {$val2} ";
311                        } else {
312                            if ($data['type'] != 'blank' && $data['type'] != 'notBlank') {
313                                $data['filter'] = addslashes($data['filter']);
314
315                                if ($data['type'] == 'inRange') {
316                                    $data['filterTo'] = addslashes($data['filterTo']);
317                                    $inRange = str_replace('[value1]', $data['filter'], $filterType['inRange']);
318                                    $val = str_replace('[value2]', $data['filterTo'], $inRange);
319                                } else {
320                                    $val = str_replace('[value]', $data['filter'], $filterType[$data['type']]);
321                                }
322                            } else {
323                                $val = $filterType[$data['type']];
324                            }
325
326                            $where .= " AND a.{$key} {$val} ";
327                        }
328                    }
329
330                    if ($data['filterType'] == 'text') {
331                        if (array_key_exists('operator', $data)) {
332                            $val1 = '';
333                            $val2 = '';
334                            if ($data['condition1']['type'] != 'blank' && $data['condition2']['type'] != 'notBlank') {
335                                $data['condition1']['filter'] = addslashes($data['condition1']['filter']);
336                                $val1 = str_replace('[value]', $data['condition1']['filter'], $filterType[$data['condition1']['type']]);
337                            }
338
339                            if ($data['condition2']['type'] != 'blank' && $data['condition2']['type'] != 'notBlank') {
340                                $data['condition2']['filter'] = addslashes($data['condition2']['filter']);
341                                $val2 = str_replace('[value]', $data['condition2']['filter'], $filterType[$data['condition2']['type']]);
342                            }
343
344                            $where .= " AND {$key} {$val1} {$data['operator']} {$key} {$val2} ";
345                        } else {
346                            if ($data['type'] != 'blank' && $data['type'] != 'notBlank') {
347                                $data['filter'] = addslashes($data['filter']);
348                                $val = str_replace('[value]', $data['filter'], $filterType[$data['type']]);
349                            } else {
350                                $val = $filterType[$data['type']];
351                            }
352
353                            $where .= " AND {$key} {$val} ";
354                        }
355                    }
356
357                    if ($data['filterType'] == 'set') {
358                        $statusName = $key;
359
360                        if ($key == 'updated_by') {
361                            $statusName = 'a.updated_by';
362                        } elseif ($key == 'company_name') {
363                            $statusName = 'b.name';
364                        } elseif ($key == 'commercial') {
365                            $statusName = 'a.commercial';
366                        } elseif ($key == 'created_by') {
367                            $statusName = 'a.created_by';
368                        } elseif ($key == 'client_type') {
369                            $statusName = 'a.client_type';
370                        } elseif ($key == 'visit_type') {
371                            $statusName = 'a.visit_type';
372                        } elseif ($key == 'opportunity_type') {
373                            $statusName = 'a.opportunity_type';
374                        }
375
376                        $val = implode("','", $data['values']);
377
378                        if (in_array(null, $data['values'], true)) {
379                            $where .= " AND ({$statusName} IN ('{$val}') OR {$statusName} IS NULL) ";
380                        } else {
381                            $where .= " AND {$statusName} IN ('{$val}') ";
382                        }
383                    }
384                }
385            }
386
387            $offset = $start;
388            $limit = $end - $start;
389
390            $query = "SELECT 
391                        a.id,
392                        b.company_id,
393                        b.region,
394                        b.name company_name,
395                        a.client_name, 
396                        a.client_type,
397                        v.visit_type_id,
398                        v.name visit_type,
399                        vtg.name visit_type_group,
400                        vtg.visit_type_group_id,
401                        a.commercial,
402                        a.location, 
403                        a.visit_date,
404                        DATE_FORMAT(a.visit_date, '%d/%m/%Y') visit_date_translate,
405                        a.opportunity_type,
406                        a.comments,
407                        a.visit_call,
408                        a.campaign,
409                        a.created_by,
410                        a.created_at,
411                        a.updated_by,
412                        a.updated_at
413                        {$matchScoreCol}
414                    FROM 
415                        tbl_pipelines a 
416                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id
417                        LEFT JOIN tbl_visit_types v ON a.visit_type_id = v.visit_type_id
418                        LEFT JOIN tbl_visit_type_groups vtg ON v.visit_type_group_id = vtg.visit_type_group_id
419                    WHERE a.id > 0 
420                    {$where}
421                    {$orderBy}
422                    LIMIT {$offset}{$limit}
423                    ";
424
425            $value = Cache::get(base64_encode($query));
426
427            if (! $value) {
428                $result = DB::select($query);
429
430                Cache::put(base64_encode($query), $result, 600);
431            } else {
432                $result = $value;
433            }
434
435            $totalQuery = "SELECT 
436                            COUNT(a.id) totalRowCount
437                        FROM 
438                            tbl_pipelines a 
439                        WHERE a.id > 0
440                        {$where}";
441
442            $value = Cache::get(base64_encode($totalQuery));
443
444            if (! $value) {
445                $countQuery = DB::select($totalQuery);
446
447                Cache::put(base64_encode($totalQuery), $countQuery, 600);
448            } else {
449                $countQuery = $value;
450            }
451
452            return response([
453                'message' => 'OK',
454                'data' => $result,
455                'totalRowCount' => $countQuery[0]->totalRowCount,
456            ]);
457
458        } catch (\Exception $e) {
459            /** @disregard P1014 */
460            $e->exceptionCode = 'LIST_PIPELINES_EXCEPTION';
461            report($e);
462
463            return response(['message' => 'KO', 'error' => $e->getMessage()]);
464        }
465
466    }
467
468    public function create_pipeline(Request $request)
469    {
470
471        try {
472
473            $data = $request->all();
474
475            $result = TblPipelines::create($data);
476
477            Cache::flush();
478
479            return response(['message' => 'OK', 'data' => $result]);
480
481        } catch (\Exception $e) {
482            /** @disregard P1014 */
483            $e->exceptionCode = 'CREATE_PIPELINE_EXCEPTION';
484            report($e);
485
486            return response(['message' => 'KO', 'error' => $e->getMessage()]);
487        }
488    }
489
490    public function update_pipeline(Request $request, $id)
491    {
492
493        try {
494
495            $data = $request->all();
496            $id = intval($id);
497
498            $data['updated_at'] = date('Y-m-d H:i:s');
499            TblPipelines::where('id', $id)->update($data);
500
501            Cache::flush();
502
503            return response([
504                'message' => 'OK',
505            ]);
506
507        } catch (\Exception $e) {
508            /** @disregard P1014 */
509            $e->exceptionCode = 'UPDATE_PIPELINE_EXCEPTION';
510            report($e);
511
512            return response(['message' => 'KO', 'error' => $e->getMessage()]);
513        }
514    }
515
516    public function delete_pipelines(Request $request)
517    {
518
519        try {
520
521            $data = $request->all();
522            $result = [];
523
524            $r = new Request([
525                'filterModel' => $data['filterModel'],
526                'sortModel' => $data['sortModel'],
527                'start' => 0,
528                'end' => 999999999,
529                'company_id' => @$data['company_id'],
530                'user_id' => $data['user_id'],
531                'ids' => $data['ids'],
532                'searchText' => $data['searchText'],
533                'ids_not_in' => $data['ids_not_in'],
534            ]);
535
536            $result = $this->list_pipelines($r);
537            $result = $result->original['data'];
538
539            $outputArray = [];
540
541            foreach ($result as $item) {
542                if (isset($item->id)) {
543                    $outputArray[] = $item->id;
544                }
545            }
546
547            TblPipelines::whereIn('id', $outputArray)->delete();
548
549            Cache::flush();
550
551            return response(['message' => 'OK', 'data' => $result]);
552
553        } catch (\Exception $e) {
554            /** @disregard P1014 */
555            $e->exceptionCode = 'DELETE_PIPELINES_EXCEPTION';
556            report($e);
557
558            return response(['message' => 'KO', 'error' => $e->getMessage()]);
559        }
560
561    }
562
563    public function get_dates($companyId)
564    {
565
566        try {
567
568            $where = '';
569
570            if ($companyId != 0) {
571                $where .= " a.company_id = {$companyId} ";
572            } else {
573                $where .= " a.company_id IN ({$this->companyId}";
574            }
575
576            $query = "SELECT
577                        DATE_FORMAT(a.visit_date, '%d/%m/%Y') visit_date_translate,
578                        DATE_FORMAT(a.created_at, '%d/%m/%Y') created_at_translate,
579                        DATE_FORMAT(a.updated_at, '%d/%m/%Y') updated_at_translate
580                    FROM tbl_pipelines a
581                    WHERE {$where}";
582
583            $result = DB::select($query);
584
585            return response([
586                'message' => 'OK',
587                'data' => $result,
588            ]);
589
590        } catch (\Exception $e) {
591            /** @disregard P1014 */
592            $e->exceptionCode = 'GET_DATES_EXCEPTION';
593            report($e);
594
595            return response(['message' => 'KO', 'error' => $e->getMessage()]);
596        }
597
598    }
599
600    public function get_all_users($companyId)
601    {
602
603        try {
604
605            $companyId = intval($companyId);
606
607            $where = '';
608
609            if ($companyId != 0) {
610                $where = "WHERE company_id = {$companyId} ";
611            } else {
612                $where = "WHERE company_id IN ({$this->companyId}";
613            }
614
615            $query = "SELECT 
616                        DISTINCT created_by 
617                    FROM 
618                        tbl_pipelines
619                    {$where}
620                    ORDER BY 
621                        created_by ASC";
622
623            $createdBy = DB::select($query);
624
625            $query = "SELECT 
626                        DISTINCT commercial 
627                    FROM 
628                        tbl_pipelines
629                    {$where}
630                    ORDER BY 
631                        commercial ASC";
632
633            $commercial = DB::select($query);
634
635            return response([
636                'message' => 'OK',
637                'createdBy' => $createdBy,
638                'commercial' => $commercial,
639            ]);
640
641        } catch (\Exception $e) {
642            /** @disregard P1014 */
643            $e->exceptionCode = 'GET_ALL_USERS_EXCEPTION';
644            report($e);
645
646            return response(['message' => 'KO', 'error' => $e->getMessage()]);
647        }
648    }
649
650    public function get_pipeline($id)
651    {
652
653        try {
654
655            $id = intval($id);
656
657            $query = "SELECT 
658                        a.id,
659                        a.client_name,
660                        a.client_type,
661                        a.commercial,
662                        a.location,
663                        a.opportunity_type,
664                        a.visit_type,
665                        a.visit_date,
666                        a.visit_call,
667                        a.campaign,
668                        a.created_by,
669                        a.created_at,
670                        a.updated_by,
671                        a.updated_at,                        
672                        DATE_FORMAT(a.visit_date, '%d/%m/%Y') last_itv_date_translate,
673                        DATE_FORMAT(a.created_at, '%d/%m/%Y') created_at_translate,
674                        DATE_FORMAT(a.updated_at, '%d/%m/%Y') updated_at_translate,
675                        a.comments
676                    FROM 
677                        tbl_pipelines a 
678                    WHERE a.id = {$id}";
679
680            $result = DB::select($query);
681
682            Cache::flush();
683
684            return response(['message' => 'OK', 'data' => $result]);
685
686        } catch (\Exception $e) {
687            /** @disregard P1014 */
688            $e->exceptionCode = 'GET_PIPELINE_EXCEPTION';
689            report($e);
690
691            return response(['message' => 'KO', 'error' => $e->getMessage()]);
692        }
693    }
694
695    public function get_distincts($companyId)
696    {
697
698        try {
699
700            $where = '';
701
702            if ($companyId != 0) {
703                $where .= " a.company_id = {$companyId} ";
704            } else {
705                $where .= " a.company_id IN ({$this->companyId}";
706            }
707
708            $query = "SELECT DISTINCT a.campaign FROM tbl_pipelines a WHERE {$where} ORDER BY a.campaign ASC";
709            $campaign = DB::select($query);
710
711            $query = "SELECT DISTINCT a.client_type FROM tbl_pipelines a WHERE {$where} ORDER BY a.client_type ASC";
712            $clientType = DB::select($query);
713
714            $query = "SELECT DISTINCT a.visit_call FROM tbl_pipelines a WHERE {$where} ORDER BY a.visit_call ASC";
715            $visitCall = DB::select($query);
716
717            $query = "SELECT DISTINCT a.commercial FROM tbl_pipelines a WHERE {$where} ORDER BY a.commercial ASC";
718            $commercial = DB::select($query);
719
720            $query = "SELECT DISTINCT a.location FROM tbl_pipelines a WHERE {$where} ORDER BY a.location ASC";
721            $location = DB::select($query);
722
723            $query = "SELECT
724                        DISTINCT b.name
725                    FROM tbl_pipelines a
726                    LEFT JOIN tbl_visit_types b
727                        ON a.visit_type_id = b.visit_type_id
728                    WHERE {$where}
729                    ORDER BY ISNULL(b.priority), b.priority ASC";
730            $visitType = DB::select($query);
731
732            $query = "SELECT DISTINCT a.opportunity_type FROM tbl_pipelines a WHERE {$where} ORDER BY a.opportunity_type ASC";
733            $opportunityType = DB::select($query);
734
735            $query = "SELECT DISTINCT a.created_by FROM tbl_pipelines a WHERE {$where} ORDER BY a.created_by ASC";
736            $createdBy = DB::select($query);
737
738            return response([
739                'message' => 'OK',
740                'campaign' => $campaign,
741                'clientType' => $clientType,
742                'commercial' => $commercial,
743                'location' => $location,
744                'visitType' => $visitType,
745                'opportunityType' => $opportunityType,
746                'createdBy' => $createdBy,
747                'visitCall' => $visitCall,
748            ]);
749
750        } catch (\Exception $e) {
751            /** @disregard P1014 */
752            $e->exceptionCode = 'GET_DISTINCT_EXCEPTION';
753            report($e);
754
755            return response(['message' => 'KO', 'error' => $e->getMessage()]);
756        }
757
758    }
759
760    public function get_past_added_pipelines(Request $request)
761    {
762
763        try {
764
765            $data = $request->all();
766            $keyword = addslashes($data['keyword'] ?? '');
767            $result = [];
768
769            if (! empty($keyword)) {
770                $array = explode(' ', $keyword);
771
772                $where = '';
773
774                $availableParameters = [$data['field']];
775
776                $searchTextArray = explode(' ', $keyword);
777
778                $searchArray = [];
779                $matchScoreArray = [];
780                foreach ($availableParameters as $field) {
781                    foreach ($searchTextArray as $word) {
782                        array_push($searchArray, "({$field} LIKE '%{$word}%')");
783                        array_push($matchScoreArray, "CASE WHEN {$field} LIKE '%{$word}%' THEN 1 ELSE 0 END");
784                    }
785                }
786
787                $searchArray = implode(' OR ', $searchArray);
788                $matchScoreArray = implode(' + ', $matchScoreArray);
789                $matchScoreCol = "({$matchScoreArray})";
790                $where .= " AND ({$searchArray}";
791
792                $query = "SELECT
793                            id,
794                            client_name,
795                            campaign,
796                            {$matchScoreCol} match_score
797                        FROM tbl_pipelines 
798                        WHERE client_name IS NOT NULL
799                        {$where}
800                        GROUP BY client_name
801                        ORDER BY match_score DESC, client_name ASC
802                        ";
803
804                $result = DB::select($query);
805            }
806
807            return response(['message' => 'OK', 'data' => $result]);
808
809        } catch (\Exception $e) {
810            /** @disregard P1014 */
811            $e->exceptionCode = 'GET_PAST_ADDED_PIPELINES_EXCEPTION';
812            report($e);
813
814            return response(['message' => 'KO', 'error' => $e->getMessage()]);
815        }
816    }
817}