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