Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
12.76% covered (danger)
12.76%
49 / 384
7.14% covered (danger)
7.14%
1 / 14
CRAP
0.00% covered (danger)
0.00%
0 / 1
CofraiController
12.76% covered (danger)
12.76%
49 / 384
7.14% covered (danger)
7.14%
1 / 14
4882.10
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
49 / 49
100.00% covered (success)
100.00%
1 / 1
1
 updateApiCredentials
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 getApiDetails
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 getLastUpdate
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
20
 getAcceptanceWarnings
0.00% covered (danger)
0.00%
0 / 24
0.00% covered (danger)
0.00%
0 / 1
42
 getSyncStatus
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 getCofraiActive
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
12
 updateCofraiActive
0.00% covered (danger)
0.00%
0 / 10
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
0.00% covered (danger)
0.00%
0 / 61
0.00% covered (danger)
0.00%
0 / 1
272
 deleteMappings
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
30
 getAllBudgetMonitor
0.00% covered (danger)
0.00%
0 / 105
0.00% covered (danger)
0.00%
0 / 1
306
 syncAllBudgetMonitor
0.00% covered (danger)
0.00%
0 / 51
0.00% covered (danger)
0.00%
0 / 1
156
 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\TblCofraiOrdersUpdateLogs;
7use App\Models\TblCompanies;
8use App\Models\TblQuotations;
9use App\Models\TblSegmentCofraiMapping;
10use App\Models\TblSourceCofraiMapping;
11use App\Models\TblSources;
12use App\Models\TblStatusCofraiMapping;
13use App\Models\TblTypeCofraiMapping;
14use App\Models\TblUserCofraiMapping;
15use App\Models\TblUsers;
16use App\Services\CofraiQuotationsService;
17use App\Services\CofraiService;
18use Carbon\Carbon;
19use Illuminate\Database\QueryException;
20use Illuminate\Http\JsonResponse;
21use Illuminate\Http\Request;
22use Illuminate\Support\Facades\DB;
23use Illuminate\Support\Facades\Log;
24use Illuminate\Support\Facades\Schema;
25
26class CofraiController extends Controller
27{
28    protected $cofraiService;
29
30    protected $cofraiQuotationsService;
31
32    protected $tables;
33
34    public function __construct(CofraiService $cofraiService, CofraiQuotationsService $cofraiQuotationsService)
35    {
36        $this->cofraiService = $cofraiService;
37        $this->cofraiQuotationsService = $cofraiQuotationsService;
38
39        // FIRE-1077: Cofrai mappings — mirror of GestionaController::$tables.
40        // The column names differ (name_cofrai / id_cofrai / *_by_cofrai)
41        // so this is a parallel config, not shared.
42        $this->tables = [
43            'status' => [
44                'model' => TblStatusCofraiMapping::class,
45                'index' => 'budget_status_id',
46                'relation' => 'budgetStatus',
47                'tblQuotationsG3wNameColumn' => 'status_by_cofrai',
48                'tblMappingNameColumn' => 'name_cofrai',
49                'tblQuotationsNameColumn' => 'budget_status_id',
50                'requestNameKey' => 'budget_status_id',
51            ],
52            'segment' => [
53                'model' => TblSegmentCofraiMapping::class,
54                'index' => 'segment_id',
55                'relation' => 'segment',
56                'tblQuotationsG3wNameColumn' => 'segment_by_cofrai',
57                'tblMappingNameColumn' => 'name_cofrai',
58                'tblQuotationsNameColumn' => 'segment_id',
59                'requestNameKey' => 'segment_id',
60            ],
61            'type' => [
62                'model' => TblTypeCofraiMapping::class,
63                'index' => 'budget_type_name',
64                'relation' => 'budgetType',
65                'tblQuotationsG3wNameColumn' => 'type_by_cofrai',
66                'tblMappingNameColumn' => 'id_cofrai',
67                'tblQuotationsNameColumn' => 'budget_type_id',
68                'requestNameKey' => 'id_cofrai',
69            ],
70            'source' => [
71                'model' => TblSourceCofraiMapping::class,
72                'index' => 'source_name',
73                'relation' => 'source',
74                'tblQuotationsG3wNameColumn' => 'source_by_cofrai',
75                'tblMappingNameColumn' => 'id_cofrai',
76                'tblQuotationsNameColumn' => 'source_id',
77                'requestNameKey' => 'id_cofrai',
78            ],
79            'user' => [
80                'model' => TblUserCofraiMapping::class,
81                'index' => 'id_fst',
82                'relation' => 'user',
83                'tblQuotationsG3wNameColumn' => 'Cofrai_code',
84                'tblMappingNameColumn' => 'id_fst',
85                'tblQuotationsNameColumn' => 'Cofrai_code',
86                'requestNameKey' => 'id_fst',
87            ],
88        ];
89    }
90
91    /**
92     * Sincroniza un presupuesto por su ID.
93     *
94     * @param  $id
95     * @return JsonResponse
96     */
97    public function updateApiCredentials(Request $request)
98    {
99        try {
100            $region = urldecode(@getallheaders()['Region']);
101
102            if ($region == 'Catalunya') {
103                $region = 'Cataluña';
104            }
105
106            $params = $request->only(['url', 'user', 'password', 'user_id']);
107            $this->cofraiService->updateApiCredentials($params, $region);
108
109            return response()->json(['message' => 'Credentials updated successfully'], 200);
110        } catch (\Exception $e) {
111            return response()->json(['error' => $e->getMessage()], 400);
112        }
113    }
114
115    /**
116     * @return JsonResponse
117     *
118     * @throws \Exception
119     */
120    public function getApiDetails()
121    {
122        try {
123            $region = urldecode(@getallheaders()['Region']);
124
125            if ($region === 'Catalunya') {
126                $region = 'Cataluña';
127            }
128
129            $apiDetailsResponse = $this->cofraiService->getApiDetails($region);
130
131            if (! $apiDetailsResponse) {
132                throw new \Exception('Api details not found');
133            }
134
135            $apiDetails = json_decode($apiDetailsResponse->getContent(), true);
136
137            return response()->json([
138                'url' => $apiDetails['url'] ?? null,
139                'user' => $apiDetails['user'] ?? null,
140            ], 200);
141
142        } catch (QueryException $e) {
143            return response()->json(['error' => $e->getMessage()], 400);
144        }
145    }
146
147    public function getLastUpdate()
148    {
149        try {
150            $region = urldecode(@getallheaders()['Region']);
151
152            if ($region === 'Catalunya') {
153                $region = 'Cataluña';
154            }
155
156            $apiLastUpdateResponse = $this->cofraiService->getLastUpdate($region);
157
158            if (! $apiLastUpdateResponse) {
159                throw new \Exception('Last update not found');
160            }
161
162            $apiLastUpdate = json_decode($apiLastUpdateResponse->getContent(), true);
163
164            return response()->json([
165                'lastUpdate' => $apiLastUpdate['lastUpdate'] ?? null,
166                'updatingNow' => $apiLastUpdate['updatingNow'] ?? null,
167            ], 200);
168
169        } catch (QueryException $e) {
170            return response()->json(['error' => $e->getMessage()], 400);
171        }
172    }
173
174    public function getAcceptanceWarnings(Request $request)
175    {
176        try {
177            $region = urldecode(@getallheaders()['Region']) ?? null;
178
179            if (! $region) {
180                return response()->json(['error' => 'Region header is missing'], 400);
181            }
182
183            if ($region == 'Catalunya') {
184                $region = 'Cataluña';
185            }
186
187            $commercial = $request->input('commercial', null);
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            $countWarnings = TblQuotations::where('sync_import', 1)
228                ->where('company_id', $companyId)
229                ->where('g3w_warning', 1)
230                ->when(! empty($commercial) && $commercial !== 'All', function ($query) use ($commercial) {
231                    return $query->where('commercial', $commercial);
232                })
233                ->count();
234
235            return response()->json([
236                'countWarnings' => $countWarnings,
237            ], 200);
238
239        } catch (QueryException $e) {
240            return response()->json(['error' => $e->getMessage()], 400);
241        }
242    }
243
244    public function getSyncStatus()
245    {
246        try {
247            $region = urldecode(@getallheaders()['Region']);
248
249            if ($region === 'Catalunya') {
250                $region = 'Cataluña';
251            }
252
253            return response()->json([
254                'status' => $this->cofraiService->getSyncStatus($region),
255            ], 200);
256
257        } catch (QueryException $e) {
258            return response()->json(['error' => $e->getMessage()], 400);
259        }
260    }
261
262    public function getCofraiActive()
263    {
264        try {
265            $region = urldecode(@getallheaders()['Region']);
266
267            if ($region === 'Catalunya') {
268                $region = 'Cataluña';
269            }
270
271            return response()->json([
272                'active' => $this->cofraiService->getCofraiActive($region),
273            ], 200);
274
275        } catch (QueryException $e) {
276            return response()->json(['error' => $e->getMessage()], 400);
277        }
278    }
279
280    public function updateCofraiActive(Request $request)
281    {
282        try {
283            $region = urldecode(@getallheaders()['Region']);
284
285            if ($region === 'Catalunya') {
286                $region = 'Cataluña';
287            }
288
289            $active = $request->input('active');
290
291            $this->cofraiService->updateCofraiActive($active, $region);
292
293            return response()->json([
294                'success' => 1,
295            ], 200);
296
297        } catch (QueryException $e) {
298            return response()->json(['error' => $e->getMessage()], 400);
299        }
300    }
301
302    // ----- FIRE-1077: mapping management (status / segment / type / source / user) -----
303
304    public function getMappings(Request $request)
305    {
306        try {
307            if (! $request->has('type') || ! array_key_exists($request->type, $this->tables)) {
308                throw new \Exception('Type parameter is missing or invalid');
309            }
310
311            $tableConfig = $this->tables[$request->type];
312
313            if (isset($tableConfig['model'])) {
314                $mappings = $tableConfig['model']::with([$tableConfig['relation'] => function ($query) use ($tableConfig): void {
315                    $relatedModel = (new $tableConfig['model'])->{$tableConfig['relation']}()->getRelated();
316                    $relatedTable = $relatedModel->getTable();
317
318                    if (Schema::hasColumn($relatedTable, 'priority')) {
319                        $query->orderBy('priority', 'desc');
320                    }
321                }])->get();
322            } else {
323                $mappings = DB::table($tableConfig['table'])->get();
324            }
325
326            return response()->json($mappings);
327        } catch (\Exception $e) {
328            report(AppException::fromException($e, 'GET_COFRAI_MAPPINGS_EXCEPTION'));
329
330            return response()->json(['error' => $e->getMessage()], 400);
331        }
332    }
333
334    public function setMappings(Request $request)
335    {
336        try {
337            if (! $request->has('type')) {
338                return response()->json(['message' => 'Not type especified']);
339            }
340
341            $tableConfig = $this->tables[$request->type];
342
343            if (! isset($tableConfig['tblQuotationsG3wNameColumn'], $tableConfig['tblMappingNameColumn'], $tableConfig['tblQuotationsNameColumn'], $tableConfig['requestNameKey'])) {
344                return response()->json(['message' => 'Missing configuration keys'], 500);
345            }
346
347            $data = $request->except('type');
348
349            if (! $request->has('id')) {
350                $tableConfig['model']::create($data);
351
352                return response()->json(['message' => $request->type.' created successfully']);
353            }
354
355            if ($tableConfig['relation'] === 'user') {
356                if (is_numeric($request['id'])) {
357                    $rowMapping = $tableConfig['model']::where('id_fst', $request['id'])->first();
358                    $data = $request->except('id');
359
360                    if (! $rowMapping) {
361                        $tableConfig['model']::create($data);
362
363                        return response()->json(['error' => 'User mapping not found'], 404);
364                    }
365
366                    $userName = TblUsers::where('id', $rowMapping->id_fst)->first()->name;
367                    $nameCofrai = $rowMapping->name_cofrai ?? null;
368
369                    if ($nameCofrai !== null && $nameCofrai !== '') {
370                        TblQuotations::where('user_create_by_cofrai', $nameCofrai)
371                            ->update(['created_by' => $userName]);
372
373                        TblQuotations::where('user_commercial_by_cofrai', $nameCofrai)
374                            ->update(['commercial' => $userName]);
375
376                        TblQuotations::where('user_create_by_cofrai', $nameCofrai)
377                            ->whereNull('commercial')
378                            ->whereNull('user_commercial_by_cofrai')
379                            ->update(['commercial' => $nameCofrai]);
380                    }
381
382                    $rowMapping->update($data);
383                } else {
384                    $rowMapping = $tableConfig['model']::where('name_cofrai', $request['id'])->first();
385
386                    if (! $rowMapping) {
387                        return response()->json(['error' => 'User mapping not found'], 404);
388                    }
389
390                    $rowMapping->update(['id_fst' => $request['id_fst']]);
391
392                    $userName = TblUsers::where('id', $request['id_fst'])->first();
393
394                    if (! $userName) {
395                        return response()->json(['error' => 'User mapping not found'], 404);
396                    }
397
398                    TblQuotations::where('user_create_by_cofrai', $request['id'])
399                        ->update(['created_by' => $userName->name]);
400
401                    TblQuotations::where('user_commercial_by_cofrai', $request['id'])
402                        ->update(['commercial' => $userName->name]);
403
404                    TblQuotations::where('user_create_by_cofrai', $request['id'])
405                        ->whereNull('commercial')
406                        ->whereNull('user_commercial_by_cofrai')
407                        ->update(['commercial' => $userName->name]);
408                }
409
410                return response()->json(['message' => $request->type.' edited successfully']);
411            }
412
413            $rowMapping = $tableConfig['model']::where('id', $request['id'])->first();
414
415            if ($tableConfig['relation'] === 'source') {
416                $data = [];
417                $sourceRow = TblSources::where('source_id', $request['id_fst'])->first();
418                if (! $sourceRow) {
419                    return response()->json(['error' => 'Source mapping not found'], 404);
420                }
421
422                $data['source_name'] = $sourceRow->name;
423            }
424
425            $rowMapping->update($data);
426
427            $cofraiKey = $rowMapping[$tableConfig['tblMappingNameColumn']] ?? null;
428
429            // Mirror of GestionaController guard (FIRE-958): an empty cofrai
430            // key would translate to `WHERE col IS NULL` and propagate the
431            // mapping change to every manually-created quotation. Skip when
432            // the mapping has no source key.
433            if ($cofraiKey === null || $cofraiKey === '') {
434                return response()->json(['message' => $request->type.' edited successfully']);
435            }
436
437            TblQuotations::where($tableConfig['tblQuotationsG3wNameColumn'], $cofraiKey)
438                ->update([$tableConfig['tblQuotationsNameColumn'] => $rowMapping[$tableConfig['requestNameKey']]]);
439
440            return response()->json(['message' => $request->type.' edited successfully']);
441        } catch (QueryException $e) {
442            report(AppException::fromException($e, 'SET_COFRAI_MAPPING_EXCEPTION'));
443
444            return response()->json(['error' => $e->getMessage()], 400);
445        }
446    }
447
448    public function deleteMappings(Request $request)
449    {
450        try {
451            if (! $request->has('id')) {
452                return response()->json(['message' => 'Can`t be deleted without ID']);
453            }
454
455            if (! $request->has('type')) {
456                return response()->json(['message' => 'Not type especified']);
457            }
458
459            $tableConfig = $this->tables[$request->type];
460
461            if ($tableConfig['relation'] === 'user') {
462                $tableConfig['model']::where('id_fst', $request['id'])->delete();
463
464                return response()->json(['message' => $request->type.' deleted successfully']);
465            }
466
467            $tableConfig['model']::where('id', $request['id'])->delete();
468
469            return response()->json(['message' => $request->type.' deleted successfully']);
470        } catch (QueryException $e) {
471            report(AppException::fromException($e, 'DELETE_COFRAI_MAPPING_EXCEPTION'));
472
473            return response()->json(['error' => $e->getMessage()], 400);
474        }
475    }
476
477    // ----- FIRE-1077: budget monitor (parity with GestionaController) -----
478
479    public function getAllBudgetMonitor(Request $request)
480    {
481        try {
482            $data = $request->all();
483            $region = urldecode((string) request()->header('Region'));
484            $page = $data['page'];
485
486            $daysOffset = $page * 10;
487            $endDate = Carbon::today()->subDays($daysOffset);
488            $startDate = $endDate->copy()->addDays(10);
489
490            $dataResponse = [];
491            $currentDate = $startDate->copy();
492            $companyId = TblCompanies::where('region', $region)->first()->company_id;
493
494            // FIRE-1077: fetch the FULL Cofrai budget list once (with dates).
495            // Cofrai's API has no date-filtered endpoint (unlike Gestiona's
496            // `presupuesto?fecha=X`), so we fetch everything and bucket by
497            // day locally — one API call instead of one per day in the range.
498            $cofraiAllResponse = $this->cofraiService->getAllBudgetsWithDates($region);
499            if (is_string($cofraiAllResponse)) {
500                $cofraiAllResponse = json_decode($cofraiAllResponse, true);
501            }
502            $cofraiAllList = is_array($cofraiAllResponse) && isset($cofraiAllResponse['data'])
503                ? $cofraiAllResponse['data']
504                : [];
505
506            // Build date → [ids] bucket map. Cofrai returns ISO datetime
507            // in the `date` field; we truncate to YYYY-MM-DD.
508            $cofraiByDate = [];
509            $allCofraiIds = [];
510            foreach ($cofraiAllList as $b) {
511                if (! isset($b['id'])) {
512                    continue;
513                }
514                $dateKey = isset($b['date']) ? substr((string) $b['date'], 0, 10) : null;
515                if ($dateKey) {
516                    $cofraiByDate[$dateKey][] = $b['id'];
517                }
518                $allCofraiIds[(string) $b['id']] = true;
519            }
520
521            while ($currentDate > $endDate) {
522                $dateStr = $currentDate->format('Y-m-d');
523
524                $newCofraiBudgetIds = $cofraiByDate[$dateStr] ?? [];
525                $countCofraiBudgets = count($newCofraiBudgetIds);
526
527                $fstQuery = ($companyId == 18 || $companyId == 22)
528                    ? TblQuotations::whereIn('company_id', [18, 22])
529                    : TblQuotations::where('company_id', $companyId);
530
531                // The "imported correctly" count must restrict to rows imported
532                // from Cofrai (`sync_cofrai_import = 1`). The G3W flags
533                // (`sync_import`, `sync_import_edited`) were copied verbatim
534                // when this monitor was built and missed every Cofrai row,
535                // making the count always 0.
536                $fstBudgets = (clone $fstQuery)
537                    ->where('sync_cofrai_import', 1)
538                    ->whereDate('created_at', $dateStr)
539                    ->pluck('internal_quote_id')
540                    ->toArray();
541
542                $countFstBudgets = count($fstBudgets);
543
544                $missingIds = array_diff($newCofraiBudgetIds, $fstBudgets);
545
546                $existingIds = (clone $fstQuery)
547                    ->where('sync_cofrai_import', 1)
548                    ->whereIn('internal_quote_id', $missingIds)
549                    ->pluck('internal_quote_id')
550                    ->toArray();
551
552                $finalMissingIds = array_diff($missingIds, $existingIds);
553
554                $duplicatedFst = $this->getDuplicatedValues($fstBudgets);
555
556                // "Deleted in Cofrai" = present in Titan, absent from the
557                // full Cofrai ID set. O(1) membership check instead of an
558                // N-call checkDeleted loop.
559                $deletedIds = array_values(array_filter(
560                    $fstBudgets,
561                    fn ($id) => $id !== null && ! isset($allCofraiIds[(string) $id])
562                ));
563
564                $cofraiOrdersUpdateLogs = TblCofraiOrdersUpdateLogs::where('company_id', $companyId)
565                    ->whereDate('ended_at', $dateStr)
566                    ->where('processed_by', 'System')
567                    ->get();
568
569                $syncs = $cofraiOrdersUpdateLogs->count();
570
571                $syncErrorIds = $cofraiOrdersUpdateLogs->flatMap(function ($item): array {
572                    $ids = $item->sync_error_ids;
573                    if (is_string($ids)) {
574                        $decoded = json_decode($ids, true);
575                        $ids = is_array($decoded) ? $decoded : explode(',', $ids);
576                    }
577
578                    return (array) $ids;
579                })
580                    ->filter()
581                    ->unique()
582                    ->toArray();
583
584                $countSyncErrorIds = count(array_values(array_unique($syncErrorIds)));
585
586                $dataResponse[] = [
587                    'date' => $dateStr,
588                    'cofraiBudgets' => array_values($newCofraiBudgetIds),
589                    'countCofraiBudgets' => $countCofraiBudgets,
590                    'fstBudgets' => $fstBudgets,
591                    'countfstBudgets' => $countFstBudgets,
592                    'missingIds' => array_values($finalMissingIds),
593                    'duplicatedFst' => $duplicatedFst,
594                    'deletedIds' => $deletedIds,
595                    'syncs' => $syncs,
596                    'syncErrorIds' => $syncErrorIds,
597                    'countSyncErrorIds' => $countSyncErrorIds,
598                ];
599
600                $currentDate->subDay();
601            }
602
603            usort($dataResponse, fn (array $a, array $b) => strtotime($b['date']) - strtotime($a['date']));
604
605            return response()->json([
606                'data' => $dataResponse,
607                'meta' => [
608                    'current_page' => (int) $page,
609                    'date_range' => [
610                        'start' => $startDate->format('Y-m-d'),
611                        'end' => $endDate->format('Y-m-d'),
612                    ],
613                ]]);
614        } catch (\Exception $e) {
615            report(AppException::fromException($e, 'GET_ALL_COFRAI_BUDGET_MONITOR_EXCEPTION'));
616            Log::error('Error en getAllBudgetMonitor (Cofrai): '.$e->getMessage());
617
618            if ($e->getMessage() == 'API URL is not defined.') {
619                return response()->json([
620                    'error' => 'KO',
621                    'message' => 'La conexión con la API de Cofrai no está configurada. Por favor, configúrala en los ajustes de la empresa.',
622                ], 200);
623            }
624
625            if (str_contains($e->getMessage(), 'Authentication')) {
626                return response()->json([
627                    'error' => 'KO',
628                    'message' => 'Las credenciales de Cofrai no son válidas o han caducado para esta región. Revisa la configuración de la empresa en los ajustes.',
629                ], 200);
630            }
631
632            return response()->json([
633                'message' => 'Error interno del servidor',
634            ], 500);
635        }
636    }
637
638    public function syncAllBudgetMonitor(Request $request)
639    {
640        try {
641            $data = $request->all();
642            if (app()->runningInConsole()) {
643                $region = $request->header('Region');
644            } else {
645                $region = urldecode(request()->header('Region') ?? '');
646            }
647            $day = $data['day'];
648            $companyId = TblCompanies::where('region', $region)->first()->company_id;
649
650            // FIRE-1077: one Cofrai call up front (id + date), then bucket
651            // locally to the requested day. Same approach as getAllBudgetMonitor.
652            $cofraiAllResponse = $this->cofraiService->getAllBudgetsWithDates($region);
653            if (is_string($cofraiAllResponse)) {
654                $cofraiAllResponse = json_decode($cofraiAllResponse, true);
655            }
656            $cofraiAllList = is_array($cofraiAllResponse) && isset($cofraiAllResponse['data'])
657                ? $cofraiAllResponse['data']
658                : [];
659
660            $newCofraiBudgetIds = [];
661            $allCofraiIds = [];
662            foreach ($cofraiAllList as $b) {
663                if (! isset($b['id'])) {
664                    continue;
665                }
666                $allCofraiIds[(string) $b['id']] = true;
667                $dateKey = isset($b['date']) ? substr((string) $b['date'], 0, 10) : null;
668                if ($dateKey === $day) {
669                    $newCofraiBudgetIds[] = $b['id'];
670                }
671            }
672
673            $fstBudgets = TblQuotations::where('company_id', $companyId)
674                ->where('sync_import', 1)
675                ->whereDate('created_at', $day)
676                ->pluck('internal_quote_id')
677                ->toArray();
678
679            $missingIds = array_diff($newCofraiBudgetIds, $fstBudgets);
680
681            $existingIds = TblQuotations::where('company_id', $companyId)
682                ->where('sync_import', 1)
683                ->whereIn('internal_quote_id', $missingIds)
684                ->pluck('internal_quote_id')
685                ->toArray();
686
687            $finalMissingIds = array_diff($missingIds, $existingIds);
688
689            // "Deleted in Cofrai" via O(1) membership check against the
690            // full ID set (no per-id round-trip).
691            $deletedIds = array_values(array_filter(
692                $fstBudgets,
693                fn ($id) => $id !== null && ! isset($allCofraiIds[(string) $id])
694            ));
695
696            if (! empty($finalMissingIds)) {
697                $this->cofraiQuotationsService->syncByIds(implode(',', $finalMissingIds), $region, $day);
698            }
699
700            return response()->json([
701                'success' => true,
702                'message' => 'Presupuestos que faltan sincronizados correctamente',
703                'missingIds' => array_values($finalMissingIds),
704                'deletedIds' => $deletedIds,
705            ]);
706        } catch (\Exception $e) {
707            report(AppException::fromException($e, 'SYNC_ALL_COFRAI_BUDGET_MONITOR_EXCEPTION'));
708            Log::error('Error en syncAllBudgetMonitor (Cofrai): '.$e->getMessage());
709
710            return response()->json([
711                'message' => 'Error interno del servidor',
712            ], 500);
713        }
714    }
715
716    private function getDuplicatedValues($fstBudgets): array
717    {
718        $filteredValues = array_filter($fstBudgets, fn ($value) => $value !== null);
719
720        if (empty($filteredValues)) {
721            return [];
722        }
723
724        $counts = array_count_values($filteredValues);
725        $duplicates = array_filter($counts, fn ($count) => $count > 1);
726
727        return array_keys($duplicates);
728    }
729}