Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
34.51% |
117 / 339 |
|
56.25% |
9 / 16 |
CRAP | |
0.00% |
0 / 1 |
| IfexController | |
34.51% |
117 / 339 |
|
56.25% |
9 / 16 |
2212.68 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
1 | |||
| resolveSyncRange | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
3 | |||
| autoRecoveryFrom | |
100.00% |
18 / 18 |
|
100.00% |
1 / 1 |
4 | |||
| readLastCoveredDate | |
0.00% |
0 / 6 |
|
0.00% |
0 / 1 |
6 | |||
| normalizeSyncDate | |
100.00% |
12 / 12 |
|
100.00% |
1 / 1 |
5 | |||
| normalizeAcceptanceDate | |
100.00% |
9 / 9 |
|
100.00% |
1 / 1 |
4 | |||
| budgetsInWindow | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
| apiUrl | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
3 | |||
| request | |
0.00% |
0 / 33 |
|
0.00% |
0 / 1 |
132 | |||
| syncQuotations | |
0.00% |
0 / 53 |
|
0.00% |
0 / 1 |
110 | |||
| budgetTypeForSeries | |
100.00% |
6 / 6 |
|
100.00% |
1 / 1 |
5 | |||
| logChanges | |
47.06% |
8 / 17 |
|
0.00% |
0 / 1 |
17.50 | |||
| deriveSentDate | |
100.00% |
11 / 11 |
|
100.00% |
1 / 1 |
6 | |||
| resolveAcceptance | |
100.00% |
18 / 18 |
|
100.00% |
1 / 1 |
5 | |||
| createQuotation | |
0.00% |
0 / 75 |
|
0.00% |
0 / 1 |
90 | |||
| updateQuotation | |
0.00% |
0 / 44 |
|
0.00% |
0 / 1 |
110 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Http\Controllers; |
| 4 | |
| 5 | use App\Exceptions\AppException; |
| 6 | use App\Models\TblIfexLastUpdate; |
| 7 | use App\Models\TblQuotations; |
| 8 | use App\Models\TblQuotationsLog; |
| 9 | use App\Services\IfexReference; |
| 10 | use App\Services\PresupuestosService; |
| 11 | use Carbon\Carbon; |
| 12 | use Illuminate\Support\Facades\Log; |
| 13 | |
| 14 | class IfexController extends Controller |
| 15 | { |
| 16 | protected $statusNormalize; |
| 17 | |
| 18 | public function __construct(protected PresupuestosService $presupuestosService) |
| 19 | { |
| 20 | // FIRE-1672: 'Finalizado' now maps to 12 (En curso), not 3 (Aceptado). |
| 21 | // IFEX's Aceptado count was 676 while Titan reported 1,370 because |
| 22 | // Finalizado (completed) was being counted as accepted — that's what |
| 23 | // put €19.54M into the accepted report against IFEX's €3.36M. A |
| 24 | // finalized budget was accepted earlier; if IFEX still holds a real |
| 25 | // fechaAceptacion the next sync will separately land it on Aceptado. |
| 26 | // Never invent an acceptance date from a completion timestamp. |
| 27 | $this->statusNormalize = [ |
| 28 | 'Oportunidad' => 1, // Oportunidad => Nuevo |
| 29 | 'Pendiente' => 11, // Pendiente => Listo para enviar |
| 30 | 'Pendiente Cliente' => 2, // Pendiente Cliente => Enviado |
| 31 | 'Aceptado' => 3, // Aceptado => Aceptado (requires fechaAceptacion) |
| 32 | 'En ejecución' => 12, // En ejecución => En curso |
| 33 | 'Rechazado' => 4, // Rechazado => Rechazado |
| 34 | 'Anulado' => 5, // Anulado => Anulado |
| 35 | 'Finalizado' => 12, // Finalizado => En curso (FIRE-1672) |
| 36 | ]; |
| 37 | |
| 38 | } |
| 39 | |
| 40 | /** |
| 41 | * Resolve the fechainicio/fechafin window for a sync run. |
| 42 | * |
| 43 | * Precedence per side: explicit argument (console `--from`/`--to`) → request |
| 44 | * query (`fechainicio`/`fechafin`, or `from`/`to`) → auto-recovery fallback. |
| 45 | * Both are validated to Y-m-d before they reach the URL, so a typo fails |
| 46 | * loudly here instead of silently asking IFEX for a nonsense window. |
| 47 | * |
| 48 | * FIRE-1673 auto-recovery: when the cron passes no --from, `from` falls back |
| 49 | * to `tbl_ifex_last_update.last_date` (the `to` of the last successful run) |
| 50 | * — not `today`. That way, if the sync has been down for N days, the next |
| 51 | * successful run replays the missing window instead of losing it. The |
| 52 | * window is capped at `services.ifex.sync_catchup_max_days` from today so |
| 53 | * a long stall doesn't pull half a year in one request. `to` still defaults |
| 54 | * to today; when no successful run has ever completed, `from` also |
| 55 | * defaults to today (preserves single-day behaviour on a fresh install). |
| 56 | * |
| 57 | * @return array{0: string, 1: string} Both as Y-m-d |
| 58 | */ |
| 59 | private function resolveSyncRange(?string $from, ?string $to): array |
| 60 | { |
| 61 | $today = Carbon::now()->format('Y-m-d'); |
| 62 | $request = request(); |
| 63 | |
| 64 | $toResolved = $this->normalizeSyncDate( |
| 65 | $to ?? $request?->query('fechafin') ?? $request?->query('to'), |
| 66 | 'fechafin' |
| 67 | ) ?? $today; |
| 68 | |
| 69 | $fromResolved = $this->normalizeSyncDate( |
| 70 | $from ?? $request?->query('fechainicio') ?? $request?->query('from'), |
| 71 | 'fechainicio' |
| 72 | ); |
| 73 | |
| 74 | if ($fromResolved === null) { |
| 75 | $fromResolved = $this->autoRecoveryFrom($toResolved); |
| 76 | } |
| 77 | |
| 78 | // An inverted window returns nothing from IFEX, which reads as "no |
| 79 | // budgets to sync" — fail instead of reporting a successful no-op. |
| 80 | if ($fromResolved > $toResolved) { |
| 81 | throw new \InvalidArgumentException( |
| 82 | "IFEX sync window is inverted: fechainicio {$fromResolved} is after fechafin {$toResolved}." |
| 83 | ); |
| 84 | } |
| 85 | |
| 86 | return [$fromResolved, $toResolved]; |
| 87 | } |
| 88 | |
| 89 | /** |
| 90 | * FIRE-1673: derive `from` for the auto-recovery cron path. |
| 91 | * |
| 92 | * Uses the last successfully covered date (stored as Y-m-d in |
| 93 | * `tbl_ifex_last_update.last_date`) and caps the resulting window at |
| 94 | * `sync_catchup_max_days` from today. If we've never had a successful run |
| 95 | * — fresh install, or the row hasn't been seeded — falls back to today so |
| 96 | * behaviour matches the pre-1673 single-day sync. |
| 97 | */ |
| 98 | private function autoRecoveryFrom(string $to): string |
| 99 | { |
| 100 | $today = Carbon::now()->format('Y-m-d'); |
| 101 | $lastCovered = $this->readLastCoveredDate(); |
| 102 | |
| 103 | if (empty($lastCovered)) { |
| 104 | // Fresh install or DB blip → preserve the pre-1673 single-day-of- |
| 105 | // today default. `to` was preserved as-is by resolveSyncRange, so |
| 106 | // returning today here keeps an operator's `--to=<past>` inverted |
| 107 | // (correct) instead of silently degrading to a single-day sync at |
| 108 | // whatever they typed. |
| 109 | return $today; |
| 110 | } |
| 111 | |
| 112 | try { |
| 113 | $from = Carbon::parse($lastCovered)->format('Y-m-d'); |
| 114 | } catch (\Throwable) { |
| 115 | Log::channel('ifex')->warning( |
| 116 | "IFEX sync: last_date '{$lastCovered}' is unparseable — defaulting to single-day window." |
| 117 | ); |
| 118 | |
| 119 | return $today; |
| 120 | } |
| 121 | |
| 122 | $maxDays = (int) config('services.ifex.sync_catchup_max_days', 30); |
| 123 | $earliest = Carbon::parse($to)->subDays(max($maxDays, 1))->format('Y-m-d'); |
| 124 | |
| 125 | if ($from < $earliest) { |
| 126 | Log::channel('ifex')->warning( |
| 127 | "IFEX sync: last_date {$from} is more than {$maxDays} days behind — capping window at {$earliest}." |
| 128 | ); |
| 129 | $from = $earliest; |
| 130 | } |
| 131 | |
| 132 | return $from; |
| 133 | } |
| 134 | |
| 135 | /** |
| 136 | * FIRE-1673: read `tbl_ifex_last_update.last_date` for the auto-recovery |
| 137 | * fallback. Extracted so the resolveSyncRange unit tests can stub it via |
| 138 | * reflection without booting a database, and so a DB blip degrades the |
| 139 | * sync to single-day mode instead of crashing it outright. |
| 140 | */ |
| 141 | protected function readLastCoveredDate(): ?string |
| 142 | { |
| 143 | try { |
| 144 | return TblIfexLastUpdate::where('id', 1)->value('last_date'); |
| 145 | } catch (\Throwable $e) { |
| 146 | Log::channel('ifex')->warning( |
| 147 | 'IFEX sync: could not read last_date, defaulting to single-day window: '.$e->getMessage() |
| 148 | ); |
| 149 | |
| 150 | return null; |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | /** |
| 155 | * Validate one side of the window. Empty/absent → null (caller defaults to |
| 156 | * today); anything present must be a real Y-m-d date. |
| 157 | */ |
| 158 | private function normalizeSyncDate($value, string $label): ?string |
| 159 | { |
| 160 | $value = trim((string) ($value ?? '')); |
| 161 | |
| 162 | if ($value === '') { |
| 163 | return null; |
| 164 | } |
| 165 | |
| 166 | $parsed = null; |
| 167 | try { |
| 168 | $parsed = Carbon::createFromFormat('Y-m-d', $value); |
| 169 | } catch (\Throwable) { |
| 170 | $parsed = null; |
| 171 | } |
| 172 | |
| 173 | // The round-trip comparison also rejects overflow values that |
| 174 | // createFromFormat happily rolls over (e.g. 2026-13-45 → 2027-02-14). |
| 175 | if (! $parsed || $parsed->format('Y-m-d') !== $value) { |
| 176 | throw new \InvalidArgumentException( |
| 177 | "IFEX sync {$label} must be a date in Y-m-d format, got '{$value}'." |
| 178 | ); |
| 179 | } |
| 180 | |
| 181 | return $parsed->format('Y-m-d'); |
| 182 | } |
| 183 | |
| 184 | /** |
| 185 | * IFEX `fechaAceptacion` → `acceptance_date` (nullable datetime). |
| 186 | * |
| 187 | * Nothing is ever invented here: no date in the payload means no date in |
| 188 | * the column. This only separates "genuinely empty" from "a date that |
| 189 | * arrived in a shape the column can't take": |
| 190 | * |
| 191 | * - absent / null / '' / whitespace / a zero-date → NULL, i.e. empty |
| 192 | * - a real date in any parseable shape → stored as a proper datetime, so |
| 193 | * a formatting difference never loses the date |
| 194 | * - non-empty but unparseable → NULL + a warning, because the raw value |
| 195 | * would land in a `datetime` column as 0000-00-00 (or be rejected |
| 196 | * outright under strict mode) |
| 197 | */ |
| 198 | private function normalizeAcceptanceDate($value, $codigo = null): ?string |
| 199 | { |
| 200 | $raw = trim((string) ($value ?? '')); |
| 201 | |
| 202 | // Zero-dates are MySQL's "no date" — same representations the G3W sync |
| 203 | // normalises in PresupuestosService::normalizeG3wAcceptance(). |
| 204 | if ($raw === '' || in_array($raw, ['0000-00-00', '0000/00/00', '0000-00-00 00:00:00'], true)) { |
| 205 | return null; |
| 206 | } |
| 207 | |
| 208 | try { |
| 209 | return Carbon::parse($raw)->format('Y-m-d H:i:s'); |
| 210 | } catch (\Throwable) { |
| 211 | Log::channel('ifex')->warning( |
| 212 | 'IFEX '.($codigo ?? '?').": unparseable fechaAceptacion '{$raw}' — storing acceptance_date as NULL." |
| 213 | ); |
| 214 | |
| 215 | return null; |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | /** |
| 220 | * Raw IFEX budgets created or edited in a window (read-only), for tools |
| 221 | * that need IFEX's own data without running the sync, e.g. the |
| 222 | * acceptance-date backfill reading fechaAceptacion. |
| 223 | * |
| 224 | * @return array<int, array<string, mixed>> |
| 225 | */ |
| 226 | public function budgetsInWindow(string $from, string $to): array |
| 227 | { |
| 228 | return (array) $this->request('GET', 'presupuestos/creados-editados' |
| 229 | .'?fechainicio='.urlencode($from).'&fechafin='.urlencode($to)); |
| 230 | } |
| 231 | |
| 232 | /** |
| 233 | * Absolute IFEX URL for an endpoint path. |
| 234 | * |
| 235 | * Sentry PHP-LARAVEL-7R: with IFEX_API_URL unset the URL was just |
| 236 | * "presupuestos/creados-editados?..." and cURL failed with "Could not |
| 237 | * resolve host: presupuestos". Fail with a message that names the setting |
| 238 | * instead, and join with exactly one slash so a base URL with or without |
| 239 | * a trailing "/" both work. |
| 240 | * |
| 241 | * FIRE-1258: config() not env() — env() returns null once |
| 242 | * `php artisan config:cache` has run. |
| 243 | */ |
| 244 | protected function apiUrl(string $endpoint): string |
| 245 | { |
| 246 | $base = rtrim((string) config('services.ifex.url', ''), '/'); |
| 247 | |
| 248 | if (! in_array(parse_url($base, PHP_URL_SCHEME), ['http', 'https'], true) |
| 249 | || ! parse_url($base, PHP_URL_HOST)) { |
| 250 | throw new \RuntimeException( |
| 251 | 'IFEX_API_URL is not configured (got "'.$base.'"). Set it to the absolute IFEX API URL ' |
| 252 | .'(https://...) in .env and re-run `php artisan config:cache`.' |
| 253 | ); |
| 254 | } |
| 255 | |
| 256 | return $base.'/'.ltrim($endpoint, '/'); |
| 257 | } |
| 258 | |
| 259 | protected function request($method, $endpoint, array $data = []) |
| 260 | { |
| 261 | try { |
| 262 | // $this->getCredentials($region); |
| 263 | |
| 264 | /*if (!$this->apiUrl) { |
| 265 | throw new \Exception('API URL is not defined.'); |
| 266 | } |
| 267 | |
| 268 | if (!$this->accessToken) { |
| 269 | $this->auth($region); |
| 270 | }*/ |
| 271 | $url = $this->apiUrl((string) $endpoint); |
| 272 | $curl = curl_init(); |
| 273 | |
| 274 | curl_setopt_array($curl, [ |
| 275 | CURLOPT_URL => $url, |
| 276 | CURLOPT_RETURNTRANSFER => true, |
| 277 | CURLOPT_CUSTOMREQUEST => strtoupper((string) $method), |
| 278 | CURLOPT_HTTPHEADER => [ |
| 279 | 'x-api-key: '.config('services.ifex.api_key', ''), |
| 280 | ], |
| 281 | ]); |
| 282 | |
| 283 | if (in_array(strtoupper((string) $method), ['POST', 'PUT', 'PATCH']) && ! empty($data)) { |
| 284 | if (! is_array($data)) { |
| 285 | throw new \Exception('The $data parameter must be an array.'); |
| 286 | } |
| 287 | curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); |
| 288 | } |
| 289 | |
| 290 | $response = curl_exec($curl); |
| 291 | |
| 292 | if (curl_errno($curl)) { |
| 293 | throw new \Exception('cURL error: '.curl_error($curl)); |
| 294 | } |
| 295 | |
| 296 | $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); |
| 297 | curl_close($curl); |
| 298 | |
| 299 | /*if ($httpCode === 401) { |
| 300 | $this->auth($region); |
| 301 | return $this->request($method, $endpoint, $region, $data); |
| 302 | }*/ |
| 303 | |
| 304 | if ($httpCode < 200 || $httpCode >= 300) { |
| 305 | Log::channel('ifex')->error('API Response Error: '.$response); |
| 306 | |
| 307 | $errorResponse = json_decode($response, true); |
| 308 | $errorMessage = is_array($errorResponse) && isset($errorResponse['message']) |
| 309 | ? $errorResponse['message'] |
| 310 | : 'Request error: '.$response; |
| 311 | |
| 312 | throw new \Exception($errorMessage); |
| 313 | } |
| 314 | |
| 315 | $responseData = json_decode($response, true); |
| 316 | |
| 317 | if (json_last_error() !== JSON_ERROR_NONE) { |
| 318 | throw new \Exception('Invalid JSON response: '.$response); |
| 319 | } |
| 320 | |
| 321 | return $responseData; |
| 322 | } catch (\Throwable $e) { |
| 323 | // FIRE-1258: catch Throwable (not Exception). PHP 8 promotes |
| 324 | // many failure modes to Error (subclass of Throwable, not |
| 325 | // Exception) — those bypassed the old catch and made |
| 326 | // incidents invisible in the channel log. |
| 327 | Log::channel('g3w')->error('Error in request: '.$e->getMessage()); |
| 328 | throw $e; |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | /** |
| 333 | * Sync the IFEX budgets created or edited within a date window. |
| 334 | * |
| 335 | * The window is dynamic: the console command passes `--from` / `--to`, the |
| 336 | * HTTP route accepts `?fechainicio=` / `?fechafin=` (`from` / `to` also |
| 337 | * work), and whichever side is missing falls back to today — so calling it |
| 338 | * with nothing keeps the original single-day behaviour the cron relies on. |
| 339 | */ |
| 340 | public function syncQuotations(?string $from = null, ?string $to = null) |
| 341 | { |
| 342 | try { |
| 343 | [$from, $to] = $this->resolveSyncRange($from, $to); |
| 344 | |
| 345 | $requestDate = 'presupuestos/creados-editados' |
| 346 | .'?fechainicio='.urlencode($from) |
| 347 | .'&fechafin='.urlencode($to); |
| 348 | |
| 349 | Log::channel('ifex')->info("IFEX sync window {$from} → {$to}"); |
| 350 | |
| 351 | $quotationsToSync = json_decode(json_encode($this->request('GET', $requestDate))); |
| 352 | |
| 353 | foreach ($quotationsToSync as $quotation) { |
| 354 | // Everything downstream keys off the CANONICAL reference, never |
| 355 | // the raw codigo: a stray space or a lower-case letter used to |
| 356 | // produce a second row for a budget that already existed. |
| 357 | $reference = IfexReference::normalize($quotation->codigo ?? null); |
| 358 | |
| 359 | if (! IfexReference::isValid($reference)) { |
| 360 | // Refuse rather than store. This is the rule that stops new |
| 361 | // malformed references being written — the five existing |
| 362 | // ones (e.g. 20260000000000100, no series letter at all) |
| 363 | // could only ever have got in because nothing checked. |
| 364 | Log::channel('ifex')->warning( |
| 365 | 'IFEX sync: refusing unparseable codigo ' |
| 366 | .json_encode($quotation->codigo ?? null) |
| 367 | .' — expected '.IfexReference::MYSQL_PATTERN |
| 368 | ); |
| 369 | |
| 370 | continue; |
| 371 | } |
| 372 | |
| 373 | $quotation->codigo = $reference; |
| 374 | |
| 375 | $matches = TblQuotations::where('internal_quote_id', $reference)->count(); |
| 376 | |
| 377 | if ($matches > 1) { |
| 378 | // Never guess which of several rows to update: picking one |
| 379 | // silently is how a collision turns into diverging data. |
| 380 | Log::channel('ifex')->error( |
| 381 | "IFEX sync: {$reference} matches {$matches} rows — skipped. " |
| 382 | .'Resolve with `php artisan ifex:repair --collisions`.' |
| 383 | ); |
| 384 | |
| 385 | continue; |
| 386 | } |
| 387 | |
| 388 | if ($matches === 1) { |
| 389 | $this->updateQuotation($quotation); |
| 390 | } else { |
| 391 | $this->createQuotation($quotation); |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | // FIRE-1258: was ->where('id',1)->first()->update(...) which |
| 396 | // crashed with "Call to a member function update() on null" |
| 397 | // when the row didn't exist (e.g. after a fresh DB restore). |
| 398 | // updateOrCreate is idempotent and seeds the row on first run. |
| 399 | // |
| 400 | // FIRE-1673: `last_date` now stores the `to` we just covered, not |
| 401 | // Carbon::now(). autoRecoveryFrom() reads it to compute the next |
| 402 | // run's `from`, so recording wall-clock time here would replay the |
| 403 | // same single day forever after an outage instead of the missed |
| 404 | // window. Only bumped when `to` is not behind the stored value — |
| 405 | // never regress the checkpoint if a manual --to backfill runs. |
| 406 | $existingLastDate = TblIfexLastUpdate::where('id', 1)->value('last_date'); |
| 407 | $existingLastDate = $existingLastDate |
| 408 | ? Carbon::parse($existingLastDate)->format('Y-m-d') |
| 409 | : null; |
| 410 | $nextLastDate = $existingLastDate !== null && $existingLastDate > $to |
| 411 | ? $existingLastDate |
| 412 | : $to; |
| 413 | |
| 414 | TblIfexLastUpdate::updateOrCreate( |
| 415 | ['id' => 1], |
| 416 | [ |
| 417 | 'last_date' => $nextLastDate, |
| 418 | 'updatingNow' => 0, |
| 419 | 'updated_by' => 'Ifex', |
| 420 | ] |
| 421 | ); |
| 422 | |
| 423 | return ['success' => true, 'quotations' => $quotationsToSync]; |
| 424 | } catch (\Throwable $e) { |
| 425 | report(AppException::fromException($e, 'SYNC_QUOTATIONS_IFEX_EXCEPTION')); |
| 426 | Log::channel('ifex')->error('Error updating quotations: '.$e->getMessage(), [ |
| 427 | 'exception' => $e, |
| 428 | ]); |
| 429 | |
| 430 | return response()->json([ |
| 431 | 'success' => false, |
| 432 | 'message' => 'Failed to update ifex quotations', |
| 433 | 'error' => $e->getMessage(), |
| 434 | 'error_code' => $e->exceptionCode ?: 500, |
| 435 | ], 500); |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | /** |
| 440 | * Map a canonical reference's series letter to a Titan budget type. |
| 441 | * C = correctivos, O = instalaciones, P = mantenimiento. G (oportunidades) |
| 442 | * is not imported and returns false so callers skip the row. |
| 443 | */ |
| 444 | private function budgetTypeForSeries(string $series): int|false |
| 445 | { |
| 446 | return match ($series) { |
| 447 | 'O' => 6, |
| 448 | 'C' => 3, |
| 449 | 'P' => 1, |
| 450 | default => false, |
| 451 | }; |
| 452 | } |
| 453 | |
| 454 | /** |
| 455 | * Write one audit row per changed field. |
| 456 | * |
| 457 | * The importer previously wrote NOTHING to tbl_quotations_log — a budget |
| 458 | * could have its status, amount and dates rewritten by a sync pass with no |
| 459 | * record that the pass happened, let alone of what it changed. That is what |
| 460 | * made the issue_date rewriting (id 128973: 09/02 → 16/02) impossible to |
| 461 | * investigate after the fact. |
| 462 | * |
| 463 | * @param array<string, mixed> $before field => value before the write |
| 464 | * @param array<string, mixed> $after field => value after the write |
| 465 | * @return int number of audit rows written |
| 466 | */ |
| 467 | private function logChanges(int $quotationId, array $before, array $after, string $category): int |
| 468 | { |
| 469 | $written = 0; |
| 470 | |
| 471 | foreach ($after as $field => $newValue) { |
| 472 | $oldValue = $before[$field] ?? null; |
| 473 | |
| 474 | // Compare loosely on the string form: the payload gives '1234.50' |
| 475 | // where the column holds '1234.5000', and logging that as a change |
| 476 | // every pass would bury the real ones. |
| 477 | if ((string) $oldValue === (string) $newValue) { |
| 478 | continue; |
| 479 | } |
| 480 | if (is_numeric($oldValue) && is_numeric($newValue) && (float) $oldValue === (float) $newValue) { |
| 481 | continue; |
| 482 | } |
| 483 | |
| 484 | TblQuotationsLog::create([ |
| 485 | 'category' => $category, |
| 486 | 'quotation_id' => $quotationId, |
| 487 | 'user' => 'Ifex', |
| 488 | 'field' => $field, |
| 489 | 'old_value' => $oldValue === null ? 'N/A' : (string) $oldValue, |
| 490 | 'new_value' => $newValue === null ? 'N/A' : (string) $newValue, |
| 491 | ]); |
| 492 | $written++; |
| 493 | } |
| 494 | |
| 495 | return $written; |
| 496 | } |
| 497 | |
| 498 | /** |
| 499 | * IFEX has no send-date field (the endpoint returns codigo, estado, |
| 500 | * clienteNombre, clienteTelefono, clienteMail, fecha, fechaAlta, |
| 501 | * fechaAceptacion, fechaUltimaModificacion, baseImponible — nothing else). |
| 502 | * |
| 503 | * So sent_date is derived the same way Titan derives it for its own budgets |
| 504 | * (Quotations::update_quotation): the moment a budget reaches "Enviado", the |
| 505 | * time of that transition is the send time. Here that timestamp is |
| 506 | * fechaUltimaModificacion, the pass that moved it. |
| 507 | * |
| 508 | * Deliberately one-way — only ever set when currently empty, so a real send |
| 509 | * date recorded in Titan is never overwritten by a later IFEX edit. |
| 510 | */ |
| 511 | private function deriveSentDate($quotation, ?int $statusId, $currentSentDate): ?string |
| 512 | { |
| 513 | if ($statusId !== 2 || ! empty($currentSentDate)) { |
| 514 | return null; |
| 515 | } |
| 516 | |
| 517 | $raw = trim((string) ($quotation->fechaUltimaModificacion ?? '')); |
| 518 | if ($raw === '' || in_array($raw, ['0000-00-00', '0000-00-00 00:00:00'], true)) { |
| 519 | return null; |
| 520 | } |
| 521 | |
| 522 | try { |
| 523 | return Carbon::parse($raw)->format('Y-m-d H:i:s'); |
| 524 | } catch (\Throwable) { |
| 525 | Log::channel('ifex')->warning( |
| 526 | 'IFEX '.($quotation->codigo ?? '?').": unparseable fechaUltimaModificacion '{$raw}' — sent_date left NULL." |
| 527 | ); |
| 528 | |
| 529 | return null; |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | /** |
| 534 | * FIRE-1672 invariant: `budget_status_id = 3` is only ever written together |
| 535 | * with a real `acceptance_date`. Returns the resolved acceptance status so |
| 536 | * both create and update paths agree. |
| 537 | * |
| 538 | * Nothing is invented: if IFEX gives us no `fechaAceptacion` the row is |
| 539 | * held at "En curso" (12), never advanced to Aceptado. This is what stops |
| 540 | * the 1,343 "accepted with no date" rows from being re-created on future |
| 541 | * syncs. |
| 542 | * |
| 543 | * @return array{status: ?int, acceptance_date: ?string} |
| 544 | */ |
| 545 | private function resolveAcceptance($quotation, ?int $statusId): array |
| 546 | { |
| 547 | $acceptanceDate = $this->normalizeAcceptanceDate( |
| 548 | $quotation->fechaAceptacion ?? null, |
| 549 | $quotation->codigo ?? null, |
| 550 | ); |
| 551 | |
| 552 | if ($statusId !== 3) { |
| 553 | return ['status' => $statusId, 'acceptance_date' => $acceptanceDate]; |
| 554 | } |
| 555 | |
| 556 | if ($acceptanceDate === null) { |
| 557 | Log::channel('ifex')->warning( |
| 558 | 'IFEX '.($quotation->codigo ?? '?').': estado maps to Aceptado but fechaAceptacion is empty — holding at En curso (12) instead of Aceptado.' |
| 559 | ); |
| 560 | |
| 561 | return ['status' => 12, 'acceptance_date' => null]; |
| 562 | } |
| 563 | |
| 564 | // Guard against IFEX payloads where fechaAceptacion pre-dates fecha. |
| 565 | // Query 2 of the DoD showed 3 such rows in prod. Log and keep the |
| 566 | // date null rather than write a value the report can't trust. |
| 567 | $issue = trim((string) ($quotation->fecha ?? '')); |
| 568 | if ($issue !== '' && $acceptanceDate < $issue) { |
| 569 | Log::channel('ifex')->warning( |
| 570 | 'IFEX '.($quotation->codigo ?? '?').": fechaAceptacion {$acceptanceDate} < fecha {$issue} — impossible date, holding at En curso." |
| 571 | ); |
| 572 | |
| 573 | return ['status' => 12, 'acceptance_date' => null]; |
| 574 | } |
| 575 | |
| 576 | return ['status' => 3, 'acceptance_date' => $acceptanceDate]; |
| 577 | } |
| 578 | |
| 579 | public function createQuotation($quotation): void |
| 580 | { |
| 581 | if (! $quotation || empty($quotation->codigo)) { |
| 582 | Log::channel('ifex')->warning( |
| 583 | 'IfexController::createQuotation skipped — missing quotation or empty codigo' |
| 584 | ); |
| 585 | |
| 586 | return; |
| 587 | } |
| 588 | |
| 589 | // The series letter decides the budget type. Read it from the PARSED |
| 590 | // reference instead of substring-matching the raw codigo: the old |
| 591 | // `preg_match('/\d{2}O/')` style scanned the whole string, so a sequence |
| 592 | // that happened to contain those digits could pick the wrong type, and |
| 593 | // an unparseable codigo silently produced budget_type_id = null. |
| 594 | $reference = IfexReference::normalize($quotation->codigo ?? null); |
| 595 | $parsed = IfexReference::parse($reference); |
| 596 | |
| 597 | if ($parsed === null) { |
| 598 | Log::channel('ifex')->warning( |
| 599 | 'IfexController::createQuotation skipped — unparseable codigo '.json_encode($quotation->codigo ?? null) |
| 600 | ); |
| 601 | |
| 602 | return; |
| 603 | } |
| 604 | |
| 605 | // Series G (oportunidades) is not imported into Titan. |
| 606 | $type = $this->budgetTypeForSeries($parsed['series']); |
| 607 | if ($type === false) { |
| 608 | return; |
| 609 | } |
| 610 | |
| 611 | $quotation->codigo = $reference; |
| 612 | |
| 613 | $generateNumber = $this->presupuestosService->generateQuoteId(30); |
| 614 | |
| 615 | if (! is_array($generateNumber) || empty($generateNumber['id'])) { |
| 616 | Log::channel('ifex')->error( |
| 617 | 'IfexController::createQuotation aborted — generateQuoteId returned unexpected shape for codigo '.$quotation->codigo |
| 618 | ); |
| 619 | |
| 620 | return; |
| 621 | } |
| 622 | |
| 623 | $g3wNewId = $generateNumber['id']; |
| 624 | $newQuoteId = $generateNumber['number'] ?? null; |
| 625 | |
| 626 | $statusId = $this->statusNormalize[$quotation->estado] ?? null; |
| 627 | $acceptance = $this->resolveAcceptance($quotation, $statusId); |
| 628 | $statusId = $acceptance['status']; |
| 629 | |
| 630 | $ifexArray = [ |
| 631 | 'internal_quote_id' => $quotation->codigo, |
| 632 | 'quote_id' => $newQuoteId, |
| 633 | 'company_id' => 30, |
| 634 | 'customer_type_id' => 2, |
| 635 | 'segment_id' => null, |
| 636 | 'budget_type_id' => $type, |
| 637 | 'budget_status_id' => $statusId, |
| 638 | 'source_id' => 55, |
| 639 | 'client' => $quotation->clienteNombre ?? null, |
| 640 | 'phone_number' => $quotation->clienteTelefono ?? null, |
| 641 | 'email' => $quotation->clienteMail ?? null, |
| 642 | // The DOCUMENT date belongs here, and only here. |
| 643 | 'issue_date' => $quotation->fecha ?? null, |
| 644 | 'request_date' => $quotation->fechaAlta ?? null, |
| 645 | 'acceptance_date' => $acceptance['acceptance_date'], |
| 646 | // FIRE-1672: audit fields for accepted rows. IFEX doesn't tell us |
| 647 | // who accepted, so accepted_by mirrors created_by's 'Ifex' marker. |
| 648 | 'accepted_at' => $statusId === 3 ? $acceptance['acceptance_date'] : null, |
| 649 | 'accepted_by' => $statusId === 3 ? 'Ifex' : null, |
| 650 | 'sent_date' => $this->deriveSentDate($quotation, $statusId, null), |
| 651 | 'amount' => $quotation->baseImponible ?? null, |
| 652 | 'last_follow_up_date' => null, |
| 653 | 'commercial' => 'Ifex', |
| 654 | // created_at is when THIS ROW WAS INSERTED, not the document date. |
| 655 | // It used to be set to $quotation->fecha, a date with no time, which |
| 656 | // is why every IFEX row carried 00:00:00 and why "when did the sync |
| 657 | // first see this budget" was unanswerable. |
| 658 | 'created_at' => Carbon::now()->format('Y-m-d H:i:s'), |
| 659 | 'created_by' => 'Ifex', |
| 660 | 'has_attachment' => 0, |
| 661 | 'cost_of_labor' => 0, |
| 662 | 'total_cost_of_job' => 0, |
| 663 | 'invoice_margin' => 0, |
| 664 | 'margin_for_the_company' => 0, |
| 665 | 'revenue_per_date_per_worked' => 0, |
| 666 | 'gross_margin' => 100, |
| 667 | 'labor_percentage' => 0, |
| 668 | 'sync_import' => 1, |
| 669 | 'box_work_g3w' => null, |
| 670 | 'for_add' => 0, |
| 671 | 'for_approval' => 0, |
| 672 | 'reason_for_not_following_up_id' => 2, |
| 673 | ]; |
| 674 | |
| 675 | TblQuotations::where('id', $g3wNewId)->update($ifexArray); |
| 676 | |
| 677 | // Audit the creation. generateQuoteId() pre-inserts a placeholder row |
| 678 | // and this fills it in, so from the log's point of view every field is |
| 679 | // new — record the ones that carry meaning rather than all 25. |
| 680 | $this->logChanges( |
| 681 | (int) $g3wNewId, |
| 682 | [], |
| 683 | array_intersect_key($ifexArray, array_flip([ |
| 684 | 'internal_quote_id', 'budget_type_id', 'budget_status_id', 'client', |
| 685 | 'issue_date', 'request_date', 'acceptance_date', 'accepted_at', |
| 686 | 'accepted_by', 'sent_date', 'amount', |
| 687 | ])), |
| 688 | 'Creacion presupuesto' |
| 689 | ); |
| 690 | } |
| 691 | |
| 692 | public function updateQuotation($quotation): void |
| 693 | { |
| 694 | $fstQuotation = TblQuotations::where('internal_quote_id', $quotation->codigo)->first(); |
| 695 | |
| 696 | // Caller `syncQuotations` already pre-checks `exists()` before |
| 697 | // dispatching here, but TOCTOU and direct callers can still land |
| 698 | // with no matching row. Bail out rather than NPE on the property |
| 699 | // reads / final `update()` below. |
| 700 | if (! $fstQuotation) { |
| 701 | Log::channel('ifex')->warning( |
| 702 | 'IfexController::updateQuotation skipped — no tbl_quotations row for codigo '.$quotation->codigo |
| 703 | ); |
| 704 | |
| 705 | return; |
| 706 | } |
| 707 | |
| 708 | // Series → type from the PARSED reference. The previous version matched |
| 709 | // the literal strings '25O' / '25C' / '25P' / 'G25', which stopped |
| 710 | // matching on 1 January 2026: every 2026 row kept whatever type it had, |
| 711 | // and — worse — series G stopped being skipped here, so oportunidades |
| 712 | // that createQuotation correctly refuses were still being updated. |
| 713 | $parsed = IfexReference::parse(IfexReference::normalize($quotation->codigo ?? null)); |
| 714 | |
| 715 | if ($parsed === null) { |
| 716 | Log::channel('ifex')->warning( |
| 717 | 'IfexController::updateQuotation skipped — unparseable codigo '.json_encode($quotation->codigo ?? null) |
| 718 | ); |
| 719 | |
| 720 | return; |
| 721 | } |
| 722 | |
| 723 | $type = $this->budgetTypeForSeries($parsed['series']); |
| 724 | if ($type === false) { |
| 725 | return; // series G is not imported |
| 726 | } |
| 727 | |
| 728 | $statusId = $this->statusNormalize[$quotation->estado] ?? null; |
| 729 | $acceptance = $this->resolveAcceptance($quotation, $statusId); |
| 730 | $statusId = $acceptance['status']; |
| 731 | |
| 732 | $ifexArray = [ |
| 733 | 'internal_quote_id' => $parsed['reference'], |
| 734 | 'budget_type_id' => $type, |
| 735 | 'budget_status_id' => $statusId, |
| 736 | 'client' => $quotation->clienteNombre ?? null, |
| 737 | 'phone_number' => $quotation->clienteTelefono ?? null, |
| 738 | 'email' => $quotation->clienteMail ?? null, |
| 739 | 'request_date' => $quotation->fechaAlta ?? null, |
| 740 | 'acceptance_date' => $acceptance['acceptance_date'], |
| 741 | // FIRE-1672: only stamp accepted_at/by when the row lands on |
| 742 | // Aceptado. On transition away from Aceptado we clear them so |
| 743 | // the audit fields never contradict the status column. |
| 744 | 'accepted_at' => $statusId === 3 ? $acceptance['acceptance_date'] : null, |
| 745 | 'accepted_by' => $statusId === 3 ? 'Ifex' : null, |
| 746 | 'amount' => $quotation->baseImponible ?? null, |
| 747 | 'updated_at' => Carbon::now()->format('Y-m-d H:i:s'), |
| 748 | 'updated_by' => 'Ifex', |
| 749 | ]; |
| 750 | |
| 751 | // issue_date is WRITE-ONCE. IFEX re-sends `fecha` on every edit, and |
| 752 | // rewriting it moved issued budgets between months — id 128973 was |
| 753 | // created dated 09/02 and later silently moved to 16/02, which shifts |
| 754 | // the figure out of the month it was reported in. Only fill it when the |
| 755 | // row has no issue date at all. |
| 756 | if (empty($fstQuotation->issue_date) && ! empty($quotation->fecha)) { |
| 757 | $ifexArray['issue_date'] = $quotation->fecha; |
| 758 | } |
| 759 | |
| 760 | $sentDate = $this->deriveSentDate($quotation, $statusId, $fstQuotation->sent_date); |
| 761 | if ($sentDate !== null) { |
| 762 | $ifexArray['sent_date'] = $sentDate; |
| 763 | } |
| 764 | |
| 765 | $before = []; |
| 766 | foreach (array_keys($ifexArray) as $field) { |
| 767 | $before[$field] = $fstQuotation->{$field}; |
| 768 | } |
| 769 | |
| 770 | $fstQuotation->update($ifexArray); |
| 771 | |
| 772 | // updated_at/updated_by are bookkeeping, not content — logging them |
| 773 | // would put two rows in the audit trail on every no-op pass. |
| 774 | unset($ifexArray['updated_at'], $ifexArray['updated_by']); |
| 775 | |
| 776 | $this->logChanges((int) $fstQuotation->id, $before, $ifexArray, 'Modificacion de presupuesto'); |
| 777 | } |
| 778 | } |