Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 684
0.00% covered (danger)
0.00%
0 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
DigitalCampaignAnalytics
0.00% covered (danger)
0.00%
0 / 684
0.00% covered (danger)
0.00%
0 / 13
23256
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
20
 list_campaign_channel_and_landing
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
240
 list_lead_status
0.00% covered (danger)
0.00%
0 / 28
0.00% covered (danger)
0.00%
0 / 1
132
 toCamelCase
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
12
 list_time_between_status
0.00% covered (danger)
0.00%
0 / 120
0.00% covered (danger)
0.00%
0 / 1
110
 list_g3w_order_status
0.00% covered (danger)
0.00%
0 / 104
0.00% covered (danger)
0.00%
0 / 1
650
 get_sources_digital_campaign_analytics
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
6
 update_final_summary
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
6
 get_final_summary
0.00% covered (danger)
0.00%
0 / 33
0.00% covered (danger)
0.00%
0 / 1
42
 get_main_kpis
0.00% covered (danger)
0.00%
0 / 127
0.00% covered (danger)
0.00%
0 / 1
812
 list_type_of_order
0.00% covered (danger)
0.00%
0 / 148
0.00% covered (danger)
0.00%
0 / 1
1260
 getG3wTasksExecuted
0.00% covered (danger)
0.00%
0 / 10
0.00% covered (danger)
0.00%
0 / 1
6
 list_performance_metrics
