Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 390
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 / 390
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 / 234
0.00% covered (danger)
0.00%
0 / 1
4970
 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 / 13
0.00% covered (danger)
0.00%
0 / 1
12
 get_all_users
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
12
 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 / 35
0.00% covered (danger)
0.00%
0 / 1
12
 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        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            return response(['message' => 'KO', 'error' => $e->getMessage()]);
449        }
450
451    }
452
453    function create_pipeline(Request $request){
454
455        try {
456            
457            $data = $request->all();
458
459            $result = TblPipelines::create($data);
460
461            Cache::flush();
462            return response(['message' => 'OK', 'data' => $result]);
463
464        } catch (\Exception $e) {
465            return response(['message' => 'KO', 'error' => $e->getMessage()]);
466        }
467    }
468
469    function update_pipeline(Request $request, $id){
470
471        try {
472            
473            $data = $request->all();
474            $id = addslashes($id);
475
476            $data['updated_at'] = date('Y-m-d H:i:s');
477            TblPipelines::where('id', $id)->update($data);
478
479            Cache::flush();
480            return response([
481                'message' => 'OK'
482            ]);
483
484        } catch (\Exception $e) {
485            return response(['message' => 'KO', 'error' => $e->getMessage()]);
486        }
487    }
488
489    public function delete_pipelines(Request $request){
490
491        try {            
492
493            $data = $request->all();
494            $result = array();
495
496            $r = new Request([
497                'filterModel' => $data['filterModel'],
498                'sortModel' => $data['sortModel'],
499                'start' => 0,
500                'end' => 999999999,
501                'company_id' => @$data['company_id'],
502                'user_id' => $data['user_id'],
503                'ids' => $data['ids'],
504                'searchText' => $data['searchText'],
505                'ids_not_in' => $data['ids_not_in']
506            ]);
507    
508            $result = $this->list_pipelines($r);
509            $result = $result->original['data'];
510
511            $outputArray = array();
512
513            foreach ($result as $item) {
514                if (isset($item->id)) {
515                    $outputArray[] = $item->id;
516                }
517            }
518
519            TblPipelines::whereIn('id', $outputArray)->delete();
520
521            Cache::flush();
522            return response(['message' => 'OK', 'data' => $result]);
523
524        } catch (\Exception $e) {
525            return response(['message' => 'KO', 'error' => $e->getMessage()]);
526        }
527
528    }
529
530    public function get_dates(){
531
532        try {
533
534            $where = "";
535
536            if($companyId != 0){
537                $where .= " a.company_id = {$companyId} ";
538            }else{
539                $where .= " a.company_id IN ({$this->companyId}";
540            }
541
542            $query = "SELECT
543                        DATE_FORMAT(a.visit_date, '%d/%m/%Y') visit_date_translate,
544                        DATE_FORMAT(a.created_at, '%d/%m/%Y') created_at_translate,
545                        DATE_FORMAT(a.updated_at, '%d/%m/%Y') updated_at_translate
546                    FROM tbl_pipelines a
547                    WHERE {$where}";
548
549            $result = DB::select($query);
550
551            return response([
552                'message' => 'OK', 
553                'data' => $result
554            ]);
555
556        } catch (\Exception $e) {
557            return response(['message' => 'KO', 'error' => $e->getMessage()]);
558        }
559
560    }
561
562    function get_all_users($companyId){
563
564        try {
565            
566            $companyId = addslashes($companyId);
567
568            $where = "";
569
570            if($companyId != 0){
571                $where = "WHERE company_id = {$companyId} ";
572            }else{
573                $where = "WHERE company_id IN ({$this->companyId}";
574            }
575
576            $query = "SELECT 
577                        DISTINCT created_by 
578                    FROM 
579                        tbl_pipelines
580                    {$where}
581                    ORDER BY 
582                        created_by ASC";
583
584            $createdBy = DB::select($query);
585
586            $query = "SELECT 
587                        DISTINCT commercial 
588                    FROM 
589                        tbl_pipelines
590                    {$where}
591                    ORDER BY 
592                        commercial ASC";
593
594            $commercial = DB::select($query);
595
596            return response([
597                'message' => 'OK', 
598                'createdBy' => $createdBy, 
599                'commercial' => $commercial,
600            ]);
601
602        } catch (\Exception $e) {
603            return response(['message' => 'KO', 'error' => $e->getMessage()]);
604        }
605    }
606
607    function get_pipeline($id){
608
609        try {
610
611            $id = addslashes($id);
612
613            $query = "SELECT 
614                        a.id,
615                        a.client_name,
616                        a.client_type,
617                        a.commercial,
618                        a.location,
619                        a.opportunity_type,
620                        a.visit_type,
621                        a.visit_date,
622                        a.visit_call,
623                        a.campaign,
624                        a.created_by,
625                        a.created_at,
626                        a.updated_by,
627                        a.updated_at,                        
628                        DATE_FORMAT(a.visit_date, '%d/%m/%Y') last_itv_date_translate,
629                        DATE_FORMAT(a.created_at, '%d/%m/%Y') created_at_translate,
630                        DATE_FORMAT(a.updated_at, '%d/%m/%Y') updated_at_translate,
631                        a.comments
632                    FROM 
633                        tbl_pipelines a 
634                    WHERE a.id = {$id}";
635
636            $result = DB::select($query);
637
638            Cache::flush();
639            return response(['message' => 'OK', 'data' => $result]);
640
641        } catch (\Exception $e) {
642            return response(['message' => 'KO', 'error' => $e->getMessage()]);
643        }
644    }
645
646    function get_distincts($companyId){
647
648        try {
649
650            $where = "";
651
652            if($companyId != 0){
653                $where .= " a.company_id = {$companyId} ";
654            }else{
655                $where .= " a.company_id IN ({$this->companyId}";
656            }
657
658            $query = "SELECT DISTINCT a.campaign FROM tbl_pipelines a WHERE {$where} ORDER BY a.campaign ASC";
659            $campaign = DB::select($query);
660            
661            $query = "SELECT DISTINCT a.client_type FROM tbl_pipelines a WHERE {$where} ORDER BY a.client_type ASC";
662            $clientType = DB::select($query);
663
664            $query = "SELECT DISTINCT a.visit_call FROM tbl_pipelines a WHERE {$where} ORDER BY a.visit_call ASC";
665            $visitCall = DB::select($query);
666
667            $query = "SELECT DISTINCT a.commercial FROM tbl_pipelines a WHERE {$where} ORDER BY a.commercial ASC";
668            $commercial = DB::select($query);
669
670            $query = "SELECT DISTINCT a.location FROM tbl_pipelines a WHERE {$where} ORDER BY a.location ASC";
671            $location = DB::select($query);
672
673            $query = "SELECT
674                        DISTINCT b.name
675                    FROM tbl_pipelines a
676                    LEFT JOIN tbl_visit_types b
677                        ON a.visit_type_id = b.visit_type_id
678                    WHERE {$where}
679                    ORDER BY ISNULL(b.priority), b.priority ASC";
680            $visitType = DB::select($query);
681
682            $query = "SELECT DISTINCT a.opportunity_type FROM tbl_pipelines a WHERE {$where} ORDER BY a.opportunity_type ASC";
683            $opportunityType = DB::select($query);
684
685            $query = "SELECT DISTINCT a.created_by FROM tbl_pipelines a WHERE {$where} ORDER BY a.created_by ASC";
686            $createdBy = DB::select($query);
687
688            return response([
689                'message' => 'OK', 
690                'campaign' => $campaign,
691                'clientType' => $clientType,
692                'commercial' => $commercial,
693                'location' => $location,
694                'visitType' => $visitType,
695                'opportunityType' => $opportunityType,
696                'createdBy' => $createdBy,
697                'visitCall' => $visitCall
698            ]);
699
700        } catch (\Exception $e) {
701            return response(['message' => 'KO', 'error' => $e->getMessage()]);
702        }
703
704    }
705
706    function get_past_added_pipelines(Request $request){
707
708        try {
709            
710            $data = $request->all();
711            $keyword = addslashes($data['keyword']);
712            $result = array();
713
714            if(isset($keyword) && !empty($keyword)){
715                $array = explode(' ', $keyword);
716
717                $where = "";
718    
719                $availableParameters = array($data['field']);
720
721                $searchTextArray = explode(" ", $keyword);
722
723                $searchArray = array();
724                $matchScoreArray = array();
725                foreach ($availableParameters as $field) {
726                    foreach ($searchTextArray as $word) {
727                        array_push($searchArray, "({$field} LIKE '%{$word}%')");    
728                        array_push($matchScoreArray, "CASE WHEN {$field} LIKE '%{$word}%' THEN 1 ELSE 0 END");
729                    }
730                }
731
732                $searchArray = implode(" OR ", $searchArray);
733                $matchScoreArray = implode(" + ", $matchScoreArray);
734                $matchScoreCol = "({$matchScoreArray})";
735                $where .= " AND ({$searchArray}";
736    
737                $query = "SELECT
738                            id,
739                            client_name,
740                            campaign,
741                            {$matchScoreCol} match_score
742                        FROM tbl_pipelines 
743                        WHERE client_name IS NOT NULL
744                        {$where}
745                        GROUP BY client_name
746                        ORDER BY match_score DESC, client_name ASC
747                        ";
748                
749                $result = DB::select($query);    
750            }
751
752            return response(['message' => 'OK', 'data' => $result]);
753
754        } catch (\Exception $e) {
755            return response(['message' => 'KO', 'error' => $e->getMessage()]);
756        }
757    }
758}