Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
22.91% covered (danger)
22.91%
96 / 419
13.33% covered (danger)
13.33%
2 / 15
CRAP
0.00% covered (danger)
0.00%
0 / 1
GestionaController
22.91% covered (danger)
22.91%
96 / 419
13.33% covered (danger)
13.33%
2 / 15
2582.59
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
47 / 47
100.00% covered (success)
100.00%
1 / 1
1
 regionFromHeader
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
2
 updateApiCredentials
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 getApiDetails
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 getLastUpdate
0.00% covered (danger)
0.00%
0 / 14
0.00% covered (danger)
0.00%
0 / 1
12
 getAcceptanceWarnings
0.00% covered (danger)
0.00%
0 / 23
0.00% covered (danger)
0.00%
0 / 1
30
 getSyncStatus
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 getG3wActive
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
6
 updateG3wActive
0.00% covered (danger)
0.00%
0 / 11
0.00% covered (danger)
0.00%
0 / 1
12
 getMappings
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
42
 setMappings
33.33% covered (danger)
33.33%
33 / 99
0.00% covered (danger)
0.00%
0 / 1
138.52
 deleteMappings
56.00% covered (warning)
56.00%
14 / 25
0.00% covered (danger)
0.00%
0 / 1
15.90
 getAllBudgetMonitor
0.00% covered (danger)
0.00%
0 / 98
0.00% covered (danger)
0.00%
0 / 1
90
 syncAllBudgetMonitor
