Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 301
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 / 301
0.00% covered (danger)
0.00%
0 / 17
5256
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 / 17
0.00% covered (danger)
0.00%
0 / 1
20
 getInvoiceReminderActive
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
30
 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            // 'All' is the cross-region view — the same sentinel every other
118            // controller checks (Companies, AnalyticsRedesign, …) — so it means
119            // "no region filter", i.e. every company. Before this, the query ran
120            // WHERE region = 'All', which matches no row: the toggle answered
121            // success and changed nothing, then snapped back on reload.
122            $companies = $region === 'All'
123                ? TblCompanies::query()
124                : TblCompanies::where('region', $region);
125
126            $companies->update(['invoice_reminder_active' => $value === 'true']);
127
128            return response()->json([
129                'success' => true,
130            ]);
131
132        } catch (\Exception $e) {
133            report(AppException::fromException($e, 'SET_INVOICE_REMINDER_ACTIVE_EXCEPTION'));
134            Log::channel('g3w_invoices')->error('Failed to set invoice reminder active: '.$e->getMessage());
135
136            return response()->json([
137                'success' => false,
138                'message' => $e->getMessage(),
139            ], 500);
140        }
141    }
142
143    public function getInvoiceReminderActive()
144    {
145        try {
146            $region = urldecode((string) request()->header('Region'));
147
148            if (! $region) {
149                throw new \Exception('No region provided');
150            }
151
152            // Same scoping as the setter: 'All' covers every company, anything
153            // else is that one region.
154            //
155            // A missing row is not an error — 'All' matches no region, and a
156            // region can legitimately have no companies. Reading
157            // ->invoice_reminder_active off that null was the 500 this replaces
158            // ("Attempt to read property ... on null" whenever an admin opened
159            // the settings page in the cross-region view).
160            //
161            // The flag is stored per company but only ever written per region,
162            // so the companies in a region agree. The switch reads "on" only
163            // when every company in scope has it on: in the 'All' view a
164            // half-on state must not display as on, or turning it off would
165            // silently misreport the regions still sending.
166            $scope = fn () => $region === 'All'
167                ? TblCompanies::query()
168                : TblCompanies::where('region', $region);
169
170            $total = $scope()->count();
171            $active = $scope()->where('invoice_reminder_active', 1)->count();
172
173            return response()->json([
174                'success' => true,
175                'invoice_reminder_active' => $total > 0 && $active === $total,
176            ]);
177
178        } catch (\Exception $e) {
179            report(AppException::fromException($e, 'GET_INVOICE_REMINDER_ACTIVE_EXCEPTION'));
180            Log::channel('g3w_invoices')->error('Failed to set invoice reminder active: '.$e->getMessage());
181
182            return response()->json([
183                'success' => false,
184                'message' => $e->getMessage(),
185            ], 500);
186        }
187    }
188
189    public function addInvoiceReminderException(Request $request)
190    {
191        $data = $request->all();
192
193        return TblInvoicesExceptions::create($data);
194    }
195
196    public function getInvoice($invoiceId)
197    {
198        if (! $invoiceId) {
199            return response()->json([
200                'success' => false,
201                'message' => 'No invoice id provided',
202                'data' => null,
203            ], 400);
204        }
205
206        $data = TblInvoiceReminders::where('invoice_number', $invoiceId)->get();
207
208        if ($data->isEmpty()) {
209            return response()->json([
210                'success' => false,
211                'message' => 'No invoices found',
212                'data' => null,
213            ], 404);
214        }
215
216        return response()->json([
217            'success' => true,
218            'message' => 'Invoices found',
219            'data' => $data,
220        ]);
221    }
222
223    public function addInvoiceNextReminder(Request $request)
224    {
225        $data = $request->all();
226
227        if (! isset($data['region']) || $data['region'] === '') {
228            $data['region'] = urldecode($request->header('Region'));
229        }
230
231        /*$requiredFields = ['invoice_number', 'next_reminders'];
232        $missingFields = [];
233
234        foreach ($requiredFields as $field) {
235            if(!isset($data[$field]) || $data[$field] === null || $data[$field] === "") {
236                $missingFields[] = $field;
237            }
238        }
239
240        if(!empty($missingFields)) {
241            return response()->json([
242                'success' => false,
243                'message' => "Next fields are required: " . implode(', ', $missingFields),
244                'data' => null
245            ], 400);
246        }*/
247
248        try {
249            $dataNewInvoiceNextReminder = TblInvoicesNextReminders::create($data);
250
251            if (isset($data['payment_day'])) {
252                $idClient = $data['id_client'] ?? 0;
253                $invoiceNumber = $data['invoice_number'] ?? 0;
254                $this->facturasService->addToSheets($idClient, $invoiceNumber, $data['region']);
255            }
256
257            return response()->json([
258                'success' => true,
259                'message' => 'Invoice next reminder created successfully',
260                'data' => $dataNewInvoiceNextReminder,
261            ], 201);
262
263        } catch (\Exception $e) {
264            report(AppException::fromException($e, 'ADD_INVOICE_NEXT_REMINDER_EXCEPTION'));
265            Log::error('Error creating invoice next reminder: '.$e->getMessage());
266
267            return response()->json([
268                'success' => false,
269                'message' => 'Error al crear el recordatorio',
270                'data' => null,
271            ], 500);
272        }
273    }
274
275    public function uploadToCyC(Request $request)
276    {
277        try {
278            $region = urldecode($request->header('Region'));
279            if (! $region) {
280                throw new \Exception('No region provided');
281            }
282
283            $result = $this->facturasService->sendCyCInvoices($region);
284
285            if (! $result['success']) {
286                throw new \Exception($result['error']);
287            }
288
289            return response()->json([
290                'success' => true,
291            ], 200);
292
293        } catch (\Exception $e) {
294            report(AppException::fromException($e, 'UPLOAD_TO_CYC_EXCEPTION'));
295            Log::channel('third-party')->error('Fail in upload to CyC: '.$e->getMessage());
296
297            return response()->json([
298                'success' => false,
299                'message' => $e->getMessage(),
300            ], 500);
301        }
302    }
303
304    public function setAllMonthAdministratorsInvoices(Request $request)
305    {
306        try {
307            $region = urldecode($request->header('Region'));
308            if (! $region) {
309                throw new \Exception('No region provided');
310            }
311
312            $result = $this->facturasService->setAllMonthAdministratorsInvoices($region);
313
314            if (! $result['success']) {
315                throw new \Exception($result['error']);
316            }
317
318            return response()->json([
319                'success' => true,
320            ], 200);
321
322        } catch (\Exception $e) {
323            report(AppException::fromException($e, 'SET_ALL_MONTH_ADMINISTRATORS_INVOICES_EXCEPTION'));
324            Log::channel('third-party')->error('Fail in set all month administrators invoices: '.$e->getMessage());
325
326            return response()->json([
327                'success' => false,
328                'message' => $e->getMessage(),
329            ], 500);
330        }
331    }
332
333    public function sendAdministratorsInvoices(Request $request)
334    {
335        try {
336            $region = urldecode($request->header('Region'));
337            if (! $region) {
338                throw new \Exception('No region provided');
339            }
340
341            $result = $this->facturasService->sendAdministratorsInvoices($region);
342
343            if (! $result['success']) {
344                throw new \Exception($result['error']);
345            }
346
347            return response()->json([
348                'success' => true,
349            ], 200);
350
351        } catch (\Exception $e) {
352            report(AppException::fromException($e, 'SEND_ADMINISTRATORS_INVOICES_EXCEPTION'));
353            Log::channel('third-party')->error('Fail in send all month administrators invoices: '.$e->getMessage());
354
355            return response()->json([
356                'success' => false,
357                'message' => $e->getMessage(),
358            ], 500);
359        }
360    }
361
362    public function sendCallCenterInvoices(Request $request)
363    {
364        try {
365            $result = $this->facturasService->sendCallCenterInvoices();
366
367            if (! $result['success']) {
368                throw new \Exception($result['error']);
369            }
370
371            return response()->json([
372                'success' => true,
373            ], 200);
374
375        } catch (\Exception $e) {
376            report(AppException::fromException($e, 'SEND_CALL_CENTER_INVOICES_EXCEPTION'));
377            Log::channel('third-party')->error('Fail in send call center invoices: '.$e->getMessage());
378
379            return response()->json([
380                'success' => false,
381                'message' => $e->getMessage(),
382            ], 500);
383        }
384    }
385
386    public function handleGoogleAuthCallback(Request $request)
387    {
388        return $this->facturasService->handleGoogleAuthCallback($request);
389    }
390
391    public function downloadAllInvoices(Request $request)
392    {
393        try {
394            $region = urldecode($request->header('Region'));
395
396            if ($region === 'Catalunya') {
397                $region = 'Cataluña';
398            }
399
400            if ($region === 'All') {
401                $invoices = TblInvoiceReminders::orderBy('id', 'desc')->get();
402            } else {
403                $invoices = TblInvoiceReminders::where('region', $region)
404                    ->orderBy('id', 'desc')
405                    ->get();
406            }
407
408            return response(['data' => $invoices]);
409
410        } catch (\Exception $e) {
411            report(AppException::fromException($e, 'DOWNLOAD_ALL_INVOICES_EXCEPTION'));
412            Log::channel('g3w_invoices')->error('Failed to download all invoices: '.$e->getMessage());
413
414            return response()->json([
415                'success' => false,
416                'message' => $e->getMessage(),
417            ], 500);
418        }
419    }
420
421    public function downloadAllInvoicesExceptions(Request $request)
422    {
423        try {
424            $invoices = TblInvoicesExceptions::orderBy('id', 'desc')->get();
425
426            return response(['data' => $invoices]);
427
428        } catch (\Exception $e) {
429            report(AppException::fromException($e, 'DOWNLOAD_ALL_INVOICES_EXCEPTIONS_EXCEPTION'));
430            Log::channel('g3w_invoices')->error('Failed to download all invoices exceptions: '.$e->getMessage());
431
432            return response()->json([
433                'success' => false,
434                'message' => $e->getMessage(),
435            ], 500);
436        }
437    }
438
439    public function listCreditDaysOffered(Request $request)
440    {
441        try {
442
443            $result = [];
444            $currentYear = null;
445            $currentMonth = null;
446
447            $region = urldecode($request->header('Region'));
448
449            $where = '';
450
451            if ($region && $region != 'All') {
452                if ($region == 'Cataluña') {
453                    $region = 'Catalunya';
454                }
455                $where = " AND region = '{$region}' ";
456            }
457
458            DB::statement('SET SESSION group_concat_max_len = 1000000');
459
460            $query = "SELECT
461                        YEAR(high_date) AS 'year',
462                        MONTH(high_date) AS 'month',
463                        WEEK(high_date, 1) AS 'week',
464
465                        CASE 
466                            WHEN WEEK(high_date, 1) IS NULL THEN '[]'
467                            ELSE COALESCE(
468                                CONCAT(
469                                    '[',
470                                    GROUP_CONCAT(
471                                        JSON_OBJECT(
472                                            'cif', cif,
473                                            'client_code', client_code,
474                                            'client_name', client_name,
475                                            'value', taxable_invoice_base,
476                                            'credit_days', credit_days,
477                                            'payment_days', payment_days,
478                                            'date', DATE(high_date),
479                                            'has_invoice', has_invoice
480                                        )
481                                    ),
482                                    ']'
483                                ),
484                                '[]'
485                            )
486                        END AS clients,
487
488                        AVG(credit_days) AS avg_credit_days,
489                        AVG(CAST(taxable_invoice_base AS DECIMAL(15,2))) AS avg_taxable_invoice_base
490
491                    FROM tbl_credit_days_offered
492
493                    WHERE high_date IS NOT NULL
494                    {$where}
495                    GROUP BY 
496                        YEAR(high_date),
497                        MONTH(high_date),
498                        WEEK(high_date, 1)
499                    WITH ROLLUP
500
501                    ORDER BY
502                        (YEAR(high_date) IS NULL) DESC,
503                        YEAR(high_date) DESC,
504
505                        (MONTH(high_date) IS NULL) DESC,
506                        MONTH(high_date) DESC,
507
508                        (WEEK(high_date, 1) IS NULL) DESC,
509                        WEEK(high_date, 1) DESC";
510
511            $rows = DB::select($query);
512
513            $result = [];
514
515            $monthNames = [
516                1 => 'Enero', 2 => 'Febrero', 3 => 'Marzo', 4 => 'Abril',
517                5 => 'Mayo', 6 => 'Junio', 7 => 'Julio', 8 => 'Agosto',
518                9 => 'Septiembre', 10 => 'Octubre', 11 => 'Noviembre', 12 => 'Diciembre',
519            ];
520
521            foreach ($rows as $row) {
522
523                $year = $row->year;
524                $month = $row->month;
525                $week = $row->week;
526
527                if (is_null($year)) {
528                    continue;
529                }
530
531                if (! isset($result[$year])) {
532                    $result[$year] = [
533                        'year' => (int) $year,
534                        'value' => null,
535                        'credit_days' => 0,
536                        'months' => [],
537                    ];
538                }
539
540                if (is_null($month) && is_null($week)) {
541                    $result[$year]['value'] = $row->avg_taxable_invoice_base;
542                    $result[$year]['credit_days'] = $row->avg_credit_days;
543
544                    continue;
545                }
546
547                if (! is_null($month)) {
548
549                    $monthKey = $year.'-'.$month;
550
551                    if (! isset($result[$year]['months'][$monthKey])) {
552                        $result[$year]['months'][$monthKey] = [
553                            'month' => $monthNames[$month],
554                            'value' => null,
555                            'credit_days' => 0,
556                            'weeks' => [],
557                        ];
558                    }
559
560                    if (is_null($week)) {
561                        $result[$year]['months'][$monthKey]['value'] = $row->avg_taxable_invoice_base;
562                        $result[$year]['months'][$monthKey]['credit_days'] = $row->avg_credit_days;
563
564                        continue;
565                    }
566
567                    $weekKey = $week;
568
569                    if (! isset($result[$year]['months'][$monthKey]['weeks'][$weekKey])) {
570                        $result[$year]['months'][$monthKey]['weeks'][$weekKey] = [
571                            'created_at' => 'Semana '.$week,
572                            'value' => (float) $row->avg_taxable_invoice_base,
573                            'credit_days' => $row->avg_credit_days,
574                            'clients' => [],
575                        ];
576
577                    }
578
579                    if (! empty($row->clients)) {
580                        $clients = json_decode($row->clients, true);
581
582                        if (json_last_error() === JSON_ERROR_NONE && is_array($clients)) {
583
584                            foreach ($clients as $client) {
585                                $result[$year]['months'][$monthKey]['weeks'][$weekKey]['clients'][] = [
586                                    'cif' => $client['cif'] ?? null,
587                                    'client_code' => $client['client_code'] ?? null,
588                                    'client_name' => $client['client_name'] ?? null,
589                                    'value' => $client['value'] ?? 0,
590                                    'credit_days' => (int) ($client['credit_days'] ?? 0),
591                                    'payment_days' => $client['payment_days'] ?? null,
592                                    'date' => $client['date'] ?? null,
593                                    'has_invoice' => (bool) ($client['has_invoice'] ?? false),
594                                ];
595                            }
596                        }
597                    }
598                }
599            }
600
601            foreach ($result as &$yearData) {
602                $yearData['months'] = array_values($yearData['months']);
603
604                foreach ($yearData['months'] as &$monthData) {
605                    $monthData['weeks'] = array_values($monthData['weeks']);
606                }
607            }
608
609            return response()->json([
610                'success' => true,
611                'data' => array_values($result),
612            ], 200);
613
614            // $region = urldecode($request->header('Region'));
615            // if (! $region) {
616            //     throw new \Exception('No region provided');
617            // }
618
619            // $result = $this->facturasService->listCreditDaysOffered($region);
620
621            // if (! $result['success']) {
622            //     throw new \Exception($result['error']);
623            // }
624
625            // return response()->json([
626            //     'success' => true,
627            //     'data' => $result['data'],
628            // ], 200);
629
630        } catch (\Exception $e) {
631            report(AppException::fromException($e, 'LIST_CREDIT_DAYS_OFFERED_EXCEPTION'));
632            Log::channel('third-party')->error('Fail in list credit days offered: '.$e->getMessage());
633
634            return response()->json([
635                'success' => false,
636                'message' => $e->getMessage(),
637            ], 500);
638        }
639    }
640}