Files
flux/lib/features/operations/data/operations_repository.dart
T
brontomark 9374f4ab46
Build and Release FLUX (Multi-Platform) / build-android (push) Successful in 4m30s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 9m21s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 2m29s
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m17s
nuova strategia per le liste delle operazioni e correzione bug indirizzo predefinito di spedizione dei provider
2026-08-18 19:24:53 +02:00

255 lines
7.7 KiB
Dart

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flux/core/enums_and_consts/consts.dart';
import 'package:flux/features/master_data/store/models/store_model.dart';
import 'package:flux/features/operations/models/operation_detail_model.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:flux/features/operations/models/paginated_operations.dart';
import 'package:flux/service_locator.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
class OperationsRepository {
final SupabaseClient _supabase = sl<SupabaseClient>();
final StreamController<void> _operationsChangedController =
StreamController<void>.broadcast();
Stream<void> get onOperationsChanged => _operationsChangedController.stream;
void notifyOperationsChanged() {
if (!_operationsChangedController.isClosed) {
_operationsChangedController.add(null);
}
}
Future<OperationModel?> getOperationById(String id) async {
try {
final response = await _supabase
.from(Tables.operations)
.select('''
*,
${Tables.customers}(*),
${Tables.stores}(*),
${Tables.staffMembers}(*),
${Tables.attachments}(*),
${Tables.operationDetails}(
*,
${Tables.providers}(*),
${Tables.models}(*)
)
''')
.eq('id', id)
.single();
debugPrint('response: $response');
return OperationModel.fromMap(response);
} on Exception catch (e) {
debugPrint('response error: $e');
return null;
}
}
Future<PaginatedOperations> fetchPaginatedOperations({
required String companyId,
String? storeId,
String? staffId,
String? providerId,
required int page,
int itemsPerPage = 20,
String? searchTerm,
DateTimeRange? dateRange,
bool onlyShowInDashboard = false,
}) async {
try {
// Calcoliamo il range di partenza e fine per Supabase
// Es. Pagina 1, 25 items -> range(0, 24)
// Es. Pagina 2, 25 items -> range(25, 49)
final from = (page - 1) * itemsPerPage;
final to = from + itemsPerPage - 1;
var query = _supabase
.from(Tables.operations)
.select('''
*,
${Tables.customers}(*),
${Tables.stores}(*),
${Tables.staffMembers}(*),
${Tables.attachments}(*),
${Tables.operationDetails}(
*,
${Tables.providers}(*),
${Tables.models}(*)
)
''')
.eq('company_id', companyId);
if (onlyShowInDashboard) {
query = query.eq('show_in_dashboard', true);
}
// Filtro Range Date
if (dateRange != null) {
query = query
.gte('created_at', dateRange.start.toIso8601String())
.lte('created_at', dateRange.end.toIso8601String());
}
if (storeId != null) {
query = query.or('store_id.eq.$storeId,store_id.is.null');
}
if (staffId != null) {
query = query.or('staff_id.eq.$staffId,staff_id.is.null');
}
if (providerId != null) {
query = query.or('provider_id.eq.$providerId,provider_id.is.null');
}
if (searchTerm != null && searchTerm.trim().isNotEmpty) {
final cleanTerm = searchTerm.trim().replaceAll(',', ' ');
List<String> matchingCustomerIds = [];
try {
final customersRes = await _supabase
.from(Tables.customers)
.select('id')
.eq('company_id', companyId)
.or('name.ilike.%$cleanTerm%,phone_number.ilike.%$cleanTerm%')
.limit(100);
matchingCustomerIds = (customersRes as List)
.map((c) => c['id'].toString())
.toList();
} catch (_) {}
final List<String> orConditions = [
'reference.ilike.%$cleanTerm%',
'note.ilike.%$cleanTerm%',
'description.ilike.%$cleanTerm%',
];
if (matchingCustomerIds.isNotEmpty) {
orConditions.add('customer_id.in.(${matchingCustomerIds.join(',')})');
}
query = query.or(orConditions.join(','));
}
final response = await query
.order('created_at', ascending: false)
.range(from, to)
.count(CountOption.exact);
// 3. Estrazione dei dati
final List<OperationModel> operations = (response.data as List)
.map((map) => OperationModel.fromMap(map))
.toList();
final int totalCount = response.count;
return PaginatedOperations(
operations: operations,
totalCount: totalCount,
);
} catch (e) {
debugPrint('Errore nel recupero della pagina $page: $e');
throw Exception('Errore nel recupero della pagina $page: $e');
}
}
Stream<List<Map<String, dynamic>>> watchStoreOperations({
required String storeId,
required int limit,
}) {
return _supabase
.from(Tables.operations)
.stream(primaryKey: ['id'])
.eq('store_id', storeId)
.order('created_at', ascending: false)
.limit(limit);
}
Future<OperationModel> createNewOperation({
required StoreModel currentStore,
required String createdById,
}) async {
try {
final res = await _supabase
.from(Tables.operations)
.insert(
OperationModel.empty()
.copyWith(
storeId: currentStore.id,
staffId: createdById,
companyId: currentStore.companyId,
status: OperationStatus.success,
showInDashboard: false,
)
.toMap(),
)
.select('''
*,
${Tables.staffMembers}(*)
''')
.single();
notifyOperationsChanged();
return OperationModel.fromMap(res);
} on Exception catch (e) {
debugPrint('ERRORE CREAZIONE OPERAZIONE: $e');
throw Exception('Errore nella creazione dell\'operazione: $e');
}
}
Future<void> deleteOperation(String id) async {
try {
await _supabase.from(Tables.operations).delete().eq('id', id);
notifyOperationsChanged();
} catch (e) {
debugPrint('ERRORE CANCELLAZIONE OPERAZIONE: $e');
throw Exception('Errore nella cancellazione dell\'operazione: $e');
}
}
Future<void> updateOperation(OperationModel operation) async {
try {
await _supabase
.from(Tables.operations)
.update(operation.toMap())
.eq('id', operation.id!);
final currentDetailIds =
operation.details
.map((d) => d.id)
.where((id) => id != null && id.isNotEmpty)
.cast<String>()
.toList();
if (currentDetailIds.isNotEmpty) {
await _supabase
.from(Tables.operationDetails)
.delete()
.eq('operation_id', operation.id!)
.not('id', 'in', currentDetailIds);
} else {
await _supabase
.from(Tables.operationDetails)
.delete()
.eq('operation_id', operation.id!);
}
for (OperationDetailModel detail in operation.details) {
final detailToSave = detail.copyWith(
operationId:
detail.operationId.isNotEmpty ? detail.operationId : operation.id!,
companyId:
detail.companyId.isNotEmpty
? detail.companyId
: operation.companyId,
);
await _supabase
.from(Tables.operationDetails)
.upsert(detailToSave.toMap());
}
notifyOperationsChanged();
} catch (e) {
debugPrint('ERRORE SALVATAGGIO OPERAZIONE: $e');
throw Exception('Errore nel salvataggio dell\'operazione: $e');
}
}
}