84 lines
2.7 KiB
Dart
84 lines
2.7 KiB
Dart
import 'package:supabase_flutter/supabase_flutter.dart';
|
|
import '../models/service_model.dart';
|
|
// Importa gli altri modelli se sono in file separati
|
|
|
|
class ServicesRepository {
|
|
final _supabase = Supabase.instance.client;
|
|
|
|
// --- RECUPERO TUTTI I SERVIZI ---
|
|
Future<List<ServiceModel>> fetchAllServices() async {
|
|
try {
|
|
// La stringa di selezione tira giù il padre e TUTTI i record correlati dalle tabelle figlie
|
|
final response = await _supabase
|
|
.from('service')
|
|
.select('''
|
|
*,
|
|
energy_service(*),
|
|
fin_service(*),
|
|
entertainment_service(*)
|
|
''')
|
|
.order('created_at', ascending: false);
|
|
|
|
return (response as List)
|
|
.map((map) => ServiceModel.fromMap(map))
|
|
.toList();
|
|
} catch (e) {
|
|
throw Exception('Errore nel recupero servizi: $e');
|
|
}
|
|
}
|
|
|
|
// --- SALVATAGGIO COMPLETO (A CASCATA) ---
|
|
Future<void> saveFullService(ServiceModel service) async {
|
|
try {
|
|
// 1. Inserimento Padre
|
|
final serviceData = await _supabase
|
|
.from('service')
|
|
.insert(service.toMap())
|
|
.select()
|
|
.single();
|
|
|
|
final String newId = serviceData['id'];
|
|
|
|
// 2. Inserimento Energy (se presenti)
|
|
if (service.energyServices.isNotEmpty) {
|
|
final List<Map<String, dynamic>> energyToInsert = [];
|
|
for (var item in service.energyServices) {
|
|
energyToInsert.add(item.copyWith(serviceId: newId).toMap());
|
|
}
|
|
await _supabase.from('energy_service').insert(energyToInsert);
|
|
}
|
|
|
|
// 3. Inserimento Finanziamenti (se presenti)
|
|
if (service.finServices.isNotEmpty) {
|
|
final List<Map<String, dynamic>> finToInsert = [];
|
|
for (var item in service.finServices) {
|
|
finToInsert.add(item.copyWith(serviceId: newId).toMap());
|
|
}
|
|
await _supabase.from('fin_service').insert(finToInsert);
|
|
}
|
|
|
|
// 4. Inserimento Entertainment (se presenti)
|
|
if (service.entertainmentServices.isNotEmpty) {
|
|
final List<Map<String, dynamic>> entToInsert = [];
|
|
for (var item in service.entertainmentServices) {
|
|
entToInsert.add(item.copyWith(serviceId: newId).toMap());
|
|
}
|
|
await _supabase.from('entertainment_service').insert(entToInsert);
|
|
}
|
|
} catch (e) {
|
|
throw Exception('Errore durante il salvataggio: $e');
|
|
}
|
|
}
|
|
|
|
// --- ELIMINAZIONE ---
|
|
// Grazie ai "ON DELETE CASCADE" che hai messo nell'SQL,
|
|
// cancellando il padre Supabase pialla automaticamente i figli. Top!
|
|
Future<void> deleteService(String id) async {
|
|
try {
|
|
await _supabase.from('service').delete().eq('id', id);
|
|
} catch (e) {
|
|
throw Exception('Errore durante l\'eliminazione: $e');
|
|
}
|
|
}
|
|
}
|