93 lines
2.6 KiB
Dart
93 lines
2.6 KiB
Dart
import 'package:dio/dio.dart';
|
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
import '../../../core/network/dio_client.dart';
|
|
import '../domain/vendor.dart';
|
|
|
|
class VendorsNotifier extends AsyncNotifier<List<Vendor>> {
|
|
@override
|
|
Future<List<Vendor>> build() async {
|
|
return _fetchVendors();
|
|
}
|
|
|
|
Future<List<Vendor>> _fetchVendors() async {
|
|
try {
|
|
final response = await DioClient().dio.get('/vendors');
|
|
if (response.statusCode == 200) {
|
|
final List<dynamic> data = response.data;
|
|
return data.map((json) => Vendor.fromJson(json)).toList();
|
|
}
|
|
return [];
|
|
} catch (e) {
|
|
throw Exception('Failed to load vendors: $e');
|
|
}
|
|
}
|
|
|
|
Future<Vendor> getVendor(int id) async {
|
|
try {
|
|
final response = await DioClient().dio.get('/vendors/$id');
|
|
if (response.statusCode == 200) {
|
|
return Vendor.fromJson(response.data);
|
|
}
|
|
throw Exception('Vendor not found');
|
|
} catch (e) {
|
|
throw Exception('Failed to load vendor: $e');
|
|
}
|
|
}
|
|
|
|
Future<Vendor> addVendor(Vendor vendor) async {
|
|
try {
|
|
final response = await DioClient().dio.post(
|
|
'/vendors',
|
|
data: vendor.toJson(),
|
|
);
|
|
if (response.statusCode == 200) {
|
|
final newVendor = Vendor.fromJson(response.data);
|
|
final current = state.value ?? [];
|
|
state = AsyncValue.data([...current, newVendor]);
|
|
return newVendor;
|
|
}
|
|
throw Exception('Failed to add vendor');
|
|
} catch (e) {
|
|
throw Exception('Error adding vendor: $e');
|
|
}
|
|
}
|
|
|
|
Future<Vendor> updateVendor(Vendor vendor) async {
|
|
try {
|
|
final response = await DioClient().dio.put(
|
|
'/vendors/${vendor.id}',
|
|
data: vendor.toJson(),
|
|
);
|
|
if (response.statusCode == 200) {
|
|
final updatedVendor = Vendor.fromJson(response.data);
|
|
final current = state.value ?? [];
|
|
state = AsyncValue.data(
|
|
current
|
|
.map((c) => c.id == updatedVendor.id ? updatedVendor : c)
|
|
.toList(),
|
|
);
|
|
return updatedVendor;
|
|
}
|
|
throw Exception('Failed to update vendor');
|
|
} catch (e) {
|
|
throw Exception('Error updating vendor: $e');
|
|
}
|
|
}
|
|
|
|
Future<void> deleteVendor(int id) async {
|
|
try {
|
|
await DioClient().dio.delete('/vendors/$id');
|
|
final current = state.value ?? [];
|
|
state = AsyncValue.data(current.where((c) => c.id != id).toList());
|
|
} catch (e) {
|
|
throw Exception('Error deleting vendor: $e');
|
|
}
|
|
}
|
|
}
|
|
|
|
final vendorsProvider = AsyncNotifierProvider<VendorsNotifier, List<Vendor>>(
|
|
() {
|
|
return VendorsNotifier();
|
|
},
|
|
);
|