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