0.00% covered (danger)
0.00%
0 / 45
0.00% covered (danger)
0.00%
0 / 1
30
 getDuplicatedValues
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Exceptions\AppException;
6use App\Models\TblCompanies;
7use App\Models\TblG3WOrdersUpdateLogs;
8use App\Models\TblQuotations;
9use App\Models\TblSegmentG3wMapping;
10use App\Models\TblSourceG3wMapping;
11use App\Models\TblSources;
12use App\Models\TblStatusG3wMapping;
13use App\Models\TblTypeG3wMapping;
14use App\Models\TblUserG3wMapping;
15use App\Models\TblUsers;
16use App\Services\GestionaService;
17use App\Services\PresupuestosService;
18use Illuminate\Database\QueryException;
19use Illuminate\Http\JsonResponse;
20use Illuminate\Http\Request;
21use Illuminate\Support\Carbon;
22use Illuminate\Support\Facades\DB;
23use Illuminate\Support\Facades\Log;
24use Illuminate\Support\Facades\Schema;
25
26class GestionaController extends Controller
27{
28    protected $tables;
29
30    public function __construct(protected GestionaService $gestionaService, protected PresupuestosService $presupuestoService)
31    {
32        $this->tables = [
33            'status' => [
34                'model' => TblStatusG3wMapping::class,
35                'index' => 'budget_status_id',
36                'relation' => 'budgetStatus',
37                'tblQuotationsG3wNameColumn' => 'status_by_g3w',
38                'tblMappingNameColumn' => 'name_g3w',
39                'tblQuotationsNameColumn' => 'budget_status_id',
40                'requestNameKey' => 'budget_status_id',
41            ],
42            'segment' => [
43                'model' => TblSegmentG3wMapping::class,
44                'index' => 'segment_id',
45                'relation' => 'segment',
46                'tblQuotationsG3wNameColumn' => 'segment_by_g3w',
47                'tblMappingNameColumn' => 'name_g3w',
48                'tblQuotationsNameColumn' => 'segment_id',
49                'requestNameKey' => 'segment_id',
50            ],
51            'type' => [
52                'model' => TblTypeG3wMapping::class,
53                'index' => 'budget_type_name',
54                'relation' => 'budgetType',
55                'tblQuotationsG3wNameColumn' => 'type_by_g3w',
56                'tblMappingNameColumn' => 'id_g3w',
57                'tblQuotationsNameColumn' => 'budget_type_id',
58                'requestNameKey' => 'id_g3w',
59            ],
60            'source' => [
61                'model' => TblSourceG3wMapping::class,
62                'index' => 'source_name',
63                'relation' => 'source',
64                'tblQuotationsG3wNameColumn' => 'source_by_g3w',
65                'tblMappingNameColumn' => 'id_g3w',
66                'tblQuotationsNameColumn' => 'source_id',
67                'requestNameKey' => 'id_g3w',
68            ],
69            'user' => [
70                'model' => TblUserG3wMapping::class,
71                'index' => 'id_fst',
72                'relation' => 'user',
73                'tblQuotationsG3wNameColumn' => 'G3W_code',
74                'tblMappingNameColumn' => 'id_fst',
75                'tblQuotationsNameColumn' => 'G3W_code',
76                'requestNameKey' => 'id_fst',
77            ],
78        ];
79    }
80
81    /**
82     * The caller's region, in the form the platform stores it.
83     *
84     * Every client service sets the header with `encodeURIComponent()`, so a
85     * region carrying an accent — Castellón, Aragón, Andalucía — arrives as
86     * `Castell%C3%B3n` and matches no row in `tbl_companies`,
87     * `tbl_g3w_last_update` or any of the region-scoped mapping tables.
88     * Cataluña is the one accented region that never showed the symptom: the
89     * client rewrites it to the ASCII "Catalunya" first, which is why the
90     * long-standing `=== 'Catalunya'` checks looked sufficient.
91     */
92    private function regionFromHeader(?Request $request = null): string
93    {
94        $region = urldecode((string) (($request ?? request())->header('Region') ?? ''));
95
96        return $region === 'Catalunya' ? 'Cataluña' : $region;
97    }
98
99    /**
100     * Sincroniza un presupuesto por su ID.
101     *
102     * @param  $id
103     * @return JsonResponse
104     */
105    public function updateApiCredentials(Request $request)
106    {
107        try {
108            $region = $this->regionFromHeader();
109
110            $params = $request->only(['url', 'user', 'password', 'user_id']);
111            $this->gestionaService->updateApiCredentials($params, $region);
112
113            return response()->json(['message' => 'Credentials updated successfully'], 200);
114        } catch (\Exception $e) {
115            report(AppException::fromException($e, 'UPDATE_API_CREDENTIALS_EXCEPTION'));
116
117            return response()->json(['error' => $e->getMessage()], 400);
118        }
119    }
120
121    /**
122     * @return JsonResponse
123     *
124     * @throws \Exception
125     */
126    public function getApiDetails()
127    {
128        try {
129            $region = $this->regionFromHeader();
130
131            $apiDetailsResponse = $this->gestionaService->getApiDetails($region);
132
133            if (! $apiDetailsResponse) {
134                throw new \Exception('Api details not found');
135            }
136
137            $apiDetails = json_decode((string) $apiDetailsResponse->getContent(), true);
138
139            return response()->json([
140                'url' => $apiDetails['url'] ?? null,
141                'user' => $apiDetails['user'] ?? null,
142            ], 200);
143
144        } catch (QueryException $e) {
145            report(AppException::fromException($e, 'GET_API_DETAILS_EXCEPTION'));
146
147            return response()->json(['error' => $e->getMessage()], 400);
148        }
149    }
150
151    public function getLastUpdate()
152    {
153        try {
154            $region = $this->regionFromHeader();
155
156            $apiLastUpdateResponse = $this->gestionaService->getLastUpdate($region);
157
158            if (! $apiLastUpdateResponse) {
159                throw new \Exception('Last update not found');
160            }
161
162            $apiLastUpdate = json_decode((string) $apiLastUpdateResponse->getContent(), true);
163
164            return response()->json([
165                'lastUpdate' => $apiLastUpdate['lastUpdate'] ?? null,
166                'lastUpdateIso' => $apiLastUpdate['lastUpdateIso'] ?? null,
167                'updatingNow' => $apiLastUpdate['updatingNow'] ?? null,
168            ], 200);
169
170        } catch (QueryException $e) {
171            report(AppException::fromException($e, 'GET_LAST_UPDATE_EXCEPTION'));
172            Log::error('Error en getLastUpdate: '.$e->getMessage());
173
174            return response()->json(['error' => $e->getMessage()], 400);
175        }
176    }
177
178    public function getAcceptanceWarnings(Request $request)
179    {
180        try {
181            $region = $this->regionFromHeader();
182
183            if ($region === '') {
184                return response()->json(['error' => 'Region header is missing'], 400);
185            }
186
187            $commercial = $request->input('commercial');
188
189            $company = TblCompanies::where('region', $region)->first();
190            if (! $company) {
191                return response()->json([
192                    'countWarnings' => 0,
193                ], 200);
194            }
195
196            $companyId = $company->company_id;
197
198            /*$countWarnings = TblQuotations::where('sync_import', 1)
199                ->where('company_id', $companyId)
200                ->when(!empty($commercial) && $commercial !== "All", function ($query) use ($commercial) {
201                    return $query->where('commercial', $commercial);
202                })
203                ->where(function ($query) {
204                    $query->WhereIn('budget_status_id', [13, 14])
205                        ->orWhere(function ($subQuery) {
206                            $subQuery->whereNull('commercial')
207                                ->orWhereNotExists(function ($subQuery) {
208                                    $subQuery->select(DB::raw(1))
209                                        ->from('tbl_users')
210                                        ->whereColumn('tbl_users.name', 'tbl_quotations.commercial');
211                                });
212                        })
213                        ->orWhereNull('phone_number')
214                        ->orWhereNull('source_id')
215                        ->orWhereNull('budget_type_id')
216                        ->orWhere(function ($subQuery) {
217                            $subQuery->whereNull('client')
218                                ->orWhere(DB::raw('TRIM(client)'), '');
219                        })
220                        ->orWhere(function ($subQuery) {
221                            $subQuery->whereNull('email')
222                                ->orWhere(DB::raw('TRIM(email)'), '');
223                        });
224                })
225                ->count();*/
226
227            // FIRE-1560: presupuestos rechazados/anulados (y sus variantes)
228            // no deben contar en el badge de "Fallos en G3W" que la
229            // orders.component lee vía totalG3wWarnings. Mismo NOT IN que
230            // en Quotations::list_orders_table (is_g3w_warning) y en el
231            // contador del tile ({$tile counter}). Statuses:
232            //   4  Rechazado, 5 Anulado, 7 Rechazado - automaticamente,
233            //   12 En proceso, 15 Solicitud tramitada, 17/18 (reservado),
234            //   20 Rechazado-duplicado, 21 Fallo envio correo erroneo,
235            //   22 Correo erroneo.
236            $countWarnings = TblQuotations::where('sync_import', 1)
237                ->where('company_id', $companyId)
238                ->where('g3w_warning', 1)
239                ->whereNotIn('budget_status_id', [4, 5, 7, 12, 15, 17, 18, 20, 21, 22])
240                ->when(! empty($commercial) && $commercial !== 'All', fn ($query) => $query->where('commercial', $commercial))
241                ->count();
242
243            return response()->json([
244                'countWarnings' => $countWarnings,
245            ], 200);
246
247        } catch (QueryException $e) {
248            report(AppException::fromException($e, 'ADD_WORK_STATUS_EXCEPTION'));
249            Log::error('Error en getAcceptanceWarnings: '.$e->getMessage());
250
251            return response()->json(['error' => $e->getMessage()], 400);
252        }
253    }
254
255    public function getSyncStatus()
256    {
257        try {
258            $region = $this->regionFromHeader();
259
260            return response()->json([
261                'status' => $this->gestionaService->getSyncStatus($region),
262            ], 200);
263
264        } catch (QueryException $e) {
265            report(AppException::fromException($e, 'GET_SYNC_STATUS_EXCEPTION'));
266
267            return response()->json(['error' => $e->getMessage()], 400);
268        }
269    }
270
271    public function getG3wActive()
272    {
273        try {
274            $region = $this->regionFromHeader();
275
276            return response()->json([
277                'active' => $this->gestionaService->getG3wActive($region),
278            ], 200);
279
280        } catch (QueryException $e) {
281            report(AppException::fromException($e, 'GET_G3W_ACTIVE_EXCEPTION'));
282            Log::error('Error en getG3wActive: '.$e->getMessage());
283
284            return response()->json(['error' => $e->getMessage()], 400);
285        }
286    }
287
288    public function updateG3wActive(Request $request)
289    {
290        try {
291            $region = urldecode($request->header('Region'));
292
293            if ($region === 'Catalunya') {
294                $region = 'Cataluña';
295            }
296
297            $active = $request->input('active');
298
299            $this->gestionaService->updateG3wActive($active, $region);
300
301            return response()->json([
302                'success' => 1,
303            ], 200);
304
305        } catch (QueryException $e) {
306            report(AppException::fromException($e, 'UPDATE_G3W_ACTIVE_EXCEPTION'));
307
308            return response()->json(['error' => $e->getMessage()], 400);
309        }
310    }
311
312    public function getMappings(Request $request)
313    {
314        try {
315
316            if (! $request->has('type') || ! array_key_exists($request->type, $this->tables)) {
317                throw new \Exception('Type parameter is missing or invalid');
318            }
319
320            $tableConfig = $this->tables[$request->type];
321
322            if (isset($tableConfig['model'])) {
323                $mappings = $tableConfig['model']::with([$tableConfig['relation'] => function ($query) use ($tableConfig): void {
324                    $relatedModel = (new $tableConfig['model'])->{$tableConfig['relation']}()->getRelated();
325                    $relatedTable = $relatedModel->getTable();
326
327                    if (Schema::hasColumn($relatedTable, 'priority')) {
328                        $query->orderBy('priority', 'desc');
329                    }
330                }])->get();
331            } else {
332                $mappings = DB::table($tableConfig['table'])->get();
333            }
334
335            return response()->json($mappings);
336
337        } catch (\Exception $e) {
338            report(AppException::fromException($e, 'GET_MAPPINGS_EXCEPTION'));
339
340            return response()->json(['error' => $e->getMessage()], 400);
341        }
342    }
343
344    public function setMappings(Request $request)
345    {
346        try {
347            if (! $request->has('type')) {
348                return response()->json(['message' => 'Not type especified']);
349            }
350
351            $tableConfig = $this->tables[$request->type];
352
353            if (! isset($tableConfig['tblQuotationsG3wNameColumn'], $tableConfig['tblMappingNameColumn'], $tableConfig['tblQuotationsNameColumn'], $tableConfig['requestNameKey'])) {
354                return response()->json(['message' => 'Missing configuration keys'], 500);
355            }
356
357            // User mappings are region-scoped (each region is an independent
358            // G3W instance). The Region header arrives as "Catalunya" (and
359            // percent-encoded for accented regions); the rest of the platform
360            // stores "Cataluña", so normalise before matching.
361            $region = $this->regionFromHeader();
362
363            $data = $request->except('type');
364
365            // Stamp the region on new user rows so the code resolves within the
366            // right region only. Other mapping types get their region from the
367            // sync (normalizeType / normalizeSource), so leave them untouched.
368            if ($request->type === 'user') {
369                $data['region'] = $region;
370            }
371
372            if (! $request->has('id')) {
373                $tableConfig['model']::create($data);
374
375                return response()->json(['message' => $request->type.' created successfully']);
376            }
377
378            if ($tableConfig['relation'] === 'user') {
379                // Only rewrite quotations belonging to this region's companies,
380                // so editing e.g. Madrid's "001 -> Alice" never clobbers a
381                // different person mapped to "001" in another region.
382                $regionCompanyIds = TblCompanies::where('region', $region)->pluck('company_id');
383
384                // One specific G3W code (its own row id). A user can hold several
385                // codes ("Agustín Salvatierra => 002, asc, asp"); keyed by the FST
386                // user (`id`) the edit hit whichever of them came ->first(), and
387                // there was no way to change just one.
388                if ($request->filled('mapping_id')) {
389                    $rowMapping = $tableConfig['model']::where('id', (int) $request['mapping_id'])
390                        ->where('region', $region)
391                        ->first();
392
393                    if (! $rowMapping) {
394                        return response()->json(['error' => 'User mapping not found'], 404);
395                    }
396
397                    $rowMapping->update(array_filter(
398                        $request->only(['name_g3w', 'id_fst']),
399                        fn ($value) => $value !== null && $value !== ''
400                    ));
401
402                    // Re-point this region's quotations to the code's (new) user.
403                    $user = $rowMapping->id_fst ? TblUsers::where('id', $rowMapping->id_fst)->first() : null;
404                    if ($user) {
405                        TblQuotations::whereIn('company_id', $regionCompanyIds)
406                            ->where('user_create_by_g3w', $rowMapping->name_g3w)
407                            ->update(['created_by' => $user->name]);
408
409                        TblQuotations::whereIn('company_id', $regionCompanyIds)
410                            ->where('user_commercial_by_g3w', $rowMapping->name_g3w)
411                            ->update(['commercial' => $user->name]);
412
413                        TblQuotations::whereIn('company_id', $regionCompanyIds)
414                            ->where('user_create_by_g3w', $rowMapping->name_g3w)
415                            ->whereNull('commercial')
416                            ->whereNull('user_commercial_by_g3w')
417                            ->update(['commercial' => $user->name]);
418                    }
419
420                    return response()->json(['message' => $request->type.' edited successfully']);
421                }
422
423                if (is_numeric($request['id'])) {
424                    $rowMapping = $tableConfig['model']::where('id_fst', $request['id'])
425                        ->where('region', $region)
426                        ->first();
427                    $data = $request->except('id');
428                    $data['region'] = $region;
429
430                    if (! $rowMapping) {
431                        $tableConfig['model']::create($data);
432
433                        return response()->json(['error' => 'User mapping not found'], 404);
434                    }
435
436                    $userName = TblUsers::where('id', $rowMapping->id_fst)->first()->name;
437                    $nameG3w = $rowMapping->name_g3w;
438
439                    TblQuotations::whereIn('company_id', $regionCompanyIds)
440                        ->where('user_create_by_g3w', $nameG3w)
441                        ->update(['created_by' => $userName]);
442
443                    TblQuotations::whereIn('company_id', $regionCompanyIds)
444                        ->where('user_commercial_by_g3w', $nameG3w)
445                        ->update(['commercial' => $userName]);
446
447                    TblQuotations::whereIn('company_id', $regionCompanyIds)
448                        ->where('user_create_by_g3w', $nameG3w)
449                        ->whereNull('commercial')
450                        ->whereNull('user_commercial_by_g3w')
451                        ->update(['commercial' => $nameG3w]);
452
453                    $rowMapping->update($data);
454
455                } else {
456                    $rowMapping = $tableConfig['model']::where('name_g3w', $request['id'])
457                        ->where('region', $region)
458                        ->first();
459
460                    if (! $rowMapping) {
461                        return response()->json(['error' => 'User mapping not found'], 404);
462                    }
463
464                    $rowMapping->update(['id_fst' => $request['id_fst']]);
465
466                    $userName = TblUsers::where('id', $request['id_fst'])->first();
467
468                    if (! $userName) {
469                        return response()->json(['error' => 'User mapping not found'], 404);
470                    }
471
472                    TblQuotations::whereIn('company_id', $regionCompanyIds)
473                        ->where('user_create_by_g3w', $request['id'])
474                        ->update(['created_by' => $userName->name]);
475
476                    TblQuotations::whereIn('company_id', $regionCompanyIds)
477                        ->where('user_commercial_by_g3w', $request['id'])
478                        ->update(['commercial' => $userName->name]);
479
480                    TblQuotations::whereIn('company_id', $regionCompanyIds)
481                        ->where('user_create_by_g3w', $request['id'])
482                        ->whereNull('commercial')
483                        ->whereNull('user_commercial_by_g3w')
484                        ->update(['commercial' => $userName->name]);
485
486                }
487
488                return response()->json(['message' => $request->type.' edited successfully']);
489            }
490
491            $rowMapping = $tableConfig['model']::where('id', $request['id'])->first();
492
493            if ($tableConfig['relation'] === 'source') {
494                $data = [];
495                $sourceRow = TblSources::where('source_id', $request['id_fst'])->first();
496                if (! $sourceRow) {
497                    return response()->json(['error' => 'Source mapping not found'], 404);
498                }
499
500                $data['source_name'] = $sourceRow->name;
501            }
502
503            $rowMapping->update($data);
504
505            $g3wKey = $rowMapping[$tableConfig['tblMappingNameColumn']] ?? null;
506
507            // A null/empty G3W key would collapse Eloquent's `where(col, null)`
508            // to `WHERE col IS NULL` and null tbl_quotations.budget_type_id
509            // (or source_id) on every row whose corresponding *_by_g3w column
510            // is unset — i.e. every manually-created quotation. Skip the
511            // propagation when the mapping has no key to match against.
512            if ($g3wKey === null || $g3wKey === '') {
513                return response()->json(['message' => $request->type.' edited successfully']);
514            }
515
516            TblQuotations::where($tableConfig['tblQuotationsG3wNameColumn'], $g3wKey)
517                ->update([$tableConfig['tblQuotationsNameColumn'] => $rowMapping[$tableConfig['requestNameKey']]]);
518
519            return response()->json(['message' => $request->type.' edited successfully']);
520
521        } catch (QueryException $e) {
522            report(AppException::fromException($e, 'SET_MAPPING_EXCEPTION'));
523
524            return response()->json(['error' => $e->getMessage()], 400);
525        }
526    }
527
528    public function deleteMappings(Request $request)
529    {
530        try {
531            if (! $request->has('id')) {
532                return response()->json(['message' => 'Can`t be deleted without ID']);
533            }
534
535            if (! $request->has('type')) {
536                return response()->json(['message' => 'Not type especified']);
537            }
538
539            $tableConfig = $this->tables[$request->type];
540
541            if ($tableConfig['relation'] === 'user') {
542                // Region-scoped: only remove this region's mapping row so the
543                // same FST user stays mapped in the other regions.
544                $region = $this->regionFromHeader();
545
546                // One specific G3W code: remove just that row, keep the user's
547                // other codes (e.g. drop "asc" but keep "002" and "asp").
548                if ($request->filled('mapping_id')) {
549                    $deleted = $tableConfig['model']::where('id', (int) $request['mapping_id'])
550                        ->where('region', $region)
551                        ->delete();
552
553                    return $deleted
554                        ? response()->json(['message' => $request->type.' deleted successfully'])
555                        : response()->json(['error' => 'User mapping not found'], 404);
556                }
557
558                // Never delete by an empty user id: where('id_fst', null) matches
559                // every unassigned code in the region. The old screen sent exactly
560                // that when deleting a code under "Usuarios con error".
561                if ($request['id'] === null || $request['id'] === '') {
562                    return response()->json(['error' => 'A user id or mapping_id is required'], 422);
563                }
564
565                $tableConfig['model']::where('id_fst', $request['id'])
566                    ->where('region', $region)
567                    ->delete();
568
569                return response()->json(['message' => $request->type.' deleted successfully']);
570            }
571
572            $tableConfig['model']::where('id', $request['id'])->delete();
573
574            return response()->json(['message' => $request->type.' deleted successfully']);
575
576        } catch (QueryException $e) {
577            report(AppException::fromException($e, 'DELETE_MAPPING_EXCEPTION'));
578
579            return response()->json(['error' => $e->getMessage()], 400);
580        }
581    }
582
583    public function getAllBudgetMonitor(Request $request)
584    {
585        try {
586            $data = $request->all();
587            $region = urldecode((string) request()->header('Region'));
588            $page = $data['page'];
589
590            $daysOffset = $page * 10;
591            $endDate = Carbon::today()->subDays($daysOffset);
592            $startDate = $endDate->copy()->addDays(10);
593
594            $dataResponse = [];
595            $currentDate = $startDate->copy();
596            $companyId = TblCompanies::where('region', $region)->first()->company_id;
597            $alreadyG3wBudgets = [];
598
599            while ($currentDate > $endDate) {
600                $dateStr = $currentDate->format('Y-m-d');
601
602                $g3wBudgets = $this->gestionaService->getBudgetsByDay($dateStr, $region);
603                if (is_string($g3wBudgets)) {
604                    $g3wBudgets = json_decode($g3wBudgets, true);
605                }
606
607                $g3wBudgetIds = array_map(fn (array $item) => $item['ID'], $g3wBudgets);
608
609                $newG3wBudgetIds = array_diff($g3wBudgetIds, $alreadyG3wBudgets);
610                $alreadyG3wBudgets = array_merge($alreadyG3wBudgets, $newG3wBudgetIds);
611                $countG3wBudgets = count($newG3wBudgetIds);
612
613                $fstBudgets = TblQuotations::where('company_id', $companyId)
614                    ->where(function ($query): void {
615                        $query->where('sync_import', 1)
616                            ->orWhere('sync_import_edited', 1);
617                    })
618                    ->whereDate('created_at', $dateStr)
619                    ->pluck('internal_quote_id')
620                    ->toArray();
621
622                // FIRE-1476: CLM (22) merged into Madrid — no dual-company override.
623
624                $countFstBudgets = count($fstBudgets);
625
626                $missingIds = array_diff($newG3wBudgetIds, $fstBudgets);
627
628                $existingIds = TblQuotations::where('company_id', $companyId)
629                    ->where(function ($query): void {
630                        $query->where('sync_import', 1)
631                            ->orWhere('sync_import_edited', 1);
632                    })
633                    ->whereIn('internal_quote_id', $missingIds)
634                    ->pluck('internal_quote_id')
635                    ->toArray();
636
637                // FIRE-1476: CLM merged into Madrid — no dual-company override.
638
639                $finalMissingIds = array_diff($missingIds, $existingIds);
640
641                $duplicatedFst = $this->getDuplicatedValues($fstBudgets);
642
643                $deletedIds = array_diff($fstBudgets, $newG3wBudgetIds);
644                foreach ($deletedIds as $key => $id) {
645                    $deleted = $this->gestionaService->checkDeleted($id, $region);
646                    if (! $deleted) {
647                        unset($deletedIds[$key]);
648                    }
649                }
650
651                $g3wOrdersUpdateLogs = TblG3WOrdersUpdateLogs::where('company_id', $companyId)
652                    ->whereDate('ended_at', $dateStr)
653                    ->where('processed_by', 'System')
654                    ->get();
655
656                $syncs = $g3wOrdersUpdateLogs->count();
657
658                $allUniqueErrorIds = [];
659
660                $syncErrorIds = $g3wOrdersUpdateLogs->flatMap(function ($item): array {
661                    $ids = $item->sync_error_ids;
662                    if (is_string($ids)) {
663                        $decoded = json_decode($ids, true);
664                        $ids = is_array($decoded) ? $decoded : explode(',', $ids);
665                    }
666
667                    return (array) $ids;
668                })
669                    ->filter()
670                    ->unique()
671                    ->toArray();
672
673                $allUniqueErrorIds = array_merge($allUniqueErrorIds, $syncErrorIds);
674
675                $finalUniqueIds = array_values(array_unique($allUniqueErrorIds));
676                $countSyncErrorIds = count($finalUniqueIds);
677
678                $dataResponse[] = [
679                    'date' => $dateStr,
680                    'g3wBudgets' => array_values($newG3wBudgetIds),
681                    'countG3wBudgets' => $countG3wBudgets,
682                    'fstBudgets' => $fstBudgets,
683                    'countfstBudgets' => $countFstBudgets,
684                    'missingIds' => array_values($finalMissingIds),
685                    'duplicatedFst' => $duplicatedFst,
686                    'deletedIds' => array_values($deletedIds),
687                    'syncs' => $syncs,
688                    'syncErrorIds' => $syncErrorIds,
689                    'countSyncErrorIds' => $countSyncErrorIds,
690                ];
691
692                $currentDate->subDay();
693
694            }
695
696            usort($dataResponse, fn (array $a, array $b) => strtotime($b['date']) - strtotime($a['date']));
697
698            return response()->json([
699                'data' => $dataResponse,
700                'meta' => [
701                    'current_page' => (int) $page,
702                    'date_range' => [
703                        'start' => $startDate->format('Y-m-d'),
704                        'end' => $endDate->format('Y-m-d'),
705                    ],
706                ]]);
707        } catch (\Exception $e) {
708            report(AppException::fromException($e, 'GET_ALL_BUDGET_MONITOR_EXCEPTION'));
709            Log::error('Error en getAllBudgetMonitor: '.$e->getMessage());
710
711            if ($e->getMessage() == 'API URL is not defined.') {
712                return response()->json([
713                    'error' => 'KO',
714                    'message' => 'La conexión con la API de G3W no está configurada. Por favor, configúrala en los ajustes de la empresa.',
715                ], 200);
716            }
717
718            return response()->json([
719                'message' => 'Error interno del servidor',
720            ], 500);
721        }
722    }
723
724    public function syncAllBudgetMonitor(Request $request)
725    {
726        try {
727            $data = $request->all();
728            $region = $this->regionFromHeader($request);
729            $day = $data['day'];
730            $dataResponse = [];
731            $companyId = TblCompanies::where('region', $region)->first()->company_id;
732            $alreadyG3wBudgets = [];
733
734            $g3wBudgets = $this->gestionaService->getBudgetsByDay($day, $region);
735
736            if (is_string($g3wBudgets)) {
737                $g3wBudgets = json_decode($g3wBudgets, true);
738            }
739
740            $g3wBudgetIds = array_map(fn (array $item) => $item['ID'], $g3wBudgets);
741
742            $newG3wBudgetIds = array_diff($g3wBudgetIds, $alreadyG3wBudgets);
743            $alreadyG3wBudgets = array_merge($alreadyG3wBudgets, $newG3wBudgetIds);
744
745            $fstBudgets = TblQuotations::where('company_id', $companyId)
746                ->where('sync_import', 1)
747                ->whereDate('created_at', $day)
748                ->pluck('internal_quote_id')
749                ->toArray();
750
751            $missingIds = array_diff($newG3wBudgetIds, $fstBudgets);
752
753            $existingIds = TblQuotations::where('company_id', $companyId)
754                ->where('sync_import', 1)
755                ->whereIn('internal_quote_id', $missingIds)
756                ->pluck('internal_quote_id')
757                ->toArray();
758
759            $finalMissingIds = array_diff($missingIds, $existingIds);
760
761            $duplicatedFst = $this->getDuplicatedValues($fstBudgets);
762
763            $deletedIds = array_diff($fstBudgets, $newG3wBudgetIds);
764
765            foreach ($deletedIds as $key => $id) {
766                $deleted = $this->gestionaService->checkDeleted($id, $region);
767                if (! $deleted) {
768                    unset($deletedIds[$key]);
769                }
770            }
771
772            $this->presupuestoService->syncByIds(implode(',', $finalMissingIds), $region, $day);
773
774            $dataResponse[] = [
775                'missingIds' => array_values($finalMissingIds),
776                'deletedIds' => array_values($deletedIds),
777            ];
778
779            return response()->json([
780                'success' => true,
781                'message' => 'Presupuestos que faltan sincronizados correctamente',
782            ]);
783        } catch (\Exception $e) {
784            report(AppException::fromException($e, 'SYNC_ALL_BUDGET_MONITOR_EXCEPTION'));
785            Log::error('Error en getAllBudgetMonitor: '.$e->getMessage());
786
787            return response()->json([
788                'message' => 'Error interno del servidor',
789            ], 500);
790        }
791    }
792
793    /**
794     * @return int[]|string[]
795     */
796    private function getDuplicatedValues($fstBudgets): array
797    {
798        $filteredValues = array_filter($fstBudgets, fn ($value) => $value !== null);
799
800        if (empty($filteredValues)) {
801            return [];
802        }
803
804        $counts = array_count_values($filteredValues);
805        $duplicates = array_filter($counts, fn ($count) => $count > 1);
806
807        return array_keys($duplicates);
808    }
809}