feat-insert-service (#5)

Reviewed-on: http://catelliub.zapto.org:3000/brontomark/flux/pulls/5
Co-authored-by: mark-cachy <marco@catelli.it>
Co-committed-by: mark-cachy <marco@catelli.it>
This commit is contained in:
2026-04-20 16:52:20 +02:00
committed by brontomark
parent 667bbf6404
commit c3d4f3fac7
63 changed files with 4715 additions and 1371 deletions

View File

@@ -1,37 +1,38 @@
import 'dart:io';
import 'package:file_picker/file_picker.dart';
import 'package:flux/core/blocs/session/session_bloc.dart';
import 'package:flux/core/utils/string_extensions.dart';
import 'package:flux/features/customers/models/customer_file_model.dart';
import 'package:get_it/get_it.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
import '../models/customer_model.dart';
class CustomerRepository {
final SupabaseClient _client = GetIt.I<SupabaseClient>();
final SupabaseClient _supabase = GetIt.I<SupabaseClient>();
final String companyId = GetIt.I.get<SessionBloc>().state.company!.id;
// Crea un nuovo cliente
Future<CustomerModel> createCustomer(CustomerModel customer) async {
Future<CustomerModel> saveCustomer(CustomerModel customer) async {
try {
final response = await _client
final response = await _supabase
.from('customer')
.insert(customer.toJson())
.upsert(customer.toJson())
.select()
.single();
return CustomerModel.fromJson(response);
return CustomerModel.fromMap(response);
} catch (e) {
throw 'Errore durante la creazione del cliente: $e';
throw 'Errore durante il salvataggio del cliente: $e';
}
}
Future<CustomerModel> updateCustomer(CustomerModel customer) async {
try {
final response = await _client
final response = await _supabase
.from('customer')
.update(customer.toJson())
.eq('id', customer.id!)
.select()
.single();
return CustomerModel.fromJson(response);
return CustomerModel.fromMap(response);
} catch (e) {
throw 'Errore durante la modifica del cliente: $e';
}
@@ -40,14 +41,17 @@ class CustomerRepository {
// Recupera tutti i clienti dell'azienda
Future<List<CustomerModel>> getCustomers(String companyId) async {
try {
final response = await _client
final response = await _supabase
.from('customer')
.select('*, customer_file(count)')
.select('''
*,
customer_file(*)
''')
.eq('company_id', companyId)
.eq('is_active', true)
.order('nome');
return (response as List).map((c) => CustomerModel.fromJson(c)).toList();
return (response as List).map((c) => CustomerModel.fromMap(c)).toList();
} catch (e) {
throw 'Errore nel recupero clienti';
}
@@ -59,14 +63,14 @@ class CustomerRepository {
String query,
) async {
try {
final response = await _client
final response = await _supabase
.from('customer')
.select()
.eq('company_id', companyId)
.or('nome.ilike.%$query%,telefono.ilike.%$query%')
.limit(10);
return (response as List).map((c) => CustomerModel.fromJson(c)).toList();
return (response as List).map((c) => CustomerModel.fromMap(c)).toList();
} catch (e) {
return [];
}
@@ -75,13 +79,13 @@ class CustomerRepository {
/// Recupera i file di un cliente specifico
Future<List<CustomerFileModel>> getCustomerFiles(String customerId) async {
try {
final response = await _client
final response = await _supabase
.from('customer_file')
.select()
.eq('customer_id', customerId);
return (response as List)
.map((f) => CustomerFileModel.fromJson(f))
.map((f) => CustomerFileModel.fromMap(f))
.toList();
} catch (e) {
throw 'Errore recupero file: $e';
@@ -89,8 +93,8 @@ class CustomerRepository {
}
/// Salva il riferimento del file nel DB
Future<void> saveFileReference(CustomerFileModel file) async {
await _client.from('customer_file').insert(file.toJson());
Future<void> saveCustomerFile(CustomerFileModel file) async {
await _supabase.from('customer_file').insert(file.toMap());
}
/// Carica un file e salva il riferimento nel database
@@ -98,15 +102,24 @@ class CustomerRepository {
required String customerId,
required PlatformFile pickedFile,
}) async {
final cleanFileName = pickedFile.name.replaceAll(
RegExp(r'[^a-zA-Z0-9\.\-]'),
'_',
);
final storagePath =
'$companyId/customers/${DateTime.now().millisecondsSinceEpoch}_$cleanFileName';
final int fileSize = pickedFile.size;
final fileToSave = CustomerFileModel(
customerId: customerId,
name: cleanFileName.fileNameWithoutExtension(),
extension: cleanFileName.fileExtension(),
url: storagePath,
fileSize: fileSize,
);
final String mimeType = fileToSave.extension.toLowerCase() == 'pdf'
? 'application/pdf'
: 'image/${fileToSave.extension}';
try {
final user = _client.auth.currentUser;
if (user == null) throw 'Utente non autenticato';
final fileName = pickedFile.name;
final extension = pickedFile.extension ?? '';
final path =
'${user.id}/$customerId/${DateTime.now().millisecondsSinceEpoch}_$fileName';
// Usiamo bytes invece del path per massima compatibilità
if (pickedFile.bytes == null && pickedFile.path == null) {
throw 'Impossibile leggere il contenuto del file';
@@ -114,46 +127,43 @@ class CustomerRepository {
// Se siamo su desktop/mobile abbiamo il path, su web abbiamo i bytes
if (pickedFile.bytes != null) {
await _client.storage
await _supabase.storage
.from('documents')
.uploadBinary(path, pickedFile.bytes!);
} else {
final file = File(pickedFile.path!);
await _client.storage.from('documents').upload(path, file);
.uploadBinary(
storagePath,
pickedFile.bytes!,
fileOptions: FileOptions(contentType: mimeType, upsert: true),
);
}
final String publicUrl = _client.storage
.from('documents')
.getPublicUrl(path);
final fileRecord = CustomerFileModel(
customerId: customerId,
name: fileName,
url: publicUrl,
extension: extension,
);
final response = await _client
final response = await _supabase
.from('customer_file')
.insert(fileRecord.toJson())
.insert(fileToSave.toMap())
.select()
.single();
return CustomerFileModel.fromJson(response);
return CustomerFileModel.fromMap(response);
} catch (e) {
throw 'Errore durante l\'upload: $e';
}
}
Future<void> saveFileReference(CustomerFileModel file) async {
await _supabase.from('customer_file').upsert(file.toMap());
}
/// Aggiorna la lista degli URL nel database
Future<void> updateCustomerDocuments(int id, List<String> urls) async {
await _client.from('customer').update({'document_urls': urls}).eq('id', id);
await _supabase
.from('customer')
.update({'document_urls': urls})
.eq('id', id);
}
/// Elimina un file dallo storage
Future<void> deleteDocument(String fullPath) async {
// Il path dovrebbe essere ricavato dall'URL
final path = fullPath.split('documents/').last;
await _client.storage.from('documents').remove([path]);
await _supabase.storage.from('documents').remove([path]);
}
}