83 lines
2.4 KiB
Dart
83 lines
2.4 KiB
Dart
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
||
|
|
import 'package:equatable/equatable.dart';
|
||
|
|
import 'package:flux/features/customers/data/customer_repository.dart';
|
||
|
|
import 'package:flux/features/customers/models/customer_model.dart';
|
||
|
|
import 'package:get_it/get_it.dart';
|
||
|
|
|
||
|
|
part 'customer_events.dart';
|
||
|
|
part 'customer_state.dart';
|
||
|
|
|
||
|
|
class CustomerBloc extends Bloc<CustomerEvent, CustomerState> {
|
||
|
|
final CustomerRepository _repository = GetIt.I<CustomerRepository>();
|
||
|
|
|
||
|
|
CustomerBloc() : super(const CustomerState()) {
|
||
|
|
on<LoadCustomersRequested>(_onLoadCustomers);
|
||
|
|
on<CreateCustomerRequested>(_onCreateCustomer);
|
||
|
|
on<SearchCustomersRequested>(_onSearchCustomers);
|
||
|
|
}
|
||
|
|
|
||
|
|
Future<void> _onLoadCustomers(
|
||
|
|
LoadCustomersRequested event,
|
||
|
|
Emitter<CustomerState> emit,
|
||
|
|
) async {
|
||
|
|
emit(state.copyWith(status: CustomerStatus.loading));
|
||
|
|
try {
|
||
|
|
final customers = await _repository.getCustomers(event.companyId);
|
||
|
|
emit(
|
||
|
|
state.copyWith(status: CustomerStatus.success, customers: customers),
|
||
|
|
);
|
||
|
|
} catch (e) {
|
||
|
|
emit(
|
||
|
|
state.copyWith(
|
||
|
|
status: CustomerStatus.failure,
|
||
|
|
errorMessage: e.toString(),
|
||
|
|
),
|
||
|
|
);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
Future<void> _onCreateCustomer(
|
||
|
|
CreateCustomerRequested event,
|
||
|
|
Emitter<CustomerState> emit,
|
||
|
|
) async {
|
||
|
|
emit(state.copyWith(status: CustomerStatus.loading));
|
||
|
|
try {
|
||
|
|
final newCustomer = await _repository.createCustomer(event.customer);
|
||
|
|
|
||
|
|
// Aggiorniamo la lista locale aggiungendo il nuovo cliente in cima
|
||
|
|
final updatedList = List<CustomerModel>.from(state.customers)
|
||
|
|
..insert(0, newCustomer);
|
||
|
|
|
||
|
|
emit(
|
||
|
|
state.copyWith(
|
||
|
|
status: CustomerStatus.success,
|
||
|
|
customers: updatedList,
|
||
|
|
lastCreatedCustomer:
|
||
|
|
newCustomer, // Lo passiamo per le Dialog "al volo"
|
||
|
|
),
|
||
|
|
);
|
||
|
|
} catch (e) {
|
||
|
|
emit(
|
||
|
|
state.copyWith(
|
||
|
|
status: CustomerStatus.failure,
|
||
|
|
errorMessage: e.toString(),
|
||
|
|
),
|
||
|
|
);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
Future<void> _onSearchCustomers(
|
||
|
|
SearchCustomersRequested event,
|
||
|
|
Emitter<CustomerState> emit,
|
||
|
|
) async {
|
||
|
|
// Non mettiamo loading per evitare flickering durante la digitazione
|
||
|
|
try {
|
||
|
|
final results = await _repository.searchCustomers(
|
||
|
|
event.companyId,
|
||
|
|
event.query,
|
||
|
|
);
|
||
|
|
emit(state.copyWith(status: CustomerStatus.success, customers: results));
|
||
|
|
} catch (_) {}
|
||
|
|
}
|
||
|
|
}
|