option('legacy'))); $dry = (bool) $this->option('dry'); $forcedTenant = $this->option('tenant'); $query = GesconImportMapping::query() ->whereNotNull('legacy_code') ->where('legacy_code', '!=', ''); if (!empty($legacyFilter)) { $query->whereIn('legacy_code', $legacyFilter); } $mappings = $query ->orderBy('legacy_code') ->get() ->unique('legacy_code'); if ($mappings->isEmpty()) { $this->warn('Nessun mapping disponibile per la sincronizzazione.'); return Command::SUCCESS; } $this->info(sprintf('Sincronizzazione stabili (%d) %s', $mappings->count(), $dry ? '(DRY-RUN)' : '')); $updated = 0; $created = 0; foreach ($mappings as $mapping) { $legacyCode = (string) $mapping->legacy_code; if ($legacyCode === '' || $legacyCode === '*') { $this->line('• [*] mapping globale ignorato'); continue; } $meta = (array) ($mapping->meta ?? []); $user = User::find($mapping->user_id); $tenantId = $forcedTenant ?? ($user->tenant_id ?? 'default'); $importer = new QuickStabiliImporter((string) $tenantId); if ($dry) { $this->line(sprintf('• [%s] DRY-RUN → salterei import (tenant "%s")', $legacyCode, $tenantId)); continue; } try { $result = $importer->import($legacyCode, $meta); if (!($result['ok'] ?? false)) { $this->error(sprintf('× [%s] Import fallito: %s', $legacyCode, $result['error'] ?? 'errore sconosciuto')); continue; } $created += (int) ($result['created'] ?? 0); $updated += (int) ($result['updated'] ?? 0); $stabileId = $result['stabile_id'] ?? null; $this->line(sprintf( '✓ [%s] stabile #%s: created=%d updated=%d', $legacyCode, $stabileId ?: '—', (int) ($result['created'] ?? 0), (int) ($result['updated'] ?? 0) )); } catch (\Throwable $e) { $this->error(sprintf('× [%s] Eccezione: %s', $legacyCode, $e->getMessage())); } } if (!$dry) { $this->info(sprintf('Completato. Nuovi stabili: %d · Aggiornati: %d', $created, $updated)); } return Command::SUCCESS; } }