This commit is contained in:
2026-05-01 10:11:44 +02:00
parent 9c8576ada5
commit f8bcac51e1
48 changed files with 1187 additions and 1141 deletions

View File

@@ -4,50 +4,51 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/utils/extensions.dart';
import 'package:flux/features/operations/data/services_repository.dart';
import 'package:flux/features/operations/models/energy_service_model.dart';
import 'package:flux/features/operations/models/entertainment_service_model.dart';
import 'package:flux/features/operations/models/fin_service_model.dart';
import 'package:flux/features/operations/models/service_file_model.dart';
import 'package:flux/features/operations/models/service_model.dart';
import 'package:flux/features/operations/data/operations_repository.dart';
import 'package:flux/features/operations/models/energy_operation_model.dart';
import 'package:flux/features/operations/models/entertainment_operation_model.dart';
import 'package:flux/features/operations/models/fin_operation_model.dart';
import 'package:flux/features/operations/models/operation_file_model.dart';
import 'package:flux/features/operations/models/operation_model.dart';
import 'package:get_it/get_it.dart';
import 'package:collection/collection.dart';
part 'services_state.dart';
part 'operations_state.dart';
class ServicesCubit extends Cubit<ServicesState> {
final ServicesRepository _repository = GetIt.I<ServicesRepository>();
class OperationsCubit extends Cubit<OperationsState> {
final OperationsRepository _repository = GetIt.I<OperationsRepository>();
final SessionCubit _sessionCubit = GetIt.I<SessionCubit>();
ServicesCubit() : super(const ServicesState(status: ServicesStatus.initial));
OperationsCubit()
: super(const OperationsState(status: OperationsStatus.initial));
// --- CARICAMENTO E PAGINAZIONE ---
Future<void> loadServices({bool refresh = false}) async {
Future<void> loadOperations({bool refresh = false}) async {
// Se stiamo già caricando, evitiamo chiamate doppie
if (state.status == ServicesStatus.loading) return;
if (state.status == OperationsStatus.loading) return;
// Se non è un refresh e abbiamo già raggiunto la fine dei dati, ci fermiamo
if (!refresh && state.hasReachedMax) return;
emit(
state.copyWith(
status: ServicesStatus.loading,
status: OperationsStatus.loading,
errorMessage: null,
// Se è un refresh, svuotiamo la lista attuale per mostrare lo shimmer/loading
allServices: refresh ? [] : state.allServices,
allOperations: refresh ? [] : state.allOperations,
hasReachedMax: refresh ? false : state.hasReachedMax,
),
);
try {
final currentOffset = refresh ? 0 : state.allServices.length;
final currentOffset = refresh ? 0 : state.allOperations.length;
final companyId = _sessionCubit.state.company?.id;
if (companyId == null) {
throw Exception("Company ID non trovato nella sessione");
}
final newServices = await _repository.fetchServices(
final newOperations = await _repository.fetchOperations(
companyId: companyId,
offset: currentOffset,
limit: 50,
@@ -56,21 +57,21 @@ class ServicesCubit extends Cubit<ServicesState> {
);
// Se ricevi meno record del limite, significa che non ce ne sono altri sul DB
final bool reachedMax = newServices.length < 50;
final bool reachedMax = newOperations.length < 50;
emit(
state.copyWith(
status: ServicesStatus.ready,
allServices: refresh
? newServices
: [...state.allServices, ...newServices],
status: OperationsStatus.ready,
allOperations: refresh
? newOperations
: [...state.allOperations, ...newOperations],
hasReachedMax: reachedMax,
),
);
} catch (e) {
emit(
state.copyWith(
status: ServicesStatus.failure,
status: OperationsStatus.failure,
errorMessage: "Errore nel caricamento servizi: $e",
),
);
@@ -87,51 +88,51 @@ class ServicesCubit extends Cubit<ServicesState> {
dateRange: range ?? state.dateRange,
),
);
loadServices(refresh: true);
loadOperations(refresh: true);
}
/// Pulisce tutti i filtri
void clearFilters() {
emit(state.copyWith(query: '', dateRange: null));
loadServices(refresh: true);
loadOperations(refresh: true);
}
// --- GESTIONE BOZZA (DRAFT) ---
/// Inizializza un nuovo servizio o ne carica uno esistente per la modifica
void initServiceForm({
ServiceModel? existingService,
String? serviceId,
void initOperationForm({
OperationModel? existingOperation,
String? operationId,
}) async {
if (existingService != null) {
if (existingOperation != null) {
emit(
state.copyWith(
currentService: existingService,
status: ServicesStatus.ready,
currentOperation: existingOperation,
status: OperationsStatus.ready,
),
);
} else if (serviceId != null) {
ServiceModel? serviceModel = state.allServices.firstWhereOrNull(
(s) => s.id == serviceId,
} else if (operationId != null) {
OperationModel? operationModel = state.allOperations.firstWhereOrNull(
(s) => s.id == operationId,
);
serviceModel ??= await _repository.fetchServiceById(serviceId);
operationModel ??= await _repository.fetchOperationById(operationId);
emit(
state.copyWith(
currentService: serviceModel,
status: ServicesStatus.ready,
currentOperation: operationModel,
status: OperationsStatus.ready,
),
);
} else {
// Crea un template vuoto con lo store di default (se disponibile)
emit(
state.copyWith(
currentService: ServiceModel(
currentOperation: OperationModel(
storeId: _sessionCubit.state.currentStore?.id ?? '',
number: '', // Sarà compilato dall'utente
createdAt: DateTime.now(),
companyId: _sessionCubit.state.company!.id!,
),
status: ServicesStatus.ready,
status: OperationsStatus.ready,
),
);
}
@@ -151,9 +152,9 @@ class ServicesCubit extends Cubit<ServicesState> {
String? customerId,
String? customerDisplayName,
}) {
if (state.currentService == null) return;
if (state.currentOperation == null) return;
final updated = state.currentService!.copyWith(
final updated = state.currentOperation!.copyWith(
al: al,
mnp: mnp,
nip: nip,
@@ -167,34 +168,38 @@ class ServicesCubit extends Cubit<ServicesState> {
customerDisplayName: customerDisplayName,
);
emit(state.copyWith(currentService: updated));
emit(state.copyWith(currentOperation: updated));
}
// --- GESTIONE MODULI COMPLESSI ---
void updateEnergyServices(List<EnergyServiceModel> energyList) {
void updateEnergyOperations(List<EnergyOperationModel> energyList) {
emit(
state.copyWith(
currentService: state.currentService?.copyWith(
energyServices: energyList,
currentOperation: state.currentOperation?.copyWith(
energyOperations: energyList,
),
),
);
}
void updateFinServices(List<FinServiceModel> finList) {
void updateFinOperations(List<FinOperationModel> finList) {
emit(
state.copyWith(
currentService: state.currentService?.copyWith(finServices: finList),
currentOperation: state.currentOperation?.copyWith(
finOperations: finList,
),
),
);
}
void updateEntertainmentServices(List<EntertainmentServiceModel> entList) {
void updateEntertainmentOperations(
List<EntertainmentOperationModel> entList,
) {
emit(
state.copyWith(
currentService: state.currentService?.copyWith(
entertainmentServices: entList,
currentOperation: state.currentOperation?.copyWith(
entertainmentOperations: entList,
),
),
);
@@ -202,36 +207,40 @@ class ServicesCubit extends Cubit<ServicesState> {
// --- PERSISTENZA ---
Future<void> saveCurrentService({
Future<void> saveCurrentOperation({
required bool isBozza,
bool shouldPop = true,
List<ServiceFileModel>? files,
List<OperationFileModel>? files,
}) async {
if (state.currentService == null) return;
if (state.currentOperation == null) return;
emit(state.copyWith(status: ServicesStatus.saving, errorMessage: null));
emit(state.copyWith(status: OperationsStatus.saving, errorMessage: null));
try {
// 1. Aggiorniamo il flag bozza in base a quale pulsante ha premuto l'utente
final serviceToSave = state.currentService!.copyWith(
final operationToSave = state.currentOperation!.copyWith(
isBozza: isBozza,
files: files,
);
// 2. Salvataggio corazzato
final updatedService = await _repository.saveFullService(serviceToSave);
final updatedOperation = await _repository.saveFullOperation(
operationToSave,
);
// 3. Reset e ricaricamento
emit(
state.copyWith(
status: shouldPop ? ServicesStatus.saved : ServicesStatus.savedNoPop,
currentService: shouldPop ? null : updatedService,
status: shouldPop
? OperationsStatus.saved
: OperationsStatus.savedNoPop,
currentOperation: shouldPop ? null : updatedOperation,
),
);
await loadServices(refresh: true);
await loadOperations(refresh: true);
} catch (e) {
emit(
state.copyWith(
status: ServicesStatus.failure,
status: OperationsStatus.failure,
errorMessage: e.toString(),
),
);
@@ -242,9 +251,9 @@ class ServicesCubit extends Cubit<ServicesState> {
void addAttachments(List<PlatformFile> files) {
final newAttachments = files.map((file) {
return ServiceFileModel(
return OperationFileModel(
id: null, // Meglio null se non è su DB
serviceId: state.currentService?.id ?? '',
operationId: state.currentOperation?.id ?? '',
name: file.name.fileNameWithoutExtension(),
extension: file.name.fileExtension(),
storagePath: '',
@@ -255,44 +264,46 @@ class ServicesCubit extends Cubit<ServicesState> {
}).toList();
// Creiamo una nuova lista pulita
final List<ServiceFileModel> updatedList = [
...(state.currentService?.files ?? []),
final List<OperationFileModel> updatedList = [
...(state.currentOperation?.files ?? []),
...newAttachments,
];
// Emettiamo lo stato assicurandoci che il ServiceModel venga clonato
if (state.currentService != null) {
// Emettiamo lo stato assicurandoci che il OperationModel venga clonato
if (state.currentOperation != null) {
emit(
state.copyWith(
currentService: state.currentService!.copyWith(files: updatedList),
currentOperation: state.currentOperation!.copyWith(
files: updatedList,
),
),
);
}
}
void removeAttachment(int index) {
if (state.currentService == null) return;
if (state.currentOperation == null) return;
final updatedList = List<ServiceFileModel>.from(
state.currentService!.files,
final updatedList = List<OperationFileModel>.from(
state.currentOperation!.files,
);
updatedList.removeAt(index);
emit(
state.copyWith(
currentService: state.currentService?.copyWith(files: updatedList),
currentOperation: state.currentOperation?.copyWith(files: updatedList),
),
);
}
void saveAndCopyFileToCustomer(List<ServiceFileModel> selectedFiles) async {
final currentService = state.currentService;
void saveAndCopyFileToCustomer(List<OperationFileModel> selectedFiles) async {
final currentOperation = state.currentOperation;
// 1. Check di sicurezza: se non c'è il cliente, non sappiamo dove copiare
if (currentService == null || currentService.customerId == null) {
if (currentOperation == null || currentOperation.customerId == null) {
emit(
state.copyWith(
status: ServicesStatus.failure,
status: OperationsStatus.failure,
errorMessage:
"Impossibile copiare: nessun cliente associato alla pratica.",
),
@@ -300,19 +311,21 @@ class ServicesCubit extends Cubit<ServicesState> {
return;
}
emit(state.copyWith(status: ServicesStatus.loading));
emit(state.copyWith(status: OperationsStatus.loading));
try {
// 2. SALVATAGGIO CORAZZATO
// Chiamiamo il repo e otteniamo la pratica con TUTTI i file ora dotati di ID e storagePath
final updatedService = await _repository.saveFullService(currentService);
final updatedOperation = await _repository.saveFullOperation(
currentOperation,
);
// 3. COPIA RELAZIONALE
// Per ogni file che l'utente ha selezionato nella UI, cerchiamo la sua versione
// "ufficiale" (quella con lo storagePath) nel modello appena tornato dal DB.
for (var selectedFile in selectedFiles) {
// Cerchiamo il match nel modello aggiornato
final persistedFile = updatedService.files.firstWhere(
final persistedFile = updatedOperation.files.firstWhere(
(f) =>
f.name == selectedFile.name &&
f.extension == selectedFile.extension,
@@ -324,7 +337,7 @@ class ServicesCubit extends Cubit<ServicesState> {
// Creiamo il link nel database del cliente
await _repository.copyFileToCustomer(
file: persistedFile,
customerId: currentService.customerId!,
customerId: currentOperation.customerId!,
);
}
@@ -332,14 +345,14 @@ class ServicesCubit extends Cubit<ServicesState> {
// Aggiorniamo il Cubit con il servizio salvato così la UI mostra i file come "Remoti"
emit(
state.copyWith(
status: ServicesStatus.success,
currentService: updatedService,
status: OperationsStatus.success,
currentOperation: updatedOperation,
),
);
} catch (e) {
emit(
state.copyWith(
status: ServicesStatus.failure,
status: OperationsStatus.failure,
errorMessage: "Errore durante il salvataggio e copia: $e",
),
);