feat - Service - Providers

This commit is contained in:
2026-04-16 11:48:11 +02:00
parent 29790a7a36
commit 787873a26f
11 changed files with 758 additions and 55 deletions

View File

@@ -1,94 +1,106 @@
import 'package:flutter/material.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 ---
// --- RECUPERO PAGINATO CON FILTRI E JOIN ---
Future<List<ServiceModel>> fetchServices({
required String companyId,
required int offset,
int limit = 50,
String? searchTerm,
DateTimeRange? dateRange,
}) async {
try {
var query = _supabase.from('service').select('''
*,
energy_service(*),
fin_service(*),
entertainment_service(*)
''');
// Nota: 'customer(name, surname)' serve per il display name nella card
var query = _supabase
.from('service')
.select('''
*,
customer(name, surname),
energy_service(*),
fin_service(*),
entertainment_service(*)
''')
.eq('company_id', companyId);
// Filtro per range di date
// Filtro Range Date
if (dateRange != null) {
query = query
.gte('created_at', dateRange.start.toIso8601String())
.lte('created_at', dateRange.end.toIso8601String());
}
// Ordinamento e Paginazione
if (searchTerm != null && searchTerm.isNotEmpty) {
// Filtra sui campi della tabella principale O su quelli della tabella joinata
query = query.or(
'number.ilike.%$searchTerm%,note.ilike.%$searchTerm%,customer.name.ilike.%$searchTerm%,customer.surname.ilike.%$searchTerm%',
);
}
final response = await query
.order('created_at', ascending: false)
.range(offset, offset + limit - 1);
final List<ServiceModel> services = (response as List)
return (response as List)
.map((map) => ServiceModel.fromMap(map))
.toList();
// Filtro testuale lato client per semplicità (o potresti farlo in SQL se preferisci)
if (searchTerm != null && searchTerm.isNotEmpty) {
return services.where((s) {
// Qui cercheremo per numero pratica o note (il nome cliente lo vedremo poi con le Join)
return s.number.toLowerCase().contains(searchTerm.toLowerCase()) ||
s.note.toLowerCase().contains(searchTerm.toLowerCase());
}).toList();
}
return services;
} catch (e) {
throw Exception('Errore fetch: $e');
throw Exception('Errore nel caricamento servizi: $e');
}
}
// --- SALVATAGGIO COMPLETO (A CASCATA) ---
// --- SALVATAGGIO COMPLETO (PRIMA PADRE, POI FIGLI) ---
Future<void> saveFullService(ServiceModel service) async {
try {
// 1. Inserimento Padre
// 1. Inseriamo il record principale
// Se service.id è null, Supabase fa INSERT. Se c'è, fa UPDATE (grazie all'upsert o gestione manuale)
final serviceData = await _supabase
.from('service')
.insert(service.toMap())
.upsert(service.toMap())
.select()
.single();
final String newId = serviceData['id'];
// 2. Inserimento Energy (se presenti)
// 2. Pulizia vecchi record figli (necessaria se è una MODIFICA)
// Se stiamo modificando, cancelliamo i vecchi per reinserire i nuovi (più semplice)
if (service.id != null) {
await _supabase.from('energy_service').delete().eq('service_id', newId);
await _supabase.from('fin_service').delete().eq('service_id', newId);
await _supabase
.from('entertainment_service')
.delete()
.eq('service_id', newId);
}
// 3. Inserimento EnergyServices
if (service.energyServices.isNotEmpty) {
final List<Map<String, dynamic>> energyToInsert = [];
final List<Map<String, dynamic>> toInsert = [];
for (var item in service.energyServices) {
energyToInsert.add(item.copyWith(serviceId: newId).toMap());
toInsert.add(item.copyWith(serviceId: newId).toMap());
}
await _supabase.from('energy_service').insert(energyToInsert);
await _supabase.from('energy_service').insert(toInsert);
}
// 3. Inserimento Finanziamenti (se presenti)
// 4. Inserimento FinServices
if (service.finServices.isNotEmpty) {
final List<Map<String, dynamic>> finToInsert = [];
final List<Map<String, dynamic>> toInsert = [];
for (var item in service.finServices) {
finToInsert.add(item.copyWith(serviceId: newId).toMap());
toInsert.add(item.copyWith(serviceId: newId).toMap());
}
await _supabase.from('fin_service').insert(finToInsert);
await _supabase.from('fin_service').insert(toInsert);
}
// 4. Inserimento Entertainment (se presenti)
// 5. Inserimento EntertainmentServices
if (service.entertainmentServices.isNotEmpty) {
final List<Map<String, dynamic>> entToInsert = [];
final List<Map<String, dynamic>> toInsert = [];
for (var item in service.entertainmentServices) {
entToInsert.add(item.copyWith(serviceId: newId).toMap());
toInsert.add(item.copyWith(serviceId: newId).toMap());
}
await _supabase.from('entertainment_service').insert(entToInsert);
await _supabase.from('entertainment_service').insert(toInsert);
}
} catch (e) {
throw Exception('Errore durante il salvataggio: $e');
@@ -96,8 +108,6 @@ class ServicesRepository {
}
// --- 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);