0.00% covered (danger)
0.00%
0 / 38
0.00% covered (danger)
0.00%
0 / 1
90
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Models\TblCompanyUsers;
6use App\Models\TblQuotations;
7use App\Models\TblSources;
8use App\Models\TblBudgetTypes;
9use App\Models\TblBudgetTypeGroups;
10use App\Models\TblFinalSummary;
11use App\Services\FacturasService;
12use App\Services\WorkService;
13use Illuminate\Support\Facades\DB;
14use Illuminate\Support\Facades\App;
15use Illuminate\Support\Facades\Cache;
16use Illuminate\Http\Request;
17use Illuminate\Support\Facades\Log;
18
19class DigitalCampaignAnalytics extends Controller
20{
21
22    private $locale;
23    private $userId;
24    private $region;
25    private $companyIds;
26    private $companyId;
27    private $workService;
28
29
30    public function __construct(WorkService $workService){
31        $this->workService = $workService;
32        $this->locale = @getallheaders()['Locale-ID'];
33        $this->userId = @getallheaders()['User-ID'];
34        $this->region = @getallheaders()['Region'];
35
36        App::setLocale($this->locale);
37
38        $this->companyIds = array();
39
40        if($this->region != null && $this->region != "" && $this->region != "All"){
41            $this->region = urldecode($this->region);
42
43            $query = "SELECT
44                        b.company_id
45                    FROM
46                        tbl_company_users a
47                        LEFT JOIN tbl_companies b ON a.company_id = b.company_id
48                    WHERE
49                        a.user_id = {$this->userId}
50                        AND b.region = '{$this->region}'";
51
52            $this->companyIds = DB::select($query);
53
54            $this->companyIds = collect($this->companyIds)->pluck('company_id')->toArray();
55        }else{
56            $this->companyIds = TblCompanyUsers::where('user_id', $this->userId)->pluck('company_id')->all();
57        }
58
59        $this->companyId = implode(',', $this->companyIds);
60    }
61
62    function list_campaign_channel_and_landing(Request $request){
63
64        try {
65
66            $data = $request->all();
67
68            $companyId = addslashes($data['company_id']);
69            $where  = "";
70
71            if($companyId != 0){
72                $where .= " AND q.company_id = {$companyId} ";
73            }else{
74                $where .= " AND q.company_id IN ({$this->companyId}";
75            }
76
77            if(isset($data['commercial']) && $data['commercial'] != null){
78                $commercial = implode("','", $data['commercial']);
79                if(count($data['commercial']) > 0){
80                    $where .= " AND q.commercial IN ('{$commercial}') ";
81                }
82            }
83
84            if((isset($data['start_date']) && $data['start_date'] != null) && (isset($data['end_date']) && $data['end_date'] != null)){
85                $where .= " AND q.request_date BETWEEN '{$data['start_date']}' AND '{$data['end_date']}";
86            }
87
88            $sortBy = "";
89
90            if(isset($data['sort_by']) && $data['sort_by'] != null){
91                if(isset($data['column']) && $data['column'] != null){
92                    $sortBy = "{$data['column']} {$data['sort_by']} ";
93                }
94            }
95
96            $query = "SELECT q.* FROM
97                        (
98                            SELECT
99                                c.region,
100                                s.source_id,
101                                s.name source,
102                                COUNT(1) totalOrders,
103                                COUNT(CASE WHEN q.acceptance_date IS NOT NULL AND q.acceptance_date != '0000-00-00 00:00:00' THEN 1 END) totalOrdersAcceptance,
104                                COUNT(CASE WHEN q.acceptance_date IS NOT NULL AND q.acceptance_date != '0000-00-00 00:00:00' THEN 1 END) / COUNT(1) * 100 percentageOrders,
105                                SUM(q.amount) totalOrdersAmount,
106                                AVG(q.amount) averageOrdersAmount,
107                                SUM(CASE WHEN q.acceptance_date IS NOT NULL AND q.acceptance_date != '0000-00-00 00:00:00' THEN q.amount END) totalOrdersAcceptanceAmount,
108                                AVG(CASE WHEN q.acceptance_date IS NOT NULL AND q.acceptance_date != '0000-00-00 00:00:00' THEN q.amount END) averageOrdersAcceptanceAmount,
109                                SUM(CASE WHEN q.acceptance_date IS NOT NULL AND q.acceptance_date != '0000-00-00 00:00:00' THEN q.amount END) / SUM(q.amount) * 100 percentageOrdersAmount,
110                                GROUP_CONCAT(q.id) groupConcatIdsTotalOrders,
111                                GROUP_CONCAT(CASE WHEN q.acceptance_date IS NOT NULL AND q.acceptance_date != '0000-00-00 00:00:00' THEN q.id END) groupConcatIdsOrdersAcceptance,
112                                GROUP_CONCAT(CASE WHEN q.acceptance_date IS NOT NULL AND q.acceptance_date != '0000-00-00 00:00:00' THEN q.amount END) groupConcatIdsOrdersAcceptanceAmount
113                            FROM tbl_quotations q
114                            LEFT JOIN tbl_sources s
115                                ON q.source_id = s.source_id
116                            LEFT JOIN tbl_companies c
117                                ON q.company_id = c.company_id
118                            WHERE
119                                q.for_add != 1
120                                AND (q.commercial IS NOT NULL AND q.commercial != '')
121                                AND q.source_id IS NOT NULL
122                                AND s.digital_campaign_source > 0
123                                AND q.budget_status_id != 18
124                                {$where}
125                            GROUP BY c.region, s.source_id WITH ROLLUP
126                            ORDER BY
127                                (c.region IS NULL AND s.source_id IS NULL) ASC,
128                                c.region IS NULL ASC,
129                                c.region ASC,
130                                (s.source_id IS NULL) DESC,
131                                CASE WHEN s.source_id IS NOT NULL THEN COUNT(1) ELSE NULL END DESC
132                        ) q ORDER BY (q.region IS NULL AND q.source_id IS NULL) ASC {$sortBy}";
133
134            $value = Cache::get(base64_encode($query));
135
136            if(!$value){
137                $result = DB::select($query);
138
139                Cache::put(base64_encode($query), $result, 600);
140            }else{
141                $result = $value;
142            }
143
144            return response([
145                'message' => 'OK',
146                'data' => $result
147            ]);
148
149
150        } catch (\Exception $e) {
151            return response(['message' => 'KO', 'error' => $e->getMessage()]);
152        }
153    }
154
155    function list_lead_status(Request $request){
156
157        try {
158
159            $data = $request->all();
160
161            $companyId = addslashes($data['company_id']);
162            $where  = "";
163
164            if($companyId != 0){
165                $where .= " AND q.company_id = {$companyId} ";
166            }else{
167                $where .= " AND q.company_id IN ({$this->companyId}";
168            }
169
170            if(isset($data['commercial']) && $data['commercial'] != null){
171                $commercial = implode("','", $data['commercial']);
172                if(count($data['commercial']) > 0){
173                    $where .= " AND q.commercial IN ('{$commercial}') ";
174                }
175            }
176
177            if((isset($data['start_date']) && $data['start_date'] != null) && (isset($data['end_date']) && $data['end_date'] != null)){
178                $where .= " AND q.created_at BETWEEN '{$data['start_date']}' AND '{$data['end_date']}";
179            }
180
181            $query = "SELECT
182                        bs.name AS 'status',
183                        s.name AS 'source',
184                        grouped.groupConcatIds,
185                        grouped.totalOrders,
186                        CAST(grouped.totalOrders / (case when s.name is NOT null then status_subtotals.totalOrders else overall.totalOrders END) * 100 AS DOUBLE) averageTotalOrders,
187                        grouped.totalAmount,
188                        CAST(grouped.totalAmount / (CASE WHEN s.name IS NOT NULL THEN status_subtotals.totalAmount ELSE overall.totalAmount END) * 100 AS DOUBLE) averageTotalAmount
189                    FROM (
190                        SELECT
191                            GROUP_CONCAT(q.id) groupConcatIds,
192                            q.budget_status_id,
193                            q.source_id,
194                            q.issue_date,
195                            COUNT(1) AS totalOrders,
196                            SUM(q.amount) AS totalAmount
197                        FROM tbl_quotations q
198                        LEFT JOIN tbl_sources s ON q.source_id = s.source_id
199                        WHERE
200                            q.for_add != 1
201                            AND (q.commercial IS NOT NULL AND q.commercial != '')
202                            AND q.source_id > 0
203                            AND q.budget_status_id > 0
204                            AND q.budget_status_id != 18
205                            AND s.digital_campaign_source > 0
206                            {$where}
207                        GROUP BY q.budget_status_id, q.source_id WITH ROLLUP
208                    ) AS grouped
209                    LEFT JOIN tbl_budget_status bs ON grouped.budget_status_id = bs.budget_status_id
210                    LEFT JOIN tbl_sources s ON grouped.source_id = s.source_id
211                    LEFT JOIN (
212                        SELECT
213                            q.budget_status_id,
214                            COUNT(1) AS totalOrders,
215                            SUM(q.amount) AS totalAmount
216                        FROM tbl_quotations q
217                            LEFT JOIN tbl_sources s ON q.source_id = s.source_id
218                        WHERE
219                            q.for_add != 1
220                            AND q.commercial IS NOT NULL AND q.commercial != ''
221                            AND q.budget_status_id > 0
222                            AND q.budget_status_id != 18
223                            AND s.digital_campaign_source > 0
224                            {$where}
225                        GROUP BY q.budget_status_id
226                    ) AS status_subtotals ON grouped.budget_status_id = status_subtotals.budget_status_id
227                    CROSS JOIN (
228                        SELECT
229                            COUNT(1) AS totalOrders,
230                            SUM(q.amount) AS totalAmount
231                        FROM tbl_quotations q
232                        LEFT JOIN tbl_sources s ON q.source_id = s.source_id
233                        WHERE
234                            q.for_add != 1
235                            AND (q.commercial IS NOT NULL AND q.commercial != '')
236                            AND q.source_id > 0
237                            AND q.budget_status_id > 0
238                            AND q.budget_status_id != 18
239                            AND s.digital_campaign_source > 0
240                            {$where}
241                    ) AS overall
242                    ORDER BY
243                        CASE
244                            WHEN grouped.budget_status_id IS NULL AND grouped.source_id IS NULL THEN 2
245                            ELSE 1
246                        END,
247                        bs.priority ASC,
248                        CASE
249                            WHEN grouped.source_id IS NULL THEN 0
250                            ELSE 1
251                        END,
252                        s.priority ASC";
253
254            $value = Cache::get(base64_encode($query));
255
256            if(!$value){
257                $result = DB::select($query);
258
259                Cache::put(base64_encode($query), $result, 600);
260            }else{
261                $result = $value;
262            }
263
264            return response([
265                'message' => 'OK',
266                'data' => $result
267            ]);
268
269
270        } catch (\Exception $e) {
271            return response(['message' => 'KO', 'error' => $e->getMessage()]);
272        }
273    }
274
275    function toCamelCase($string) {
276        $cleaned = preg_replace('/[^a-zA-Z0-9]+/', ' ', $string);
277        $words = explode(' ', trim($cleaned));
278
279        $camelCased = '';
280        foreach ($words as $word) {
281            if ($word !== '') {
282                $camelCased .= ucfirst(strtolower($word));
283            }
284        }
285
286        return $camelCased;
287    }
288
289    function list_time_between_status(Request $request){
290
291        try {
292
293            $data = $request->all();
294
295            $companyId = addslashes($data['company_id']);
296            $where  = "";
297
298            if($companyId != 0){
299                $where .= " AND q.company_id = {$companyId} ";
300            }else{
301                $where .= " AND q.company_id IN ({$this->companyId}";
302            }
303
304            if(isset($data['commercial']) && $data['commercial'] != null){
305                $commercial = implode("','", $data['commercial']);
306                if(count($data['commercial']) > 0){
307                    $where .= " AND q.commercial IN ('{$commercial}') ";
308                }
309            }
310
311            $averageDateCol = "";
312
313            if(isset($data['average_date']) && count($data['average_date']) == 2){
314                foreach ($data['average_date'] as $k => $v) {
315                    $data['average_date'][$k] = "q.{$v}";
316                }
317
318                $averageDate = implode(",", $data['average_date']);
319            }
320
321            $query = "SELECT
322                        -- Less than 1 day
323                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) < 1 THEN 1 END) AS totalRowsLt1,
324                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) < 1 THEN amount ELSE 0 END) AS totalAmountLt1,
325                        GROUP_CONCAT(CASE WHEN ABS(DATEDIFF({$averageDate})) < 1 THEN id END) AS groupConcatIdsLt1,
326
327                        -- 1 to 3 days
328                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) >= 1
329                                AND ABS(DATEDIFF({$averageDate})) <= 3 THEN 1 END) AS totalRows1To3,
330                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) >= 1
331                                AND ABS(DATEDIFF({$averageDate})) <= 3 THEN amount ELSE 0 END) AS totalAmount1To3,
332                        GROUP_CONCAT(CASE WHEN ABS(DATEDIFF({$averageDate})) >= 1 AND ABS(DATEDIFF({$averageDate})) <= 3 THEN id END) AS groupConcatIds1To3,
333
334                        -- More than 3 to 7 days
335                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 3
336                                AND ABS(DATEDIFF({$averageDate})) <= 7 THEN 1 END) AS totalRows3To7,
337                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 3
338                                AND ABS(DATEDIFF({$averageDate})) <= 7 THEN amount ELSE 0 END) AS totalAmount3To7,
339                        GROUP_CONCAT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 3 AND ABS(DATEDIFF({$averageDate})) <= 7 THEN id END) AS groupConcatIds3To7,
340
341                        -- More than 7 to 15 days
342                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 7
343                                AND ABS(DATEDIFF({$averageDate})) <= 15 THEN 1 END) AS totalRows7To15,
344                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 7
345                                AND ABS(DATEDIFF({$averageDate})) <= 15 THEN amount ELSE 0 END) AS totalAmount7To15,
346                        GROUP_CONCAT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 7 AND ABS(DATEDIFF({$averageDate})) <= 15 THEN id END) AS groupConcatIds7To15,
347
348                        -- More than 15 to 30 days
349                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 15
350                                AND ABS(DATEDIFF({$averageDate})) <= 30 THEN 1 END) AS totalRows15To30,
351                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 15
352                                AND ABS(DATEDIFF({$averageDate})) <= 30 THEN amount ELSE 0 END) AS totalAmount15To30,
353                        GROUP_CONCAT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 15 AND ABS(DATEDIFF({$averageDate})) <= 30 THEN id END) AS groupConcatIds15To30,
354
355                        -- More than 30 days
356                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 30 THEN 1 END) AS totalRowsGt30,
357                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 30 THEN amount ELSE 0 END) AS totalAmountGt30,
358                        GROUP_CONCAT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 30 THEN id END) AS groupConcatIdsGt30,
359
360
361
362                        -- Less than 1 day Acceptance
363                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) < 1 AND q.budget_status_id = 3 THEN 1 END) AS totalRowsLt1Acceptance,
364                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) < 1 AND q.budget_status_id = 3 THEN amount ELSE 0 END) AS totalAmountLt1Acceptance,
365                        GROUP_CONCAT(CASE WHEN ABS(DATEDIFF({$averageDate})) < 1 AND q.budget_status_id = 3 THEN id END) AS groupConcatIdsLt1Acceptance,
366
367                        -- 1 to 3 days Acceptance
368                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) >= 1
369                                AND ABS(DATEDIFF({$averageDate})) <= 3 AND q.budget_status_id = 3 THEN 1 END) AS totalRows1To3Acceptance,
370                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) >= 1
371                                AND ABS(DATEDIFF({$averageDate})) <= 3 AND q.budget_status_id = 3 THEN amount ELSE 0 END) AS totalAmount1To3Acceptance,
372                        GROUP_CONCAT(CASE WHEN ABS(DATEDIFF({$averageDate})) >= 1 AND ABS(DATEDIFF({$averageDate})) <= 3 AND q.budget_status_id = 3 THEN id END) AS groupConcatIds1To3Acceptance,
373
374                        -- More than 3 to 7 days Acceptance
375                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 3
376                                AND ABS(DATEDIFF({$averageDate})) <= 7 AND q.budget_status_id = 3 THEN 1 END) AS totalRows3To7Acceptance,
377                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 3
378                                AND ABS(DATEDIFF({$averageDate})) <= 7 AND q.budget_status_id = 3 THEN amount ELSE 0 END) AS totalAmount3To7Acceptance,
379                        GROUP_CONCAT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 3 AND ABS(DATEDIFF({$averageDate})) <= 7 AND q.budget_status_id = 3 THEN id END) AS groupConcatIds3To7Acceptance,
380
381                        -- More than 7 to 15 days Acceptance
382                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 7
383                                AND ABS(DATEDIFF({$averageDate})) <= 15 AND q.budget_status_id = 3 THEN 1 END) AS totalRows7To15Acceptance,
384                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 7
385                                AND ABS(DATEDIFF({$averageDate})) <= 15 AND q.budget_status_id = 3 THEN amount ELSE 0 END) AS totalAmount7To15Acceptance,
386                        GROUP_CONCAT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 7 AND ABS(DATEDIFF({$averageDate})) <= 15 AND q.budget_status_id = 3 THEN id END) AS groupConcatIds7To15Acceptance,
387
388                        -- More than 15 to 30 days Acceptance
389                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 15
390                                AND ABS(DATEDIFF({$averageDate})) <= 30 AND q.budget_status_id = 3 THEN 1 END) AS totalRows15To30Acceptance,
391                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 15
392                                AND ABS(DATEDIFF({$averageDate})) <= 30 AND q.budget_status_id = 3 THEN amount ELSE 0 END) AS totalAmount15To30Acceptance,
393                        GROUP_CONCAT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 15 AND ABS(DATEDIFF({$averageDate})) <= 30 AND q.budget_status_id = 3 THEN id END) AS groupConcatIds15To30Acceptance,
394
395                        -- More than 30 days Acceptance
396                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 30 AND q.budget_status_id = 3 THEN 1 END) AS totalRowsGt30Acceptance,
397                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 30 AND q.budget_status_id = 3 THEN amount ELSE 0 END) AS totalAmountGt30Acceptance,
398                        GROUP_CONCAT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 30 AND q.budget_status_id = 3 THEN id END) AS groupConcatIdsGt30Acceptance,
399
400
401
402                        -- Less than 1 day Acceptance / Issue
403                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) < 1 AND q.budget_status_id = 3 THEN 1 END) /
404                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) < 1 THEN 1 END) * 100 AS totalRowsLt1AcceptanceIssue,
405                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) < 1 AND q.budget_status_id = 3 THEN amount ELSE 0 END) /
406                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) < 1 THEN amount ELSE 0 END) * 100 AS totalAmountLt1AcceptanceIssue,
407
408                        -- 1 to 3 days Acceptance / Issue
409                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) >= 1
410                                AND ABS(DATEDIFF({$averageDate})) <= 3 AND q.budget_status_id = 3 THEN 1 END) /
411                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) >= 1
412                                AND ABS(DATEDIFF({$averageDate})) <= 3 THEN 1 END) * 100 AS totalRows1To3AcceptanceIssue,
413                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) >= 1
414                                AND ABS(DATEDIFF({$averageDate})) <= 3 AND q.budget_status_id = 3 THEN amount ELSE 0 END) /
415                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) >= 1
416                                AND ABS(DATEDIFF({$averageDate})) <= 3 THEN amount ELSE 0 END) * 100 AS totalAmount1To3AcceptanceIssue,
417
418                        -- More than 3 to 7 days Acceptance / Issue
419                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 3
420                                AND ABS(DATEDIFF({$averageDate})) <= 7 AND q.budget_status_id = 3 THEN 1 END) /
421                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 3
422                                AND ABS(DATEDIFF({$averageDate})) <= 7 THEN 1 END) * 100 AS totalRows3To7AcceptanceIssue,
423                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 3
424                                AND ABS(DATEDIFF({$averageDate})) <= 7 AND q.budget_status_id = 3 THEN amount ELSE 0 END) /
425                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 3
426                                AND ABS(DATEDIFF({$averageDate})) <= 7 THEN amount ELSE 0 END) * 100 AS totalAmount3To7AcceptanceIssue,
427
428                        -- More than 7 to 15 days Acceptance / Issue
429                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 7
430                                AND ABS(DATEDIFF({$averageDate})) <= 15 AND q.budget_status_id = 3 THEN 1 END) /
431                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 7
432                                AND ABS(DATEDIFF({$averageDate})) <= 15 THEN 1 END) * 100 AS totalRows7To15AcceptanceIssue,
433                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 7
434                                AND ABS(DATEDIFF({$averageDate})) <= 15 AND q.budget_status_id = 3 THEN amount ELSE 0 END) /
435                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 7
436                                AND ABS(DATEDIFF({$averageDate})) <= 15 THEN amount ELSE 0 END) * 100 AS totalAmount7To15AcceptanceIssue,
437
438
439                        -- More than 15 to 30 days Acceptance / Issue
440                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 15
441                                AND ABS(DATEDIFF({$averageDate})) <= 30 AND q.budget_status_id = 3 THEN 1 END) /
442                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 15
443                                AND ABS(DATEDIFF({$averageDate})) <= 30 THEN 1 END) * 100 AS totalRows15To30AcceptanceIssue,
444                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 15
445                                AND ABS(DATEDIFF({$averageDate})) <= 30 AND q.budget_status_id = 3 THEN amount ELSE 0 END) /
446                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 15
447                                AND ABS(DATEDIFF({$averageDate})) <= 30 THEN amount ELSE 0 END) * 100 AS totalAmount15To30AcceptanceIssue,
448
449                        -- More than 30 days Acceptance / Issue
450                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 30 AND q.budget_status_id = 3 THEN 1 END) /
451                        COUNT(CASE WHEN ABS(DATEDIFF({$averageDate})) > 30 THEN 1 END) * 100 AS totalRowsGt30AcceptanceIssueIssue,
452                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 30 AND q.budget_status_id = 3 THEN amount ELSE 0 END) /
453                        SUM(CASE WHEN ABS(DATEDIFF({$averageDate})) > 30 THEN amount ELSE 0 END) * 100 AS totalAmountGt30AcceptanceIssue
454                    FROM tbl_quotations q
455                        LEFT JOIN tbl_sources s ON q.source_id = s.source_id
456                    WHERE
457                        q.for_add != 1
458                        AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
459                        AND (q.commercial IS NOT NULL AND q.commercial != '')
460                        AND q.budget_type_id != 7
461                        AND q.budget_type_id IS NOT NULL
462                        AND q.source_id > 0
463                        AND q.budget_status_id > 0
464                        AND q.budget_status_id != 18
465                        AND s.digital_campaign_source > 0
466                        {$where}";
467
468        $value = Cache::get(base64_encode($query));
469
470        if(!$value){
471            $result = DB::select($query);
472
473            Cache::put(base64_encode($query), $result, 600);
474        }else{
475            $result = $value;
476        }
477
478        return response([
479            'message' => 'OK',
480            'data' => $result
481        ]);
482
483        } catch (\Exception $e) {
484            return response(['message' => 'KO', 'error' => $e->getMessage()]);
485        }
486    }
487
488    function list_g3w_order_status(Request $request){
489
490        try {
491
492            $data = $request->all();
493
494            $companyId = addslashes($data['company_id']);
495            $where  = "";
496
497            if($companyId != 0){
498                $where .= " AND q.company_id = {$companyId} ";
499            }else{
500                $where .= " AND q.company_id IN ({$this->companyId}";
501            }
502
503            if(isset($data['commercial']) && $data['commercial'] != null){
504                $commercial = implode("','", $data['commercial']);
505                if(count($data['commercial']) > 0){
506                    $where .= " AND q.commercial IN ('{$commercial}') ";
507                }
508            }
509
510            $dataToDisplay = isset($data['data_to_display']) ? $data['data_to_display'] : 1;
511
512            $col = "1";
513
514            if($dataToDisplay == 2){
515                $col = "q.amount";
516            }
517
518            $columns = "";
519            $groupedColumns = "";
520
521            $statusByG3w = array();
522
523            $workStatusAndAttributes = array("Finalizado", "Facturado", "Cerrado", "Verificado");
524
525            if(isset($data['status_by_g3w']) && count($data['status_by_g3w']) > 0){
526                $statusByG3w = $data['status_by_g3w'];
527
528                foreach ($statusByG3w as $b) {
529                    $z = $this->toCamelCase($b);
530
531                    if(!in_array($b, $workStatusAndAttributes)){
532                        $columns .= " COALESCE(SUM(CASE WHEN q.status_by_g3w = '{$b}' THEN {$col} END), 0) AS 'total{$z}', ";
533                        $columns .= " GROUP_CONCAT(CASE WHEN q.status_by_g3w = '{$b}' THEN q.id END) AS 'groupConcatIds{$z}', ";
534                    }else{
535                        if($b == "Finalizado"){
536                            $columns .= " COALESCE(SUM(CASE WHEN bw.work_status = 'Finalizado' THEN {$col} END), 0) AS 'total{$z}', ";
537                            $columns .= " GROUP_CONCAT(CASE WHEN bw.work_status = 'Finalizado' THEN q.id END) AS 'groupConcatIds{$z}', ";
538                        }
539
540                        if($b == "Facturado"){
541                            $columns .= " COALESCE(SUM(CASE WHEN bw.work_status = 'Facturado' THEN {$col} END), 0) AS 'total{$z}', ";
542                            $columns .= " GROUP_CONCAT(CASE WHEN bw.work_status = 'Facturado' THEN q.id END) AS 'groupConcatIds{$z}', ";
543                        }
544
545                        if($b == "Cerrado"){
546                            $columns .= " COALESCE(SUM(CASE WHEN bw.closed_attribute = '1' THEN {$col} END), 0) AS 'total{$z}', ";
547                            $columns .= " GROUP_CONCAT(CASE WHEN bw.closed_attribute = '1' THEN q.id END) AS 'groupConcatIds{$z}', ";
548                        }
549
550                        if($b == "Verificado"){
551                            $columns .= " COALESCE(SUM(CASE WHEN bw.verified_attribute = '1' THEN {$col} END), 0) AS 'total{$z}', ";
552                            $columns .= " GROUP_CONCAT(CASE WHEN bw.verified_attribute = '1' THEN q.id END) AS 'groupConcatIds{$z}', ";
553                        }
554                    }
555
556                    if($dataToDisplay == 3){
557                        $groupedColumns .= " CAST(grouped.total{$z} / (CASE WHEN s.name IS NOT NULL THEN subtotals.total{$z} ELSE overall.total{$z} END) * 100 AS DOUBLE) 'total{$z}', ";
558                    }else{
559                        $groupedColumns .= " grouped.total{$z}";
560                    }
561
562                    $groupedColumns .= " grouped.groupConcatIds{$z}";
563                }
564            }
565
566            $query = "SELECT
567                            c.name AS company_name,
568                            s.name AS source,
569                            {$groupedColumns}
570                            grouped.company_id
571                        FROM (
572                            SELECT
573                            q.company_id,
574                            {$columns}
575                            q.source_id
576                            FROM tbl_quotations q
577                            LEFT JOIN tbl_sources s ON q.source_id = s.source_id
578                            INNER JOIN tbl_box_work_g3w_mapping bw ON q.box_work_g3w = bw.box_work_g3w
579                            WHERE
580                                q.for_add != 1
581                                AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
582                                AND (q.commercial IS NOT NULL AND q.commercial != '')
583                                AND q.budget_type_id != 7
584                                AND q.budget_type_id IS NOT NULL
585                                AND q.source_id > 0
586                                AND q.budget_status_id > 0
587                                AND q.budget_status_id != 18
588                                AND s.digital_campaign_source > 0
589                                {$where}
590                            GROUP BY q.company_id, q.source_id WITH ROLLUP
591                        ) AS grouped
592                        LEFT JOIN tbl_sources s ON grouped.source_id = s.source_id
593                        LEFT JOIN tbl_companies c ON grouped.company_id = c.company_id
594                        LEFT JOIN (
595                            SELECT
596                            q.company_id,
597                            {$columns}
598                            q.source_id
599                            FROM tbl_quotations q
600                            LEFT JOIN tbl_sources s ON q.source_id = s.source_id
601                            INNER JOIN tbl_box_work_g3w_mapping bw ON q.box_work_g3w = bw.box_work_g3w
602                            WHERE
603                                q.for_add != 1
604                                AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
605                                AND (q.commercial IS NOT NULL AND q.commercial != '')
606                                AND q.budget_type_id != 7
607                                AND q.budget_type_id IS NOT NULL
608                                AND q.source_id > 0
609                                AND q.budget_status_id > 0
610                                AND q.budget_status_id != 18
611                                AND s.digital_campaign_source > 0
612                                {$where}
613                            GROUP BY q.company_id
614                        ) AS subtotals ON grouped.company_id = subtotals.company_id
615                        CROSS JOIN (
616                            SELECT
617                            q.company_id,
618                            {$columns}
619                            q.source_id
620                            FROM tbl_quotations q
621                            LEFT JOIN tbl_sources s ON q.source_id = s.source_id
622                            INNER JOIN tbl_box_work_g3w_mapping bw ON q.box_work_g3w = bw.box_work_g3w
623                            WHERE
624                                q.for_add != 1
625                                AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
626                                AND (q.commercial IS NOT NULL AND q.commercial != '')
627                                AND q.budget_type_id != 7
628                                AND q.budget_type_id IS NOT NULL
629                                AND q.source_id > 0
630                                AND q.budget_status_id > 0
631                                AND q.budget_status_id != 18
632                                AND s.digital_campaign_source > 0
633                                {$where}
634                        ) overall
635                        ORDER BY
636                            CASE
637                                WHEN grouped.company_id IS NULL AND grouped.source_id IS NULL THEN 2
638                                ELSE 1
639                            END,
640                            c.name ASC,
641                            CASE
642                                WHEN grouped.source_id IS NULL THEN 0
643                                ELSE 1
644                            END,
645                            s.priority ASC";
646
647            $value = Cache::get(base64_encode($query));
648
649            if(!$value){
650                $result = DB::select($query);
651
652                Cache::put(base64_encode($query), $result, 600);
653            }else{
654                $result = $value;
655            }
656
657            $labelMap = [
658                'totalAceptado'                  => 'Aceptado',
659                'totalEnviado'                   => 'Enviado',
660                'totalAnulado'                   => 'Anulado',
661                'totalRechazado'                 => 'Rechazado',
662                'totalNuevo'                     => 'Nuevo',
663                'totalListoParaEnviar'           => 'Listo para enviar',
664                'totalRechazadoAutomTicamente'   => 'Rechazado - automáticamente',
665                'totalEnProceso'                 => 'En proceso',
666                'totalFinalizado'                => 'Finalizado',
667                'totalFacturado'                 => 'Facturado',
668                'totalCerrado'                   => 'Cerrado',
669                'totalVerificado'                => 'Verificado',
670            ];
671
672            $headers = [];
673
674            foreach ($result as &$row) {
675                $rowArr = (array) $row;
676
677                if($rowArr['company_name'] == null){
678                    $totals = [];
679                    foreach ($rowArr as $key => $value) {
680                        if (str_starts_with($key, 'total')) {
681                            $groupKey = str_replace('total', 'groupConcatIds', $key);
682                            $totals[] = [
683                                'totalKey'   => $key,
684                                'totalValue' => (int) $value,
685                                'groupKey'   => $groupKey,
686                                'groupValue' => $rowArr[$groupKey] ?? null
687                            ];
688                        }
689                    }
690
691                    usort($totals, fn($a, $b) => $b['totalValue'] <=> $a['totalValue']);
692
693                    if (empty($headers)) {
694                        foreach ($totals as $t) {
695                            $headers[] = $labelMap[$t['totalKey']] ?? $t['totalKey'];
696                        }
697                    }
698
699                    $sortedRow = [
700                        'company_name' => $rowArr['company_name'],
701                        'source'       => $rowArr['source'],
702                        'company_id'   => $rowArr['company_id']
703                    ];
704
705                    foreach ($totals as $t) {
706                        $sortedRow[$t['totalKey']]  = (string) $t['totalValue'];
707                        $sortedRow[$t['groupKey']]  = $t['groupValue'];
708                    }
709
710                    $row = (object) $sortedRow;
711                }
712            }
713            unset($row);
714
715            return response([
716                'message' => 'OK',
717                'data' => $result,
718                'headers' => $headers,
719            ]);
720
721
722        } catch (\Exception $e) {
723            return response(['message' => 'KO', 'error' => $e->getMessage()]);
724        }
725
726    }
727
728    function get_sources_digital_campaign_analytics(){
729
730        try {
731
732            $sources = TblSources::where('digital_campaign_source', 1)->orderByRaw("ISNULL(priority), priority ASC")->get();
733
734            $query = "SELECT
735                        bt.budget_type_id,
736                        bt.name
737                    FROM tbl_budget_types bt
738                    LEFT JOIN tbl_budget_type_groups btg
739                        ON bt.budget_type_group_id = btg.budget_type_group_id
740                    WHERE bt.name != '' AND bt.budget_type_id != 7
741                    ORDER BY ISNULL(bt.priority), bt.priority ASC";
742
743            $budgetTypes = DB::select($query);
744
745            $query = "SELECT
746                        DISTINCT q.status_by_g3w
747                    FROM tbl_quotations q
748                    WHERE q.status_by_g3w IS NOT NULL";
749
750            $g3wStatus = DB::select($query);
751
752            return response([
753                'message' => 'OK',
754                'sources' => $sources,
755                'budgetTypes' => $budgetTypes,
756                'g3wStatus' => $g3wStatus
757            ]);
758
759        } catch (\Exception $e) {
760            return response(['message' => 'KO', 'error' => $e->getMessage()]);
761        }
762
763    }
764
765    function update_final_summary(Request $request, $companyId){
766
767        try {
768
769            $data = $request->all();
770            $companyId = addslashes($companyId);
771
772            $data['updated_at'] = date('Y-m-d H:i:s');
773            TblFinalSummary::where('company_id', $companyId)->update($data);
774
775            return response([
776                'message' => 'OK',
777            ]);
778
779        } catch (\Exception $e) {
780            return response(['message' => 'KO', 'error' => $e->getMessage()]);
781        }
782
783    }
784
785    function get_final_summary(Request $request){
786
787        try {
788
789            $data = $request->all();
790
791            $companyId = addslashes($data['company_id']);
792            $where  = "";
793
794            if($companyId != 0){
795                $where .= " AND q.company_id = {$companyId} ";
796            }else{
797                $where .= " AND q.company_id IN ({$this->companyId}";
798            }
799
800            $query = "SELECT
801                        CAST(SUM(q.impressions_total) AS UNSIGNED) AS impressions_total,
802                        CAST(SUM(q.impressions_mdm) AS UNSIGNED) AS impressions_mdm,
803                        CAST(SUM(q.impressions_mdg) AS UNSIGNED) AS impressions_mdg,
804                        CAST(SUM(q.clicks) AS UNSIGNED) AS clicks,
805                        CAST(SUM(q.clicks_mdm) AS UNSIGNED) AS clicks_mdm,
806                        CAST(SUM(q.clicks_mdg) AS UNSIGNED) AS clicks_mdg,
807                        CAST(SUM(q.conversions) AS UNSIGNED) AS conversions,
808                        CAST(SUM(q.conversions_mdm) AS UNSIGNED) AS conversions_mdm,
809                        CAST(SUM(q.leads_total) AS UNSIGNED) AS leads_total,
810                        CAST(SUM(q.leads_total_mdm) AS UNSIGNED) AS leads_total_mdm,
811                        CAST(SUM(q.leads_total_mdg) AS UNSIGNED) AS leads_total_mdg,
812                        CAST(SUM(q.calls) AS UNSIGNED) AS calls,
813                        CAST(SUM(q.forms_and_emails) AS UNSIGNED) AS forms_and_emails,
814                        CAST(SUM(q.whats_app) AS UNSIGNED) AS whats_app,
815                        CAST(SUM(q.campaign_cost_meta) AS UNSIGNED) AS campaign_cost_meta,
816                        CAST(SUM(q.campaign_cost_google) AS UNSIGNED) AS campaign_cost_google,
817                        CAST(SUM(q.invested_p1) AS UNSIGNED) AS invested_p1,
818                        CAST(SUM(q.invested_p2) AS UNSIGNED) AS invested_p2,
819                        CAST(SUM(q.invested_p3) AS UNSIGNED) AS invested_p3,
820                        CAST(SUM(q.avg_cost_per_lead_obj_v1) AS UNSIGNED) AS avg_cost_per_lead_obj_v1,
821                        CAST(SUM(q.cac_per_budget_accepted_obj_v1) AS UNSIGNED) AS cac_per_budget_accepted_obj_v1,
822                        CAST(SUM(q.cac_per_amount_accepted_obj_v1) AS UNSIGNED) AS cac_per_amount_accepted_obj_v1,
823                        CAST(SUM(q.avg_cost_per_lead_obj_v2) AS UNSIGNED) AS avg_cost_per_lead_obj_v2,
824                        CAST(SUM(q.cac_per_budget_accepted_obj_v2) AS UNSIGNED) AS cac_per_budget_accepted_obj_v2,
825                        CAST(SUM(q.cac_per_amount_accepted_obj_v2) AS UNSIGNED) AS cac_per_amount_accepted_obj_v2,
826                        CAST(SUM(q.g3w_total) AS UNSIGNED) AS g3w_total,
827                        CAST(SUM(q.g3w_total_amount) AS UNSIGNED) AS g3w_total_amount,
828                        q.created_at,
829                        q.updated_at
830                    FROM tbl_final_summary q
831                    WHERE
832                        q.company_id != 0
833                        {$where}";
834
835            $result = DB::select($query);
836
837            if(isset($data['source_ids']) && $data['source_ids'] != null){
838                $sourceIds = implode(",", $data['source_ids']);
839                if(count($data['source_ids']) > 0){
840                    $where .= " AND q.source_id IN ({$sourceIds}";
841                }
842            }
843
844            $query = "SELECT
845                            COUNT(q.created_at) totalOrders,
846                            SUM(q.amount) amount,
847                            GROUP_CONCAT(q.id) groupConcatIds,
848                            COUNT(CASE WHEN s.name LIKE '%MDM%' THEN 1 END) leadsMDM,
849                            COUNT(CASE WHEN s.name LIKE '%MDG%' THEN 1 END) leadsMDG
850                        FROM
851                        tbl_quotations q
852                        LEFT JOIN tbl_sources s
853                            ON q.source_id = s.source_id
854                        WHERE
855                            q.for_add != 1
856                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
857                            AND (q.commercial IS NOT NULL AND q.commercial != '')
858                            AND q.budget_type_id != 7
859                            AND q.budget_type_id IS NOT NULL
860                            AND (s.name LIKE '%MDM%' OR s.name LIKE '%MDG%')
861                            {$where}";
862
863            $totalOrders = DB::select($query);
864
865            $query = "SELECT
866                            COUNT(q.issue_date) issuedOrders,
867                            SUM(q.amount) amount,
868                            GROUP_CONCAT(q.id) groupConcatIds,
869                            COUNT(CASE WHEN s.name LIKE '%MDM%' THEN 1 END) issuedMDM,
870                            COUNT(CASE WHEN s.name LIKE '%MDG%' THEN 1 END) issuedMDG,
871                            SUM(
872                                CASE
873                                    WHEN DATEDIFF(q.issue_date, q.created_at) <= 3 THEN 1
874                                    ELSE 0
875                                END
876                            ) AS onTimeOrders,
877                            GROUP_CONCAT(
878                                CASE
879                                    WHEN DATEDIFF(q.issue_date, q.created_at) <= 3 THEN q.id
880                                END
881                            ) AS groupConcatIdsonTimeOrders,
882                            SUM(
883                                CASE
884                                    WHEN DATEDIFF(q.issue_date, q.created_at) > 3 THEN 1
885                                    ELSE 0
886                                END
887                            ) AS delayedOrders,
888                            GROUP_CONCAT(
889                                CASE
890                                    WHEN DATEDIFF(q.issue_date, q.created_at) > 3 THEN q.id
891                                END
892                            ) AS groupConcatIdsdelayedOrders
893                        FROM
894                        tbl_quotations q
895                        LEFT JOIN tbl_sources s
896                            ON q.source_id = s.source_id
897                        WHERE
898                            q.issue_date IS NOT NULL
899                            AND q.for_add != 1
900                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
901                            AND (q.commercial IS NOT NULL AND q.commercial != '')
902                            AND q.budget_type_id != 7
903                            AND q.budget_type_id IS NOT NULL
904                            AND (s.name LIKE '%MDM%' OR s.name LIKE '%MDG%')
905                            {$where}";
906
907            $issuedOrders = DB::select($query);
908
909            $query = "SELECT
910                            COUNT(q.acceptance_date) acceptanceOrders,
911                            SUM(q.amount) amount,
912                            GROUP_CONCAT(q.id) groupConcatIds,
913                            COUNT(CASE WHEN s.name LIKE '%MDM%' THEN 1 END) acceptanceMDM,
914                            COUNT(CASE WHEN s.name LIKE '%MDG%' THEN 1 END) acceptanceMDG,
915                            SUM(
916                                CASE
917                                    WHEN DATEDIFF(q.issue_date, q.created_at) <= 3 THEN 1
918                                    ELSE 0
919                                END
920                            ) AS onTimeOrders,
921                            GROUP_CONCAT(
922                                CASE
923                                    WHEN DATEDIFF(q.issue_date, q.created_at) <= 3 THEN q.id
924                                END
925                            ) AS groupConcatIdsonTimeOrders,
926                            SUM(
927                                CASE
928                                    WHEN DATEDIFF(q.issue_date, q.created_at) > 3 THEN 1
929                                    ELSE 0
930                                END
931                            ) AS delayedOrders,
932                            GROUP_CONCAT(
933                                CASE
934                                    WHEN DATEDIFF(q.issue_date, q.created_at) > 3 THEN q.id
935                                END
936                            ) AS groupConcatIdsdelayedOrders
937                        FROM
938                        tbl_quotations q
939                        LEFT JOIN tbl_sources s
940                            ON q.source_id = s.source_id
941                        WHERE
942                            q.acceptance_date IS NOT NULL
943                            AND q.for_add != 1
944                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
945                            AND (q.commercial IS NOT NULL AND q.commercial != '')
946                            AND q.budget_type_id != 7
947                            AND q.budget_type_id IS NOT NULL
948                            AND (s.name LIKE '%MDM%' OR s.name LIKE '%MDG%')
949                            {$where}";
950
951            $acceptanceOrders = DB::select($query);
952
953            $allRegions = TblFinalSummary::where('company_id', 0)->first();
954
955            return response([
956                'message' => 'OK',
957                'data' => $result[0],
958                'objectivesForAllRegions' => $allRegions,
959                'acceptanceOrders' => $acceptanceOrders,
960                'issuedOrders' => $issuedOrders,
961                'totalOrders' => $totalOrders
962            ]);
963
964        } catch (\Exception $e) {
965            return response(['message' => 'KO', 'error' => $e->getMessage()]);
966        }
967
968    }
969
970    function get_main_kpis(Request $request){
971
972        try {
973
974            $data = $request->all();
975
976            $companyId = addslashes($data['company_id']);
977            $where  = "";
978
979
980            foreach ($data as $key => $value) {
981                if (is_array($value)) {
982                    if (!empty($value['start_date'])) {
983                        $startDates[] = $value['start_date'];
984                    }
985                    if (!empty($value['end_date'])) {
986                        $endDates[] = $value['end_date'];
987                    }
988                }
989            }
990
991            $minDate = !empty($startDates) ? min($startDates) : null;
992            $maxDate = !empty($endDates)   ? max($endDates)   : null;
993
994            if($companyId != 0){
995                $where .= " AND q.company_id = {$companyId} ";
996            }else{
997                $where .= " AND q.company_id IN ({$this->companyId}";
998            }
999
1000            $whereTotalAcceptance = "";
1001            $whereTotalIssue = "";
1002
1003            if(isset($minDate) && $minDate != null){
1004                if(isset($maxDate) && $maxDate != null){
1005                    $whereTotalAcceptance .= " AND q.acceptance_date BETWEEN '{$minDate}' AND '{$maxDate}";
1006                    $whereTotalIssue .= " AND q.issue_date BETWEEN '{$minDate}' AND '{$maxDate}";
1007                }
1008            }
1009
1010            $query = "SELECT
1011                            COUNT(q.acceptance_date) totalOrdersAceptance,
1012                            COUNT(CASE WHEN q.budget_status_id = 2 THEN 1 END) acceptanceOrdersEnviado,
1013                            GROUP_CONCAT(CASE WHEN q.budget_status_id = 2 THEN q.id END) groupconcatIdsAcceptanceOrdersEnviado,
1014                            AVG(q.amount) averageAcceptanceAmount,
1015                            SUM(q.amount) amount,
1016                            GROUP_CONCAT(q.id) groupConcatIds,
1017                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 4 THEN q.id END) groupConcatIdsFacilities,
1018                            SUM(CASE WHEN bt.budget_type_group_id = 4 THEN q.amount END) facilitiesTotalAmount,
1019                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 8 THEN q.id END) groupConcatIdsNew,
1020                            SUM(CASE WHEN bt.budget_type_group_id = 8 THEN q.amount END) newTotalAmount,
1021                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 5 THEN q.id END) groupConcatIdsCorrectives,
1022                            SUM(CASE WHEN bt.budget_type_group_id = 5 THEN q.amount END) correctivesTotalAmount,
1023                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 3 THEN q.id END) groupConcatIdsPreventive,
1024                            SUM(CASE WHEN bt.budget_type_group_id = 3 THEN q.amount END) preventiveTotalAmount,
1025
1026                            COUNT(CASE WHEN q.budget_status_id = 2 AND bt.budget_type_group_id IN (3, 8) THEN 1 END) acceptanceOrdersEnviado38,
1027                            GROUP_CONCAT(CASE WHEN q.budget_status_id = 2 AND bt.budget_type_group_id IN (3, 8) THEN q.id END) groupConcatIdsAcceptanceOrdersEnviado38,
1028                            COUNT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN 1 END) totalOrdersAceptance38,
1029                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.id END) groupConcatIdsAcceptanceOrders38,
1030                            AVG(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.amount END) averageAcceptanceAmount38,
1031                            SUM(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.amount END) amount38
1032                        FROM
1033                        tbl_quotations q
1034                        LEFT JOIN tbl_sources s
1035                            ON q.source_id = s.source_id
1036                        LEFT JOIN tbl_budget_types bt
1037                            ON bt.budget_type_id = q.budget_type_id
1038                        WHERE
1039                            q.acceptance_date IS NOT NULL
1040                            AND q.for_add != 1
1041                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1042                            AND (q.commercial IS NOT NULL AND q.commercial != '')
1043                            AND q.budget_status_id = 3
1044                            AND q.budget_type_id != 7
1045                            AND q.budget_type_id IS NOT NULL
1046                            AND (s.name LIKE '%MDM%' OR s.name LIKE '%MDG%')
1047                            {$where}
1048                            {$whereTotalAcceptance}";
1049
1050            $resultTotalAcceptance = DB::select($query);
1051
1052            $query = "SELECT
1053                        SUM(q.amount) amount,
1054                        COUNT(q.issue_date) totalOrdersIssue,
1055                        GROUP_CONCAT(q.id) groupConcatIds,
1056                        SUM(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.amount END) amount38,
1057                        COUNT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN 1 END) totalOrdersIssue38,
1058                        GROUP_CONCAT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.id END) groupConcatIds38
1059                    FROM
1060                        tbl_quotations q
1061                        LEFT JOIN tbl_sources s
1062                            ON q.source_id = s.source_id
1063                        LEFT JOIN tbl_budget_types bt
1064                            ON bt.budget_type_id = q.budget_type_id
1065                    WHERE
1066                        q.issue_date IS NOT NULL
1067                        AND q.for_add != 1
1068                        AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1069                        AND (q.commercial IS NOT NULL AND q.commercial != '')
1070                        AND q.budget_type_id != 7
1071                        AND q.budget_type_id IS NOT NULL
1072                        AND (s.name LIKE '%MDM%' OR s.name LIKE '%MDG%')
1073                        {$where}
1074                        {$whereTotalIssue}";
1075
1076            $resultTotalIssue = DB::select($query);
1077
1078            $resultTotal = array(
1079                "result" => $resultTotalAcceptance[0],
1080                "otherStatus" => $resultTotalIssue[0],
1081                "groupConcatIds" => implode(",", array_merge(...array_map(fn($v) => explode(",", $v), [
1082                    $resultTotalAcceptance[0]->groupConcatIdsFacilities,
1083                    $resultTotalAcceptance[0]->groupConcatIdsNew,
1084                    $resultTotalAcceptance[0]->groupConcatIdsCorrectives,
1085                    $resultTotalAcceptance[0]->groupConcatIdsPreventive]))
1086                )
1087            );
1088
1089            $whereP1Acceptance = "";
1090            $whereP1Issue = "";
1091
1092            if(isset($data['p1'])){
1093                $p1 = $data['p1'];
1094
1095                if(isset($p1['start_date']) && $p1['start_date'] != null){
1096                    if(isset($p1['end_date']) && $p1['end_date'] != null){
1097                        $whereP1Acceptance .= " AND q.acceptance_date BETWEEN '{$p1['start_date']}' AND '{$p1['end_date']}";
1098                        $whereP1Issue .= " AND q.issue_date BETWEEN '{$p1['start_date']}' AND '{$p1['end_date']}";
1099                    }
1100                }
1101            }
1102
1103            $query = "SELECT
1104                            COUNT(q.acceptance_date) totalOrdersAceptance,
1105                            COUNT(CASE WHEN q.budget_status_id = 2 THEN 1 END) acceptanceOrdersEnviado,
1106                            GROUP_CONCAT(CASE WHEN q.budget_status_id = 2 THEN q.id END) groupconcatIdsAcceptanceOrdersEnviado,
1107                            AVG(q.amount) averageAcceptanceAmount,
1108                            SUM(q.amount) amount,
1109                            GROUP_CONCAT(q.id) groupConcatIds,
1110                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 4 THEN q.id END) groupConcatIdsFacilities,
1111                            SUM(CASE WHEN bt.budget_type_group_id = 4 THEN q.amount END) facilitiesTotalAmount,
1112                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 8 THEN q.id END) groupConcatIdsNew,
1113                            SUM(CASE WHEN bt.budget_type_group_id = 8 THEN q.amount END) newTotalAmount,
1114                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 5 THEN q.id END) groupConcatIdsCorrectives,
1115                            SUM(CASE WHEN bt.budget_type_group_id = 5 THEN q.amount END) correctivesTotalAmount,
1116                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 3 THEN q.id END) groupConcatIdsPreventive,
1117                            SUM(CASE WHEN bt.budget_type_group_id = 3 THEN q.amount END) preventiveTotalAmount,
1118
1119                            COUNT(CASE WHEN q.budget_status_id = 2 AND bt.budget_type_group_id IN (3, 8) THEN 1 END) acceptanceOrdersEnviado38,
1120                            GROUP_CONCAT(CASE WHEN q.budget_status_id = 2 AND bt.budget_type_group_id IN (3, 8) THEN q.id END) groupConcatIdsAcceptanceOrdersEnviado38,
1121                            COUNT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN 1 END) totalOrdersAceptance38,
1122                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.id END) groupConcatIdsAcceptanceOrders38,
1123                            AVG(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.amount END) averageAcceptanceAmount38,
1124                            SUM(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.amount END) amount38
1125                        FROM
1126                        tbl_quotations q
1127                        LEFT JOIN tbl_sources s
1128                            ON q.source_id = s.source_id
1129                        LEFT JOIN tbl_budget_types bt
1130                            ON bt.budget_type_id = q.budget_type_id
1131                        WHERE
1132                            q.acceptance_date IS NOT NULL
1133                            AND q.for_add != 1
1134                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1135                            AND (q.commercial IS NOT NULL AND q.commercial != '')
1136                            AND q.budget_status_id = 3
1137                            AND q.budget_type_id != 7
1138                            AND q.budget_type_id IS NOT NULL
1139                            AND (s.name LIKE '%MDM%' OR s.name LIKE '%MDG%')
1140                            {$where}
1141                            {$whereP1Acceptance}";
1142
1143            $resultAcceptance = DB::select($query);
1144
1145            $query = "SELECT
1146                        SUM(q.amount) amount,
1147                        COUNT(q.issue_date) totalOrdersIssue,
1148                        GROUP_CONCAT(q.id) groupConcatIds,
1149                        SUM(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.amount END) amount38,
1150                        COUNT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN 1 END) totalOrdersIssue38,
1151                        GROUP_CONCAT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.id END) groupConcatIds38
1152                    FROM
1153                        tbl_quotations q
1154                        LEFT JOIN tbl_sources s
1155                            ON q.source_id = s.source_id
1156                        LEFT JOIN tbl_budget_types bt
1157                            ON bt.budget_type_id = q.budget_type_id
1158                    WHERE
1159                        q.issue_date IS NOT NULL
1160                        AND q.for_add != 1
1161                        AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1162                        AND (q.commercial IS NOT NULL AND q.commercial != '')
1163                        AND q.budget_type_id != 7
1164                        AND q.budget_type_id IS NOT NULL
1165                        AND (s.name LIKE '%MDM%' OR s.name LIKE '%MDG%')
1166                        {$where}
1167                        {$whereP1Issue}";
1168
1169            $resultIssue = DB::select($query);
1170
1171            $resultP1 = array(
1172                "result" => $resultAcceptance[0],
1173                "otherStatus" => $resultIssue[0],
1174                "groupConcatIds" => implode(",", array_merge(...array_map(fn($v) => explode(",", $v), [
1175                    $resultAcceptance[0]->groupConcatIdsFacilities,
1176                    $resultAcceptance[0]->groupConcatIdsNew,
1177                    $resultAcceptance[0]->groupConcatIdsCorrectives,
1178                    $resultAcceptance[0]->groupConcatIdsPreventive]))
1179                )
1180            );
1181
1182            $whereP2Acceptance = "";
1183            $whereP2Issue = "";
1184
1185            if(isset($data['p2'])){
1186                $p2 = $data['p2'];
1187
1188                if(isset($p2['start_date']) && $p2['start_date'] != null){
1189                    if(isset($p2['end_date']) && $p2['end_date'] != null){
1190                        $whereP2Acceptance .= " AND q.acceptance_date BETWEEN '{$p2['start_date']}' AND '{$p2['end_date']}";
1191                        $whereP2Issue .= " AND q.issue_date BETWEEN '{$p2['start_date']}' AND '{$p2['end_date']}";
1192                    }
1193                }
1194            }
1195
1196            $query = "SELECT
1197                            COUNT(q.acceptance_date) totalOrdersAceptance,
1198                            COUNT(CASE WHEN q.budget_status_id = 2 THEN 1 END) acceptanceOrdersEnviado,
1199                            GROUP_CONCAT(CASE WHEN q.budget_status_id = 2 THEN q.id END) groupconcatIdsAcceptanceOrdersEnviado,
1200                            AVG(q.amount) averageAcceptanceAmount,
1201                            SUM(q.amount) amount,
1202                            GROUP_CONCAT(q.id) groupConcatIds,
1203                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 4 THEN q.id END) groupConcatIdsFacilities,
1204                            SUM(CASE WHEN bt.budget_type_group_id = 4 THEN q.amount END) facilitiesTotalAmount,
1205                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 8 THEN q.id END) groupConcatIdsNew,
1206                            SUM(CASE WHEN bt.budget_type_group_id = 8 THEN q.amount END) newTotalAmount,
1207                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 5 THEN q.id END) groupConcatIdsCorrectives,
1208                            SUM(CASE WHEN bt.budget_type_group_id = 5 THEN q.amount END) correctivesTotalAmount,
1209                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 3 THEN q.id END) groupConcatIdsPreventive,
1210                            SUM(CASE WHEN bt.budget_type_group_id = 3 THEN q.amount END) preventiveTotalAmount,
1211
1212                            COUNT(CASE WHEN q.budget_status_id = 2 AND bt.budget_type_group_id IN (3, 8) THEN 1 END) acceptanceOrdersEnviado38,
1213                            GROUP_CONCAT(CASE WHEN q.budget_status_id = 2 AND bt.budget_type_group_id IN (3, 8) THEN q.id END) groupConcatIdsAcceptanceOrdersEnviado38,
1214                            COUNT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN 1 END) totalOrdersAceptance38,
1215                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.id END) groupConcatIdsAcceptanceOrders38,
1216                            AVG(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.amount END) averageAcceptanceAmount38,
1217                            SUM(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.amount END) amount38
1218                        FROM
1219                        tbl_quotations q
1220                        LEFT JOIN tbl_sources s
1221                            ON q.source_id = s.source_id
1222                        LEFT JOIN tbl_budget_types bt
1223                            ON bt.budget_type_id = q.budget_type_id
1224                        WHERE
1225                            q.acceptance_date IS NOT NULL
1226                            AND q.for_add != 1
1227                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1228                            AND (q.commercial IS NOT NULL AND q.commercial != '')
1229                            AND q.budget_status_id = 3
1230                            AND q.budget_type_id != 7
1231                            AND q.budget_type_id IS NOT NULL
1232                            AND (s.name LIKE '%MDM%' OR s.name LIKE '%MDG%')
1233                            {$where}
1234                            {$whereP2Acceptance}";
1235
1236            $resultAcceptance = DB::select($query);
1237
1238            $query = "SELECT
1239                        SUM(q.amount) amount,
1240                        COUNT(q.issue_date) totalOrdersIssue,
1241                        GROUP_CONCAT(q.id) groupConcatIds,
1242                        SUM(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.amount END) amount38,
1243                        COUNT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN 1 END) totalOrdersIssue38,
1244                        GROUP_CONCAT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.id END) groupConcatIds38
1245                    FROM
1246                        tbl_quotations q
1247                        LEFT JOIN tbl_sources s
1248                            ON q.source_id = s.source_id
1249                        LEFT JOIN tbl_budget_types bt
1250                            ON bt.budget_type_id = q.budget_type_id
1251                    WHERE
1252                        q.issue_date IS NOT NULL
1253                        AND q.for_add != 1
1254                        AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1255                        AND (q.commercial IS NOT NULL AND q.commercial != '')
1256                        AND q.budget_type_id != 7
1257                        AND q.budget_type_id IS NOT NULL
1258                        AND (s.name LIKE '%MDM%' OR s.name LIKE '%MDG%')
1259                        {$where}
1260                        {$whereP2Issue}";
1261
1262            $resultIssue = DB::select($query);
1263
1264            $resultP2 = array(
1265                "result" => $resultAcceptance[0],
1266                "otherStatus" => $resultIssue[0],
1267                "groupConcatIds" => implode(",", array_merge(...array_map(fn($v) => explode(",", $v), [
1268                    $resultAcceptance[0]->groupConcatIdsFacilities,
1269                    $resultAcceptance[0]->groupConcatIdsNew,
1270                    $resultAcceptance[0]->groupConcatIdsCorrectives,
1271                    $resultAcceptance[0]->groupConcatIdsPreventive]))
1272                )
1273            );
1274
1275
1276            $whereP3Acceptance = "";
1277            $whereP3Issue = "";
1278
1279            if(isset($data['p3'])){
1280                $p3 = $data['p3'];
1281
1282                if(isset($p3['start_date']) && $p3['start_date'] != null){
1283                    if(isset($p3['end_date']) && $p3['end_date'] != null){
1284                        $whereP3Acceptance .= " AND q.acceptance_date BETWEEN '{$p3['start_date']}' AND '{$p3['end_date']}";
1285                        $whereP3Issue .= " AND q.issue_date BETWEEN '{$p3['start_date']}' AND '{$p3['end_date']}";
1286                    }
1287                }
1288            }
1289
1290            $query = "SELECT
1291                            COUNT(q.acceptance_date) totalOrdersAceptance,
1292                            COUNT(CASE WHEN q.budget_status_id = 2 THEN 1 END) acceptanceOrdersEnviado,
1293                            GROUP_CONCAT(CASE WHEN q.budget_status_id = 2 THEN q.id END) groupconcatIdsAcceptanceOrdersEnviado,
1294                            AVG(q.amount) averageAcceptanceAmount,
1295                            SUM(q.amount) amount,
1296                            GROUP_CONCAT(q.id) groupConcatIds,
1297                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 4 THEN q.id END) groupConcatIdsFacilities,
1298                            SUM(CASE WHEN bt.budget_type_group_id = 4 THEN q.amount END) facilitiesTotalAmount,
1299                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 8 THEN q.id END) groupConcatIdsNew,
1300                            SUM(CASE WHEN bt.budget_type_group_id = 8 THEN q.amount END) newTotalAmount,
1301                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 5 THEN q.id END) groupConcatIdsCorrectives,
1302                            SUM(CASE WHEN bt.budget_type_group_id = 5 THEN q.amount END) correctivesTotalAmount,
1303                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id = 3 THEN q.id END) groupConcatIdsPreventive,
1304                            SUM(CASE WHEN bt.budget_type_group_id = 3 THEN q.amount END) preventiveTotalAmount,
1305
1306                            COUNT(CASE WHEN q.budget_status_id = 2 AND bt.budget_type_group_id IN (3, 8) THEN 1 END) acceptanceOrdersEnviado38,
1307                            GROUP_CONCAT(CASE WHEN q.budget_status_id = 2 AND bt.budget_type_group_id IN (3, 8) THEN q.id END) groupConcatIdsAcceptanceOrdersEnviado38,
1308                            COUNT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN 1 END) totalOrdersAceptance38,
1309                            GROUP_CONCAT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.id END) groupConcatIdsAcceptanceOrders38,
1310                            AVG(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.amount END) averageAcceptanceAmount38,
1311                            SUM(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.amount END) amount38
1312                        FROM
1313                        tbl_quotations q
1314                        LEFT JOIN tbl_sources s
1315                            ON q.source_id = s.source_id
1316                        LEFT JOIN tbl_budget_types bt
1317                            ON bt.budget_type_id = q.budget_type_id
1318                        WHERE
1319                            q.acceptance_date IS NOT NULL
1320                            AND q.for_add != 1
1321                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1322                            AND (q.commercial IS NOT NULL AND q.commercial != '')
1323                            AND q.budget_status_id = 3
1324                            AND q.budget_type_id != 7
1325                            AND q.budget_type_id IS NOT NULL
1326                            AND (s.name LIKE '%MDM%' OR s.name LIKE '%MDG%')
1327                            {$where}
1328                            {$whereP3Acceptance}";
1329
1330            $resultAcceptance = DB::select($query);
1331
1332            $query = "SELECT
1333                        SUM(q.amount) amount,
1334                        COUNT(q.issue_date) totalOrdersIssue,
1335                        GROUP_CONCAT(q.id) groupConcatIds,
1336                        SUM(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.amount END) amount38,
1337                        COUNT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN 1 END) totalOrdersIssue38,
1338                        GROUP_CONCAT(CASE WHEN bt.budget_type_group_id IN (3, 8) THEN q.id END) groupConcatIds38
1339                    FROM
1340                        tbl_quotations q
1341                        LEFT JOIN tbl_sources s
1342                            ON q.source_id = s.source_id
1343                        LEFT JOIN tbl_budget_types bt
1344                            ON bt.budget_type_id = q.budget_type_id
1345                    WHERE
1346                        q.issue_date IS NOT NULL
1347                        AND q.for_add != 1
1348                        AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1349                        AND (q.commercial IS NOT NULL AND q.commercial != '')
1350                        AND q.budget_type_id != 7
1351                        AND q.budget_type_id IS NOT NULL
1352                        AND (s.name LIKE '%MDM%' OR s.name LIKE '%MDG%')
1353                        {$where}
1354                        {$whereP3Issue}";
1355
1356            $resultIssue = DB::select($query);
1357
1358            $resultP3 = array(
1359                "result" => $resultAcceptance[0],
1360                "otherStatus" => $resultIssue[0],
1361                "groupConcatIds" => implode(",", array_merge(...array_map(fn($v) => explode(",", $v), [
1362                    $resultAcceptance[0]->groupConcatIdsFacilities,
1363                    $resultAcceptance[0]->groupConcatIdsNew,
1364                    $resultAcceptance[0]->groupConcatIdsCorrectives,
1365                    $resultAcceptance[0]->groupConcatIdsPreventive]))
1366                )
1367            );
1368
1369            return response([
1370                'message' => 'OK',
1371                "totals" => $resultTotal,
1372                'data' => array(
1373                    'p1' => $resultP1,
1374                    'p2' => $resultP2,
1375                    'p3' => $resultP3
1376                )
1377            ]);
1378
1379
1380        } catch (\Exception $e) {
1381            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1382        }
1383
1384    }
1385
1386    function list_type_of_order(Request $request){
1387
1388        try {
1389
1390            $data = $request->all();
1391            $companyId = addslashes($data['company_id']);
1392            $where = "";
1393
1394            if($companyId != 0){
1395                $where .= " AND q.company_id = {$companyId} ";
1396            }else{
1397                $where .= " AND q.company_id IN ({$this->companyId}";
1398            }
1399
1400            if(isset($data['commercial']) && $data['commercial'] != null){
1401                $where .= " AND q.commercial = '{$data['commercial']}'";
1402            }
1403
1404            if(isset($data['budget_status_id']) && count($data['budget_status_id']) > 0){
1405                $budgetStatusIds = implode(',', $data['budget_status_id']);
1406                $where .= " AND q.budget_status_id IN ({$budgetStatusIds})";
1407            }
1408
1409            if((isset($data['start_date']) && $data['start_date'] != null) && (isset($data['end_date']) && $data['end_date'] != null)){
1410                $where .= " AND q.created_at BETWEEN '{$data['start_date']}' AND '{$data['end_date']}";
1411            }
1412
1413            $col = "1";
1414
1415            if(isset($data['data_to_display']) && $data['data_to_display'] != null){
1416                if($data['data_to_display'] == 1){
1417                    $col = "1";
1418                }
1419
1420                if($data['data_to_display'] == 2){
1421                    $col = "q.amount";
1422                }
1423            }
1424
1425            $totalCols = "";
1426
1427            $budgetTypes = TblBudgetTypes::orderByRaw("ISNULL(priority), priority ASC")->get();
1428            $cols = "";
1429            foreach ($budgetTypes as $item) {
1430                $item->name = preg_replace('/\s+/', ' ', $item->name);
1431                $ranAlias = substr(bin2hex(random_bytes(6)), 0, 6);
1432                if($item->name == '' || $item->name == null){
1433                    $cols .= ",COALESCE(SUM(CASE WHEN bt.name IS NULL THEN {$col} ELSE 0 END), 0) AS 'Otros'";
1434                    $totalCols .= ",totals.`Otros` AS '{$ranAlias}'";
1435                }else{
1436                    $cols .= ",COALESCE(SUM(CASE WHEN bt.name = '{$item->name}' THEN {$col} ELSE 0 END), 0) AS '{$item->name}'";
1437                    $totalCols .= ",totals.`{$item->name}` AS '{$ranAlias}'";
1438                }
1439            }
1440
1441            $budgetTypeGroups = TblBudgetTypeGroups::orderByRaw("ISNULL(priority), priority ASC")->get();
1442
1443            $colsGroups = "";
1444            $totalColGroups = "";
1445            $totalColIndex = array(
1446                20 => 59,
1447                21 => 43,
1448                22 => 44,
1449                23 => 45,
1450                9 => 37,
1451                25 => 47,
1452                26 => 48,
1453                27 => 49,
1454                11 => 38,
1455                29 => 51,
1456                30 => 52,
1457                13 => 39,
1458                28 => 50,
1459                15 => 40,
1460                24 => 46,
1461                31 => 53,
1462                17 => 41,
1463                32 => 54,
1464                33 => 55,
1465                34 => 56,
1466                35 => 57,
1467                36 => 58,
1468                19 => 42
1469            );
1470
1471            if(@$data['data_to_display'] != 4 && @$data['data_to_display'] != 3){
1472                foreach ($budgetTypeGroups as $item) {
1473                    $budgetTypeGroupName = str_replace(" ", "", $item->name) . $item->budget_type_group_id;
1474                    $ranAlias = substr(bin2hex(random_bytes(6)), 0, 6);
1475                    $totalColGroups .= ",totals." . preg_replace('/\s+/', ' ', $budgetTypeGroupName) . " AS '{$ranAlias}'";
1476                    $colsGroups .= ",GROUP_CONCAT(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) THEN q.id END) AS 'groupConcatIds{$budgetTypeGroupName}'";
1477                    $colsGroups .= ",COALESCE(SUM(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) THEN {$col} END), 0) AS '{$budgetTypeGroupName}'";
1478                }
1479
1480                $colsGroups .= ",COALESCE(SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) THEN {$col} END), 0) AS 'total'";
1481                $ranAlias = substr(bin2hex(random_bytes(6)), 0, 6);
1482                $totalCols .= ",totals.`total` AS '{$ranAlias}'";
1483
1484                $col = $colsGroups . $cols;
1485            }
1486
1487            if(@$data['data_to_display'] == 4){
1488
1489                foreach ($budgetTypeGroups as $item) {
1490                    $budgetTypeGroupName = str_replace(" ", "", $item->name) . $item->budget_type_group_id;
1491                    $ranAlias = substr(bin2hex(random_bytes(6)), 0, 6);
1492                    $totalColGroups .= ",totals." . preg_replace('/\s+/', ' ', $budgetTypeGroupName) . " AS '{$ranAlias}'";
1493                    $colsGroups .= ",GROUP_CONCAT(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) THEN q.id END) AS 'groupConcatIds{$budgetTypeGroupName}'";
1494                    $colsGroups .= ",COALESCE(
1495                                        SUM(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) THEN {$col} END) /
1496                                        SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) THEN {$col} END)
1497                                    , 0) AS '{$budgetTypeGroupName}'";
1498                }
1499
1500                $colsGroups .= ",COALESCE(SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) THEN {$col} END), 0) AS 'total'";
1501                $ranAlias = substr(bin2hex(random_bytes(6)), 0, 6);
1502                $totalCols .= ",totals.`total` AS '{$ranAlias}'";
1503
1504                $col = $colsGroups . $cols;
1505            }
1506
1507            if(@$data['data_to_display'] == 3){
1508
1509                $cols = "";
1510                foreach ($budgetTypes as $item) {
1511                    $item->name = preg_replace('/\s+/', ' ', $item->name);
1512                    if($item->name == '' || $item->name == null){
1513                        $ranAlias = substr(bin2hex(random_bytes(6)), 0, 6);
1514                        $totalCols .= ",totals.`Otros` AS '{$ranAlias}'";
1515                        $cols .= ",COALESCE(
1516                                        SUM(CASE WHEN bt.name IS NULL THEN q.amount ELSE 0 END) /
1517                                        SUM(CASE WHEN bt.name IS NULL THEN 1 ELSE 0 END) * 100 , 0
1518                                    ) AS 'Otros'";
1519                    }else{
1520                        $ranAlias = substr(bin2hex(random_bytes(6)), 0, 6);
1521                        $totalCols .= ",totals.`{$item->name}` AS '{$ranAlias}'";
1522                        $cols .= ",COALESCE(
1523                                        SUM(CASE WHEN bt.name = '{$item->name}' THEN q.amount ELSE 0 END) /
1524                                        SUM(CASE WHEN bt.name = '{$item->name}' THEN 1 ELSE 0 END), 0
1525                                    ) AS '{$item->name}'";
1526                    }
1527                }
1528
1529                $ranAlias = substr(bin2hex(random_bytes(6)), 0, 6);
1530                $totalColGroups .= ",totals.Otros AS '{$ranAlias}'";
1531                foreach ($budgetTypeGroups as $item) {
1532                    $budgetTypeGroupName = str_replace(" ", "", $item->name) . $item->budget_type_group_id;
1533                    $ranAlias = substr(bin2hex(random_bytes(6)), 0, 6);
1534                    $totalColGroups .= ",totals." . preg_replace('/\s+/', ' ', $budgetTypeGroupName) . " AS '{$ranAlias}'";
1535                    $colsGroups .= ",GROUP_CONCAT(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) THEN q.id END) AS 'groupConcatIds{$budgetTypeGroupName}'";
1536                    $colsGroups .= ",COALESCE(
1537                                        (SUM(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) THEN q.amount END)) /
1538                                        (SUM(CASE WHEN (bt.budget_type_group_id = {$item->budget_type_group_id} OR bt.name IS NULL) THEN 1 END))
1539                                    , 0) '{$budgetTypeGroupName}'";
1540                }
1541
1542                $colsGroups .= ",COALESCE(
1543                                    (SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) THEN q.amount END)) /
1544                                    (SUM(CASE WHEN (bt.budget_type_group_id IS NOT NULL OR bt.name IS NULL) THEN 1 END))
1545                                , 0) 'total'";
1546
1547                $ranAlias = substr(bin2hex(random_bytes(6)), 0, 6);
1548                $totalColGroups .= ",totals.`total` AS '{$ranAlias}'";
1549                $col = $colsGroups . $cols;
1550
1551            }
1552
1553            $totalCols = $totalColGroups . $totalCols;
1554
1555            if(isset($data['budget_type_id']) && count($data['budget_type_id']) > 0){
1556                $budgetTypeIds = implode(',', $data['budget_type_id']);
1557                $where .= " AND q.budget_type_id IN ({$budgetTypeIds})";
1558            }
1559
1560            $sortByFirst = "";
1561            $sortBySecond = "";
1562
1563            if(isset($data['sort_by']) && $data['sort_by'] != null){
1564                if(isset($data['column']) && $data['column'] != null){
1565                    $orderCol = $totalColIndex[$data['column']];
1566                    $sortByFirst = "{$orderCol} {$data['sort_by']},";
1567                    $sortBySecond = "{$data['column']} {$data['sort_by']},";
1568                }
1569            }
1570
1571            $query  = "SELECT
1572                            s.name AS 'source',
1573                            bs.name AS 'status',
1574                            q.source_id,
1575                            q.budget_status_id,
1576                            GROUP_CONCAT(q.id) groupConcatIds,
1577                            COUNT(1) AS totalOrders,
1578                            SUM(q.amount) AS totalAmount
1579                            {$col}
1580                            {$totalCols}
1581                        FROM
1582                            tbl_quotations q
1583                            LEFT JOIN tbl_sources s ON s.source_id = q.source_id
1584                            LEFT JOIN tbl_budget_status bs ON bs.budget_status_id = q.budget_status_id
1585                            LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
1586                            LEFT JOIN tbl_budget_type_groups btg ON bt.budget_type_group_id = btg.budget_type_group_id
1587                            LEFT JOIN tbl_customer_types ct ON q.customer_type_id = ct.customer_type_id
1588                        JOIN
1589                            (
1590                            SELECT
1591                                q.source_id,
1592                                NULL a,
1593                                NULL b,
1594                                NULL c,
1595                                NULL d,
1596                                NULL e,
1597                                NULL f
1598                                {$col}
1599                            FROM
1600                                tbl_quotations q
1601                                LEFT JOIN tbl_sources s ON s.source_id = q.source_id
1602                                LEFT JOIN tbl_budget_status bs ON bs.budget_status_id = q.budget_status_id
1603                                LEFT JOIN tbl_budget_types bt ON q.budget_type_id = bt.budget_type_id
1604                                LEFT JOIN tbl_budget_type_groups btg ON bt.budget_type_group_id = btg.budget_type_group_id
1605                                LEFT JOIN tbl_customer_types ct ON q.customer_type_id = ct.customer_type_id
1606                            WHERE
1607                                q.for_add != 1
1608                                AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1609                                AND (q.commercial IS NOT NULL AND q.commercial != '')
1610                                AND q.budget_type_id != 7
1611                                AND q.budget_type_id IS NOT NULL
1612                                AND q.source_id > 0
1613                                AND q.budget_status_id > 0
1614                                AND q.budget_status_id != 18
1615                                AND s.digital_campaign_source > 0
1616                                {$where}
1617                            GROUP BY q.source_id
1618                            ) AS totals
1619                                ON q.source_id = totals.source_id
1620                        WHERE
1621                            q.for_add != 1
1622                            AND q.amount REGEXP '^[0-9]+\\.?[0-9]*$' = 1
1623                            AND (q.commercial IS NOT NULL AND q.commercial != '')
1624                            AND q.budget_type_id != 7
1625                            AND q.budget_type_id IS NOT NULL
1626                            AND q.source_id > 0
1627                            AND q.budget_status_id > 0
1628                            AND q.budget_status_id != 18
1629                            AND s.digital_campaign_source > 0
1630                            {$where}
1631                        GROUP BY
1632                            q.source_id,
1633                            q.budget_status_id WITH ROLLUP
1634                        ORDER BY
1635                            CASE WHEN q.source_id IS NULL THEN 1 ELSE 0 END,
1636                            {$sortByFirst}
1637                            q.source_id,
1638                            CASE WHEN q.budget_status_id IS NULL THEN 0 ELSE 1 END,
1639                            {$sortBySecond}
1640                            q.budget_status_id";
1641            // return $query;
1642            $result = DB::select($query);
1643
1644            $query = "SELECT
1645                        btg.budget_type_group_id,
1646                        btg.name,
1647                        (
1648                            SELECT
1649                                GROUP_CONCAT(COALESCE(bt.name, '') ORDER BY ISNULL(bt.priority), bt.priority ASC SEPARATOR '|')
1650                            FROM
1651                                tbl_budget_types bt
1652                            WHERE
1653                                bt.budget_type_group_id = btg.budget_type_group_id
1654                        ) budget_types
1655                        FROM
1656                            tbl_budget_type_groups btg
1657                        ORDER BY
1658                            ISNULL(btg.priority),
1659                            btg.priority ASC";
1660
1661            $budgetTypeGroups = DB::select($query);
1662
1663            foreach ($budgetTypeGroups as $item) {
1664                $item->group_key_name = str_replace(" ", "", $item->name) . $item->budget_type_group_id;
1665                $item->budget_types = explode("|", $item->budget_types);
1666            }
1667
1668            return response([
1669                'message' => 'OK',
1670                'data' => $result,
1671                'budgetTypeGroups' => $budgetTypeGroups
1672            ]);
1673
1674        } catch (\Exception $e) {
1675            return response(['message' => 'KO', 'error' => $e->getMessage()]);
1676        }
1677    }
1678
1679    function getG3wTasksExecuted(Request $request){
1680        $region = urldecode(@getallheaders()["Region"]);
1681        try {
1682            $result = $this->workService->getG3wTasksExecuted($region);
1683            return response()->json([
1684                'data' => $result,
1685            ]);
1686
1687        }catch (\Exception $e) {
1688            Log::channel('g3w_invoices')->error("Failed to get g3w tasks executed: " . $e->getMessage());
1689            return response()->json([
1690                'message' => $e->getMessage(),
1691            ], 500);
1692        }
1693
1694    }
1695
1696    function list_performance_metrics(Request $request){
1697
1698        try {
1699            
1700            $data = $request->all();
1701
1702            $companyId = addslashes($data['company_id']);
1703            $where  = "";
1704
1705            if($companyId != 0){
1706                $where .= " AND q.company_id = {$companyId} ";
1707            }else{
1708                $where .= " AND q.company_id IN ({$this->companyId}";
1709            }
1710
1711            $ticketMedium = 1;
1712
1713            if(isset($data['medium_ticket_index']) && $data['medium_ticket_index']){
1714                $ticketMedium = $data['medium_ticket_index'];
1715            }
1716
1717            $createdRange = "";
1718            $issuedRange = "";
1719            $acceptanceRange = "";
1720            $requestRange = "";
1721            
1722            $issuedWhere = $where;            
1723            
1724
1725            if((isset($data['start_date']) && $data['start_date'] != null) && (isset($data['end_date']) && $data['end_date'] != null)){
1726                // $createdRange .= " AND q.created_at BETWEEN '{$data['start_date']}' AND '{$data['end_date']}' ";
1727                $issuedRange .= " AND q.issue_date BETWEEN '{$data['start_date']}' AND '{$data['end_date']}";
1728                $acceptanceRange .= " AND q.acceptance_date BETWEEN '{$data['start_date']}' AND '{$data['end_date']}";
1729                $requestRange .= " AND q.request_date BETWEEN '{$data['start_date']}' AND '{$data['end_date']}";
1730            }
1731            
1732            $query = "SELECT 
1733                            q.company_name,
1734                            q.company_id,
1735                            SUM(q.total_investment) totalInvestment,
1736                            SUM(q.totalOrders) totalOrders,
1737                            GROUP_CONCAT(q.groupConcatIdsTotalOrders) groupConcatIdsTotalOrders,                           
1738                            COALESCE(SUM(q.total_investment) / SUM(q.totalOrders), 0) CPL,
1739                            COALESCE(SUM(q.total_investment) / SUM(q.totalOrdersAcceptanceAmount), 0) CAC1,
1740                            COALESCE(SUM(q.total_investment) / SUM(q.totalOrdersAcceptanceAmountAnyMonth), 0) CAC2,
1741                            COALESCE(SUM(q.total_investment) / SUM(q.totalOrdersAcceptanceAmountSent), 0) CAC3,
1742                            SUM(q.totalOrdersSent) totalOrdersSent,
1743                            SUM(q.totalOrdersAmountSent) totalOrdersAmountSent,
1744                            GROUP_CONCAT(q.groupConcatIdsTotalOrdersSent) groupConcatIdsTotalOrdersSent,
1745                            SUM(q.totalOrdersAmount) totalOrdersAmount,
1746                            SUM(q.totalOrdersSentAnyMonth) totalOrdersSentAnyMonth,
1747                            SUM(q.totalOrdersAmountSentAnyMonth) totalOrdersAmountSentAnyMonth,
1748                            GROUP_CONCAT(q.groupConcatIdsTotalOrdersSentAnyMonth) groupConcatIdsTotalOrdersSentAnyMonth,
1749                            COALESCE(SUM(q.totalOrdersSent) / SUM(q.totalOrders) * 100, 0) percentageOfLeadsSentMonthlyOutOfLeadsMonthly,
1750                            SUM(q.totalOrdersAcceptance) totalOrdersAcceptance,
1751                            GROUP_CONCAT(q.groupConcatIdsTotalOrdersAcceptance) groupConcatIdsTotalOrdersAcceptance,
1752                            SUM(q.totalOrdersAcceptanceAmount) totalOrdersAcceptanceAmount,
1753                            SUM(q.totalOrdersAcceptanceAnyMonth) totalOrdersAcceptanceAnyMonth,
1754                            GROUP_CONCAT(q.groupConcatIdsTotalOrdersAcceptanceAnyMonth) groupConcatIdsTotalOrdersAcceptanceAnyMonth,
1755                            SUM(q.totalOrdersAcceptanceAmountAnyMonth) totalOrdersAcceptanceAmountAnyMonth,
1756                            SUM(q.totalOrdersAcceptanceSent) totalOrdersAcceptanceSent,
1757                            GROUP_CONCAT(q.groupConcatIdsTotalOrdersAcceptanceSent) groupConcatIdsTotalOrdersAcceptanceSent,
1758                            SUM(q.totalOrdersAcceptanceAmountSent) totalOrdersAcceptanceAmountSent,
1759                            CASE {$ticketMedium}
1760                                WHEN 1 THEN COALESCE(SUM(q.totalOrdersAcceptance) / SUM(q.totalOrdersAcceptanceAmount), 0)
1761                                WHEN 2 THEN COALESCE(SUM(q.totalOrdersAcceptanceAnyMonth) / SUM(q.totalOrdersAcceptanceAmountAnyMonth), 0)
1762                                WHEN 3 THEN COALESCE(SUM(q.totalOrdersAcceptanceSent) / SUM(q.totalOrdersAcceptanceAmountSent), 0)    
1763                            END AS ticketMedio,
1764                            COALESCE(SUM(q.totalOrdersAcceptance) / SUM(q.totalOrdersSent) * 100, 0) percentageAcceptanceOne,
1765                            COALESCE(SUM(q.totalOrdersAcceptanceAnyMonth) / SUM(q.totalOrdersSentAnyMonth) * 100, 0) percentageAcceptanceTwo,
1766                            COALESCE(SUM(q.totalOrdersAcceptanceAnyMonth) - SUM(q.total_investment), 0) leadsBenefitMonth,
1767                            COALESCE(SUM(q.totalOrdersAcceptance) - SUM(q.total_investment), 0) realBenefit,
1768                            SUM(q.totalOrdersSent1) totalOrdersSent1,
1769                            SUM(q.totalOrdersAmountSent1) totalOrdersAmountSent1,
1770                            GROUP_CONCAT(q.groupConcatIdsTotalOrdersSent1) groupConcatIdsTotalOrdersSent1
1771                        FROM
1772                        (
1773                        SELECT
1774                            c.region company_name,
1775                            c.company_id,
1776                            c.total_investment,
1777                            COUNT(1) totalOrders,                            
1778                            SUM(q.amount) totalOrdersAmount,
1779                            GROUP_CONCAT(q.id) groupConcatIdsTotalOrders,
1780                            0 totalOrdersSent,                            
1781                            0 totalOrdersAmountSent,
1782                            NULL groupConcatIdsTotalOrdersSent,
1783                            0 totalOrdersSentAnyMonth,
1784                            0 totalOrdersAmountSentAnyMonth,
1785                            NULL groupConcatIdsTotalOrdersSentAnyMonth,    
1786                            COUNT(CASE WHEN q.acceptance_date IS NOT NULL AND q.acceptance_date != '0000-00-00 00:00:00' THEN 1 END) totalOrdersAcceptance,                            
1787                            SUM(CASE WHEN q.acceptance_date IS NOT NULL AND q.acceptance_date != '0000-00-00 00:00:00' THEN q.amount END) totalOrdersAcceptanceAmount,
1788                            GROUP_CONCAT(CASE WHEN q.acceptance_date IS NOT NULL AND q.acceptance_date != '0000-00-00 00:00:00' THEN q.id END) groupConcatIdsTotalOrdersAcceptance,
1789                            0 totalOrdersAcceptanceAnyMonth,                            
1790                            0 totalOrdersAcceptanceAmountAnyMonth,
1791                            NULL groupConcatIdsTotalOrdersAcceptanceAnyMonth,
1792                            COUNT(CASE WHEN q.acceptance_date IS NOT NULL AND q.acceptance_date != '0000-00-00 00:00:00' AND q.budget_status_id = 2  THEN 1 END) totalOrdersAcceptanceSent,                            
1793                            SUM(CASE WHEN q.acceptance_date IS NOT NULL AND q.acceptance_date != '0000-00-00 00:00:00' AND q.budget_status_id = 2  THEN q.amount END) totalOrdersAcceptanceAmountSent,
1794                            GROUP_CONCAT(CASE WHEN q.acceptance_date IS NOT NULL AND q.acceptance_date != '0000-00-00 00:00:00' AND q.budget_status_id = 2 THEN q.id END) groupConcatIdsTotalOrdersAcceptanceSent,
1795                            0 totalOrdersSent1,
1796                            0 totalOrdersAmountSent1,
1797                            NULL groupConcatIdsTotalOrdersSent1
1798                        FROM tbl_quotations q
1799                        LEFT JOIN tbl_sources s
1800                            ON q.source_id = s.source_id
1801                        LEFT JOIN tbl_companies c
1802                            ON q.company_id = c.company_id
1803                        WHERE
1804                            q.for_add != 1                                
1805                            AND q.issue_date IS NOT NULL
1806                            AND (q.commercial IS NOT NULL AND q.commercial != '')
1807                            AND q.source_id IS NOT NULL
1808                            AND s.digital_campaign_source > 0
1809                            AND q.budget_status_id != 18
1810                            {$where}
1811                            {$issuedRange}
1812                        GROUP BY q.company_id
1813
1814                        UNION ALL
1815
1816                        SELECT
1817                            c.region company_name,
1818                            c.company_id,
1819                            0 total_investment,
1820                            0 totalOrders,
1821                            0 totalOrdersAmount,                            
1822                            NULL groupConcatIdsTotalOrders,
1823                            COUNT(1) totalOrdersSent,                            
1824                            SUM(q.amount) totalOrdersAmountSent,
1825                            GROUP_CONCAT(q.id) groupConcatIdsTotalOrdersSent,
1826                            0 totalOrdersSentAnyMonth,
1827                            0 totalOrdersAmountSentAnyMonth,
1828                            NULL groupConcatIdsTotalOrdersSentAnyMonth,    
1829                            0 totalOrdersAcceptance,
1830                            0 totalOrdersAcceptanceAmount,
1831                            NULL groupConcatIdsTotalOrdersAcceptance,
1832                            0 totalOrdersAcceptanceAnyMonth,                            
1833                            0 totalOrdersAcceptanceAmountAnyMonth,
1834                            NULL groupConcatIdsTotalOrdersAcceptanceAnyMonth,
1835                            0 totalOrdersAcceptanceSent,                            
1836                            0 totalOrdersAcceptanceAmountSent,
1837                            NULL groupConcatIdsTotalOrdersAcceptanceSent,
1838                            0 totalOrdersSent1,
1839                            0 totalOrdersAmountSent1,
1840                            NULL groupConcatIdsTotalOrdersSent1
1841                        FROM tbl_quotations q
1842                        LEFT JOIN tbl_sources s
1843                            ON q.source_id = s.source_id
1844                        LEFT JOIN tbl_companies c
1845                            ON q.company_id = c.company_id
1846                        WHERE
1847                            q.for_add != 1                            
1848                            AND q.issue_date IS NOT NULL 
1849                            AND (q.commercial IS NOT NULL AND q.commercial != '')
1850                            AND q.source_id IS NOT NULL
1851                            AND s.digital_campaign_source > 0
1852                            AND q.budget_status_id = 2
1853                            AND q.budget_status_id != 18
1854                            {$where}
1855                            {$requestRange}
1856                        GROUP BY q.company_id
1857
1858                        UNION ALL
1859
1860                        SELECT
1861                            c.region company_name,
1862                            c.company_id,
1863                            0 total_investment,
1864                            0 totalOrders,
1865                            0 totalOrdersAmount,
1866                            0 totalOrdersSent,                            
1867                            0 totalOrdersAmountSent,
1868                            NULL groupConcatIdsTotalOrdersSent,
1869                            NULL groupConcatIdsTotalOrders,
1870                            COUNT(1) totalOrdersSentAnyMonth,
1871                            SUM(q.amount) totalOrdersAmountSentAnyMonth,
1872                            GROUP_CONCAT(q.id) groupConcatIdsTotalOrdersSentAnyMonth,    
1873                            0 totalOrdersAcceptance,
1874                            0 totalOrdersAcceptanceAmount,
1875                            NULL groupConcatIdsTotalOrdersAcceptance,
1876                            0 totalOrdersAcceptanceAnyMonth,                            
1877                            0 totalOrdersAcceptanceAmountAnyMonth,
1878                            NULL groupConcatIdsTotalOrdersAcceptanceAnyMonth,
1879                            0 totalOrdersAcceptanceSent,                            
1880                            0 totalOrdersAcceptanceAmountSent,
1881                            NULL groupConcatIdsTotalOrdersAcceptanceSent,
1882                            0 totalOrdersSent1,
1883                            0 totalOrdersAmountSent1,
1884                            NULL groupConcatIdsTotalOrdersSent1
1885                        FROM tbl_quotations q
1886                        LEFT JOIN tbl_sources s
1887                            ON q.source_id = s.source_id
1888                        LEFT JOIN tbl_companies c
1889                            ON q.company_id = c.company_id
1890                        WHERE
1891                            q.for_add != 1                            
1892                            AND q.request_date IS NOT NULL 
1893                            AND (q.commercial IS NOT NULL AND q.commercial != '')
1894                            AND q.source_id IS NOT NULL
1895                            AND s.digital_campaign_source > 0
1896                            AND q.budget_status_id = 2
1897                            AND q.budget_status_id != 18
1898                            {$where}
1899                            {$issuedRange}
1900                        GROUP BY q.company_id
1901
1902                        UNION ALL
1903
1904                        SELECT
1905                            c.region company_name,
1906                            c.company_id,
1907                            0 total_investment,
1908                            0 totalOrders,
1909                            0 totalOrdersAmount,
1910                            0 totalOrdersSent,                            
1911                            0 totalOrdersAmountSent,
1912                            NULL groupConcatIdsTotalOrdersSent,
1913                            NULL groupConcatIdsTotalOrders,
1914                            0 totalOrdersSentAnyMonth,
1915                            0 totalOrdersAmountSentAnyMonth,
1916                            NULL groupConcatIdsTotalOrdersSentAnyMonth,    
1917                            0 totalOrdersAcceptance,
1918                            0 totalOrdersAcceptanceAmount,
1919                            NULL groupConcatIdsTotalOrdersAcceptance,
1920                            0 totalOrdersAcceptanceAnyMonth,                            
1921                            0 totalOrdersAcceptanceAmountAnyMonth,
1922                            NULL groupConcatIdsTotalOrdersAcceptanceAnyMonth,
1923                            0 totalOrdersAcceptanceSent,                            
1924                            0 totalOrdersAcceptanceAmountSent,
1925                            NULL groupConcatIdsTotalOrdersAcceptanceSent,
1926                            COUNT(1) totalOrdersSent1,
1927                            SUM(q.amount) totalOrdersAmountSent1,
1928                            GROUP_CONCAT(q.id) groupConcatIdsTotalOrdersSent1
1929                        FROM tbl_quotations q
1930                        LEFT JOIN tbl_sources s
1931                            ON q.source_id = s.source_id
1932                        LEFT JOIN tbl_companies c
1933                            ON q.company_id = c.company_id
1934                        WHERE
1935                            q.for_add != 1                            
1936                            AND q.issue_date IS NOT NULL 
1937                            AND (q.commercial IS NOT NULL AND q.commercial != '')
1938                            AND q.source_id IS NOT NULL
1939                            AND s.digital_campaign_source > 0
1940                            AND q.budget_status_id = 2
1941                            AND q.budget_status_id != 18
1942                            {$where}
1943                            {$issuedRange}
1944                        GROUP BY q.company_id
1945                            
1946                        UNION ALL
1947
1948                        SELECT
1949                            c.region company_name,
1950                            c.company_id,
1951                            0 total_investment,
1952                            0 totalOrders,
1953                            0 totalOrdersAmount,
1954                            NULL groupConcatIdsTotalOrders,
1955                            0 totalOrdersSent,                            
1956                            0 totalOrdersAmountSent,
1957                            NULL groupConcatIdsTotalOrdersSent,
1958                            0 totalOrdersSentAnyMonth,
1959                            0 totalOrdersAmountSentAnyMonth,
1960                            NULL groupConcatIdsTotalOrdersSentAnyMonth,     
1961                            0 totalOrdersAcceptance,
1962                            0 totalOrdersAcceptanceAmount,
1963                            NULL groupConcatIdsTotalOrdersAcceptance,
1964                            COUNT(CASE WHEN q.acceptance_date != '0000-00-00 00:00:00' THEN 1 END) totalOrdersAcceptanceAnyMonth,                            
1965                            SUM(CASE WHEN q.acceptance_date != '0000-00-00 00:00:00' THEN q.amount END) totalOrdersAcceptanceAmountAnyMonth,
1966                            GROUP_CONCAT(CASE WHEN q.acceptance_date != '0000-00-00 00:00:00' THEN q.id END) groupConcatIdsTotalOrdersAcceptanceAnyMonth,
1967                            0 totalOrdersAcceptanceSent,                            
1968                            0 totalOrdersAcceptanceAmountSent,
1969                            NULL groupConcatIdsTotalOrdersAcceptanceSent,
1970                            0 totalOrdersSent1,
1971                            0 totalOrdersAmountSent1,
1972                            NULL groupConcatIdsTotalOrdersSent1
1973                        FROM tbl_quotations q
1974                        LEFT JOIN tbl_sources s
1975                            ON q.source_id = s.source_id
1976                        LEFT JOIN tbl_companies c
1977                            ON q.company_id = c.company_id
1978                        WHERE
1979                            q.for_add != 1
1980                            AND q.acceptance_date IS NOT NULL
1981                            AND q.request_date IS NOT NULL
1982                            AND (q.commercial IS NOT NULL AND q.commercial != '')
1983                            AND q.source_id IS NOT NULL
1984                            AND s.digital_campaign_source > 0
1985                            AND q.budget_status_id != 18
1986                            {$where}
1987                            {$acceptanceRange}
1988                        GROUP BY q.company_id
1989                    ) q
1990                    GROUP BY q.company_name WITH ROLLUP";
1991
1992            // $value = Cache::get(base64_encode($query));
1993
1994            // if(!$value){
1995                $result = DB::select($query);
1996
1997                // Cache::put(base64_encode($query), $result, 600);
1998            // }else{
1999            //     $result = $value;
2000            // }
2001
2002            return response([
2003                'message' => 'OK',
2004                'data' => $result
2005            ]);
2006
2007        } catch (\Exception $e) {
2008            return response(['message' => 'KO', 'error' => $e->getMessage()]);
2009        }
2010
2011    }
2012}