190 lines
5.8 KiB
Dart
190 lines
5.8 KiB
Dart
import 'dart:io';
|
|
|
|
import 'package:file_picker/file_picker.dart';
|
|
import 'package:flux/core/blocs/session/session_cubit.dart';
|
|
import 'package:flux/core/utils/functions.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 _supabase = GetIt.I<SupabaseClient>();
|
|
final String companyId = GetIt.I.get<SessionCubit>().state.company!.id!;
|
|
|
|
// Crea un nuovo cliente
|
|
Future<CustomerModel> saveCustomer(CustomerModel customer) async {
|
|
try {
|
|
final response = await _supabase
|
|
.from('customer')
|
|
.upsert(customer.toJson())
|
|
.select()
|
|
.single();
|
|
return CustomerModel.fromMap(response);
|
|
} catch (e) {
|
|
throw 'Errore durante il salvataggio del cliente: $e';
|
|
}
|
|
}
|
|
|
|
Future<CustomerModel> updateCustomer(CustomerModel customer) async {
|
|
try {
|
|
final response = await _supabase
|
|
.from('customer')
|
|
.update(customer.toJson())
|
|
.eq('id', customer.id!)
|
|
.select()
|
|
.single();
|
|
return CustomerModel.fromMap(response);
|
|
} catch (e) {
|
|
throw 'Errore durante la modifica del cliente: $e';
|
|
}
|
|
}
|
|
|
|
// Recupera tutti i clienti dell'azienda
|
|
Future<List<CustomerModel>> getCustomers(String companyId) async {
|
|
try {
|
|
final response = await _supabase
|
|
.from('customer')
|
|
.select('''
|
|
*,
|
|
customer_file(*)
|
|
''')
|
|
.eq('company_id', companyId)
|
|
.eq('is_active', true)
|
|
.order('nome');
|
|
|
|
return (response as List).map((c) => CustomerModel.fromMap(c)).toList();
|
|
} catch (e) {
|
|
throw 'Errore nel recupero clienti';
|
|
}
|
|
}
|
|
|
|
// Ricerca clienti per nome o telefono (fondamentale per la UX)
|
|
Future<List<CustomerModel>> searchCustomers(
|
|
String companyId,
|
|
String query,
|
|
) async {
|
|
try {
|
|
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.fromMap(c)).toList();
|
|
} catch (e) {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
/// Ascolta in tempo reale i file caricati per un cliente
|
|
Stream<List<CustomerFileModel>> getCustomerFilesStream(String customerId) {
|
|
return _supabase
|
|
.from('customer_file')
|
|
.stream(primaryKey: ['id'])
|
|
.eq('customer_id', customerId)
|
|
.order('created_at', ascending: false)
|
|
.map(
|
|
(listOfMaps) =>
|
|
listOfMaps.map((map) => CustomerFileModel.fromMap(map)).toList(),
|
|
);
|
|
}
|
|
|
|
/// Recupera i file di un cliente specifico
|
|
Future<List<CustomerFileModel>> getCustomerFiles(String customerId) async {
|
|
try {
|
|
final response = await _supabase
|
|
.from('customer_file')
|
|
.select()
|
|
.eq('customer_id', customerId);
|
|
|
|
return (response as List)
|
|
.map((f) => CustomerFileModel.fromMap(f))
|
|
.toList();
|
|
} catch (e) {
|
|
throw 'Errore recupero file: $e';
|
|
}
|
|
}
|
|
|
|
/// Salva il riferimento del file nel DB
|
|
Future<void> saveCustomerFile(CustomerFileModel file) async {
|
|
await _supabase.from('customer_file').insert(file.toMap());
|
|
}
|
|
|
|
/// Carica un file e salva il riferimento nel database
|
|
Future<CustomerFileModel> uploadAndRegisterFile({
|
|
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(),
|
|
storagePath: storagePath,
|
|
fileSize: fileSize,
|
|
);
|
|
final String mimeType = fileToSave.extension.toLowerCase() == 'pdf'
|
|
? 'application/pdf'
|
|
: 'image/${fileToSave.extension}';
|
|
try {
|
|
// Usiamo bytes invece del path per massima compatibilità
|
|
if (pickedFile.bytes == null && pickedFile.path == null) {
|
|
throw 'Impossibile leggere il contenuto del file';
|
|
}
|
|
|
|
// Se siamo su desktop/mobile abbiamo il path, su web abbiamo i bytes
|
|
if (pickedFile.bytes != null) {
|
|
await _supabase.storage
|
|
.from('documents')
|
|
.uploadBinary(
|
|
storagePath,
|
|
pickedFile.bytes!,
|
|
fileOptions: FileOptions(contentType: mimeType, upsert: true),
|
|
);
|
|
}
|
|
|
|
final response = await _supabase
|
|
.from('customer_file')
|
|
.insert(fileToSave.toMap())
|
|
.select()
|
|
.single();
|
|
|
|
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 _supabase
|
|
.from('customer')
|
|
.update({'document_urls': urls})
|
|
.eq('id', id);
|
|
}
|
|
|
|
/// Elimina un file dallo storage
|
|
Future<void> deleteDocument(CustomerFileModel file) async {
|
|
try {
|
|
final path = await getSignedUrl(file.storagePath);
|
|
await _supabase.from('customer_file').delete().eq('id', file.id!);
|
|
await _supabase.storage.from('documents').remove([path]);
|
|
} on Exception catch (e) {
|
|
throw 'Errore durante l\'eliminazione del file: $e';
|
|
}
|
|
}
|
|
}
|