migration #13

Closed
brontomark wants to merge 2 commits from migration into main
3 changed files with 1554 additions and 4 deletions
Showing only changes of commit 5214ea9745 - Show all commits

View File

@@ -87,7 +87,7 @@ class _CustomersContentState extends State<CustomersContent> {
//TODO cancella quando import finito //TODO cancella quando import finito
ElevatedButton( ElevatedButton(
onPressed: () => migrateModelsToSupabase(), onPressed: () => migrateTicketsToSupabase(),
child: const Text('migra clienti'), child: const Text('migra clienti'),
), ),

View File

@@ -75,7 +75,7 @@ Future<void> migrateModelsToSupabase() async {
// Creiamo la mappa: la chiave è il vecchio ID, il valore è il nuovo UUID // Creiamo la mappa: la chiave è il vecchio ID, il valore è il nuovo UUID
Map<String, String> brandTranslationMap = {}; Map<String, String> brandTranslationMap = {};
for (var b in brandResponse) { for (var b in brandResponse) {
if (b['legacy_firestore_id'] != null) { if (b['legacy_id'] != null) {
brandTranslationMap[b['legacy_id']] = b['id']; brandTranslationMap[b['legacy_id']] = b['id'];
} }
} }
@@ -125,7 +125,7 @@ Future<void> migrateModelsToSupabase() async {
'brand_id': newSupabaseBrandUuid, 'brand_id': newSupabaseBrandUuid,
// Mappa gli altri campi // Mappa gli altri campi
'name': (data['name'] as String).trim().toLowerCase(), 'name': (data['nome'] as String).trim().toLowerCase(),
'name_with_brand': (data['nomeConMarca'] as String) 'name_with_brand': (data['nomeConMarca'] as String)
.toLowerCase() .toLowerCase()
.trim(), .trim(),
@@ -146,3 +146,126 @@ Future<void> migrateModelsToSupabase() async {
print("Errore durante la migrazione dei modelli: $e"); print("Errore durante la migrazione dei modelli: $e");
} }
} }
Future<void> migrateTicketsToSupabase() async {
final String myRealCompanyId = '6c4b2323-2a60-4d33-bf21-c5a8eb6b4a5b';
final String myRealStoreId = '782a4638-1c03-40af-9060-9ef214a3e238';
try {
print("Inizio migrazione Ticket...");
// ==========================================================
// FASE 1: CREAZIONE DEL DIZIONARIO DI TRADUZIONE (LA MAGIA)
// ==========================================================
print("Scarico i Brand da Supabase per tradurre gli ID...");
// Chiediamo a Supabase solo 2 colonne: il nuovo UUID e il vecchio ID di Firebase
final List<dynamic> customerResponse = await Supabase.instance.client
.from('customer')
.select('id, legacy_id');
// Creiamo la mappa: la chiave è il vecchio ID, il valore è il nuovo UUID
Map<String, String> customerTranslationMap = {};
for (var b in customerResponse) {
if (b['legacy_id'] != null) {
customerTranslationMap[b['legacy_id']] = b['id'];
}
}
final List<dynamic> modelResponse = await Supabase.instance.client
.from('model')
.select('id, legacy_id');
Map<String, String> modelTranslationMap = {};
for (var b in modelResponse) {
if (b['legacy_id'] != null) {
modelTranslationMap[b['legacy_id']] = b['id'];
}
}
print(
"Dizionario pronto! Trovati ${customerTranslationMap.length} clienti e ${modelTranslationMap.length} modelli.",
);
// ==========================================================
// FASE 2: SCARICAMENTO E TRADUZIONE DEI MODELLI
// ==========================================================
final snapshot = await FirebaseFirestore.instance
.collection('schedeRiparazione')
.get(); // Controlla il nome esatto della collection!
if (snapshot.docs.isEmpty) {
print("Nessun scheda trovato su Firebase!");
return;
}
List<Map<String, dynamic>> supabaseTickets = [];
for (var doc in snapshot.docs) {
final data = doc.data();
// 1. Prendiamo il vecchio ID del brand salvato su Firebase
String? oldFirebaseCustomerId = data['idCliente'];
String? oldFirebaseModelId = data['idModello'];
// 2. TRADUZIONE ISTANTANEA! Cerchiamo il nuovo UUID nel nostro dizionario
String? newSupabaseCustomerUuid;
if (oldFirebaseCustomerId != null) {
newSupabaseCustomerUuid = customerTranslationMap[oldFirebaseCustomerId];
}
String? newSupabaseModelUuid;
if (oldFirebaseModelId != null) {
newSupabaseModelUuid = modelTranslationMap[oldFirebaseModelId];
}
// 3. Controllo di sicurezza: se il brand non esiste su Supabase, saltiamo il record o mettiamo null?
// Se nella tua tabella 'model' il 'brand_id' NON PUÒ essere null, devi per forza avere un match!
if (newSupabaseCustomerUuid == null &&
newSupabaseModelUuid == null &&
oldFirebaseCustomerId != null &&
oldFirebaseModelId != null) {
print(
"ATTENZIONE: La scheda di riparazione${data['numeroScheda']} ha un customer_id ($oldFirebaseCustomerId) o un model_id ($oldFirebaseModelId) che non esiste su Supabase. Salto o metto null.",
);
continue; // Decommenta questo se vuoi saltare i modelli orfani
}
// Creiamo la riga per Supabase
supabaseTickets.add({
'legacy_id': doc.id,
'customer_id': newSupabaseCustomerUuid,
// Mappa gli altri campi
'created_at':
(data['dataCreazione'] as Timestamp?)?.toDate().toIso8601String() ??
DateTime.now().toIso8601String(),
'company_id': myRealCompanyId,
'store_id': myRealStoreId,
'ticket_type': 'repair',
'target_model_id': newSupabaseModelUuid,
'returned_at': (data['dataRiconsegnaCliente'] as Timestamp?)
?.toDate()
.toIso8601String(),
'request': (data['guasto'] as String?)?.toLowerCase().trim(),
'public_notes': data['note'],
'internal_notes': data['noteInterne'],
'reference_number': data['numeroScheda'],
});
}
// ==========================================================
// FASE 3: INVIO A SUPABASE
// ==========================================================
print("Sto per inviare ${supabaseTickets.length} tickets a Supabase...");
await Supabase.instance.client
.from('ticket')
.upsert(supabaseTickets, onConflict: 'legacy_id');
print("BOOM! Migrazione ticket completata con successo! 🚀");
} catch (e) {
print("Errore durante la migrazione dei ticket: $e");
}
}

File diff suppressed because it is too large Load Diff