Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.00% |
0 / 408 |
|
0.00% |
0 / 16 |
CRAP | |
0.00% |
0 / 1 |
| PresupuestosController | |
0.00% |
0 / 408 |
|
0.00% |
0 / 16 |
5112 | |
0.00% |
0 / 1 |
| __construct | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| syncByDate | |
0.00% |
0 / 33 |
|
0.00% |
0 / 1 |
12 | |||
| syncErrorBudgets | |
0.00% |
0 / 29 |
|
0.00% |
0 / 1 |
12 | |||
| syncBudgetsWorks | |
0.00% |
0 / 29 |
|
0.00% |
0 / 1 |
12 | |||
| syncById | |
0.00% |
0 / 7 |
|
0.00% |
0 / 1 |
12 | |||
| getCountFailedBudgets | |
0.00% |
0 / 20 |
|
0.00% |
0 / 1 |
42 | |||
| syncByIds | |
0.00% |
0 / 7 |
|
0.00% |
0 / 1 |
6 | |||
| listResyncRuns | |
0.00% |
0 / 13 |
|
0.00% |
0 / 1 |
42 | |||
| getResyncSummary | |
0.00% |
0 / 40 |
|
0.00% |
0 / 1 |
42 | |||
| collectAllFailedIds | |
0.00% |
0 / 18 |
|
0.00% |
0 / 1 |
56 | |||
| getLatestErrorPerId | |
0.00% |
0 / 17 |
|
0.00% |
0 / 1 |
42 | |||
| isTerminalNotFoundError | |
0.00% |
0 / 4 |
|
0.00% |
0 / 1 |
20 | |||
| downloadSyncBudgetsWorks | |
0.00% |
0 / 89 |
|
0.00% |
0 / 1 |
132 | |||
| bulkSyncRegions | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
2 | |||
| bulkSync | |
0.00% |
0 / 75 |
|
0.00% |
0 / 1 |
56 | |||
| bulkSyncStatus | |
0.00% |
0 / 23 |
|
0.00% |
0 / 1 |
6 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Http\Controllers; |
| 4 | |
| 5 | use App\Exceptions\AppException; |
| 6 | use App\Models\TblCompanies; |
| 7 | use App\Models\TblG3WBulkSyncRuns; |
| 8 | use App\Models\TblG3WOrdersUpdateLogs; |
| 9 | use App\Models\TblG3WResyncRuns; |
| 10 | use App\Models\TblQuotations; |
| 11 | use App\Services\GestionaService; |
| 12 | use App\Services\PresupuestosService; |
| 13 | use Illuminate\Http\JsonResponse; |
| 14 | use Illuminate\Http\Request; |
| 15 | use Illuminate\Support\Carbon; |
| 16 | use Illuminate\Support\Facades\Log; |
| 17 | use Symfony\Component\Process\PhpExecutableFinder; |
| 18 | |
| 19 | class PresupuestosController extends Controller |
| 20 | { |
| 21 | public function __construct(protected PresupuestosService $presupuestosService, protected GestionaService $gestionaService) {} |
| 22 | |
| 23 | /** |
| 24 | * Sincroniza presupuestos a partir de una fecha. |
| 25 | * |
| 26 | * @return JsonResponse |
| 27 | */ |
| 28 | public function syncByDate(Request $request) |
| 29 | { |
| 30 | $date = escapeshellarg((string) $request->input('fecha')); |
| 31 | $name = escapeshellarg((string) request()->header('Name')); |
| 32 | // Decode BEFORE quoting: the client sets the header with |
| 33 | // encodeURIComponent(), so an accented region reaches the spawned |
| 34 | // artisan command as 'Castell%C3%B3n' and matches no company row. |
| 35 | $region = escapeshellarg(urldecode((string) request()->header('Region'))); |
| 36 | |
| 37 | if ($this->gestionaService->getSyncStatus($region) === 1) { |
| 38 | $startCronDateTime = date('Y-m-d H:i:s'); |
| 39 | $this->presupuestosService->updateLogs([['id' => 0, 'error' => 'Synchronization already in progress.']], 0, [], $startCronDateTime, 'System', $region); |
| 40 | |
| 41 | return response()->json([ |
| 42 | 'success' => false, |
| 43 | 'message' => 'Synchronization already in progress.', |
| 44 | ], 400); |
| 45 | } |
| 46 | |
| 47 | try { |
| 48 | $phpBinary = '/usr/bin/php'; |
| 49 | |
| 50 | $artisanPath = escapeshellarg(base_path('artisan')); |
| 51 | |
| 52 | $command = sprintf( |
| 53 | '%s %s quotations:sync %s %s %s > /dev/null 2>&1 &', |
| 54 | $phpBinary, |
| 55 | $artisanPath, |
| 56 | $date, |
| 57 | $name, |
| 58 | $region |
| 59 | ); |
| 60 | |
| 61 | exec($command, $output, $returnVar); |
| 62 | /*$comand = "cd /var/www/html && php artisan quotations:sync $date $name $region > /dev/null 2>&1 &"; |
| 63 | exec($comand, $output, $returnVar);*/ |
| 64 | |
| 65 | return response()->json([ |
| 66 | 'success' => true, |
| 67 | 'message' => 'Synchronization started in background.', |
| 68 | ]); |
| 69 | } catch (\Exception $e) { |
| 70 | report(AppException::fromException($e, 'SYNC_BY_DATE_EXCEPTION')); |
| 71 | $this->gestionaService->setSyncStatus(0, $region); |
| 72 | Log::channel('g3w')->error('Failed to start sync: '.$e->getMessage()); |
| 73 | |
| 74 | return response()->json([ |
| 75 | 'success' => false, |
| 76 | 'message' => $e->getMessage(), |
| 77 | ], 500); |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /** |
| 82 | * @return JsonResponse |
| 83 | */ |
| 84 | public function syncErrorBudgets() |
| 85 | { |
| 86 | $name = escapeshellarg((string) request()->header('Name')); |
| 87 | // Decode BEFORE quoting: the client sets the header with |
| 88 | // encodeURIComponent(), so an accented region reaches the spawned |
| 89 | // artisan command as 'Castell%C3%B3n' and matches no company row. |
| 90 | $region = escapeshellarg(urldecode((string) request()->header('Region'))); |
| 91 | |
| 92 | if ($this->gestionaService->getSyncStatus($region) === 1) { |
| 93 | return response()->json([ |
| 94 | 'success' => false, |
| 95 | 'message' => 'Synchronization already in progress.', |
| 96 | ], 400); |
| 97 | } |
| 98 | |
| 99 | try { |
| 100 | $phpBinary = '/usr/bin/php'; |
| 101 | |
| 102 | $artisanPath = escapeshellarg(base_path('artisan')); |
| 103 | |
| 104 | $command = sprintf( |
| 105 | '%s %s quotations:retry-failed %s %s > /dev/null 2>&1 &', |
| 106 | $phpBinary, |
| 107 | $artisanPath, |
| 108 | $name, |
| 109 | $region |
| 110 | ); |
| 111 | |
| 112 | exec($command, $output, $returnVar); |
| 113 | /*$comand = "cd /var/www/html && php artisan quotations:retry-failed $name $region > /dev/null 2>&1 &"; |
| 114 | exec($comand, $output, $returnVar);*/ |
| 115 | |
| 116 | return response()->json([ |
| 117 | 'success' => true, |
| 118 | 'message' => 'Synchronization started in background.', |
| 119 | ]); |
| 120 | } catch (\Exception $e) { |
| 121 | report(AppException::fromException($e, 'SYNC_ERROR_BUDGETS_EXCEPTION')); |
| 122 | $this->gestionaService->setSyncStatus(0, $region); |
| 123 | Log::channel('g3w')->error('Failed to start sync: '.$e->getMessage()); |
| 124 | |
| 125 | return response()->json([ |
| 126 | 'success' => false, |
| 127 | 'message' => $e->getMessage(), |
| 128 | ], 500); |
| 129 | } |
| 130 | |
| 131 | } |
| 132 | |
| 133 | /** |
| 134 | * @return JsonResponse |
| 135 | */ |
| 136 | public function syncBudgetsWorks() |
| 137 | { |
| 138 | $name = escapeshellarg((string) request()->header('Name')); |
| 139 | // Decode BEFORE quoting: the client sets the header with |
| 140 | // encodeURIComponent(), so an accented region reaches the spawned |
| 141 | // artisan command as 'Castell%C3%B3n' and matches no company row. |
| 142 | $region = escapeshellarg(urldecode((string) request()->header('Region'))); |
| 143 | |
| 144 | if ($this->gestionaService->getSyncStatus($region) === 1) { |
| 145 | return response()->json([ |
| 146 | 'success' => false, |
| 147 | 'message' => 'Synchronization already in progress.', |
| 148 | ], 400); |
| 149 | } |
| 150 | |
| 151 | try { |
| 152 | $phpBinary = '/usr/bin/php'; |
| 153 | |
| 154 | $artisanPath = escapeshellarg(base_path('artisan')); |
| 155 | |
| 156 | $command = sprintf( |
| 157 | '%s %s quotations:sync-work %s %s > /dev/null 2>&1 &', |
| 158 | $phpBinary, |
| 159 | $artisanPath, |
| 160 | $name, |
| 161 | $region |
| 162 | ); |
| 163 | |
| 164 | exec($command, $output, $returnVar); |
| 165 | /*$comand = "cd /var/www/html && php artisan quotations:sync-work $name $region > /dev/null 2>&1 &"; |
| 166 | exec($comand, $output, $returnVar);*/ |
| 167 | |
| 168 | return response()->json([ |
| 169 | 'success' => true, |
| 170 | 'message' => 'Synchronization started in background.', |
| 171 | ]); |
| 172 | } catch (\Exception $e) { |
| 173 | report(AppException::fromException($e, 'SYNC_BUDGETS_WORKS_EXCEPTION')); |
| 174 | $this->gestionaService->setSyncStatus(0, $region); |
| 175 | Log::channel('g3w')->error('Failed to start sync: '.$e->getMessage()); |
| 176 | |
| 177 | return response()->json([ |
| 178 | 'success' => false, |
| 179 | 'message' => $e->getMessage(), |
| 180 | ], 500); |
| 181 | } |
| 182 | |
| 183 | } |
| 184 | |
| 185 | /** |
| 186 | * Sincroniza un presupuesto por su ID. |
| 187 | * |
| 188 | * @return JsonResponse |
| 189 | */ |
| 190 | public function syncById($id) |
| 191 | { |
| 192 | $region = urldecode((string) request()->header('Region')); |
| 193 | if ($region === 'Catalunya') { |
| 194 | $region = 'Cataluña'; |
| 195 | } |
| 196 | |
| 197 | $result = $this->presupuestosService->syncById($id, $region); |
| 198 | |
| 199 | // Stamp here rather than inside the service: syncById() is also the |
| 200 | // per-budget worker for the batch loops, which stamp once at the end of |
| 201 | // the cycle. Only this route is a standalone manual import. |
| 202 | if ($result['success'] ?? false) { |
| 203 | $this->gestionaService->markG3wImport($region); |
| 204 | } |
| 205 | |
| 206 | return response()->json($result); |
| 207 | } |
| 208 | |
| 209 | /** |
| 210 | * Sincroniza un presupuesto por su ID. |
| 211 | * |
| 212 | * @param $id |
| 213 | * @return JsonResponse |
| 214 | */ |
| 215 | public function getCountFailedBudgets() |
| 216 | { |
| 217 | // Decoded: the client encodes the header, so "Castell%C3%B3n" would |
| 218 | // match no company and the failed-budget count would read 0. |
| 219 | $region = urldecode((string) request()->header('Region')); |
| 220 | |
| 221 | if ($region === 'Catalunya' || $region === "'Catalunya'") { |
| 222 | $region = 'Cataluña'; |
| 223 | } |
| 224 | |
| 225 | $company = TblCompanies::where('region', $region)->first(); |
| 226 | |
| 227 | if (! $company) { |
| 228 | return response()->json([ |
| 229 | 'countWarnings' => 0, |
| 230 | ], 200); |
| 231 | } |
| 232 | |
| 233 | $ids = TblG3WOrdersUpdateLogs::whereNotNull('sync_error_ids') |
| 234 | ->where('company_id', $company->company_id) |
| 235 | ->get(['sync_error_ids']); |
| 236 | |
| 237 | $allSyncErrorIds = []; |
| 238 | |
| 239 | foreach ($ids as $id) { |
| 240 | if (is_string($id->sync_error_ids)) { |
| 241 | $id->sync_error_ids = json_decode($id->sync_error_ids, true); |
| 242 | $allSyncErrorIds = array_merge($allSyncErrorIds, $id->sync_error_ids); |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | $allSyncErrorIds = array_unique($allSyncErrorIds); |
| 247 | |
| 248 | return response()->json([ |
| 249 | 'count' => count($allSyncErrorIds), |
| 250 | ]); |
| 251 | } |
| 252 | |
| 253 | public function syncByIds(Request $request) |
| 254 | { |
| 255 | $ids = $request['ids']; |
| 256 | $date = $request['date']; |
| 257 | $region = urldecode($request->header('Region')); |
| 258 | $user = urldecode($request->header('Name')); |
| 259 | |
| 260 | if ($region === 'Catalunya') { |
| 261 | $region = 'Cataluña'; |
| 262 | } |
| 263 | |
| 264 | return response()->json($this->presupuestosService->syncByIds($ids, $region, $date, $user)); |
| 265 | } |
| 266 | |
| 267 | /** |
| 268 | * FIRE-977: List resync run logs (for monitoring UI). |
| 269 | */ |
| 270 | public function listResyncRuns(Request $request) |
| 271 | { |
| 272 | try { |
| 273 | $query = TblG3WResyncRuns::query()->orderBy('run_at', 'desc'); |
| 274 | |
| 275 | if ($request->query('date')) { |
| 276 | $query->whereDate('run_at', $request->query('date')); |
| 277 | } |
| 278 | |
| 279 | // Region filter: query param takes priority, then header |
| 280 | $region = $request->query('region') ?: $request->header('Region'); |
| 281 | if ($region) { |
| 282 | $region = urldecode((string) $region); |
| 283 | if ($region === 'Catalunya') { |
| 284 | $region = 'Cataluña'; |
| 285 | } |
| 286 | $query->where('region', $region); |
| 287 | } |
| 288 | |
| 289 | $runs = $query->limit(500)->get(); |
| 290 | |
| 291 | return response()->json(['message' => 'OK', 'data' => $runs]); |
| 292 | } catch (\Exception $e) { |
| 293 | return response()->json(['message' => 'KO', 'error' => $e->getMessage()], 500); |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | /** |
| 298 | * FIRE-977: Get resync summary (total failed, last run info). |
| 299 | * |
| 300 | * `total_failed` only counts presupuesto IDs whose latest known sync |
| 301 | * error is *actionable* — i.e. not a G3W "no se ha encontrado el |
| 302 | * presupuesto" 404 (FIRE-982 terminal pattern) and not a quotation |
| 303 | * that has already been deleted on the FST side. Without this filter |
| 304 | * the card on the sync-budget-monitor page inflates indefinitely as |
| 305 | * deleted/missing IDs linger in tbl_g3w_orders_update_logs.sync_error_ids |
| 306 | * (the cron only scrubs an ID once it actually retries and hits the |
| 307 | * terminal error, which can lag by days when the queue is large). |
| 308 | */ |
| 309 | public function getResyncSummary(Request $request) |
| 310 | { |
| 311 | try { |
| 312 | $region = urldecode((string) $request->header('Region', '')); |
| 313 | |
| 314 | if ($region === 'Catalunya') { |
| 315 | $region = 'Cataluña'; |
| 316 | } |
| 317 | |
| 318 | $allFailedIds = $this->collectAllFailedIds($region); |
| 319 | |
| 320 | if (empty($allFailedIds)) { |
| 321 | $totalFailed = 0; |
| 322 | } else { |
| 323 | // Map ID => most recent error message so we can classify each one. |
| 324 | $latestErrorPerId = $this->getLatestErrorPerId($region); |
| 325 | |
| 326 | // Filter 1: drop terminal "presupuesto no encontrado" errors — |
| 327 | // G3W will never return data for these IDs, they are not real |
| 328 | // sync work for the user to action. |
| 329 | $actionableIds = array_values(array_filter( |
| 330 | $allFailedIds, |
| 331 | fn ($id) => ! $this->isTerminalNotFoundError( |
| 332 | $latestErrorPerId[(string) $id] ?? null |
| 333 | ) |
| 334 | )); |
| 335 | |
| 336 | // Filter 2: drop IDs that no longer exist as active quotations |
| 337 | // (moved to tbl_quotations_deleted or hard-deleted on the FST |
| 338 | // side). They aren't a sync error a human can act on anymore. |
| 339 | if (! empty($actionableIds)) { |
| 340 | $idsInt = array_map('intval', $actionableIds); |
| 341 | $existing = TblQuotations::whereIn('internal_quote_id', $idsInt) |
| 342 | ->pluck('internal_quote_id') |
| 343 | ->map(fn ($id) => (int) $id) |
| 344 | ->all(); |
| 345 | $existingSet = array_flip($existing); |
| 346 | $actionableIds = array_values(array_filter( |
| 347 | $actionableIds, |
| 348 | fn ($id) => isset($existingSet[(int) $id]) |
| 349 | )); |
| 350 | } |
| 351 | |
| 352 | $totalFailed = count($actionableIds); |
| 353 | } |
| 354 | |
| 355 | $lastRunQuery = TblG3WResyncRuns::orderBy('run_at', 'desc'); |
| 356 | if ($region) { |
| 357 | $lastRunQuery->where('region', $region); |
| 358 | } |
| 359 | $lastRun = $lastRunQuery->first(); |
| 360 | |
| 361 | return response()->json([ |
| 362 | 'message' => 'OK', |
| 363 | 'data' => [ |
| 364 | 'total_failed' => $totalFailed, |
| 365 | 'last_run_at' => $lastRun?->run_at, |
| 366 | 'last_run_success' => $lastRun?->success_count ?? 0, |
| 367 | 'last_run_failed' => $lastRun?->failed_count ?? 0, |
| 368 | ], |
| 369 | ]); |
| 370 | } catch (\Exception $e) { |
| 371 | return response()->json(['message' => 'KO', 'error' => $e->getMessage()], 500); |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | /** |
| 376 | * Collect distinct failed presupuesto IDs from |
| 377 | * tbl_g3w_orders_update_logs.sync_error_ids, optionally region-filtered |
| 378 | * via the company → region join. Returns IDs as strings so they key |
| 379 | * cleanly against the per-ID error map. |
| 380 | * |
| 381 | * @return list<string> |
| 382 | */ |
| 383 | private function collectAllFailedIds(?string $region): array |
| 384 | { |
| 385 | $companiesQuery = TblCompanies::query(); |
| 386 | if ($region) { |
| 387 | $companiesQuery->where('region', $region); |
| 388 | } |
| 389 | $companies = $companiesQuery->get(); |
| 390 | |
| 391 | $idSet = []; |
| 392 | foreach ($companies as $company) { |
| 393 | $logs = TblG3WOrdersUpdateLogs::whereNotNull('sync_error_ids') |
| 394 | ->where('company_id', $company->company_id) |
| 395 | ->get(['sync_error_ids']); |
| 396 | |
| 397 | foreach ($logs as $log) { |
| 398 | if (! is_string($log->sync_error_ids)) { |
| 399 | continue; |
| 400 | } |
| 401 | $decoded = json_decode($log->sync_error_ids, true); |
| 402 | if (! is_array($decoded)) { |
| 403 | continue; |
| 404 | } |
| 405 | foreach ($decoded as $id) { |
| 406 | $idSet[(string) $id] = true; |
| 407 | } |
| 408 | } |
| 409 | } |
| 410 | |
| 411 | return array_keys($idSet); |
| 412 | } |
| 413 | |
| 414 | /** |
| 415 | * Build a map of presupuesto ID => most recent error message from |
| 416 | * tbl_g3w_resync_runs.failed_errors_json. Runs are iterated ascending |
| 417 | * by run_at so the latest entry for any given ID wins. |
| 418 | * |
| 419 | * @return array<string, string> |
| 420 | */ |
| 421 | private function getLatestErrorPerId(?string $region): array |
| 422 | { |
| 423 | $latestErrorPerId = []; |
| 424 | |
| 425 | $query = TblG3WResyncRuns::query() |
| 426 | ->whereNotNull('failed_errors_json') |
| 427 | ->orderBy('run_at', 'asc'); |
| 428 | |
| 429 | if ($region) { |
| 430 | $query->where('region', $region); |
| 431 | } |
| 432 | |
| 433 | $query->chunk(200, function ($runs) use (&$latestErrorPerId) { |
| 434 | foreach ($runs as $run) { |
| 435 | $errors = is_string($run->failed_errors_json) |
| 436 | ? json_decode($run->failed_errors_json, true) |
| 437 | : $run->failed_errors_json; |
| 438 | |
| 439 | if (! is_array($errors)) { |
| 440 | continue; |
| 441 | } |
| 442 | |
| 443 | foreach ($errors as $id => $message) { |
| 444 | $latestErrorPerId[(string) $id] = (string) $message; |
| 445 | } |
| 446 | } |
| 447 | }); |
| 448 | |
| 449 | return $latestErrorPerId; |
| 450 | } |
| 451 | |
| 452 | /** |
| 453 | * Mirror of QuotationsRetryFailed::isTerminalError (FIRE-982). If these |
| 454 | * patterns ever drift, update BOTH call sites — the cron uses the same |
| 455 | * list to scrub terminal IDs out of sync_error_ids when it retries |
| 456 | * them, and this summary endpoint uses it to hide them from the count. |
| 457 | */ |
| 458 | private function isTerminalNotFoundError(?string $error): bool |
| 459 | { |
| 460 | if ($error === null || $error === '') { |
| 461 | return false; |
| 462 | } |
| 463 | |
| 464 | return str_contains($error, 'No se ha encontrado el presupuesto') |
| 465 | || str_contains($error, 'No se encuentra el presupuesto con ID en G3W'); |
| 466 | } |
| 467 | |
| 468 | public function downloadSyncBudgetsWorks() |
| 469 | { |
| 470 | try { |
| 471 | $region = urldecode((string) request()->header('Region')); |
| 472 | |
| 473 | if ($region === 'Catalunya') { |
| 474 | $region = 'Cataluña'; |
| 475 | } |
| 476 | |
| 477 | $companyId = TblCompanies::where('region', $region)->first()->company_id; |
| 478 | $totalDays = 90; |
| 479 | $dataResponse = []; |
| 480 | $alreadyG3wBudgets = []; |
| 481 | |
| 482 | for ($i = 0; $i < $totalDays; $i++) { |
| 483 | $currentDate = Carbon::today()->subDays($i); |
| 484 | $dateStr = $currentDate->format('Y-m-d'); |
| 485 | |
| 486 | $g3wBudgets = $this->gestionaService->getBudgetsByDay($dateStr, $region); |
| 487 | if (is_string($g3wBudgets)) { |
| 488 | $g3wBudgets = json_decode($g3wBudgets, true); |
| 489 | } |
| 490 | |
| 491 | $g3wBudgetIds = array_map(fn (array $item) => $item['ID'], $g3wBudgets); |
| 492 | |
| 493 | $newG3wBudgetIds = array_diff($g3wBudgetIds, $alreadyG3wBudgets); |
| 494 | $alreadyG3wBudgets = array_merge($alreadyG3wBudgets, $newG3wBudgetIds); |
| 495 | $countG3wBudgets = count($newG3wBudgetIds); |
| 496 | |
| 497 | // FIRE-1476: CLM (22) merged into Madrid — no dual-company override. |
| 498 | $fstBudgets = TblQuotations::where('company_id', $companyId) |
| 499 | ->where(function ($query): void { |
| 500 | $query->where('sync_import', 1) |
| 501 | ->orWhere('sync_import_edited', 1); |
| 502 | }) |
| 503 | ->whereDate('created_at', $dateStr) |
| 504 | ->pluck('internal_quote_id') |
| 505 | ->toArray(); |
| 506 | |
| 507 | $countFstBudgets = count($fstBudgets); |
| 508 | |
| 509 | $missingIds = array_diff($newG3wBudgetIds, $fstBudgets); |
| 510 | |
| 511 | $existingIdsQuery = TblQuotations::where('company_id', $companyId); |
| 512 | |
| 513 | $existingIds = $existingIdsQuery |
| 514 | ->where(function ($query): void { |
| 515 | $query->where('sync_import', 1) |
| 516 | ->orWhere('sync_import_edited', 1); |
| 517 | }) |
| 518 | ->whereIn('internal_quote_id', $missingIds) |
| 519 | ->pluck('internal_quote_id') |
| 520 | ->toArray(); |
| 521 | |
| 522 | $finalMissingIds = array_diff($missingIds, $existingIds); |
| 523 | |
| 524 | $filteredFstBudgets = array_filter($fstBudgets, fn ($value) => $value !== null); |
| 525 | $duplicatedFst = []; |
| 526 | if (! empty($filteredFstBudgets)) { |
| 527 | $counts = array_count_values($filteredFstBudgets); |
| 528 | $duplicatedFst = array_keys(array_filter($counts, fn ($count) => $count > 1)); |
| 529 | } |
| 530 | |
| 531 | $deletedIds = array_diff($fstBudgets, $newG3wBudgetIds); |
| 532 | foreach ($deletedIds as $key => $id) { |
| 533 | $deleted = $this->gestionaService->checkDeleted($id, $region); |
| 534 | if (! $deleted) { |
| 535 | unset($deletedIds[$key]); |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | $g3wOrdersUpdateLogs = TblG3WOrdersUpdateLogs::where('company_id', $companyId) |
| 540 | ->whereDate('ended_at', $dateStr) |
| 541 | ->where('processed_by', 'System') |
| 542 | ->get(); |
| 543 | |
| 544 | $syncs = $g3wOrdersUpdateLogs->count(); |
| 545 | |
| 546 | $syncErrorIds = $g3wOrdersUpdateLogs->flatMap(function ($item): array { |
| 547 | $ids = $item->sync_error_ids; |
| 548 | if (is_string($ids)) { |
| 549 | $decoded = json_decode($ids, true); |
| 550 | $ids = is_array($decoded) ? $decoded : explode(',', $ids); |
| 551 | } |
| 552 | |
| 553 | return (array) $ids; |
| 554 | }) |
| 555 | ->filter() |
| 556 | ->unique() |
| 557 | ->toArray(); |
| 558 | |
| 559 | $countSyncErrorIds = count(array_values(array_unique($syncErrorIds))); |
| 560 | |
| 561 | $dataResponse[] = [ |
| 562 | 'date' => $dateStr, |
| 563 | 'g3wBudgets' => array_values($newG3wBudgetIds), |
| 564 | 'countG3wBudgets' => $countG3wBudgets, |
| 565 | 'fstBudgets' => $fstBudgets, |
| 566 | 'countfstBudgets' => $countFstBudgets, |
| 567 | 'missingIds' => array_values($finalMissingIds), |
| 568 | 'duplicatedFst' => $duplicatedFst, |
| 569 | 'deletedIds' => array_values($deletedIds), |
| 570 | 'syncs' => $syncs, |
| 571 | 'syncErrorIds' => $syncErrorIds, |
| 572 | 'countSyncErrorIds' => $countSyncErrorIds, |
| 573 | ]; |
| 574 | } |
| 575 | |
| 576 | usort($dataResponse, fn (array $a, array $b) => strtotime($b['date']) - strtotime($a['date'])); |
| 577 | |
| 578 | return response(['data' => $dataResponse]); |
| 579 | |
| 580 | } catch (\Exception $e) { |
| 581 | report(AppException::fromException($e, 'DOWNLOAD_SYNC_BUDGETS_WORKS_EXCEPTION')); |
| 582 | Log::error('Error en downloadSyncBudgetsWorks: '.$e->getMessage()); |
| 583 | |
| 584 | if ($e->getMessage() == 'API URL is not defined.') { |
| 585 | return response()->json([ |
| 586 | 'error' => 'KO', |
| 587 | 'message' => 'La conexión con la API de G3W no está configurada. Por favor, configúrala en los ajustes de la empresa.', |
| 588 | ], 200); |
| 589 | } |
| 590 | |
| 591 | return response()->json([ |
| 592 | 'message' => 'Error interno del servidor', |
| 593 | ], 500); |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | /** |
| 598 | * FIRE-1170: GET /api/g3w/bulk-sync/regions |
| 599 | * Returns the regions a bulk-sync can target. Admin-only — gated at the |
| 600 | * route level by `require.admin`. The UI uses this to populate the |
| 601 | * "Regiones" multi-select on init; the "Todas las regiones" sticky option |
| 602 | * is purely client-side and not returned here. |
| 603 | */ |
| 604 | public function bulkSyncRegions(): JsonResponse |
| 605 | { |
| 606 | return response()->json([ |
| 607 | 'data' => $this->presupuestosService->listBulkSyncRegions(), |
| 608 | ]); |
| 609 | } |
| 610 | |
| 611 | /** |
| 612 | * FIRE-1170: POST /api/g3w/bulk-sync |
| 613 | * Kick off a bulk re-sync run across regions × date range × selected |
| 614 | * fields, optionally suppressing the per-toggle approval-notification |
| 615 | * side effects. Always async — returns a `run_id` for the UI to poll |
| 616 | * via `bulkSyncStatus`. |
| 617 | * |
| 618 | * Validation cap: 90-day max range — wider than that almost always |
| 619 | * means someone picked the wrong "desde" by mistake. The G3W API can |
| 620 | * handle it but the wall-time would be hours. |
| 621 | */ |
| 622 | public function bulkSync(Request $request): JsonResponse |
| 623 | { |
| 624 | $data = $request->validate([ |
| 625 | 'regions' => 'required|array|min:1', |
| 626 | 'regions.*' => 'string|max:50', |
| 627 | 'date_from' => 'required|date_format:Y-m-d', |
| 628 | 'date_to' => 'required|date_format:Y-m-d|after_or_equal:date_from', |
| 629 | 'fields' => 'required|array|min:1', |
| 630 | 'fields.*' => 'string|in:'.implode(',', array_keys(PresupuestosService::BULK_SYNC_FIELD_MAP)), |
| 631 | 'send_approval_ops' => 'sometimes|boolean', |
| 632 | 'send_approval_fin' => 'sometimes|boolean', |
| 633 | ]); |
| 634 | |
| 635 | $from = Carbon::parse($data['date_from']); |
| 636 | $to = Carbon::parse($data['date_to']); |
| 637 | if ($from->diffInDays($to) > 90) { |
| 638 | return response()->json([ |
| 639 | 'message' => 'KO', |
| 640 | 'error' => 'El rango máximo es de 90 días. Reduce el periodo o ejecuta el bulk-sync en varias tandas.', |
| 641 | ], 422); |
| 642 | } |
| 643 | |
| 644 | $user = $request->user(); |
| 645 | $triggeredBy = $user?->name ?? 'System'; |
| 646 | $triggeredById = $user?->id; |
| 647 | |
| 648 | $suppressOps = ! ($data['send_approval_ops'] ?? true); |
| 649 | $suppressFin = ! ($data['send_approval_fin'] ?? true); |
| 650 | // ^^^ payload semantics: the UI sends `send_approval_*` (toggle ON |
| 651 | // means notify; default ON). We store the *suppression* (opposite) |
| 652 | // on the run row so the worker can read it directly. The |
| 653 | // negation here is the only place the polarity flips. |
| 654 | |
| 655 | $run = TblG3WBulkSyncRuns::create([ |
| 656 | 'triggered_by' => $triggeredBy, |
| 657 | 'triggered_by_id' => $triggeredById, |
| 658 | 'regions' => array_values($data['regions']), |
| 659 | 'date_from' => $data['date_from'], |
| 660 | 'date_to' => $data['date_to'], |
| 661 | 'fields' => array_values($data['fields']), |
| 662 | 'suppress_approval_ops' => $suppressOps, |
| 663 | 'suppress_approval_fin' => $suppressFin, |
| 664 | 'started_at' => now(), |
| 665 | ]); |
| 666 | |
| 667 | // Fire-and-forget pattern (mirrors syncByDate at line 51). Both |
| 668 | // QUEUE_CONNECTION=sync and `dispatchAfterResponse` keep the worker |
| 669 | // hostage on Apache mod_php — the response only flushes when the PHP |
| 670 | // script ends. Forking a true background process via exec() lets the |
| 671 | // POST return in milliseconds so the frontend can start polling. |
| 672 | // |
| 673 | // PHP_BINARY is empty under Apache mod_php (it's a CLI-only constant), |
| 674 | // so PhpExecutableFinder is the reliable resolution path. Fallbacks |
| 675 | // cover both Debian-style (/usr/bin/php) and source-built |
| 676 | // (/usr/local/bin/php) Docker images. |
| 677 | $phpBinary = (new PhpExecutableFinder)->find(false) |
| 678 | ?: (is_executable('/usr/local/bin/php') ? '/usr/local/bin/php' : '/usr/bin/php'); |
| 679 | $artisanPath = escapeshellarg(base_path('artisan')); |
| 680 | $fieldsArg = escapeshellarg(implode(',', array_values($data['fields']))); |
| 681 | $dateFromArg = escapeshellarg($data['date_from']); |
| 682 | $dateToArg = escapeshellarg($data['date_to']); |
| 683 | $opsArg = $suppressOps ? 1 : 0; |
| 684 | $finArg = $suppressFin ? 1 : 0; |
| 685 | |
| 686 | foreach ($data['regions'] as $region) { |
| 687 | $regionArg = escapeshellarg($region); |
| 688 | $logFile = storage_path("logs/g3w-bulk-spawn-{$run->id}-".preg_replace('/[^a-zA-Z0-9]/', '_', $region).'.log'); |
| 689 | // Detach via `nohup setsid` so the artisan keeps running after the |
| 690 | // Apache worker that fired this exec is recycled. Redirect both |
| 691 | // streams to a per-run log file so silent spawn failures are |
| 692 | // recoverable instead of vanishing. |
| 693 | $command = sprintf( |
| 694 | 'nohup setsid %s %s bulk-sync:run %d %s %s %s %s %d %d > %s 2>&1 < /dev/null &', |
| 695 | $phpBinary, |
| 696 | $artisanPath, |
| 697 | $run->id, |
| 698 | $regionArg, |
| 699 | $dateFromArg, |
| 700 | $dateToArg, |
| 701 | $fieldsArg, |
| 702 | $opsArg, |
| 703 | $finArg, |
| 704 | escapeshellarg($logFile) |
| 705 | ); |
| 706 | exec($command, $execOutput, $execCode); |
| 707 | Log::channel('g3w')->info('Bulk-sync exec', [ |
| 708 | 'run_id' => $run->id, |
| 709 | 'region' => $region, |
| 710 | 'exit_code' => $execCode, |
| 711 | 'output' => $execOutput, |
| 712 | 'cmd' => $command, |
| 713 | ]); |
| 714 | } |
| 715 | |
| 716 | Log::channel('g3w')->info('Bulk-sync run dispatched', [ |
| 717 | 'run_id' => $run->id, |
| 718 | 'regions' => $data['regions'], |
| 719 | 'fields' => $data['fields'], |
| 720 | 'triggered_by' => $triggeredBy, |
| 721 | ]); |
| 722 | |
| 723 | return response()->json([ |
| 724 | 'message' => 'OK', |
| 725 | 'run_id' => $run->id, |
| 726 | ]); |
| 727 | } |
| 728 | |
| 729 | /** |
| 730 | * FIRE-1170: GET /api/g3w/bulk-sync/{runId} |
| 731 | * Poll endpoint. The UI hits this every 2-3s while `ended_at` is null and |
| 732 | * shows the live totals. Once `ended_at` is set the polling stops and the |
| 733 | * result summary is rendered. |
| 734 | */ |
| 735 | public function bulkSyncStatus(int $runId): JsonResponse |
| 736 | { |
| 737 | $run = TblG3WBulkSyncRuns::find($runId); |
| 738 | if (! $run) { |
| 739 | return response()->json(['message' => 'KO', 'error' => 'Run not found'], 404); |
| 740 | } |
| 741 | |
| 742 | return response()->json([ |
| 743 | 'data' => [ |
| 744 | 'id' => $run->id, |
| 745 | 'triggered_by' => $run->triggered_by, |
| 746 | 'regions' => $run->regions, |
| 747 | 'date_from' => $run->date_from?->format('Y-m-d'), |
| 748 | 'date_to' => $run->date_to?->format('Y-m-d'), |
| 749 | 'fields' => $run->fields, |
| 750 | 'suppress_approval_ops' => $run->suppress_approval_ops, |
| 751 | 'suppress_approval_fin' => $run->suppress_approval_fin, |
| 752 | 'started_at' => $run->started_at?->toIso8601String(), |
| 753 | 'ended_at' => $run->ended_at?->toIso8601String(), |
| 754 | 'total_g3w_budgets' => $run->total_g3w_budgets, |
| 755 | 'updated_count' => $run->updated_count, |
| 756 | 'created_count' => $run->created_count, |
| 757 | 'skipped_count' => $run->skipped_count, |
| 758 | 'error_count' => $run->error_count, |
| 759 | 'errors_json' => $run->errors_json ?? [], |
| 760 | ], |
| 761 | ]); |
| 762 | } |
| 763 | } |