Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 280
0.00% covered (danger)
0.00%
0 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
FacturasController
0.00% covered (danger)
0.00%
0 / 280
0.00% covered (danger)
0.00%
0 / 15
4290
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getInvoices
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 getAllInvoices
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
20
 getAllInvoicesExceptions
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
12
 setInvoiceReminderActive
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
12
 getInvoiceReminderActive
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
12
 addInvoiceReminderException
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 getInvoice
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
12
 addInvoiceNextReminder
0.00% covered (danger)
0.00%
0 / 22
0.00% covered (danger)
0.00%
0 / 1
56
 uploadToCyC
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 setAllMonthAdministratorsInvoices
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 sendAdministratorsInvoices
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 sendCallCenterInvoices
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 handleGoogleAuthCallback
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 listCreditDaysOffered
0.00% covered (danger)
0.00%
0 / 87
0.00% covered (danger)
0.00%
0 / 1
420
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Models\TblCompanies;
6use App\Models\TblInvoiceReminders;
7use App\Models\TblInvoicesExceptions;
8use App\Models\TblInvoicesNextReminders;
9use App\Models\TblCreditDaysOffered;
10use App\Services\FacturasService;
11use Illuminate\Http\Request;
12use Illuminate\Support\Facades\Log;
13use Illuminate\Support\Facades\DB;
14
15class FacturasController extends GestionaController
16{
17    private $facturasService;
18
19    public function __construct(FacturasService $facturasService)
20    {
21        $this->facturasService = $facturasService;
22    }
23
24    public function getInvoices(Request $request)
25    {
26        $region = urldecode($request->header('Region'));
27
28        if ($region === 'Catalunya') {
29            $region = 'Cataluña';
30        }
31
32        try {
33            $result = $this->facturasService->getInvoices($region);
34
35            if (! $result['success']) {
36                throw new \Exception($result['error']);
37            }
38
39            return response()->json([
40                'success' => true,
41            ], 200);
42
43        } catch (\Exception $e) {
44            /** @disregard P1014 */
45            $e->exceptionCode = 'GET_INVOICES_EXCEPTION';
46            report($e);
47            Log::channel('g3w_invoices')->error('Failed to get invoices: '.$e->getMessage());
48
49            return response()->json([
50                'success' => false,
51                'message' => $e->getMessage(),
52            ], 500);
53        }
54    }
55
56    public function getAllInvoices(Request $request)
57    {
58        try {
59            $region = urldecode($request->header('Region'));
60
61            if ($region === 'Catalunya') {
62                $region = 'Cataluña';
63            }
64
65            $result = $this->facturasService->getAllInvoices($region);
66
67            if ($result->isEmpty()) {
68                throw new \Exception($result['error']);
69            }
70
71            return response()->json([
72                'success' => true,
73                'invoices' => $result->original['invoices'],
74                'pagination' => $result->original['pagination'],
75            ]);
76
77        } catch (\Exception $e) {
78            /** @disregard P1014 */
79            $e->exceptionCode = 'GET_ALL_INVOICES_EXCEPTION';
80            report($e);
81            Log::channel('g3w_invoices')->error('Failed to get invoices: '.$e->getMessage());
82
83            return response()->json([
84                'success' => false,
85                'message' => $e->getMessage(),
86            ], 500);
87        }
88    }
89
90    public function getAllInvoicesExceptions(Request $request)
91    {
92        try {
93
94            $result = $this->facturasService->getAllInvoicesExceptions();
95
96            if ($result->isEmpty()) {
97                throw new \Exception($result['error']);
98            }
99
100            return response()->json([
101                'success' => true,
102                'invoices' => $result->original['invoices'],
103                'pagination' => $result->original['pagination'],
104            ]);
105
106        } catch (\Exception $e) {
107            /** @disregard P1014 */
108            $e->exceptionCode = 'GET_ALL_INVOICES_EXCEPTIONS_EXCEPTION';
109            report($e);
110            Log::channel('g3w_invoices')->error('Failed to get invoices: '.$e->getMessage());
111
112            return response()->json([
113                'success' => false,
114                'message' => $e->getMessage(),
115            ], 500);
116        }
117    }
118
119    public function setInvoiceReminderActive($value)
120    {
121        try {
122            $region = urldecode(@getallheaders()['Region']);
123
124            if (! $region) {
125                throw new \Exception('No region provided');
126            }
127
128            TblCompanies::where('region', $region)->update(['invoice_reminder_active' => $value === 'true']);
129
130            return response()->json([
131                'success' => true,
132            ]);
133
134        } catch (\Exception $e) {
135            /** @disregard P1014 */
136            $e->exceptionCode = 'SET_INVOICE_REMINDER_ACTIVE_EXCEPTION';
137            report($e);
138            Log::channel('g3w_invoices')->error('Failed to set invoice reminder active: '.$e->getMessage());
139
140            return response()->json([
141                'success' => false,
142                'message' => $e->getMessage(),
143            ], 500);
144        }
145    }
146
147    public function getInvoiceReminderActive()
148    {
149        try {
150            $region = urldecode(@getallheaders()['Region']);
151
152            if (! $region) {
153                throw new \Exception('No region provided');
154            }
155
156            $tblCompanies = TblCompanies::where('region', $region)->first();
157
158            return response()->json([
159                'success' => true,
160                'invoice_reminder_active' => $tblCompanies->invoice_reminder_active,
161            ]);
162
163        } catch (\Exception $e) {
164            /** @disregard P1014 */
165            $e->exceptionCode = 'GET_INVOICE_REMINDER_ACTIVE_EXCEPTION';
166            report($e);
167            Log::channel('g3w_invoices')->error('Failed to set invoice reminder active: '.$e->getMessage());
168
169            return response()->json([
170                'success' => false,
171                'message' => $e->getMessage(),
172            ], 500);
173        }
174    }
175
176    public function addInvoiceReminderException(Request $request)
177    {
178        $data = $request->all();
179
180        $exception = TblInvoicesExceptions::create($data);
181
182        return $exception;
183    }
184
185    public function getInvoice($invoiceId)
186    {
187        if (! $invoiceId) {
188            return response()->json([
189                'success' => false,
190                'message' => 'No invoice id provided',
191                'data' => null,
192            ], 400);
193        }
194
195        $data = TblInvoiceReminders::where('invoice_number', $invoiceId)->get();
196
197        if ($data->isEmpty()) {
198            return response()->json([
199                'success' => false,
200                'message' => 'No invoices found',
201                'data' => null,
202            ], 404);
203        }
204
205        return response()->json([
206            'success' => true,
207            'message' => 'Invoices found',
208            'data' => $data,
209        ]);
210    }
211
212    public function addInvoiceNextReminder(Request $request)
213    {
214        $data = $request->all();
215
216        if (! isset($data['region']) || $data['region'] === '') {
217            $data['region'] = urldecode($request->header('Region'));
218        }
219
220        /*$requiredFields = ['invoice_number', 'next_reminders'];
221        $missingFields = [];
222
223        foreach ($requiredFields as $field) {
224            if(!isset($data[$field]) || $data[$field] === null || $data[$field] === "") {
225                $missingFields[] = $field;
226            }
227        }
228
229        if(!empty($missingFields)) {
230            return response()->json([
231                'success' => false,
232                'message' => "Next fields are required: " . implode(', ', $missingFields),
233                'data' => null
234            ], 400);
235        }*/
236
237        try {
238            $dataNewInvoiceNextReminder = TblInvoicesNextReminders::create($data);
239
240            if (isset($data['payment_day'])) {
241                $idClient = (isset($data['id_client'])) ? $data['id_client'] : 0;
242                $invoiceNumber = (isset($data['invoice_number'])) ? $data['invoice_number'] : 0;
243                $this->facturasService->addToSheets($idClient, $invoiceNumber, $data['region']);
244            }
245
246            return response()->json([
247                'success' => true,
248                'message' => 'Invoice next reminder created successfully',
249                'data' => $dataNewInvoiceNextReminder,
250            ], 201);
251
252        } catch (\Exception $e) {
253            /** @disregard P1014 */
254            $e->exceptionCode = 'ADD_INVOICE_NEXT_REMINDER_EXCEPTION';
255            report($e);
256            Log::error('Error creating invoice next reminder: '.$e->getMessage());
257
258            return response()->json([
259                'success' => false,
260                'message' => 'Error al crear el recordatorio',
261                'data' => null,
262            ], 500);
263        }
264    }
265
266    public function uploadToCyC(Request $request)
267    {
268        try {
269            $region = urldecode($request->header('Region'));
270            if (! $region) {
271                throw new \Exception('No region provided');
272            }
273
274            $result = $this->facturasService->sendCyCInvoices($region);
275
276            if (! $result['success']) {
277                throw new \Exception($result['error']);
278            }
279
280            return response()->json([
281                'success' => true,
282            ], 200);
283
284        } catch (\Exception $e) {
285            /** @disregard P1014 */
286            $e->exceptionCode = 'UPLOAD_TO_CYC_EXCEPTION';
287            report($e);
288            Log::channel('third-party')->error('Fail in upload to CyC: '.$e->getMessage());
289
290            return response()->json([
291                'success' => false,
292                'message' => $e->getMessage(),
293            ], 500);
294        }
295    }
296
297    public function setAllMonthAdministratorsInvoices(Request $request)
298    {
299        try {
300            $region = urldecode($request->header('Region'));
301            if (! $region) {
302                throw new \Exception('No region provided');
303            }
304
305            $result = $this->facturasService->setAllMonthAdministratorsInvoices($region);
306
307            if (! $result['success']) {
308                throw new \Exception($result['error']);
309            }
310
311            return response()->json([
312                'success' => true,
313            ], 200);
314
315        } catch (\Exception $e) {
316            /** @disregard P1014 */
317            $e->exceptionCode = 'SET_ALL_MONTH_ADMINISTRATORS_INVOICES_EXCEPTION';
318            report($e);
319            Log::channel('third-party')->error('Fail in set all month administrators invoices: '.$e->getMessage());
320
321            return response()->json([
322                'success' => false,
323                'message' => $e->getMessage(),
324            ], 500);
325        }
326    }
327
328    public function sendAdministratorsInvoices(Request $request)
329    {
330        try {
331            $region = urldecode($request->header('Region'));
332            if (! $region) {
333                throw new \Exception('No region provided');
334            }
335
336            $result = $this->facturasService->sendAdministratorsInvoices($region);
337
338            if (! $result['success']) {
339                throw new \Exception($result['error']);
340            }
341
342            return response()->json([
343                'success' => true,
344            ], 200);
345
346        } catch (\Exception $e) {
347            /** @disregard P1014 */
348            $e->exceptionCode = 'SEND_ADMINISTRATORS_INVOICES_EXCEPTION';
349            report($e);
350            Log::channel('third-party')->error('Fail in send all month administrators invoices: '.$e->getMessage());
351
352            return response()->json([
353                'success' => false,
354                'message' => $e->getMessage(),
355            ], 500);
356        }
357    }
358
359    public function sendCallCenterInvoices(Request $request)
360    {
361        try {
362            $result = $this->facturasService->sendCallCenterInvoices();
363
364            if (! $result['success']) {
365                throw new \Exception($result['error']);
366            }
367
368            return response()->json([
369                'success' => true,
370            ], 200);
371
372        } catch (\Exception $e) {
373            /** @disregard P1014 */
374            $e->exceptionCode = 'SEND_CALL_CENTER_INVOICES_EXCEPTION';
375            report($e);
376            Log::channel('third-party')->error('Fail in send call center invoices: '.$e->getMessage());
377
378            return response()->json([
379                'success' => false,
380                'message' => $e->getMessage(),
381            ], 500);
382        }
383    }
384
385    public function handleGoogleAuthCallback(Request $request)
386    {
387        return $this->facturasService->handleGoogleAuthCallback($request);
388    }
389
390    public function listCreditDaysOffered(Request $request)
391    {
392        try {
393
394            $result = [];
395            $currentYear = null;
396            $currentMonth = null;
397            
398            $region = urldecode($request->header('Region'));
399
400            $where = "";
401            
402            if ($region && $region != "All") {
403                if($region == 'Cataluña'){
404                    $region = 'Catalunya';
405                }
406                $where = " AND region = '{$region}";
407            }
408
409            $query = "SELECT 
410                        YEAR(high_date) AS 'year',
411                        MONTH(high_date) AS 'month',
412                        WEEK(high_date, 1) AS 'week',
413
414                        CASE 
415                            WHEN WEEK(high_date, 1) IS NULL THEN '[]'
416                            ELSE COALESCE(
417                                CONCAT(
418                                    '[',
419                                    GROUP_CONCAT(
420                                        JSON_OBJECT(
421                                            'cif', cif,
422                                            'client_code', client_code,
423                                            'client_name', client_name,
424                                            'value', taxable_invoice_base,
425                                            'credit_days', credit_days,
426                                            'payment_days', payment_days,
427                                            'date', DATE(high_date),
428                                            'has_invoice', has_invoice
429                                        )
430                                    ),
431                                    ']'
432                                ),
433                                '[]'
434                            )
435                        END AS clients,
436
437                        AVG(credit_days) AS avg_credit_days,
438                        AVG(CAST(taxable_invoice_base AS DECIMAL(15,2))) AS avg_taxable_invoice_base
439
440                    FROM tbl_credit_days_offered
441
442                    WHERE high_date IS NOT NULL
443                    {$where}
444                    GROUP BY 
445                        YEAR(high_date),
446                        MONTH(high_date),
447                        WEEK(high_date, 1)
448                    WITH ROLLUP
449
450                    ORDER BY
451                        (YEAR(high_date) IS NULL) DESC,
452                        YEAR(high_date) DESC,
453
454                        (MONTH(high_date) IS NULL) DESC,
455                        MONTH(high_date) DESC,
456
457                        (WEEK(high_date, 1) IS NULL) DESC,
458                        WEEK(high_date, 1) DESC";
459            
460            $rows = DB::select($query);
461            
462            $result = [];
463
464            $monthNames = [
465                1 => 'Enero', 2 => 'Febrero', 3 => 'Marzo', 4 => 'Abril',
466                5 => 'Mayo', 6 => 'Junio', 7 => 'Julio', 8 => 'Agosto',
467                9 => 'Septiembre', 10 => 'Octubre', 11 => 'Noviembre', 12 => 'Diciembre',
468            ];
469
470            foreach ($rows as $row) {
471
472                $year = $row->year;
473                $month = $row->month;
474                $week = $row->week;
475                
476                if (is_null($year)) {
477                    continue;
478                }
479                
480                if (!isset($result[$year])) {
481                    $result[$year] = [
482                        'year' => (int) $year,
483                        'value' => null,
484                        'credit_days' => 0,
485                        'months' => []
486                    ];
487                }
488                
489                if (is_null($month) && is_null($week)) {
490                    $result[$year]['value'] = $row->avg_taxable_invoice_base;
491                    $result[$year]['credit_days'] = $row->avg_credit_days;
492                    continue;
493                }
494                
495                if (!is_null($month)) {
496
497                    $monthKey = $year . '-' . $month;
498
499                    if (!isset($result[$year]['months'][$monthKey])) {
500                        $result[$year]['months'][$monthKey] = [
501                            'month' => $monthNames[$month],
502                            'value' => null,
503                            'credit_days' => 0,
504                            'weeks' => []
505                        ];
506                    }
507
508                    if (is_null($week)) {
509                        $result[$year]['months'][$monthKey]['value'] = $row->avg_taxable_invoice_base;
510                        $result[$year]['months'][$monthKey]['credit_days'] = $row->avg_credit_days;
511                        continue;
512                    }
513                    
514                    $weekKey = $week;
515
516                    if (!isset($result[$year]['months'][$monthKey]['weeks'][$weekKey])) {
517                        $result[$year]['months'][$monthKey]['weeks'][$weekKey] = [
518                            'created_at' => 'Semana ' . $week,
519                            'value' => (float) $row->avg_taxable_invoice_base,
520                            'credit_days' => $row->avg_credit_days,
521                            'clients' => []
522                        ];
523                        
524                    }
525                    
526                    if (!empty($row->clients)) {
527                        $clients = json_decode($row->clients, true);
528                        
529                        if (json_last_error() === JSON_ERROR_NONE && is_array($clients)) {
530
531                            foreach ($clients as $client) {                                
532                                $result[$year]['months'][$monthKey]['weeks'][$weekKey]['clients'][] = [
533                                    'cif' => $client['cif'] ?? null,
534                                    'client_code' => $client['client_code'] ?? null,
535                                    'client_name' => $client['client_name'] ?? null,
536                                    'value' => $client['value'] ?? 0,
537                                    'credit_days' => (int) ($client['credit_days'] ?? 0),
538                                    'payment_days' => $client['payment_days'] ?? null,
539                                    'date' => $client['date'] ?? null,
540                                    'has_invoice' => (bool) ($client['has_invoice'] ?? false),
541                                ];
542                            }
543                        }
544                    }
545                }
546            }
547            
548            foreach ($result as &$yearData) {
549                $yearData['months'] = array_values($yearData['months']);
550
551                foreach ($yearData['months'] as &$monthData) {
552                    $monthData['weeks'] = array_values($monthData['weeks']);
553                }
554            }
555            
556            return response()->json([
557                'success' => true,
558                'data' => array_values($result),
559            ], 200);
560
561            // $region = urldecode($request->header('Region'));
562            // if (! $region) {
563            //     throw new \Exception('No region provided');
564            // }
565
566            // $result = $this->facturasService->listCreditDaysOffered($region);
567
568            // if (! $result['success']) {
569            //     throw new \Exception($result['error']);
570            // }
571
572            // return response()->json([
573            //     'success' => true,
574            //     'data' => $result['data'],
575            // ], 200);
576
577        } catch (\Exception $e) {
578            /** @disregard P1014 */
579            $e->exceptionCode = 'LIST_CREDIT_DAYS_OFFERED_EXCEPTION';
580            report($e);
581            Log::channel('third-party')->error('Fail in list credit days offered: '.$e->getMessage());
582
583            return response()->json([
584                'success' => false,
585                'message' => $e->getMessage(),
586            ], 500);
587        }
588    }
589}