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