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