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