Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.13% |
1 / 750 |
|
5.00% |
1 / 20 |
CRAP | |
0.00% |
0 / 1 |
| CofraiQuotationsService | |
0.13% |
1 / 750 |
|
5.00% |
1 / 20 |
38068.10 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| syncByDate | |
0.00% |
0 / 94 |
|
0.00% |
0 / 1 |
650 | |||
| syncById | |
0.00% |
0 / 164 |
|
0.00% |
0 / 1 |
1332 | |||
| getArrayValue | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
| syncModifiedBudgetById | |
0.00% |
0 / 91 |
|
0.00% |
0 / 1 |
552 | |||
| syncErrorBudgets | |
0.00% |
0 / 73 |
|
0.00% |
0 / 1 |
272 | |||
| syncBudgetsWorks | |
0.00% |
0 / 61 |
|
0.00% |
0 / 1 |
240 | |||
| notifyErrors | |
0.00% |
0 / 5 |
|
0.00% |
0 / 1 |
2 | |||
| generateQuoteId | |
0.00% |
0 / 33 |
|
0.00% |
0 / 1 |
90 | |||
| normalizeStatus | |
0.00% |
0 / 13 |
|
0.00% |
0 / 1 |
30 | |||
| normalizeSegment | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
6 | |||
| normalizeType | |
0.00% |
0 / 16 |
|
0.00% |
0 / 1 |
20 | |||
| normalizeSource | |
0.00% |
0 / 19 |
|
0.00% |
0 / 1 |
30 | |||
| saveDocument | |
0.00% |
0 / 22 |
|
0.00% |
0 / 1 |
42 | |||
| updateLogs | |
0.00% |
0 / 34 |
|
0.00% |
0 / 1 |
20 | |||
| checkEmailInvalid | |
0.00% |
0 / 8 |
|
0.00% |
0 / 1 |
12 | |||
| checkRequiredFields | |
0.00% |
0 / 16 |
|
0.00% |
0 / 1 |
272 | |||
| syncExistingDataWithWarnings | |
0.00% |
0 / 16 |
|
0.00% |
0 / 1 |
56 | |||
| syncByIds | |
0.00% |
0 / 57 |
|
0.00% |
0 / 1 |
132 | |||
| syncNullBudget | |
0.00% |
0 / 18 |
|
0.00% |
0 / 1 |
30 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Services; |
| 4 | |
| 5 | use App\Http\Controllers\Quotations; |
| 6 | use App\Models\TblBudgetStatus; |
| 7 | use App\Models\TblBudgetTypes; |
| 8 | use App\Models\TblCofraiLastUpdate; |
| 9 | use App\Models\TblCompanies; |
| 10 | use App\Models\TblFiles; |
| 11 | use App\Models\TblLastFollowUpDate; |
| 12 | use App\Models\TblOrdersUpdateLogs; |
| 13 | use App\Models\TblQuotations; |
| 14 | use App\Models\TblSegments; |
| 15 | use App\Models\TblSources; |
| 16 | use App\Models\TblStatusCofraiMapping; |
| 17 | use App\Models\TblUserCofraiMapping; |
| 18 | use App\Models\TblUsers; |
| 19 | use Google\Service\AdMob\Date; |
| 20 | use Illuminate\Http\JsonResponse; |
| 21 | use Illuminate\Support\Carbon; |
| 22 | use Illuminate\Support\Facades\DB; |
| 23 | use Illuminate\Support\Facades\Log; |
| 24 | use Mockery\Exception; |
| 25 | use SendGrid\Mail\Mail; |
| 26 | |
| 27 | class CofraiQuotationsService extends CofraiService |
| 28 | { |
| 29 | public function __construct() |
| 30 | { |
| 31 | parent::__construct(); |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * Synchronize budgets as of a specific date. |
| 36 | * It also manages the last synchronized ID. |
| 37 | * |
| 38 | * @param string $date Default today's date |
| 39 | * @param string $name Who's launch the function |
| 40 | * @return array |
| 41 | */ |
| 42 | public function syncByDate($date = null, $name = null, $region = 'Cataluña') |
| 43 | { |
| 44 | try { |
| 45 | if ($region === 'Catalunya') { |
| 46 | $region = 'Cataluña'; |
| 47 | } |
| 48 | |
| 49 | $cofraiActive = TblCompanies::where('region', $region)->first()->cofrai_active; |
| 50 | |
| 51 | if (! $cofraiActive || $cofraiActive === 0) { |
| 52 | throw new Exception("La sincronización con cofrai debe estar desactivada en la region '$region'."); |
| 53 | } |
| 54 | |
| 55 | $this->setSyncStatus(1, $region); |
| 56 | $this->syncExistingDataWithWarnings(); |
| 57 | |
| 58 | $successfulSyncs = 0; |
| 59 | $failedSyncs = []; |
| 60 | $successIdSyncs = []; |
| 61 | |
| 62 | $startCronDateTime = date('Y-m-d H:i:s'); |
| 63 | |
| 64 | $result = DB::transaction(function () use ($date, &$successfulSyncs, &$failedSyncs, &$successIdSyncs, $region) { |
| 65 | $date = $date ?? date('Y-m-d'); |
| 66 | $lastSyncedId = TblCofraiLastUpdate::where('region', $region)->first()->cofrai_id ?? 0; |
| 67 | |
| 68 | $fields = ['id']; |
| 69 | $urlBuild = 'model/sync?model=budget&fields='.implode(',', $fields); |
| 70 | $budgets = $this->request('get', $urlBuild, $region, []); |
| 71 | |
| 72 | if (! $budgets) { |
| 73 | TblCofraiLastUpdate::where('region', $region)->first()->update(['updatingNow' => 0]); |
| 74 | |
| 75 | return [ |
| 76 | 'success' => true, |
| 77 | 'message' => 'No budgets to upload.', |
| 78 | ]; |
| 79 | } |
| 80 | |
| 81 | if (is_string($budgets)) { |
| 82 | $budgets = json_decode($budgets, true); |
| 83 | } |
| 84 | usort($budgets['data'], function ($a, $b) { |
| 85 | return $a['id'] <=> $b['id']; |
| 86 | }); |
| 87 | |
| 88 | if (! is_array($budgets) || empty($budgets)) { |
| 89 | throw new \Exception('No budgets to process.'); |
| 90 | } |
| 91 | |
| 92 | foreach ($budgets['data'] as $budget) { |
| 93 | if ($budget['id'] > $lastSyncedId) { |
| 94 | $result = $this->syncById($budget['id'], $region); |
| 95 | if ($result['success']) { |
| 96 | $successfulSyncs++; |
| 97 | $successIdSyncs[] = [ |
| 98 | 'id' => $budget['id'], |
| 99 | ]; |
| 100 | } else { |
| 101 | if (strpos($result['error'], 'No se ha encontrado el presupuesto') === false) { |
| 102 | $failedSyncs[] = [ |
| 103 | 'id' => $budget['id'], |
| 104 | 'error' => $result['error'] ?? 'Unknown error', |
| 105 | ]; |
| 106 | } |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | $ids = array_column($budgets['data'], 'id'); |
| 112 | if (empty($ids)) { |
| 113 | throw new \Exception('No valid IDs found in budgets.'); |
| 114 | } |
| 115 | |
| 116 | $lastId = max($ids); |
| 117 | |
| 118 | TblCofraiLastUpdate::where('region', $region)->first()->update([ |
| 119 | 'cofrai_id' => $lastId, |
| 120 | 'updatingNow' => 0, |
| 121 | ]); |
| 122 | |
| 123 | $lastUpdate = TblCofraiLastUpdate::where('region', $region)->first(); |
| 124 | |
| 125 | // Modified-budget second pass. G3W's |
| 126 | // `presupuesto/fechamodificacion/{date}/{time}` has no |
| 127 | // Cofrai equivalent — the spec-supported substitute is |
| 128 | // `/model/sync?model=budget&filters[updated_at][from]=...`. |
| 129 | // We anchor the watermark on the previous run's |
| 130 | // updated_at (minus one hour, matching the pre-existing |
| 131 | // safety window) so any late-arriving status/amount edits |
| 132 | // get picked up on the next sync. |
| 133 | if ($lastUpdate) { |
| 134 | $sinceDateTime = Carbon::parse($lastUpdate->updated_at) |
| 135 | ->subHour() |
| 136 | ->format('Y-m-d H:i:s'); |
| 137 | |
| 138 | $modifiedUrl = 'model/sync?model=budget' |
| 139 | .'&fields=id,updated_at' |
| 140 | .'&filters[updated_at][from]='.urlencode($sinceDateTime) |
| 141 | .'&per_page=300'; |
| 142 | |
| 143 | $modifiedBudgets = $this->request('get', $modifiedUrl, $region, []); |
| 144 | |
| 145 | if (is_string($modifiedBudgets)) { |
| 146 | $modifiedBudgets = json_decode($modifiedBudgets, true); |
| 147 | } |
| 148 | |
| 149 | if (is_array($modifiedBudgets) && ! empty($modifiedBudgets['data'] ?? [])) { |
| 150 | foreach ($modifiedBudgets['data'] as $modifiedBudget) { |
| 151 | $modifiedId = $modifiedBudget['id'] ?? null; |
| 152 | if (! $modifiedId) { |
| 153 | continue; |
| 154 | } |
| 155 | |
| 156 | $result = $this->syncModifiedBudgetById($modifiedId, $region); |
| 157 | if ($result['success']) { |
| 158 | $successfulSyncs++; |
| 159 | $successIdSyncs[] = [ |
| 160 | 'id' => $modifiedId, |
| 161 | ]; |
| 162 | } else { |
| 163 | if (! empty($result['error'])) { |
| 164 | if (strpos($result['error'], 'No se encuentra el presupuesto con ID en cofrai') === false && |
| 165 | strpos($result['error'], 'No se ha encontrado el presupuesto') === false) { |
| 166 | $failedSyncs[] = [ |
| 167 | 'id' => $modifiedId, |
| 168 | 'error' => $result['error'] ?? 'Unknown error', |
| 169 | ]; |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | } |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | TblQuotations::where('acceptance_date', '0000-00-00 00:00:00')->update(['acceptance_date' => null]); |
| 178 | |
| 179 | return [ |
| 180 | 'success' => true, |
| 181 | 'message' => 'Synchronization completed.', |
| 182 | ]; |
| 183 | }); |
| 184 | |
| 185 | // $this->updateLogs($failedSyncs, $successfulSyncs, $successIdSyncs, $startCronDateTime, $name, $region); |
| 186 | |
| 187 | return $result; |
| 188 | |
| 189 | } catch (\Exception $e) { |
| 190 | Log::channel('cofrai')->error('Error sincronizando los presupuestos: '.$e->getMessage()); |
| 191 | |
| 192 | $lastUpdate = TblCofraiLastUpdate::where('region', $region)->first(); |
| 193 | if ($lastUpdate?->updatingNow === 1) { |
| 194 | $lastUpdate->update(['updatingNow' => 0]); |
| 195 | } |
| 196 | |
| 197 | return ['success' => false, 'error' => $e->getMessage()]; |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | /** |
| 202 | * Synchronizes a budget by its ID. |
| 203 | * |
| 204 | * @param $id int ID to search in Cofrai |
| 205 | * @return array |
| 206 | */ |
| 207 | public function syncById($id, $region) |
| 208 | { |
| 209 | try { |
| 210 | $cofraiWarning = 0; |
| 211 | $cofraiWarningFields = null; |
| 212 | |
| 213 | $fields = [ |
| 214 | 'id', |
| 215 | 'status', |
| 216 | 'cliente_id', |
| 217 | 'date', |
| 218 | 'invoiced', |
| 219 | 'created_by_user_id', |
| 220 | ]; |
| 221 | |
| 222 | $urlBuild = "model/sync?model=budget&ids={$id}&fields=".implode(',', $fields); |
| 223 | $budget = $this->request('get', $urlBuild, $region, []); |
| 224 | |
| 225 | if (empty($budget['data'])) { |
| 226 | throw new \Exception('El presupuesto no contiene los datos esperados.'); |
| 227 | } |
| 228 | |
| 229 | $budgetData = $budget['data'][0]; |
| 230 | |
| 231 | $companyId = TblCompanies::where('region', $region)->first()->company_id; |
| 232 | |
| 233 | /** |
| 234 | * TODO: HOW ARE WE GOING TO PLAN THIS? IS A POSSIBILITY TO HAVE THE SAME ID IN COFRAI & G3W? |
| 235 | * Source-discriminating existence check (mirrors FIRE-1201 fix in |
| 236 | * PresupuestosService::syncById). We only treat a row as a match |
| 237 | * when it has Cofrai provenance, so a G3W row that happens to |
| 238 | * share the same internal_quote_id won't be picked up here. |
| 239 | */ |
| 240 | $existing = TblQuotations::where('internal_quote_id', $budgetData['id']) |
| 241 | ->where('company_id', $companyId) |
| 242 | ->where(function ($q) { |
| 243 | $q->where('sync_cofrai_import', 1) |
| 244 | ->orWhereNotNull('status_by_cofrai') |
| 245 | ->orWhereNotNull('user_create_by_cofrai') |
| 246 | // Legacy rows pre-FIRE-1077: no provenance flags, still match |
| 247 | ->orWhere(function ($q2) { |
| 248 | $q2->where('sync_import', '!=', 1) |
| 249 | ->whereNull('box_work_g3w') |
| 250 | ->whereNull('status_by_cofrai'); |
| 251 | }); |
| 252 | }) |
| 253 | ->exists(); |
| 254 | |
| 255 | if ($existing) { |
| 256 | return $this->syncModifiedBudgetById($id, $region); |
| 257 | } |
| 258 | |
| 259 | /** |
| 260 | * TODO: NEED THE DATABASE OF STATUS TO NORMALIZE |
| 261 | * $statusList = $this->request('get', "presupuesto/tiposestado", $region, []); |
| 262 | * $collection = collect($statusList); |
| 263 | * $nameStatus = $collection->firstWhere('ID', $budget["presupuesto"]["estado"])['nombre'] ?? null; |
| 264 | */ |
| 265 | $nameStatus = 'Listo para enviar'; |
| 266 | |
| 267 | $sinEstado = TblBudgetStatus::where('name', 'Sin estado en cofrai')->first(); |
| 268 | $estadoNoReconocido = TblBudgetStatus::where('name', 'Estado no reconocido en FST')->first(); |
| 269 | |
| 270 | if (! $nameStatus) { |
| 271 | $statusID = $sinEstado ? $sinEstado->budget_status_id : null; |
| 272 | } else { |
| 273 | $statusID = $this->normalizeStatus($nameStatus); |
| 274 | |
| 275 | if ($statusID === ($sinEstado ? $sinEstado->budget_status_id : null)) { |
| 276 | $statusID = $estadoNoReconocido ? $estadoNoReconocido->budget_status_id : null; |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | /** |
| 281 | * TODO: HOW DO WE LINK THE BUDGET TO THE SERVICE? WE ONLY HAVE CONNECTED THE CLIENT. |
| 282 | */ |
| 283 | $fields = [ |
| 284 | 'id', |
| 285 | 'businessname', |
| 286 | 'primaryphone', |
| 287 | 'email', |
| 288 | 'tipocliente_id', |
| 289 | ]; |
| 290 | |
| 291 | $urlBuild = "model/sync?model=client&ids={$budgetData['cliente_id']}&fields=".implode(',', $fields); |
| 292 | $client = $this->request('get', $urlBuild, $region, []); |
| 293 | |
| 294 | if (empty($client['data'])) { |
| 295 | throw new Exception("No client data provide for the budget with ID {$budget['presupuesto']['cod_servicio']} en la region: $region"); |
| 296 | } |
| 297 | |
| 298 | $clientData = $client['data'][0]; |
| 299 | |
| 300 | $clientName = $clientData['businessname'] ?? null; |
| 301 | $clientTelephone = $clientData['primaryphone'] ?? null; |
| 302 | $clientEmail = $clientData['email'] ?? null; |
| 303 | |
| 304 | if ($clientEmail) { |
| 305 | $clientEmail = trim($clientEmail); |
| 306 | |
| 307 | if (str_contains($clientEmail, ';')) { |
| 308 | $clientEmail = str_replace(';', ',', $clientEmail); |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | /** |
| 313 | * TODO: NEED THE DATABASE OF TIPO CLIENTE TO NORMALIZE |
| 314 | */ |
| 315 | |
| 316 | // $segmentID = $this->normalizeSegment($company["servicio"]["tipo_servicio"] ?? "Otro"); |
| 317 | $segmentID = 9; |
| 318 | |
| 319 | $generateNumber = $this->generateQuoteId($companyId); |
| 320 | |
| 321 | $cofraiNewId = $generateNumber['id']; |
| 322 | $newQuoteId = $generateNumber['number']; |
| 323 | |
| 324 | /** |
| 325 | * TODO: WE DON'T HAVE DOCUMENT ON THE BUDGET |
| 326 | */ |
| 327 | |
| 328 | /*if(!isset($budget["presupuesto"]["documento"]) || empty($budget["presupuesto"]["documento"])){ |
| 329 | throw new \Exception("El presupuesto no tiene documento asociado. Creelo y vuelva a intentarlo."); |
| 330 | } |
| 331 | |
| 332 | $clientNameFormatted = ""; |
| 333 | |
| 334 | if (!empty($clientName)) { |
| 335 | $clientNameFormatted = str_replace(' ', '_', $clientName); |
| 336 | } |
| 337 | |
| 338 | $nameDocument = $companyNameFormatted |
| 339 | ? $budget["presupuesto"]["cod_presupuesto"] . "_" . $companyNameFormatted |
| 340 | : $budget["presupuesto"]["cod_presupuesto"]; |
| 341 | |
| 342 | $document = $this->saveDocument($budget["presupuesto"]["documento"], $nameDocument); |
| 343 | |
| 344 | */ |
| 345 | |
| 346 | if (empty($budgetData['date'])) { |
| 347 | $budgetData['date'] = Carbon::now()->format('Y-m-d H:i:s'); |
| 348 | } |
| 349 | |
| 350 | $idsConcatenados = null; |
| 351 | /* |
| 352 | $fields = [ |
| 353 | "id", |
| 354 | |
| 355 | ]; |
| 356 | |
| 357 | $urlBuild = "model/sync?model=work-order&filters[presupuesto_id]={$budgetData["id"]}&fields=" . implode(",", $fields); |
| 358 | |
| 359 | $work = $this->request('get', $urlBuild, $region, []); |
| 360 | |
| 361 | if(!empty($work["data"])){ |
| 362 | $workData = $work["data"]; |
| 363 | $workIds = []; |
| 364 | |
| 365 | if (is_array($workData)) { |
| 366 | foreach ($workData as $item) { |
| 367 | if (isset($item['id'])) { |
| 368 | $workIds[] = $item['id']; |
| 369 | } |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | $idsConcatenados = implode('/', $workIds); |
| 374 | } |
| 375 | */ |
| 376 | |
| 377 | $createdByUser = TblUserCofraiMapping::where('id_cofrai', $budgetData['created_by_user_id'])->first(); |
| 378 | $createdBy = null; |
| 379 | $comercial = null; |
| 380 | |
| 381 | if (! $createdByUser) { |
| 382 | TblUserCofraiMapping::create([ |
| 383 | 'id_cofrai' => $budgetData['created_by_user_id'] ?? null, |
| 384 | ]); |
| 385 | $comercial = null; |
| 386 | $cofraiWarning = 1; |
| 387 | } else { |
| 388 | $createdBy = TblUsers::where('id', $createdByUser->id_fst)->value('name') |
| 389 | ?? null; |
| 390 | |
| 391 | $comercial = $createdBy; |
| 392 | } |
| 393 | |
| 394 | /** |
| 395 | * TODO: IS NOT A COMMERCIAL ASSIGNED TO THE BUDGET? |
| 396 | */ |
| 397 | $comercialUser = TblUserCofraiMapping::where('id_cofrai', $budgetData['created_by_user_id'])->first(); |
| 398 | |
| 399 | if (! $comercialUser && $budgetData['created_by_user_id']) { |
| 400 | TblUserCofraiMapping::create([ |
| 401 | 'id_cofrai' => $budgetData['created_by_user_id'] ?? null, |
| 402 | ]); |
| 403 | } elseif ($comercialUser) { |
| 404 | $comercial = TblUsers::where('id', $comercialUser->id_fst)->value('name') |
| 405 | ?? null; |
| 406 | } |
| 407 | |
| 408 | // FIRE-1821: Cofrai's budget model has no equivalent to G3W's |
| 409 | // `cod_empresa_presupuesto` (source) or `origen_presupuesto` (type). |
| 410 | // Previously hardcoded to 1 — that silently classified every Cofrai |
| 411 | // quotation as source_id=1 / budget_type_id=1 (real DB categories), |
| 412 | // poisoning analytics and pipeline filters. Set to null so Cofrai |
| 413 | // rows surface as "unclassified" until Cofrai exposes proxy fields |
| 414 | // (e.g. budget.tipocliente_id via the client record, or |
| 415 | // work-order.type_id) or the product team defines a Cofrai-specific |
| 416 | // source. See findings/Cofrai-Parity-Inventory.md §3 and §6 item 9. |
| 417 | $sourceId = null; |
| 418 | $typeId = null; |
| 419 | |
| 420 | // FIRE-1571 Jomar override kept for parity with G3W's syncById() — |
| 421 | // guarded on $sourceId so it never fires while sourceId is null. |
| 422 | // Will re-activate when a real Cofrai source mapping lands. |
| 423 | if ($companyId == 18 && $sourceId === 9) { |
| 424 | $companyId = 22; |
| 425 | } |
| 426 | |
| 427 | $lastFollowUp = TblLastFollowUpDate::where('company_id', $companyId)->where('budget_type_id', $typeId)->first(); |
| 428 | $workingDays = 10; |
| 429 | if ($lastFollowUp && $lastFollowUp->last_follow_up_date) { |
| 430 | $workingDays = $lastFollowUp->last_follow_up_date; |
| 431 | } |
| 432 | |
| 433 | $date = Carbon::now(); |
| 434 | |
| 435 | $daysAdded = 0; |
| 436 | while ($daysAdded < $workingDays) { |
| 437 | $date->addDay(); |
| 438 | if ($date->isWeekday()) { |
| 439 | $daysAdded++; |
| 440 | } |
| 441 | } |
| 442 | |
| 443 | $lastFollowUpDate = $date; |
| 444 | |
| 445 | Log::channel('cofrai')->info($budgetData['id'].' / create -> region -> '.$region.'company id -> '.$companyId); |
| 446 | |
| 447 | if ( |
| 448 | in_array($statusID, [13, 14]) || |
| 449 | ! $sourceId || |
| 450 | (! $typeId || $typeId == 0 || $typeId == 16) || |
| 451 | empty(trim($clientName)) || |
| 452 | empty(trim($clientEmail)) |
| 453 | // || $this->checkEmailInvalid($companyEmail) |
| 454 | ) { |
| 455 | $cofraiWarning = 1; |
| 456 | } |
| 457 | |
| 458 | $row = (object) [ |
| 459 | 'client' => $clientName, |
| 460 | 'email' => $clientEmail, |
| 461 | 'budget_status_id' => $statusID, |
| 462 | 'commercial' => $comercial, |
| 463 | 'source_id' => $sourceId, |
| 464 | 'budget_type_id' => $typeId, |
| 465 | ]; |
| 466 | |
| 467 | $cofraiWarningFields = $this->checkRequiredFields($row); |
| 468 | |
| 469 | if ($cofraiWarningFields != null && $cofraiWarningFields != '') { |
| 470 | $cofraiWarning = 1; |
| 471 | } |
| 472 | |
| 473 | $reasonForNotFollowingUp = null; |
| 474 | $facilityUser = false; |
| 475 | /** |
| 476 | * TODO: DON'T WE HAVE AN ACCEPTANCE DATE? |
| 477 | */ |
| 478 | $cofraiArray = [ |
| 479 | 'internal_quote_id' => $budgetData['id'], |
| 480 | 'quote_id' => $newQuoteId, |
| 481 | 'company_id' => $companyId, |
| 482 | 'customer_type_id' => 2, |
| 483 | 'segment_id' => $segmentID, |
| 484 | 'budget_type_id' => $typeId == 16 ? null : $typeId, |
| 485 | 'budget_status_id' => $statusID, |
| 486 | 'source_id' => $sourceId, |
| 487 | 'client' => $clientName, |
| 488 | 'phone_number' => $clientTelephone, |
| 489 | 'email' => $clientEmail, |
| 490 | 'issue_date' => ($budgetData['date'] ?? null) === '0000/00/00' ? null : $budgetData['date'], |
| 491 | 'request_date' => ($budgetData['date'] ?? null) === '0000/00/00' ? null : $budgetData['date'], |
| 492 | 'acceptance_date' => null, |
| 493 | 'amount' => $budgetData['total'] ?? null, |
| 494 | 'last_follow_up_date' => $facilityUser ? null : $lastFollowUpDate, |
| 495 | 'commercial' => $comercial, |
| 496 | 'created_at' => $budgetData['created_at'] ?? null, |
| 497 | 'created_by' => $createdBy, |
| 498 | // FIRE-1821: Cofrai's budget model has no attachment field. |
| 499 | // Previously hardcoded to 1 — that displayed a paperclip icon |
| 500 | // on every Cofrai quotation in the FE that pointed at nothing. |
| 501 | // Default 0 until Cofrai exposes an attachment endpoint. |
| 502 | 'has_attachment' => 0, |
| 503 | 'sync_cofrai_import' => 1, |
| 504 | 'box_work_cofrai' => $idsConcatenados, |
| 505 | 'segment_by_cofrai' => null, // We don't have |
| 506 | 'source_by_cofrai' => null, // We don't have |
| 507 | 'status_by_cofrai' => $nameStatus, |
| 508 | 'type_by_cofrai' => null, // We don't have |
| 509 | 'user_create_by_cofrai' => $budgetData['created_by_user_id'], |
| 510 | 'user_commercial_by_cofrai' => null, // We don't have |
| 511 | 'cofrai_warning' => $cofraiWarning, |
| 512 | 'cofrai_warning_fields' => $cofraiWarningFields, |
| 513 | 'reason_for_not_following_up_id' => $reasonForNotFollowingUp, |
| 514 | 'for_add' => 0, |
| 515 | ]; |
| 516 | |
| 517 | TblQuotations::where('id', $cofraiNewId)->update($cofraiArray); |
| 518 | |
| 519 | $companyNameFormatted = ''; |
| 520 | |
| 521 | /*if (!empty($companyName)) { |
| 522 | $companyNameFormatted = str_replace(' ', '_', $companyName); |
| 523 | } |
| 524 | |
| 525 | $nameDocument = $companyNameFormatted |
| 526 | ? $budget["presupuesto"]["cod_presupuesto"] . "_" . $companyNameFormatted |
| 527 | : $budget["presupuesto"]["cod_presupuesto"]; |
| 528 | |
| 529 | $responseSaveDocument = $this->saveDocument($budget["presupuesto"]["documento"], $nameDocument); |
| 530 | $responseDataSaveDocument = $responseSaveDocument->getData(); |
| 531 | |
| 532 | if (!isset($responseDataSaveDocument->success) || !$responseDataSaveDocument->success) { |
| 533 | throw new \Exception("No se pudo guardar el documento del presupuesto {$id} al crearlo. Error: " . ($responseDataSaveDocument->error ?? 'Desconocido')); |
| 534 | } |
| 535 | |
| 536 | $documentName = $responseDataSaveDocument->documentName; |
| 537 | |
| 538 | TblFiles::create( |
| 539 | array( |
| 540 | "quotation_id"=>$cofraiNewId, |
| 541 | "quote_id"=>$newQuoteId, |
| 542 | "original_name"=>$documentName, |
| 543 | "filename"=>$documentName, |
| 544 | "uploaded_by"=>"System", |
| 545 | ) |
| 546 | ); |
| 547 | */ |
| 548 | |
| 549 | TblQuotations::where('acceptance_date', '0000-00-00 00:00:00')->update(['acceptance_date' => null]); |
| 550 | |
| 551 | return [ |
| 552 | 'success' => true, |
| 553 | ]; |
| 554 | |
| 555 | } catch (\Exception $e) { |
| 556 | $errorMessage = $e->getMessage(); |
| 557 | |
| 558 | return ['success' => false, 'error' => "Error sincronizando el presupuesto {$id}: ".$errorMessage]; |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | private function getArrayValue(array $array, string $key, $default = null) |
| 563 | { |
| 564 | return $array[$key] ?? $default; |
| 565 | } |
| 566 | |
| 567 | /** |
| 568 | * @return array|true[] |
| 569 | */ |
| 570 | public function syncModifiedBudgetById($id, $region = null) |
| 571 | { |
| 572 | try { |
| 573 | $statusID = null; |
| 574 | |
| 575 | $cofraiWarning = 0; |
| 576 | $cofraiWarningFields = null; |
| 577 | $companyId = TblCompanies::where('region', $region)->first()->company_id; |
| 578 | |
| 579 | // Cofrai's `/model/sync` is the universal data endpoint — there |
| 580 | // is no per-resource `presupuesto/{id}` route as in G3W. Pull |
| 581 | // the budget fields consumed downstream in a single call. |
| 582 | // `per_page=300` is the documented max; a single-id lookup |
| 583 | // never approaches it, but we set it explicitly to be safe. |
| 584 | $budgetFields = [ |
| 585 | 'id', |
| 586 | 'status', |
| 587 | 'cliente_id', |
| 588 | 'date', |
| 589 | 'invoiced', |
| 590 | 'total', |
| 591 | 'created_by_user_id', |
| 592 | 'updated_at', |
| 593 | ]; |
| 594 | $budgetUrl = "model/sync?model=budget&ids={$id}&fields=" |
| 595 | .implode(',', $budgetFields) |
| 596 | .'&per_page=300'; |
| 597 | |
| 598 | $budget = $this->request('get', $budgetUrl, $region, []); |
| 599 | |
| 600 | if (empty($budget['data'])) { |
| 601 | throw new \Exception("No se encuentra el presupuesto con ID en cofrai $id. Es posible que sea debido a que se creo antes de la integracion de FST con cofrai."); |
| 602 | } |
| 603 | |
| 604 | $budgetData = $budget['data'][0]; |
| 605 | |
| 606 | if (! TblQuotations::where('internal_quote_id', $budgetData['id'])->where('company_id', $companyId)->exists()) { |
| 607 | throw new \Exception("No se encuentra el presupuesto con ID en cofrai $id. Es posible que sea debido a que se creo antes de la integracion de FST con cofrai."); |
| 608 | } |
| 609 | |
| 610 | // Cofrai's `/model/sync` enum has no `servicio` model — the |
| 611 | // service/sede data G3W carried lived alongside the client in |
| 612 | // G3W's data model. For Cofrai we read it straight off the |
| 613 | // `client` record referenced by `budget.cliente_id`. |
| 614 | $clientFields = [ |
| 615 | 'id', |
| 616 | 'businessname', |
| 617 | 'primaryphone', |
| 618 | 'email', |
| 619 | 'tipocliente_id', |
| 620 | ]; |
| 621 | $clientName = null; |
| 622 | $clientTelephone = null; |
| 623 | $clientEmail = null; |
| 624 | $clientType = null; |
| 625 | |
| 626 | if (! empty($budgetData['cliente_id'])) { |
| 627 | $clientUrl = "model/sync?model=client&ids={$budgetData['cliente_id']}&fields=" |
| 628 | .implode(',', $clientFields) |
| 629 | .'&per_page=300'; |
| 630 | |
| 631 | $client = $this->request('get', $clientUrl, $region, []); |
| 632 | |
| 633 | if (! empty($client['data'])) { |
| 634 | $clientData = $client['data'][0]; |
| 635 | $clientName = $clientData['businessname'] ?? null; |
| 636 | $clientTelephone = $clientData['primaryphone'] ?? null; |
| 637 | $clientEmail = $clientData['email'] ?? null; |
| 638 | $clientType = $clientData['tipocliente_id'] ?? null; |
| 639 | } |
| 640 | } |
| 641 | |
| 642 | // Cofrai's `budget.status` is an integer; normalizeStatus() |
| 643 | // consults TblStatusCofraiMapping by `name_cofrai` — the column |
| 644 | // accepts the value as a string. Pass the integer status as-is |
| 645 | // (cast to string) so the mapping table lookup is consistent |
| 646 | // with how setMappings()/getMappings() populate it. |
| 647 | $statusValue = $budgetData['status'] ?? null; |
| 648 | $nameStatus = $statusValue !== null ? (string) $statusValue : null; |
| 649 | |
| 650 | $sinEstado = TblBudgetStatus::where('name', 'Sin estado en cofrai')->first() |
| 651 | ?? TblBudgetStatus::where('name', 'Sin estado en G3W')->first(); |
| 652 | |
| 653 | if (! $nameStatus) { |
| 654 | $statusID = $sinEstado ? $sinEstado->budget_status_id : null; |
| 655 | } else { |
| 656 | $statusID = $this->normalizeStatus($nameStatus); |
| 657 | |
| 658 | if ($sinEstado && $statusID === $sinEstado->budget_status_id) { |
| 659 | $estadoNoReconocido = TblBudgetStatus::where('name', 'Estado no reconocido en FST')->first(); |
| 660 | $statusID = $estadoNoReconocido ? $estadoNoReconocido->budget_status_id : $statusID; |
| 661 | } |
| 662 | } |
| 663 | |
| 664 | Log::channel('cofrai')->info($budgetData['id'].' / modified -> region -> '.$region); |
| 665 | |
| 666 | $row = TblQuotations::where('internal_quote_id', $budgetData['id']) |
| 667 | ->where('company_id', $companyId) |
| 668 | ->first(); |
| 669 | |
| 670 | if ($row) { |
| 671 | if ( |
| 672 | in_array($row->budget_status_id, [13, 14]) || |
| 673 | ! $row->source_id || |
| 674 | (! $row->budget_type_id || $row->budget_type_id == 0 || $row->budget_type_id == 16) || |
| 675 | empty(trim($row->client)) || |
| 676 | empty(trim($row->email)) |
| 677 | ) { |
| 678 | $cofraiWarning = 1; |
| 679 | } |
| 680 | |
| 681 | $cofraiWarningFields = $this->checkRequiredFields($row); |
| 682 | |
| 683 | if ($cofraiWarningFields != null && $cofraiWarningFields != '') { |
| 684 | $cofraiWarning = 1; |
| 685 | } |
| 686 | |
| 687 | // The Cofrai `budget` model has no `cod_empresa_presupuesto`, |
| 688 | // `origen_presupuesto`, `usuario`, or |
| 689 | // `cod_comercial_presupuesto` equivalents per the spec — we |
| 690 | // only refresh the fields that DO have Cofrai equivalents |
| 691 | // (status, amount, status_by_cofrai). type/source/segment |
| 692 | // are intentionally untouched here so they don't blank out |
| 693 | // anything operators set manually on the FST side. |
| 694 | // Same send rule as the G3W sync (see PresupuestosService): a |
| 695 | // send is the ERP's own status becoming Enviado. Cofrai's status |
| 696 | // is still hard-coded above (TODO), so today this never fires; |
| 697 | // it starts working the day the real status mapping lands. |
| 698 | if (QuotationSendRecorder::isErpSend($row->status_by_cofrai, $nameStatus)) { |
| 699 | QuotationSendRecorder::record((int) $row->id, QuotationSendRecorder::COFRAI_STATUS, 'Cofrai', |
| 700 | null, $budgetData['total'] ?? null); |
| 701 | } |
| 702 | |
| 703 | $row->update( |
| 704 | [ |
| 705 | 'budget_status_id' => $statusID ?? $row->budget_status_id, |
| 706 | 'amount' => $budgetData['total'] ?? $row->amount, |
| 707 | 'updated_by' => 'System', |
| 708 | 'updated_at' => Carbon::now()->format('Y-m-d H:i:s'), |
| 709 | 'sync_cofrai_import' => 1, |
| 710 | 'status_by_cofrai' => $nameStatus, |
| 711 | 'user_create_by_cofrai' => $budgetData['created_by_user_id'] ?? $row->user_create_by_cofrai, |
| 712 | 'cofrai_warning' => $cofraiWarning, |
| 713 | 'cofrai_warning_fields' => $cofraiWarningFields, |
| 714 | ] |
| 715 | ); |
| 716 | } |
| 717 | |
| 718 | TblQuotations::where('acceptance_date', '0000-00-00 00:00:00')->update(['acceptance_date' => null]); |
| 719 | |
| 720 | return [ |
| 721 | 'success' => true, |
| 722 | ]; |
| 723 | |
| 724 | } catch (\Exception $e) { |
| 725 | return ['success' => false, 'error' => "Error actualizando el presupuesto {$id}: ".$e->getMessage()]; |
| 726 | } |
| 727 | } |
| 728 | |
| 729 | /** |
| 730 | * Synchronize budgets that gave us an error. |
| 731 | * |
| 732 | * FIRE-982 (2026-04-29): added `$limit` + `$daysWindow` to mirror |
| 733 | * the FIRE-1025 caps now standard on G3W's `quotations:retry-failed` |
| 734 | * — without them the retry would iterate every failed ID ever logged |
| 735 | * for the company on every fire (same shape as the runaway we saw |
| 736 | * on G3W on 2026-04-27). Returns `processed` so the calling command |
| 737 | * can decrement its remaining budget across regions. |
| 738 | * |
| 739 | * @param string|null $name Who launched the call. |
| 740 | * @param string|null $region Region to retry, e.g. "Cataluña". |
| 741 | * @param int $limit Max IDs to attempt this run. |
| 742 | * @param int $daysWindow Only consider logs newer than this many days. |
| 743 | */ |
| 744 | public function syncErrorBudgets($name = null, $region = null, int $limit = 200, int $daysWindow = 7): array |
| 745 | { |
| 746 | try { |
| 747 | if ($region === 'Catalunya') { |
| 748 | $region = 'Cataluña'; |
| 749 | } |
| 750 | |
| 751 | // FIRE-982 (2026-04-29): the retry command now iterates every |
| 752 | // region by default, so we have to handle "no company for this |
| 753 | // region" and "cofrai not active for this region" as quiet |
| 754 | // skips rather than errors — neither is a sync failure, just |
| 755 | // a region the integration doesn't apply to. |
| 756 | $company = TblCompanies::where('region', $region)->first(); |
| 757 | if (! $company) { |
| 758 | return [ |
| 759 | 'success' => true, |
| 760 | 'skipped' => true, |
| 761 | 'reason' => "No company configured for region '{$region}'", |
| 762 | 'processed' => 0, |
| 763 | ]; |
| 764 | } |
| 765 | |
| 766 | $cofraiActive = $company->cofrai_active; |
| 767 | |
| 768 | if (! $cofraiActive || $cofraiActive === 0) { |
| 769 | return [ |
| 770 | 'success' => true, |
| 771 | 'skipped' => true, |
| 772 | 'reason' => "Cofrai is not active for region '{$region}'", |
| 773 | 'processed' => 0, |
| 774 | ]; |
| 775 | } |
| 776 | |
| 777 | $this->setSyncStatus(1, $region); |
| 778 | |
| 779 | $successfulSyncs = 0; |
| 780 | $failedSyncs = []; |
| 781 | $successIdSyncs = []; |
| 782 | $processedCount = 0; |
| 783 | |
| 784 | $startCronDateTime = date('Y-m-d H:i:s'); |
| 785 | |
| 786 | $result = DB::transaction(function () use (&$successfulSyncs, &$failedSyncs, &$successIdSyncs, &$processedCount, $region, $limit, $daysWindow) { |
| 787 | $company = TblCompanies::where('region', $region)->first(); |
| 788 | if (! $company) { |
| 789 | throw new \Exception('No company found for region: '.$region); |
| 790 | } |
| 791 | $company_id = $company->company_id; |
| 792 | |
| 793 | // FIRE-982: time-bound the failed-IDs scan. Pre-fix this |
| 794 | // unioned every sync_error_ids JSON ever recorded for the |
| 795 | // company, so an ID that failed once 18 months ago and was |
| 796 | // later resolved by hand kept coming back into the retry |
| 797 | // pool every fire. |
| 798 | $logs = TblOrdersUpdateLogs::whereNotNull('sync_error_ids') |
| 799 | ->where('company_id', $company_id) |
| 800 | ->where('started_at', '>=', now()->subDays($daysWindow)) |
| 801 | ->get(['sync_error_ids']); |
| 802 | |
| 803 | $allSyncErrorIds = []; |
| 804 | |
| 805 | foreach ($logs as $log) { |
| 806 | if (is_string($log->sync_error_ids)) { |
| 807 | $decoded = json_decode($log->sync_error_ids, true); |
| 808 | if (is_array($decoded)) { |
| 809 | $allSyncErrorIds = array_merge($allSyncErrorIds, $decoded); |
| 810 | } |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | $allSyncErrorIds = array_values(array_unique($allSyncErrorIds)); |
| 815 | |
| 816 | // FIRE-982: cap per-run processing so a single backlog of |
| 817 | // e.g. 4000 IDs can't blow past the intended ~200 IDs/run |
| 818 | // and starve the box. |
| 819 | $idsToProcess = array_slice($allSyncErrorIds, 0, $limit); |
| 820 | |
| 821 | foreach ($idsToProcess as $idSyncError) { |
| 822 | $processedCount++; |
| 823 | $result = $this->syncById($idSyncError, $region); |
| 824 | if ($result['success']) { |
| 825 | $successfulSyncs++; |
| 826 | $successIdSyncs[] = [ |
| 827 | 'id' => $idSyncError, |
| 828 | ]; |
| 829 | } else { |
| 830 | if (strpos($result['error'], 'No se ha encontrado el presupuesto') === false) { |
| 831 | $failedSyncs[] = [ |
| 832 | 'id' => $idSyncError, |
| 833 | 'error' => $result['error'] ?? 'Unknown error', |
| 834 | ]; |
| 835 | } |
| 836 | } |
| 837 | } |
| 838 | |
| 839 | TblCofraiLastUpdate::where('region', $region)->first()?->update(['updatingNow' => 0]); |
| 840 | |
| 841 | return [ |
| 842 | 'success' => true, |
| 843 | 'message' => 'Synchronization of failed budgets completed.', |
| 844 | 'processed' => $processedCount, |
| 845 | ]; |
| 846 | }); |
| 847 | |
| 848 | $company = TblCompanies::where('region', $region)->first(); |
| 849 | if (! $company) { |
| 850 | throw new \Exception('No company found for region: '.$region); |
| 851 | } |
| 852 | $company_id = $company->company_id; |
| 853 | |
| 854 | // FIRE-982 (2026-04-29): the unconditional |
| 855 | // `update(['sync_error_ids' => []])` that lived here zeroed |
| 856 | // out every prior failure log for this company on every retry |
| 857 | // run, including IDs that just failed inside this run. The |
| 858 | // retry pool was therefore never able to drain — Berta's |
| 859 | // "after retries the failed list always shows empty" symptom. |
| 860 | // The pool is naturally bounded by the time-window filter in |
| 861 | // the retry command (see G3W's QuotationsRetryFailed for the |
| 862 | // canonical pattern), so this destructive sweep is removed. |
| 863 | |
| 864 | $this->updateLogs($failedSyncs, $successfulSyncs, $successIdSyncs, $startCronDateTime, $name, $region); |
| 865 | |
| 866 | return $result; |
| 867 | |
| 868 | } catch (\Exception $e) { |
| 869 | Log::channel('cofrai')->error('Error when synchronizing error budgets: '.$e->getMessage()); |
| 870 | |
| 871 | // FIRE-982 (2026-04-29): null-guard the lock release. The |
| 872 | // pre-fix chain (`->first()->updatingNow`) crashed with |
| 873 | // "Attempt to read property updatingNow on null" whenever |
| 874 | // tbl_cofrai_last_update has no row for `$region` — the same |
| 875 | // crash the new "iterate all regions" retry loop kept tripping |
| 876 | // on local DBs that don't carry every region's row. |
| 877 | $lastUpdate = TblCofraiLastUpdate::where('region', $region)->first(); |
| 878 | if ($lastUpdate && (int) $lastUpdate->updatingNow === 1) { |
| 879 | $lastUpdate->update(['updatingNow' => 0]); |
| 880 | } |
| 881 | |
| 882 | return ['success' => false, 'error' => $e->getMessage(), 'processed' => $processedCount ?? 0]; |
| 883 | } |
| 884 | } |
| 885 | |
| 886 | public function syncBudgetsWorks($name = null, $region = null) |
| 887 | { |
| 888 | try { |
| 889 | if ($region === 'Catalunya') { |
| 890 | $region = 'Cataluña'; |
| 891 | } |
| 892 | |
| 893 | $company = TblCompanies::where('region', $region)->first(); |
| 894 | if (! $company) { |
| 895 | throw new \Exception("No se encontró la compañía para la región '$region'."); |
| 896 | } |
| 897 | $cofraiActive = $company->cofrai_active; |
| 898 | |
| 899 | if (! $cofraiActive || $cofraiActive === 0) { |
| 900 | throw new Exception("La sincronización con cofrai debe estar desactivada en la region '$region'."); |
| 901 | } |
| 902 | |
| 903 | $this->setSyncStatus(1, $region); |
| 904 | |
| 905 | $successfulSyncs = 0; |
| 906 | $failedSyncs = []; |
| 907 | $successIdSyncs = []; |
| 908 | |
| 909 | $startCronDateTime = date('Y-m-d H:i:s'); |
| 910 | |
| 911 | $result = DB::transaction(function () use (&$successfulSyncs, &$failedSyncs, &$successIdSyncs, $region) { |
| 912 | |
| 913 | $quotesIds = TblQuotations::where('sync_import', 1) |
| 914 | ->where('budget_type_id', 1) |
| 915 | ->where(function ($query) { |
| 916 | $query->whereNull('box_work_cofrai') |
| 917 | ->orWhere('box_work_cofrai', '0'); |
| 918 | }) |
| 919 | ->get(); |
| 920 | |
| 921 | foreach ($quotesIds as $quoteId) { |
| 922 | // Cofrai exposes work orders through the universal |
| 923 | // `/model/sync` endpoint with the `work-order` model |
| 924 | // (per the 18-model enum in cofrai-documentation.json). |
| 925 | // Filter by `presupuesto_id` to scope to this budget. |
| 926 | // `per_page=300` is the documented max — single-budget |
| 927 | // work-order lists will never approach it. |
| 928 | $workUrl = 'model/sync?model=work-order' |
| 929 | ."&filters[presupuesto_id]={$quoteId->internal_quote_id}" |
| 930 | .'&fields=id' |
| 931 | .'&per_page=300'; |
| 932 | |
| 933 | $work = $this->request('get', $workUrl, $region, []); |
| 934 | |
| 935 | sleep(2); |
| 936 | |
| 937 | $workIds = []; |
| 938 | |
| 939 | if (is_array($work) && ! empty($work['data']) && is_array($work['data'])) { |
| 940 | foreach ($work['data'] as $item) { |
| 941 | if (isset($item['id'])) { |
| 942 | $workIds[] = $item['id']; |
| 943 | } |
| 944 | } |
| 945 | } |
| 946 | |
| 947 | $idsConcatenados = implode('/', $workIds); |
| 948 | |
| 949 | $wasUpdated = $quoteId->update(['box_work_cofrai' => $idsConcatenados]); |
| 950 | |
| 951 | if ($wasUpdated) { |
| 952 | $successfulSyncs++; |
| 953 | $successIdSyncs[] = [ |
| 954 | 'id' => $quoteId->internal_quote_id, |
| 955 | ]; |
| 956 | } else { |
| 957 | $failedSyncs[] = [ |
| 958 | 'id' => $quoteId->internal_quote_id, |
| 959 | 'error' => "Error updating the internal quote id $quoteId, work $idsConcatenados.", |
| 960 | ]; |
| 961 | |
| 962 | } |
| 963 | } |
| 964 | |
| 965 | $cofraiUpdate = TblCofraiLastUpdate::where('region', $region)->first(); |
| 966 | if ($cofraiUpdate) { |
| 967 | $cofraiUpdate->update(['updatingNow' => 0]); |
| 968 | } |
| 969 | |
| 970 | return [ |
| 971 | 'success' => true, |
| 972 | 'message' => 'Synchronization of budgets works completed.', |
| 973 | ]; |
| 974 | }); |
| 975 | |
| 976 | TblQuotations::where('acceptance_date', '0000-00-00 00:00:00')->update(['acceptance_date' => null]); |
| 977 | |
| 978 | $this->updateLogs($failedSyncs, $successfulSyncs, $successIdSyncs, $startCronDateTime, $name, $region, 'Orders Works'); |
| 979 | |
| 980 | return $result; |
| 981 | |
| 982 | } catch (\Exception $e) { |
| 983 | Log::channel('cofrai')->error('Error when synchronizing budgets works: '.$e->getMessage()); |
| 984 | |
| 985 | $lastUpdate = TblCofraiLastUpdate::where('region', $region)->first(); |
| 986 | if ($lastUpdate?->updatingNow === 1) { |
| 987 | $lastUpdate->update(['updatingNow' => 0]); |
| 988 | } |
| 989 | |
| 990 | return ['success' => false, 'error' => $e->getMessage()]; |
| 991 | } |
| 992 | } |
| 993 | |
| 994 | /** |
| 995 | * @return void |
| 996 | */ |
| 997 | public function notifyErrors($failedSyncs) |
| 998 | { |
| 999 | $errorDetails = array_map(function ($failure) { |
| 1000 | return "Budget ID: {$failure['id']}, Error: {$failure['error']}"; |
| 1001 | }, $failedSyncs); |
| 1002 | |
| 1003 | $message = implode("\n", $errorDetails); |
| 1004 | |
| 1005 | /* Mail::luis, rick & chris, tech@fire.es */ |
| 1006 | |
| 1007 | Log::channel('cofrai')->error('Error notification sent to ricardo.alemany@fire.es'); |
| 1008 | } |
| 1009 | |
| 1010 | public function generateQuoteId($companyId) |
| 1011 | { |
| 1012 | try { |
| 1013 | |
| 1014 | $companyId = addslashes($companyId); |
| 1015 | $latestBudget = []; |
| 1016 | $number = 0; |
| 1017 | $beforeLastId = null; |
| 1018 | |
| 1019 | $x = true; |
| 1020 | |
| 1021 | if ($companyId == 0) { |
| 1022 | $latestBudget = TblQuotations::orderByRaw('CAST(quote_id AS DOUBLE) DESC')->pluck('quote_id')->first(); |
| 1023 | } else { |
| 1024 | $latestBudget = TblCompanies::where('company_id', $companyId)->pluck('last_id')->first(); |
| 1025 | |
| 1026 | if ($latestBudget == null) { |
| 1027 | $latestBudget = TblQuotations::where('company_id', $companyId)->orderByRaw('id DESC')->pluck('quote_id')->first(); |
| 1028 | $beforeLastId = $latestBudget; |
| 1029 | } |
| 1030 | } |
| 1031 | |
| 1032 | $number = $latestBudget; |
| 1033 | |
| 1034 | while ($x) { |
| 1035 | |
| 1036 | if (is_numeric(substr($number, -1))) { |
| 1037 | $number++; |
| 1038 | } else { |
| 1039 | $number .= '1'; |
| 1040 | } |
| 1041 | |
| 1042 | $check = 0; |
| 1043 | |
| 1044 | if ($companyId == 0) { |
| 1045 | $check = TblQuotations::where('quote_id', (string) $number)->count(); |
| 1046 | } else { |
| 1047 | $check = TblQuotations::where('company_id', $companyId)->where('quote_id', (string) $number)->count(); |
| 1048 | } |
| 1049 | |
| 1050 | if ($check == 0) { |
| 1051 | $x = false; |
| 1052 | } |
| 1053 | } |
| 1054 | |
| 1055 | $result = TblQuotations::create(['quote_id' => $number, 'company_id' => $companyId, 'for_add' => 1]); |
| 1056 | |
| 1057 | if ($beforeLastId == null) { |
| 1058 | $beforeLastId = $number; |
| 1059 | } |
| 1060 | |
| 1061 | $query = "UPDATE tbl_companies SET last_id = '{$number}', before_last_id = CASE WHEN before_last_id IS NULL THEN '{$beforeLastId}' ELSE before_last_id END WHERE company_id = {$companyId}"; |
| 1062 | DB::select($query); |
| 1063 | |
| 1064 | return [ |
| 1065 | 'id' => $result->id, |
| 1066 | 'number' => $number, |
| 1067 | ]; |
| 1068 | |
| 1069 | } catch (\Exception $e) { |
| 1070 | return response(['message' => 'KO', 'error' => $e->getMessage()]); |
| 1071 | } |
| 1072 | } |
| 1073 | |
| 1074 | /** |
| 1075 | * Function to normalice the status provided by cofrai. |
| 1076 | * |
| 1077 | * @param $status String Row status of cofrai |
| 1078 | * @return int ID normalized in FST |
| 1079 | * |
| 1080 | * @throws \Exception |
| 1081 | */ |
| 1082 | private function normalizeStatus($status) |
| 1083 | { |
| 1084 | // Mirror of PresupuestosService::normalizeStatus(). The Cofrai |
| 1085 | // mapping table column is `name_cofrai` (per the migration at |
| 1086 | // 2026_04_29_000001_codify_cofrai_schema_fire982.php) and the |
| 1087 | // controller's setMappings/getMappings already populate it via |
| 1088 | // the same column. `budget.status` from Cofrai is an integer — |
| 1089 | // callers cast it to string before passing it in so the lookup |
| 1090 | // is type-safe. |
| 1091 | if (! $status) { |
| 1092 | $fallback = TblBudgetStatus::where('name', 'Sin estado en cofrai')->first() |
| 1093 | ?? TblBudgetStatus::where('name', 'Sin estado en G3W')->first(); |
| 1094 | |
| 1095 | return $fallback ? $fallback->budget_status_id : null; |
| 1096 | } |
| 1097 | |
| 1098 | $statusMapping = TblStatusCofraiMapping::where('name_cofrai', $status)->first(); |
| 1099 | |
| 1100 | if (! $statusMapping) { |
| 1101 | TblStatusCofraiMapping::create([ |
| 1102 | 'name_cofrai' => $status, |
| 1103 | 'budget_status_id' => 0, |
| 1104 | ]); |
| 1105 | $fallback = TblBudgetStatus::where('name', 'Estado no reconocido en FST')->first(); |
| 1106 | |
| 1107 | return $fallback ? $fallback->budget_status_id : null; |
| 1108 | } |
| 1109 | |
| 1110 | return $statusMapping->budget_status_id; |
| 1111 | } |
| 1112 | |
| 1113 | /** |
| 1114 | * Function to normalice the segment provided by cofrai. |
| 1115 | * |
| 1116 | * @param $status String Row status of cofrai |
| 1117 | * @return int ID normalized in FST |
| 1118 | * |
| 1119 | * @throws \Exception |
| 1120 | */ |
| 1121 | private function normalizeSegment($segment) |
| 1122 | { |
| 1123 | $segmentMapping = TblSegmentCofraiMapping::where('name_cofrai', $segment)->first(); |
| 1124 | |
| 1125 | if (! $segmentMapping) { |
| 1126 | TblSegmentCofraiMapping::create([ |
| 1127 | 'name_cofrai' => $segment, |
| 1128 | 'segment_id' => 0, |
| 1129 | ]); |
| 1130 | |
| 1131 | return TblSegments::where('name', 'Otro')->first()->segment_id ?? 9; |
| 1132 | } |
| 1133 | |
| 1134 | return $segmentMapping->segment_id; |
| 1135 | } |
| 1136 | |
| 1137 | /** |
| 1138 | * Function to normalize the budget type provided by cofrai. |
| 1139 | * |
| 1140 | * @param int $type ID del tipo proporcionado por la API. |
| 1141 | * @param string $region Región (Madrid o Cataluña). |
| 1142 | * @return int ID normalizado del presupuesto en el sistema. |
| 1143 | * |
| 1144 | * @throws \Exception |
| 1145 | */ |
| 1146 | private function normalizeType($type, $region) |
| 1147 | { |
| 1148 | if ($region === 'Catalunya') { |
| 1149 | $region = 'Cataluña'; |
| 1150 | } |
| 1151 | |
| 1152 | $budgetTypeMapping = TblTypeCofraiMapping::where('id_cofrai', $type) |
| 1153 | ->where('region', $region) |
| 1154 | ->first(); |
| 1155 | |
| 1156 | if (! $budgetTypeMapping) { |
| 1157 | TblTypeCofraiMapping::create([ |
| 1158 | 'id_cofrai' => $type ?? null, |
| 1159 | 'budget_type_name' => null, |
| 1160 | 'region' => $region, |
| 1161 | ]); |
| 1162 | throw new \Exception("El estado '$type' no existe en la base de datos."); |
| 1163 | } |
| 1164 | |
| 1165 | $budgetType = TblBudgetTypes::where('name', $budgetTypeMapping->budget_type_name)->first(); |
| 1166 | |
| 1167 | if (! $budgetType) { |
| 1168 | throw new \Exception("El estado '".$budgetTypeMapping->budget_type_name."' no esta normalizado en la base de datos."); |
| 1169 | } |
| 1170 | |
| 1171 | return $budgetType->budget_type_id; |
| 1172 | } |
| 1173 | |
| 1174 | private function normalizeSource($id_call, $region) |
| 1175 | { |
| 1176 | $regionTxt = ''; |
| 1177 | $region = $region == 'Catalunya' ? 'Cataluña' : $region; |
| 1178 | |
| 1179 | if (! $id_call) { |
| 1180 | $sourceDefault = TblSources::where('name', 'cofrai')->first(); |
| 1181 | |
| 1182 | return $sourceDefault->source_id ?? 20; |
| 1183 | } |
| 1184 | |
| 1185 | $sourceMapping = TblSourceCofraiMapping::where('id_cofrai', $id_call) |
| 1186 | ->where('region', $region) |
| 1187 | ->first(); |
| 1188 | |
| 1189 | if (! $sourceMapping) { |
| 1190 | TblSourceCofraiMapping::create([ |
| 1191 | 'id_cofrai' => $id_call, |
| 1192 | 'source_name' => null, |
| 1193 | 'region' => $region, |
| 1194 | ]); |
| 1195 | |
| 1196 | return null; |
| 1197 | } |
| 1198 | |
| 1199 | $sourceId = TblSources::where('name', $sourceMapping->source_name)->first(); |
| 1200 | |
| 1201 | if (! $sourceId) { |
| 1202 | return null; |
| 1203 | } |
| 1204 | |
| 1205 | return $sourceId->source_id; |
| 1206 | |
| 1207 | } |
| 1208 | |
| 1209 | /** |
| 1210 | * @return JsonResponse |
| 1211 | */ |
| 1212 | public function saveDocument($document, $nameDocument = null) |
| 1213 | { |
| 1214 | try { |
| 1215 | $binaryData = base64_decode($document, true); |
| 1216 | |
| 1217 | if ($binaryData === false) { |
| 1218 | throw new \Exception('Los datos Base64 no son válidos.'); |
| 1219 | } |
| 1220 | |
| 1221 | $documentName = $nameDocument |
| 1222 | ? preg_replace('/[^A-Za-z0-9_\-]/', '', $nameDocument).'.pdf' |
| 1223 | : time().'.pdf'; |
| 1224 | |
| 1225 | $filePath = storage_path('app/public/uploads/'.$documentName); |
| 1226 | |
| 1227 | if (! file_exists(dirname($filePath))) { |
| 1228 | mkdir(dirname($filePath), 0777, true); |
| 1229 | } |
| 1230 | |
| 1231 | if (file_put_contents($filePath, $binaryData) === false) { |
| 1232 | throw new \Exception('No se pudo guardar el archivo en el sistema de archivos.'); |
| 1233 | } |
| 1234 | |
| 1235 | return response()->json([ |
| 1236 | 'success' => true, |
| 1237 | 'message' => 'Documento guardado correctamente.', |
| 1238 | 'filePath' => $filePath, |
| 1239 | 'documentName' => $documentName, |
| 1240 | ]); |
| 1241 | } catch (\Exception $e) { |
| 1242 | return response()->json([ |
| 1243 | 'success' => false, |
| 1244 | 'error' => $e->getMessage(), |
| 1245 | ]); |
| 1246 | } |
| 1247 | } |
| 1248 | |
| 1249 | /** |
| 1250 | * @return void |
| 1251 | */ |
| 1252 | public function updateLogs($failedSyncs, $successfulSyncs, $successIdSyncs, $startCronDateTime, $name, $region, $process = null) |
| 1253 | { |
| 1254 | Log::channel('cofrai')->error($failedSyncs); |
| 1255 | |
| 1256 | if ($region === 'Catalunya') { |
| 1257 | $region = 'Cataluña'; |
| 1258 | } |
| 1259 | |
| 1260 | $companyId = TblCompanies::where('region', $region)->first()->company_id; |
| 1261 | $syncStatus = 'Success'; |
| 1262 | $failedSyncsTxt = ''; |
| 1263 | |
| 1264 | if (! empty($failedSyncs)) { |
| 1265 | $syncStatus = ($successfulSyncs > 0) ? 'Partially failed' : 'Failed'; |
| 1266 | $this->notifyErrors($failedSyncs); |
| 1267 | $errorsArray = array_column($failedSyncs, 'error'); |
| 1268 | $failedSyncsTxt = implode(', ', $errorsArray); |
| 1269 | } |
| 1270 | |
| 1271 | $idsError = array_map('intval', array_column($failedSyncs, 'id')); |
| 1272 | $idsError = array_unique($idsError); |
| 1273 | $idsErrorCount = count($idsError); |
| 1274 | $idsErrorJson = json_encode($idsError); |
| 1275 | |
| 1276 | $idsSuccess = array_map('intval', array_column($successIdSyncs, 'id')); |
| 1277 | $idsSuccess = array_unique($idsSuccess); |
| 1278 | $idsSuccessCount = count($idsSuccess); |
| 1279 | $idsSuccessJson = json_encode($idsSuccess); |
| 1280 | |
| 1281 | TblOrdersUpdateLogs::create( |
| 1282 | [ |
| 1283 | 'company_id' => $companyId, |
| 1284 | 'to_process' => $process ?? 'Orders', |
| 1285 | 'status' => $syncStatus, |
| 1286 | 'sync_succesfull' => $idsSuccessCount, |
| 1287 | 'sync_error' => $idsErrorCount, |
| 1288 | 'sync_error_message' => $failedSyncsTxt, |
| 1289 | 'sync_error_ids' => $idsErrorJson, |
| 1290 | 'sync_success_ids' => $idsSuccessJson, |
| 1291 | 'processed_by' => $name, |
| 1292 | 'started_at' => $startCronDateTime, |
| 1293 | 'ended_at' => TblCofraiLastUpdate::where('region', $region)->first()->updated_at->format('Y-m-d H:i:s'), |
| 1294 | ] |
| 1295 | ); |
| 1296 | } |
| 1297 | |
| 1298 | private function checkEmailInvalid($email) |
| 1299 | { |
| 1300 | $emailPattern = "/^[\w\.\-]+@([\w\-]+\.)+[a-zA-Z]{2,}$/"; |
| 1301 | |
| 1302 | $emails = explode(',', $email); |
| 1303 | |
| 1304 | $emailInvalid = false; |
| 1305 | |
| 1306 | foreach ($emails as $email) { |
| 1307 | if (! preg_match($emailPattern, $email)) { |
| 1308 | $emailInvalid = true; |
| 1309 | break; |
| 1310 | } |
| 1311 | } |
| 1312 | |
| 1313 | return $emailInvalid; |
| 1314 | } |
| 1315 | |
| 1316 | private function checkRequiredFields($data) |
| 1317 | { |
| 1318 | |
| 1319 | $cofraiWarningFields = []; |
| 1320 | |
| 1321 | if ($data->budget_status_id == 13 || $data->budget_status_id == 14) { |
| 1322 | array_push($cofraiWarningFields, 'Estado'); |
| 1323 | } |
| 1324 | |
| 1325 | if ($data->budget_type_id == null || $data->budget_type_id == '' || $data->budget_type_id == 0 || $data->budget_type_id == 16) { |
| 1326 | array_push($cofraiWarningFields, 'Tipo'); |
| 1327 | } |
| 1328 | |
| 1329 | if ($data->commercial == null || $data->commercial == '') { |
| 1330 | array_push($cofraiWarningFields, 'Comercial'); |
| 1331 | } |
| 1332 | |
| 1333 | if ($data->source_id == null || $data->source_id == '') { |
| 1334 | array_push($cofraiWarningFields, 'Fuente'); |
| 1335 | } |
| 1336 | |
| 1337 | if ($data->email == null || $data->email == '') { |
| 1338 | array_push($cofraiWarningFields, 'Email'); |
| 1339 | } |
| 1340 | |
| 1341 | if ($data->client == null || $data->client == '') { |
| 1342 | array_push($cofraiWarningFields, 'Datos cliente'); |
| 1343 | } |
| 1344 | |
| 1345 | if (! empty($cofraiWarningFields)) { |
| 1346 | return implode(', ', $cofraiWarningFields); |
| 1347 | } else { |
| 1348 | return null; |
| 1349 | } |
| 1350 | } |
| 1351 | |
| 1352 | public function syncExistingDataWithWarnings() |
| 1353 | { |
| 1354 | |
| 1355 | $budgets = TblQuotations::where('cofrai_warning', 1)->get(); |
| 1356 | |
| 1357 | if (count($budgets) > 0) { |
| 1358 | foreach ($budgets as $item) { |
| 1359 | $cofraiWarning = 0; |
| 1360 | $cofraiWarningFields = $this->checkRequiredFields($item); |
| 1361 | |
| 1362 | if ($cofraiWarningFields != null && $cofraiWarningFields != '') { |
| 1363 | $cofraiWarning = 1; |
| 1364 | } |
| 1365 | |
| 1366 | // FIRE-2115: runs at the start of every Cofrai sync job. Only |
| 1367 | // write when the warning changed; an unconditional update |
| 1368 | // re-stamps updated_at and adds an audit row every run. |
| 1369 | if ((int) $item->cofrai_warning !== $cofraiWarning |
| 1370 | || (string) $item->cofrai_warning_fields !== (string) $cofraiWarningFields) { |
| 1371 | TblQuotations::where('id', $item->id)->update( |
| 1372 | [ |
| 1373 | 'cofrai_warning' => $cofraiWarning, |
| 1374 | 'cofrai_warning_fields' => $cofraiWarningFields, |
| 1375 | ] |
| 1376 | ); |
| 1377 | } |
| 1378 | |
| 1379 | $cofraiWarningFields = null; |
| 1380 | } |
| 1381 | } |
| 1382 | } |
| 1383 | |
| 1384 | public function syncByIds($ids, $region, $date, $user = 'System') |
| 1385 | { |
| 1386 | try { |
| 1387 | if (! $ids) { |
| 1388 | throw new \Exception('No ids provided'); |
| 1389 | } |
| 1390 | |
| 1391 | $arrayIds = explode(',', $ids); |
| 1392 | |
| 1393 | $cofraiActive = TblCompanies::where('region', $region)->first()->cofrai_active; |
| 1394 | |
| 1395 | if (! $cofraiActive || $cofraiActive === 0) { |
| 1396 | throw new Exception("La sincronización con cofrai debe estar desactivada en la region '$region'."); |
| 1397 | } |
| 1398 | |
| 1399 | $this->setSyncStatus(1, $region); |
| 1400 | $this->syncExistingDataWithWarnings(); |
| 1401 | |
| 1402 | $successfulSyncs = 0; |
| 1403 | $failedSyncs = []; |
| 1404 | $successIdSyncs = []; |
| 1405 | |
| 1406 | $startCronDateTime = date('Y-m-d H:i:s'); |
| 1407 | |
| 1408 | $result = DB::transaction(function () use ($arrayIds, &$successfulSyncs, &$failedSyncs, &$successIdSyncs, $region, $date) { |
| 1409 | $company = TblCompanies::where('region', $region)->first(); |
| 1410 | |
| 1411 | $isNullInDate = TblQuotations::where('company_id', $company->company_id) |
| 1412 | ->where('sync_import', 1) |
| 1413 | ->whereDate('created_at', $date) |
| 1414 | ->where('internal_quote_id', null) |
| 1415 | ->exists(); |
| 1416 | |
| 1417 | foreach ($arrayIds as $id) { |
| 1418 | $result['success'] = false; |
| 1419 | $result['error'] = 'Error en sync by Ids'; |
| 1420 | if ($isNullInDate) { |
| 1421 | $result['success'] = $this->syncNullBudget($id, $region, $company->company_id, $date); |
| 1422 | } |
| 1423 | |
| 1424 | if (! $result['success']) { |
| 1425 | $result = $this->syncById($id, $region, $isNullInDate); |
| 1426 | } |
| 1427 | |
| 1428 | if ($result['success']) { |
| 1429 | $successfulSyncs++; |
| 1430 | $successIdSyncs[] = [ |
| 1431 | 'id' => $id, |
| 1432 | ]; |
| 1433 | |
| 1434 | $quote = TblQuotations::where('company_id', $company->company_id) |
| 1435 | ->where('internal_quote_id', $id) |
| 1436 | ->first(); |
| 1437 | |
| 1438 | $quote->update([ |
| 1439 | 'created_at' => Carbon::parse($date), |
| 1440 | ]); |
| 1441 | |
| 1442 | } else { |
| 1443 | if (strpos($result['error'], 'No se ha encontrado el presupuesto') === false) { |
| 1444 | $failedSyncs[] = [ |
| 1445 | 'id' => $id, |
| 1446 | 'error' => $result['error'] ?? 'Unknown error', |
| 1447 | ]; |
| 1448 | } |
| 1449 | } |
| 1450 | } |
| 1451 | |
| 1452 | $this->setSyncStatus(0, $region); |
| 1453 | |
| 1454 | TblQuotations::where('acceptance_date', '0000-00-00 00:00:00')->update(['acceptance_date' => null]); |
| 1455 | |
| 1456 | return [ |
| 1457 | 'success' => true, |
| 1458 | 'message' => 'Synchronization completed.', |
| 1459 | ]; |
| 1460 | }); |
| 1461 | |
| 1462 | $this->updateLogs($failedSyncs, $successfulSyncs, $successIdSyncs, $startCronDateTime, $user, $region); |
| 1463 | |
| 1464 | return $result; |
| 1465 | |
| 1466 | } catch (\Exception $e) { |
| 1467 | Log::channel('cofrai')->error('Error sincronizando los presupuestos: '.$e->getMessage()); |
| 1468 | |
| 1469 | $lastUpdate = TblCofraiLastUpdate::where('region', $region)->first(); |
| 1470 | if ($lastUpdate?->updatingNow === 1) { |
| 1471 | $lastUpdate->update(['updatingNow' => 0]); |
| 1472 | } |
| 1473 | |
| 1474 | return ['success' => false, 'error' => $e->getMessage()]; |
| 1475 | } |
| 1476 | |
| 1477 | } |
| 1478 | |
| 1479 | private function syncNullBudget($id, $region, $companyId, $date) |
| 1480 | { |
| 1481 | $budget = $this->request('get', "presupuesto/{$id}", $region, []); |
| 1482 | |
| 1483 | if (! isset($budget['presupuesto']) || ! is_array($budget['presupuesto'])) { |
| 1484 | throw new \Exception('El presupuesto no contiene los datos esperados.'); |
| 1485 | } |
| 1486 | |
| 1487 | $quote = TblQuotations::where('company_id', $companyId) |
| 1488 | ->where('sync_import', 1) |
| 1489 | ->whereDate('created_at', $date) |
| 1490 | ->where('internal_quote_id', null) |
| 1491 | ->where('source_by_cofrai', $budget['presupuesto']['cod_empresa_presupuesto'] ?? null) |
| 1492 | ->where('type_by_cofrai', $budget['presupuesto']['origen_presupuesto'] ?? null) |
| 1493 | ->where('user_create_by_cofrai', $budget['presupuesto']['usuario']) |
| 1494 | ->where('user_commercial_by_cofrai', ! empty($budget['presupuesto']['cod_comercial_presupuesto']) ? $budget['presupuesto']['cod_comercial_presupuesto'] : null) |
| 1495 | ->first(); |
| 1496 | |
| 1497 | if (! $quote) { |
| 1498 | return false; |
| 1499 | } |
| 1500 | |
| 1501 | $quote->update([ |
| 1502 | 'internal_quote_id' => $id, |
| 1503 | ]); |
| 1504 | |
| 1505 | return true; |
| 1506 | } |
| 1507 | } |