Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
0.00% |
0 / 156 |
|
0.00% |
0 / 4 |
CRAP | |
0.00% |
0 / 1 |
| CofraiBulkSyncService | |
0.00% |
0 / 156 |
|
0.00% |
0 / 4 |
930 | |
0.00% |
0 / 1 |
| quotations | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
6 | |||
| listBulkSyncRegions | |
0.00% |
0 / 9 |
|
0.00% |
0 / 1 |
2 | |||
| syncSpecificFieldsForId | |
0.00% |
0 / 85 |
|
0.00% |
0 / 1 |
342 | |||
| bulkSyncByFilters | |
0.00% |
0 / 59 |
|
0.00% |
0 / 1 |
90 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace App\Services; |
| 4 | |
| 5 | use App\Models\TblCofraiBulkSyncRuns; |
| 6 | use App\Models\TblCompanies; |
| 7 | use App\Models\TblQuotations; |
| 8 | use Illuminate\Support\Carbon; |
| 9 | use Illuminate\Support\Facades\DB; |
| 10 | use Illuminate\Support\Facades\Log; |
| 11 | |
| 12 | /** |
| 13 | * Cofrai mirror of the bulk-sync surface added to PresupuestosService by |
| 14 | * FIRE-1170. Lives as a sibling service (rather than a patch on |
| 15 | * CofraiQuotationsService) so the daily-sync code path stays untouched — |
| 16 | * the bulk-sync orchestrator only needs to call existing Cofrai sync |
| 17 | * primitives (`syncById`, `syncModifiedBudgetById`) and the field-allowlist |
| 18 | * revert is computed locally here. |
| 19 | * |
| 20 | * Key Cofrai-vs-G3W divergences: |
| 21 | * |
| 22 | * - **Date field name**: G3W's `presupuesto.fecha_creacion` becomes |
| 23 | * Cofrai's `budget.date` (per the model schema in |
| 24 | * docs/info/cofrai/cofrai-documentation.json). The bulk-sync filter |
| 25 | * asks Cofrai for `model/sync?model=budget&fields=id,date&filters[date][from]=…&filters[date][to]=…`, |
| 26 | * which uses Cofrai's documented range-filter idiom. |
| 27 | * |
| 28 | * - **Internal-quote-id**: Cofrai stores the budget id directly as |
| 29 | * `internal_quote_id` (no `cod_presupuesto` indirection), so the |
| 30 | * existence-check predicate is `internal_quote_id == budget.id`. |
| 31 | * |
| 32 | * - **Approval flow**: Cofrai's `syncById` / `syncModifiedBudgetById` |
| 33 | * don't yet send approval emails or compute `for_approval` (per the |
| 34 | * TODO comments in CofraiQuotationsService). So the `suppressOps` / |
| 35 | * `suppressFin` toggles are **stored** on the run row for forward |
| 36 | * compatibility and audit, but have **no behavioral effect today**. |
| 37 | * When the Cofrai approval flow lands, the sibling agent owning that |
| 38 | * work should read `$bulkSyncContext` (mirroring the G3W pattern in |
| 39 | * PresupuestosService::syncModifiedBudgetById). |
| 40 | * |
| 41 | * - **Sync-managed columns**: Cofrai's `*_by_cofrai` provenance fields |
| 42 | * are excluded from the allowlist — they're always sync-managed. |
| 43 | * |
| 44 | * - **Active-region check**: `tbl_companies.cofrai_active = 1` (parallels |
| 45 | * G3W's `g3W_active = 1`). |
| 46 | * |
| 47 | * - **Source discrimination**: when checking if a TblQuotations row |
| 48 | * already exists for a given internal_quote_id, we restrict to rows |
| 49 | * that are Cofrai-managed (`sync_cofrai_import = 1` OR any of the |
| 50 | * `*_by_cofrai` provenance columns are populated). This is the |
| 51 | * forward-compatible predicate the parent will reconcile with the |
| 52 | * FIRE-1201 source-collision fix. |
| 53 | */ |
| 54 | class CofraiBulkSyncService extends CofraiService |
| 55 | { |
| 56 | /** |
| 57 | * Per-job context for bulk-sync. When non-null, future Cofrai sync |
| 58 | * paths can consult this to suppress the approval email (when |
| 59 | * `suppressOps` is true) and clamp the recomputed `for_approval` to |
| 60 | * a max of 1 (when `suppressFin` is true). The contract is "set |
| 61 | * before calling the sync, reset in finally" — see |
| 62 | * `syncSpecificFieldsForId`. |
| 63 | * |
| 64 | * No-op today (Cofrai's sync methods don't read it yet), but kept so |
| 65 | * the wiring is in place when the Cofrai approval flow lands. |
| 66 | */ |
| 67 | public ?array $bulkSyncContext = null; |
| 68 | |
| 69 | /** |
| 70 | * Columns that bulk-sync exposes as user-selectable. Anything not |
| 71 | * in this list (sync_cofrai_import, *_by_cofrai, for_add, |
| 72 | * has_attachment, etc.) is sync-managed and always written. Order |
| 73 | * does not matter; we use array_diff against the field-allowlist to |
| 74 | * compute the revert payload. |
| 75 | */ |
| 76 | private const BULK_SYNC_USER_COLUMNS = [ |
| 77 | 'client', 'customer_type_id', 'segment_id', 'phone_number', 'email', |
| 78 | 'budget_type_id', 'budget_status_id', 'source_id', 'commercial', 'amount', |
| 79 | 'issue_date', 'request_date', 'acceptance_date', 'accepted_at', 'accepted_by', |
| 80 | 'last_follow_up_date', |
| 81 | 'cost_of_labor', 'total_cost_of_job', 'invoice_margin', 'margin_for_the_company', |
| 82 | 'revenue_per_date_per_worked', 'gross_margin', 'labor_percentage', |
| 83 | ]; |
| 84 | |
| 85 | /** |
| 86 | * Maps a UI checkbox name to the DB columns it controls. The `margins` |
| 87 | * checkbox is a bundle — picking it toggles all 7 margin columns |
| 88 | * together because they're computed from amount + project type and |
| 89 | * would produce inconsistent state if split. The `acceptance_date` |
| 90 | * checkbox also covers `accepted_at` + `accepted_by` because the three |
| 91 | * are derived from the same Cofrai payload field. |
| 92 | */ |
| 93 | public const BULK_SYNC_FIELD_MAP = [ |
| 94 | 'client' => ['client'], |
| 95 | 'customer_type_id' => ['customer_type_id'], |
| 96 | 'segment_id' => ['segment_id'], |
| 97 | 'phone_number' => ['phone_number'], |
| 98 | 'email' => ['email'], |
| 99 | 'budget_type_id' => ['budget_type_id'], |
| 100 | 'budget_status_id' => ['budget_status_id'], |
| 101 | 'source_id' => ['source_id'], |
| 102 | 'commercial' => ['commercial'], |
| 103 | 'amount' => ['amount'], |
| 104 | 'issue_date' => ['issue_date'], |
| 105 | 'request_date' => ['request_date'], |
| 106 | 'acceptance_date' => ['acceptance_date', 'accepted_at', 'accepted_by'], |
| 107 | 'last_follow_up_date' => ['last_follow_up_date'], |
| 108 | 'margins' => [ |
| 109 | 'cost_of_labor', 'total_cost_of_job', 'invoice_margin', |
| 110 | 'margin_for_the_company', 'revenue_per_date_per_worked', |
| 111 | 'gross_margin', 'labor_percentage', |
| 112 | ], |
| 113 | ]; |
| 114 | |
| 115 | private ?CofraiQuotationsService $quotationsService = null; |
| 116 | |
| 117 | /** |
| 118 | * Lazy accessor for CofraiQuotationsService — keeping the dependency |
| 119 | * lazy lets the constructor signature stay parameterless (matching |
| 120 | * CofraiService) and avoids construction-order surprises in tests. |
| 121 | */ |
| 122 | private function quotations(): CofraiQuotationsService |
| 123 | { |
| 124 | if ($this->quotationsService === null) { |
| 125 | $this->quotationsService = app(CofraiQuotationsService::class); |
| 126 | } |
| 127 | |
| 128 | return $this->quotationsService; |
| 129 | } |
| 130 | |
| 131 | /** |
| 132 | * List regions that bulk-sync can target. Returns the regions of every |
| 133 | * company with Cofrai sync turned on. The "Todas las regiones" sticky |
| 134 | * option in the UI is purely client-side — we never return that here. |
| 135 | * |
| 136 | * @return array<int,string> |
| 137 | */ |
| 138 | public function listBulkSyncRegions(): array |
| 139 | { |
| 140 | return TblCompanies::query() |
| 141 | ->where('cofrai_active', 1) |
| 142 | ->whereNotNull('region') |
| 143 | ->where('region', '!=', '') |
| 144 | ->orderBy('region') |
| 145 | ->pluck('region') |
| 146 | ->unique() |
| 147 | ->values() |
| 148 | ->all(); |
| 149 | } |
| 150 | |
| 151 | /** |
| 152 | * Per-budget bulk-sync worker. **Upsert** — updates existing rows with |
| 153 | * the field allowlist applied; creates missing rows in full (allowlist |
| 154 | * doesn't apply because there's nothing to preserve on insert). |
| 155 | * |
| 156 | * Must run inside a DB transaction so the write-then-revert window |
| 157 | * never exposes wrong values to other readers. |
| 158 | * |
| 159 | * @param array<int,string> $fields UI checkbox names — see BULK_SYNC_FIELD_MAP. |
| 160 | * @return array{status: string, columns?: array<int,string>, reason?: string} |
| 161 | */ |
| 162 | public function syncSpecificFieldsForId( |
| 163 | string $cofraiId, |
| 164 | string $region, |
| 165 | array $fields, |
| 166 | bool $suppressOps, |
| 167 | bool $suppressFin, |
| 168 | int $bulkSyncRunId, |
| 169 | ?string $dateFrom = null, |
| 170 | ?string $dateTo = null |
| 171 | ): array { |
| 172 | // 1. Fetch the Cofrai payload upfront so we can do an accurate |
| 173 | // existence check via `internal_quote_id == budget.id` (matching |
| 174 | // syncById's own lookup). The pre-fetch costs one extra Cofrai |
| 175 | // call per budget; that's acceptable for an admin-triggered bulk |
| 176 | // run and the `cofrai` rate-limiter caps the total load anyway. |
| 177 | $response = $this->request( |
| 178 | 'get', |
| 179 | "model/sync?model=budget&ids={$cofraiId}&fields=id,date", |
| 180 | $region, |
| 181 | [] |
| 182 | ); |
| 183 | |
| 184 | $budgetData = $response['data'][0] ?? null; |
| 185 | if (! is_array($budgetData) || ! isset($budgetData['id'])) { |
| 186 | return ['status' => 'skipped', 'reason' => 'bad_cofrai_payload']; |
| 187 | } |
| 188 | |
| 189 | // Date-range filter on the budget's `date` field (Cofrai's |
| 190 | // equivalent of G3W's `fecha_creacion`). Cofrai's |
| 191 | // `model/sync?model=budget&filters[date][from]=…&filters[date][to]=…` |
| 192 | // already filters server-side; this second check protects against |
| 193 | // (a) Cofrai returning slight drift and (b) future callers that |
| 194 | // skip the range filter on the orchestrator side. |
| 195 | if ($dateFrom !== null && $dateTo !== null) { |
| 196 | $rawCreated = $budgetData['date'] ?? null; |
| 197 | $creationDate = $rawCreated ? substr((string) $rawCreated, 0, 10) : null; |
| 198 | if (! $creationDate || $creationDate < $dateFrom || $creationDate > $dateTo) { |
| 199 | return ['status' => 'skipped', 'reason' => 'outside_creation_date_range']; |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | $companyIds = TblCompanies::where('region', $region)->pluck('company_id'); |
| 204 | |
| 205 | // Source-discrimination predicate — mirrors what the FIRE-1201 |
| 206 | // fix lands for the regular Cofrai syncById. Only count a row as |
| 207 | // "already exists in Cofrai" if it carries Cofrai provenance, |
| 208 | // i.e. either the canonical sync flag or one of the provenance |
| 209 | // columns is populated. A row with the same internal_quote_id |
| 210 | // but exclusively G3W provenance must NOT collide here. The |
| 211 | // parent agent should reconcile this predicate with whatever |
| 212 | // shape FIRE-1201 finally adopts. |
| 213 | $existing = TblQuotations::query() |
| 214 | ->where('internal_quote_id', $cofraiId) |
| 215 | ->whereIn('company_id', $companyIds) |
| 216 | ->where(function ($q) { |
| 217 | $q->where('sync_cofrai_import', 1) |
| 218 | ->orWhereNotNull('segment_by_cofrai') |
| 219 | ->orWhereNotNull('source_by_cofrai') |
| 220 | ->orWhereNotNull('status_by_cofrai') |
| 221 | ->orWhereNotNull('type_by_cofrai') |
| 222 | ->orWhereNotNull('user_create_by_cofrai') |
| 223 | ->orWhereNotNull('user_commercial_by_cofrai'); |
| 224 | }) |
| 225 | ->first(); |
| 226 | |
| 227 | $this->bulkSyncContext = [ |
| 228 | 'suppressOps' => $suppressOps, |
| 229 | 'suppressFin' => $suppressFin, |
| 230 | 'bulkSyncRunId' => $bulkSyncRunId, |
| 231 | ]; |
| 232 | |
| 233 | try { |
| 234 | if (! $existing) { |
| 235 | // INSERT path — delegate to syncById which hits the create |
| 236 | // branch. The field allowlist doesn't apply on insert |
| 237 | // (nothing to preserve) so we write all columns the same |
| 238 | // as a regular sync would. Approval-flow suppression |
| 239 | // (suppressOps / suppressFin) is a no-op today on Cofrai |
| 240 | // because Cofrai's syncById doesn't yet fire approval |
| 241 | // emails; the context is set on $this so a future Cofrai |
| 242 | // approval implementation can read it. |
| 243 | $this->quotations()->syncById($cofraiId, $region); |
| 244 | |
| 245 | $created = TblQuotations::query() |
| 246 | ->where('internal_quote_id', $cofraiId) |
| 247 | ->whereIn('company_id', $companyIds) |
| 248 | ->first(); |
| 249 | |
| 250 | if ($created) { |
| 251 | DB::table('tbl_quotations_log') |
| 252 | ->where('quotation_id', $created->id) |
| 253 | ->whereNull('bulk_sync_run_id') |
| 254 | ->update(['bulk_sync_run_id' => $bulkSyncRunId]); |
| 255 | } |
| 256 | |
| 257 | return ['status' => 'created']; |
| 258 | } |
| 259 | |
| 260 | // UPDATE path — snapshot, sync, then revert columns outside |
| 261 | // the allowlist. This is what implements the "only the |
| 262 | // checked fields are overwritten" contract from the ticket. |
| 263 | $before = collect(self::BULK_SYNC_USER_COLUMNS) |
| 264 | ->mapWithKeys(fn ($col) => [$col => $existing->{$col} ?? null]) |
| 265 | ->all(); |
| 266 | |
| 267 | $allowedCols = []; |
| 268 | foreach ($fields as $field) { |
| 269 | foreach (self::BULK_SYNC_FIELD_MAP[$field] ?? [] as $col) { |
| 270 | $allowedCols[$col] = true; |
| 271 | } |
| 272 | } |
| 273 | $allowedCols = array_keys($allowedCols); |
| 274 | |
| 275 | $maxLogIdBefore = (int) DB::table('tbl_quotations_log') |
| 276 | ->where('quotation_id', $existing->id) |
| 277 | ->max('id') ?: 0; |
| 278 | |
| 279 | $this->quotations()->syncModifiedBudgetById($cofraiId, $region); |
| 280 | |
| 281 | $existing->refresh(); |
| 282 | $revertPayload = []; |
| 283 | $revertedColumns = []; |
| 284 | foreach (self::BULK_SYNC_USER_COLUMNS as $col) { |
| 285 | if (in_array($col, $allowedCols, true)) { |
| 286 | continue; |
| 287 | } |
| 288 | $beforeVal = $before[$col] ?? null; |
| 289 | $afterVal = $existing->{$col} ?? null; |
| 290 | if ($beforeVal != $afterVal) { |
| 291 | $revertPayload[$col] = $beforeVal; |
| 292 | $revertedColumns[] = $col; |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | if (! empty($revertPayload)) { |
| 297 | TblQuotations::where('id', $existing->id)->update($revertPayload); |
| 298 | DB::table('tbl_quotations_log') |
| 299 | ->where('quotation_id', $existing->id) |
| 300 | ->where('id', '>', $maxLogIdBefore) |
| 301 | ->whereIn('field', $revertedColumns) |
| 302 | ->delete(); |
| 303 | } |
| 304 | |
| 305 | DB::table('tbl_quotations_log') |
| 306 | ->where('quotation_id', $existing->id) |
| 307 | ->where('id', '>', $maxLogIdBefore) |
| 308 | ->whereNull('bulk_sync_run_id') |
| 309 | ->update(['bulk_sync_run_id' => $bulkSyncRunId]); |
| 310 | |
| 311 | return [ |
| 312 | 'status' => 'updated', |
| 313 | 'columns' => array_values(array_diff($allowedCols, $revertedColumns)), |
| 314 | ]; |
| 315 | } finally { |
| 316 | $this->bulkSyncContext = null; |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | /** |
| 321 | * Orchestrate one region of a bulk-sync run. Iterates the date range |
| 322 | * via Cofrai's `model/sync?model=budget&filters[date][from]=…&filters[date][to]=…` |
| 323 | * (one call per day to keep the per-day accounting + retry granularity |
| 324 | * consistent with the G3W version), and runs each budget through the |
| 325 | * field-allowlist worker inside its own transaction. Each row's |
| 326 | * success / skip / error gets accounted against the |
| 327 | * `tbl_cofrai_bulk_sync_runs` row. |
| 328 | * |
| 329 | * Designed to be called from a queued job (see BulkSyncCofraiRun). The |
| 330 | * job holds the `cofrai` rate-limiter + |
| 331 | * `WithoutOverlapping("cofrai:bulk:{region}:{runId}")` lock — there is |
| 332 | * no need to add re-entrancy guards here. |
| 333 | * |
| 334 | * @param array<int,string> $fields |
| 335 | */ |
| 336 | public function bulkSyncByFilters( |
| 337 | int $runId, |
| 338 | string $region, |
| 339 | string $dateFrom, |
| 340 | string $dateTo, |
| 341 | array $fields, |
| 342 | bool $suppressOps, |
| 343 | bool $suppressFin |
| 344 | ): void { |
| 345 | $run = TblCofraiBulkSyncRuns::find($runId); |
| 346 | if (! $run) { |
| 347 | Log::channel('cofrai')->warning("bulkSyncByFilters: run {$runId} not found"); |
| 348 | |
| 349 | return; |
| 350 | } |
| 351 | |
| 352 | $start = microtime(true); |
| 353 | |
| 354 | try { |
| 355 | $period = Carbon::parse($dateFrom)->daysUntil(Carbon::parse($dateTo)); |
| 356 | |
| 357 | foreach ($period as $day) { |
| 358 | $dayStr = $day->format('Y-m-d'); |
| 359 | |
| 360 | // Cofrai's `model/sync` accepts range filters of the form |
| 361 | // `filters[date][from]=X&filters[date][to]=Y`. For a single |
| 362 | // day we set both to the same value — this keeps per-day |
| 363 | // accounting + retry granularity identical to the G3W |
| 364 | // version's `presupuesto?fecha=X` semantics. |
| 365 | $url = 'model/sync?model=budget&fields=id,date' |
| 366 | .'&filters[date][from]='.urlencode($dayStr) |
| 367 | .'&filters[date][to]='.urlencode($dayStr) |
| 368 | .'&per_page=300'; |
| 369 | |
| 370 | $response = $this->request('get', $url, $region, []); |
| 371 | $budgets = $response['data'] ?? null; |
| 372 | if (! is_array($budgets)) { |
| 373 | continue; |
| 374 | } |
| 375 | |
| 376 | foreach ($budgets as $budget) { |
| 377 | $cofraiId = $budget['id'] ?? null; |
| 378 | if (! $cofraiId) { |
| 379 | continue; |
| 380 | } |
| 381 | |
| 382 | $run->increment('total_cofrai_budgets'); |
| 383 | |
| 384 | try { |
| 385 | // attempts=3 retries MySQL deadlocks transparently; |
| 386 | // the bulk-sync writes to tbl_quotations_log can |
| 387 | // collide when two runs (or a run + the daily cron) |
| 388 | // touch the same rows. The retry happens inside |
| 389 | // the same job tick — no double-counting. |
| 390 | $result = DB::transaction(fn () => $this->syncSpecificFieldsForId( |
| 391 | (string) $cofraiId, |
| 392 | $region, |
| 393 | $fields, |
| 394 | $suppressOps, |
| 395 | $suppressFin, |
| 396 | $runId, |
| 397 | $dateFrom, |
| 398 | $dateTo |
| 399 | ), 3); |
| 400 | |
| 401 | $status = $result['status'] ?? null; |
| 402 | if ($status === 'updated') { |
| 403 | $run->increment('updated_count'); |
| 404 | } elseif ($status === 'created') { |
| 405 | $run->increment('created_count'); |
| 406 | } else { |
| 407 | $run->increment('skipped_count'); |
| 408 | } |
| 409 | } catch (\Throwable $e) { |
| 410 | // Atomic UPDATE so concurrent regions' error reports |
| 411 | // don't clobber each other via stale `$run->save()`. |
| 412 | $message = mb_substr($e->getMessage(), 0, 500); |
| 413 | DB::statement( |
| 414 | 'UPDATE tbl_cofrai_bulk_sync_runs |
| 415 | SET errors_json = JSON_SET(COALESCE(errors_json, JSON_OBJECT()), ?, ?), |
| 416 | error_count = error_count + 1 |
| 417 | WHERE id = ?', |
| 418 | ['$."'.$cofraiId.'"', $message, $runId] |
| 419 | ); |
| 420 | Log::channel('cofrai')->error("bulkSyncByFilters error: {$cofraiId} — {$e->getMessage()}"); |
| 421 | } |
| 422 | } |
| 423 | } |
| 424 | } finally { |
| 425 | $run->refresh(); |
| 426 | $run->ended_at = now(); |
| 427 | $run->save(); |
| 428 | Log::channel('cofrai')->info('bulkSyncByFilters finished', [ |
| 429 | 'run_id' => $runId, |
| 430 | 'region' => $region, |
| 431 | 'date_from' => $dateFrom, |
| 432 | 'date_to' => $dateTo, |
| 433 | 'wall_ms' => (int) round((microtime(true) - $start) * 1000), |
| 434 | 'updated' => $run->updated_count, |
| 435 | 'created' => $run->created_count, |
| 436 | 'skipped' => $run->skipped_count, |
| 437 | 'errors' => $run->error_count, |
| 438 | ]); |
| 439 | } |
| 440 | } |
| 441 | } |