Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 316
0.00% covered (danger)
0.00%
0 / 13
CRAP
0.00% covered (danger)
0.00%
0 / 1
CofraiBudgetsController
0.00% covered (danger)
0.00%
0 / 316
0.00% covered (danger)
0.00%
0 / 13
4970
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 syncByDate
0.00% covered (danger)
0.00%
0 / 32
0.00% covered (danger)
0.00%
0 / 1
20
 syncErrorBudgets
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
20
 syncBudgetsWorks
0.00% covered (danger)
0.00%
0 / 30
0.00% covered (danger)
0.00%
0 / 1
20
 syncById
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getCountFailedBudgets
0.00% covered (danger)
0.00%
0 / 20
0.00% covered (danger)
0.00%
0 / 1
42
 syncByIds
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 downloadSyncBudgetsWorks
0.00% covered (danger)
0.00%
0 / 99
0.00% covered (danger)
0.00%
0 / 1
342
 listResyncRuns
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
42
 getResyncSummary
0.00% covered (danger)
0.00%
0 / 40
0.00% covered (danger)
0.00%
0 / 1
42
 collectAllFailedIds
0.00% covered (danger)
0.00%
0 / 18
0.00% covered (danger)
0.00%
0 / 1
56
 getLatestErrorPerId
0.00% covered (danger)
0.00%
0 / 17
0.00% covered (danger)
0.00%
0 / 1
42
 isTerminalNotFoundError
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
20
1<?php
2
3namespace App\Http\Controllers;
4
5use App\Exceptions\AppException;
6use App\Models\TblCofraiOrdersUpdateLogs;
7use App\Models\TblCofraiResyncRuns;
8use App\Models\TblCompanies;
9use App\Models\TblQuotations;
10use App\Services\CofraiQuotationsService;
11use App\Services\CofraiService;
12use Carbon\Carbon;
13use Illuminate\Http\JsonResponse;
14use Illuminate\Http\Request;
15use Illuminate\Support\Facades\Log;
16
17class CofraiBudgetsController extends Controller
18{
19    protected $cofraiQuotationsService;
20
21    protected $cofraiService;
22
23    public function __construct(CofraiQuotationsService $cofraiQuotationsService, CofraiService $cofraiService)
24    {
25        $this->cofraiQuotationsService = $cofraiQuotationsService;
26        $this->cofraiService = $cofraiService;
27    }
28
29    /**
30     * Sincroniza presupuestos a partir de una fecha.
31     *
32     * @return JsonResponse
33     */
34    public function syncByDate(Request $request)
35    {
36        $date = escapeshellarg($request->input('fecha'));
37        $name = escapeshellarg(@getallheaders()['Name']);
38        $region = urldecode(@getallheaders()['Region']);
39
40        if ($region === 'Catalunya') {
41            $region = 'Cataluña';
42        }
43
44        if ($this->cofraiService->getSyncStatus($region) === 1) {
45            return response()->json([
46                'success' => false,
47                'message' => 'Synchronization already in progress.',
48            ], 400);
49        }
50
51        try {
52            $phpBinary = '/usr/bin/php';
53
54            $artisanPath = escapeshellarg(base_path('artisan'));
55
56            $command = sprintf(
57                '%s %s cofrai-quotations:sync %s %s %s > /dev/null 2>&1 &',
58                $phpBinary,
59                $artisanPath,
60                $date,
61                $name,
62                $region
63            );
64
65            exec($command, $output, $returnVar);
66            /*$comand = "cd /var/www/html && php artisan cofrai-quotations:sync $date $name $region > /dev/null 2>&1 &";
67            exec($comand, $output, $returnVar);*/
68
69            return response()->json([
70                'success' => true,
71                'message' => 'Synchronization started in background.',
72            ]);
73        } catch (\Exception $e) {
74            $this->cofraiService->setSyncStatus(0, $region);
75            Log::channel('cofrai')->error('Failed to start sync: '.$e->getMessage());
76
77            return response()->json([
78                'success' => false,
79                'message' => $e->getMessage(),
80            ], 500);
81        }
82    }
83
84    /**
85     * @return JsonResponse
86     */
87    public function syncErrorBudgets()
88    {
89        $name = escapeshellarg(@getallheaders()['Name']);
90        $region = urldecode(@getallheaders()['Region']);
91
92        if ($region === 'Catalunya') {
93            $region = 'Cataluña';
94        }
95
96        if ($this->cofraiService->getSyncStatus($region) === 1) {
97            return response()->json([
98                'success' => false,
99                'message' => 'Synchronization already in progress.',
100            ], 400);
101        }
102
103        try {
104            $phpBinary = '/usr/bin/php';
105
106            $artisanPath = escapeshellarg(base_path('artisan'));
107
108            $command = sprintf(
109                '%s %s cofrai-quotations:retry-failed %s %s > /dev/null 2>&1 &',
110                $phpBinary,
111                $artisanPath,
112                $name,
113                $region
114            );
115
116            exec($command, $output, $returnVar);
117            /*$comand = "cd /var/www/html && php artisan cofrai-quotations:retry-failed $name $region > /dev/null 2>&1 &";
118            exec($comand, $output, $returnVar);*/
119
120            return response()->json([
121                'success' => true,
122                'message' => 'Synchronization started in background.',
123            ]);
124        } catch (\Exception $e) {
125            $this->cofraiService->setSyncStatus(0, $region);
126            Log::channel('cofrai')->error('Failed to start sync: '.$e->getMessage());
127
128            return response()->json([
129                'success' => false,
130                'message' => $e->getMessage(),
131            ], 500);
132        }
133
134    }
135
136    /**
137     * @return JsonResponse
138     */
139    public function syncBudgetsWorks()
140    {
141        $name = escapeshellarg(@getallheaders()['Name']);
142        $region = urldecode(@getallheaders()['Region']);
143
144        if ($region === 'Catalunya') {
145            $region = 'Cataluña';
146        }
147
148        if ($this->cofraiService->getSyncStatus($region) === 1) {
149            return response()->json([
150                'success' => false,
151                'message' => 'Synchronization already in progress.',
152            ], 400);
153        }
154
155        try {
156            $phpBinary = '/usr/bin/php';
157
158            $artisanPath = escapeshellarg(base_path('artisan'));
159
160            $command = sprintf(
161                '%s %s cofrai-quotations:sync-work %s %s > /dev/null 2>&1 &',
162                $phpBinary,
163                $artisanPath,
164                $name,
165                $region
166            );
167
168            exec($command, $output, $returnVar);
169            /*$comand = "cd /var/www/html && php artisan cofrai-quotations:sync-work $name $region > /dev/null 2>&1 &";
170            exec($comand, $output, $returnVar);*/
171
172            return response()->json([
173                'success' => true,
174                'message' => 'Synchronization started in background.',
175            ]);
176        } catch (\Exception $e) {
177            $this->cofraiService->setSyncStatus(0, $region);
178            Log::channel('g3w')->error('Failed to start sync: '.$e->getMessage());
179
180            return response()->json([
181                'success' => false,
182                'message' => $e->getMessage(),
183            ], 500);
184        }
185
186    }
187
188    /**
189     * Sincroniza un presupuesto por su ID.
190     *
191     * @return JsonResponse
192     */
193    public function syncById($id)
194    {
195        // CofraiQuotationsService::syncById requires the region as 2nd arg —
196        // it's used for the credential lookup + DB joins. Mirror of G3W's
197        // PresupuestosController::syncById.
198        $region = urldecode((string) request()->header('Region'));
199        if ($region === 'Catalunya') {
200            $region = 'Cataluña';
201        }
202
203        return response()->json($this->cofraiQuotationsService->syncById($id, $region));
204    }
205
206    /**
207     * Sincroniza un presupuesto por su ID.
208     *
209     * @param  $id
210     * @return JsonResponse
211     */
212    public function getCountFailedBudgets()
213    {
214        $region = urldecode(@getallheaders()['Region']);
215
216        if ($region === 'Catalunya' || $region === "'Catalunya'") {
217            $region = 'Cataluña';
218        }
219
220        $company = TblCompanies::where('region', $region)->first();
221
222        if (! $company) {
223            return response()->json([
224                'countWarnings' => 0,
225            ], 200);
226        }
227
228        $ids = TblCofraiOrdersUpdateLogs::whereNotNull('sync_error_ids')
229            ->where('company_id', $company->company_id)
230            ->get(['sync_error_ids']);
231
232        $allSyncErrorIds = [];
233
234        foreach ($ids as $id) {
235            if (is_string($id->sync_error_ids)) {
236                $id->sync_error_ids = json_decode($id->sync_error_ids, true);
237                $allSyncErrorIds = array_merge($allSyncErrorIds, $id->sync_error_ids);
238            }
239        }
240
241        $allSyncErrorIds = array_unique($allSyncErrorIds);
242
243        return response()->json([
244            'count' => count($allSyncErrorIds),
245        ]);
246    }
247
248    public function syncByIds(Request $request)
249    {
250        $ids = $request['ids'];
251        $date = $request['date'];
252        $region = urldecode(@getallheaders()['Region']);
253        $user = urldecode(@getallheaders()['Name']);
254
255        if ($region === 'Catalunya') {
256            $region = 'Cataluña';
257        }
258
259        return response()->json($this->cofraiQuotationsService->syncByIds($ids, $region, $date, $user));
260    }
261
262    // ----- FIRE-1077: 90-day download + resync monitoring -----
263
264    public function downloadSyncBudgetsWorks()
265    {
266        try {
267            $region = urldecode((string) request()->header('Region'));
268
269            if ($region === 'Catalunya') {
270                $region = 'Cataluña';
271            }
272
273            $companyId = TblCompanies::where('region', $region)->first()->company_id;
274            $totalDays = 90;
275            $dataResponse = [];
276
277            // FIRE-1077: fetch ALL Cofrai budgets once (id + date), then
278            // bucket per-day locally. Cofrai has no date-filter endpoint,
279            // and 90 round-trips would be unacceptable for a download.
280            $cofraiAllResponse = $this->cofraiService->getAllBudgetsWithDates($region);
281            if (is_string($cofraiAllResponse)) {
282                $cofraiAllResponse = json_decode($cofraiAllResponse, true);
283            }
284            $cofraiAllList = is_array($cofraiAllResponse) && isset($cofraiAllResponse['data'])
285                ? $cofraiAllResponse['data']
286                : [];
287
288            $cofraiByDate = [];
289            $allCofraiIds = [];
290            foreach ($cofraiAllList as $b) {
291                if (! isset($b['id'])) {
292                    continue;
293                }
294                $allCofraiIds[(string) $b['id']] = true;
295                $dateKey = isset($b['date']) ? substr((string) $b['date'], 0, 10) : null;
296                if ($dateKey) {
297                    $cofraiByDate[$dateKey][] = $b['id'];
298                }
299            }
300
301            for ($i = 0; $i < $totalDays; $i++) {
302                $currentDate = Carbon::today()->subDays($i);
303                $dateStr = $currentDate->format('Y-m-d');
304
305                $newCofraiBudgetIds = $cofraiByDate[$dateStr] ?? [];
306                $countCofraiBudgets = count($newCofraiBudgetIds);
307
308                $fstBudgetsQuery = ($companyId == 18 || $companyId == 22)
309                    ? TblQuotations::whereIn('company_id', [18, 22])
310                    : TblQuotations::where('company_id', $companyId);
311
312                $fstBudgets = $fstBudgetsQuery
313                    ->where(function ($query): void {
314                        $query->where('sync_import', 1)
315                            ->orWhere('sync_import_edited', 1);
316                    })
317                    ->whereDate('created_at', $dateStr)
318                    ->pluck('internal_quote_id')
319                    ->toArray();
320
321                $countFstBudgets = count($fstBudgets);
322
323                $missingIds = array_diff($newCofraiBudgetIds, $fstBudgets);
324
325                $existingIds = TblQuotations::where('company_id', $companyId)
326                    ->where(function ($query): void {
327                        $query->where('sync_import', 1)
328                            ->orWhere('sync_import_edited', 1);
329                    })
330                    ->whereIn('internal_quote_id', $missingIds)
331                    ->pluck('internal_quote_id')
332                    ->toArray();
333
334                $finalMissingIds = array_diff($missingIds, $existingIds);
335
336                $filteredFstBudgets = array_filter($fstBudgets, fn ($value) => $value !== null);
337                $duplicatedFst = [];
338                if (! empty($filteredFstBudgets)) {
339                    $counts = array_count_values($filteredFstBudgets);
340                    $duplicatedFst = array_keys(array_filter($counts, fn ($count) => $count > 1));
341                }
342
343                // O(1) membership check against the full Cofrai ID set.
344                $deletedIds = array_values(array_filter(
345                    $fstBudgets,
346                    fn ($id) => $id !== null && ! isset($allCofraiIds[(string) $id])
347                ));
348
349                $cofraiOrdersUpdateLogs = TblCofraiOrdersUpdateLogs::where('company_id', $companyId)
350                    ->whereDate('ended_at', $dateStr)
351                    ->where('processed_by', 'System')
352                    ->get();
353
354                $syncs = $cofraiOrdersUpdateLogs->count();
355
356                $syncErrorIds = $cofraiOrdersUpdateLogs->flatMap(function ($item): array {
357                    $ids = $item->sync_error_ids;
358                    if (is_string($ids)) {
359                        $decoded = json_decode($ids, true);
360                        $ids = is_array($decoded) ? $decoded : explode(',', $ids);
361                    }
362
363                    return (array) $ids;
364                })
365                    ->filter()
366                    ->unique()
367                    ->toArray();
368
369                $countSyncErrorIds = count(array_values(array_unique($syncErrorIds)));
370
371                $dataResponse[] = [
372                    'date' => $dateStr,
373                    'cofraiBudgets' => array_values($newCofraiBudgetIds),
374                    'countCofraiBudgets' => $countCofraiBudgets,
375                    'fstBudgets' => $fstBudgets,
376                    'countfstBudgets' => $countFstBudgets,
377                    'missingIds' => array_values($finalMissingIds),
378                    'duplicatedFst' => $duplicatedFst,
379                    'deletedIds' => $deletedIds,
380                    'syncs' => $syncs,
381                    'syncErrorIds' => $syncErrorIds,
382                    'countSyncErrorIds' => $countSyncErrorIds,
383                ];
384            }
385
386            usort($dataResponse, fn (array $a, array $b) => strtotime($b['date']) - strtotime($a['date']));
387
388            return response(['data' => $dataResponse]);
389        } catch (\Exception $e) {
390            report(AppException::fromException($e, 'DOWNLOAD_SYNC_COFRAI_BUDGETS_WORKS_EXCEPTION'));
391            Log::error('Error en downloadSyncBudgetsWorks (Cofrai): '.$e->getMessage());
392
393            if ($e->getMessage() == 'API URL is not defined.') {
394                return response()->json([
395                    'error' => 'KO',
396                    'message' => 'La conexión con la API de Cofrai no está configurada. Por favor, configúrala en los ajustes de la empresa.',
397                ], 200);
398            }
399
400            return response()->json([
401                'message' => 'Error interno del servidor',
402            ], 500);
403        }
404    }
405
406    public function listResyncRuns(Request $request)
407    {
408        try {
409            $query = TblCofraiResyncRuns::query()->orderBy('run_at', 'desc');
410
411            if ($request->query('date')) {
412                $query->whereDate('run_at', $request->query('date'));
413            }
414
415            $region = $request->query('region') ?: $request->header('Region');
416            if ($region) {
417                $region = urldecode((string) $region);
418                if ($region === 'Catalunya') {
419                    $region = 'Cataluña';
420                }
421                $query->where('region', $region);
422            }
423
424            $runs = $query->limit(500)->get();
425
426            return response()->json(['message' => 'OK', 'data' => $runs]);
427        } catch (\Exception $e) {
428            return response()->json(['message' => 'KO', 'error' => $e->getMessage()], 500);
429        }
430    }
431
432    /**
433     * FIRE-1077 / mirror of PresupuestosController::getResyncSummary.
434     * Filters terminal "presupuesto not found" errors AND IDs that no
435     * longer exist as active quotations from the total_failed count.
436     */
437    public function getResyncSummary(Request $request)
438    {
439        try {
440            $region = urldecode((string) $request->header('Region', ''));
441
442            if ($region === 'Catalunya') {
443                $region = 'Cataluña';
444            }
445
446            $allFailedIds = $this->collectAllFailedIds($region);
447
448            if (empty($allFailedIds)) {
449                $totalFailed = 0;
450            } else {
451                $latestErrorPerId = $this->getLatestErrorPerId($region);
452
453                $actionableIds = array_values(array_filter(
454                    $allFailedIds,
455                    fn ($id) => ! $this->isTerminalNotFoundError(
456                        $latestErrorPerId[(string) $id] ?? null
457                    )
458                ));
459
460                if (! empty($actionableIds)) {
461                    $idsInt = array_map('intval', $actionableIds);
462                    $existing = TblQuotations::whereIn('internal_quote_id', $idsInt)
463                        ->pluck('internal_quote_id')
464                        ->map(fn ($id) => (int) $id)
465                        ->all();
466                    $existingSet = array_flip($existing);
467                    $actionableIds = array_values(array_filter(
468                        $actionableIds,
469                        fn ($id) => isset($existingSet[(int) $id])
470                    ));
471                }
472
473                $totalFailed = count($actionableIds);
474            }
475
476            $lastRunQuery = TblCofraiResyncRuns::orderBy('run_at', 'desc');
477            if ($region) {
478                $lastRunQuery->where('region', $region);
479            }
480            $lastRun = $lastRunQuery->first();
481
482            return response()->json([
483                'message' => 'OK',
484                'data' => [
485                    'total_failed' => $totalFailed,
486                    'last_run_at' => $lastRun?->run_at,
487                    'last_run_success' => $lastRun?->success_count ?? 0,
488                    'last_run_failed' => $lastRun?->failed_count ?? 0,
489                ],
490            ]);
491        } catch (\Exception $e) {
492            return response()->json(['message' => 'KO', 'error' => $e->getMessage()], 500);
493        }
494    }
495
496    private function collectAllFailedIds(?string $region): array
497    {
498        $companiesQuery = TblCompanies::query();
499        if ($region) {
500            $companiesQuery->where('region', $region);
501        }
502        $companies = $companiesQuery->get();
503
504        $idSet = [];
505        foreach ($companies as $company) {
506            $logs = TblCofraiOrdersUpdateLogs::whereNotNull('sync_error_ids')
507                ->where('company_id', $company->company_id)
508                ->get(['sync_error_ids']);
509
510            foreach ($logs as $log) {
511                if (! is_string($log->sync_error_ids)) {
512                    continue;
513                }
514                $decoded = json_decode($log->sync_error_ids, true);
515                if (! is_array($decoded)) {
516                    continue;
517                }
518                foreach ($decoded as $id) {
519                    $idSet[(string) $id] = true;
520                }
521            }
522        }
523
524        return array_keys($idSet);
525    }
526
527    private function getLatestErrorPerId(?string $region): array
528    {
529        $latestErrorPerId = [];
530
531        $query = TblCofraiResyncRuns::query()
532            ->whereNotNull('failed_errors_json')
533            ->orderBy('run_at', 'asc');
534
535        if ($region) {
536            $query->where('region', $region);
537        }
538
539        $query->chunk(200, function ($runs) use (&$latestErrorPerId) {
540            foreach ($runs as $run) {
541                $errors = is_string($run->failed_errors_json)
542                    ? json_decode($run->failed_errors_json, true)
543                    : $run->failed_errors_json;
544
545                if (! is_array($errors)) {
546                    continue;
547                }
548
549                foreach ($errors as $id => $message) {
550                    $latestErrorPerId[(string) $id] = (string) $message;
551                }
552            }
553        });
554
555        return $latestErrorPerId;
556    }
557
558    private function isTerminalNotFoundError(?string $error): bool
559    {
560        if ($error === null || $error === '') {
561            return false;
562        }
563
564        return str_contains($error, 'No se ha encontrado el presupuesto')
565            || str_contains($error, 'No se encuentra el presupuesto con ID en Cofrai');
566    }
567}