89 lines
2.5 KiB
Dart
89 lines
2.5 KiB
Dart
import 'dart:async';
|
|
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
|
import '../../../core/network/dio_client.dart';
|
|
import '../domain/commodity_rate.dart';
|
|
|
|
class CommodityRatesNotifier extends AsyncNotifier<List<CommodityRateHistory>> {
|
|
@override
|
|
FutureOr<List<CommodityRateHistory>> build() async {
|
|
return _fetchLatestRates();
|
|
}
|
|
|
|
Future<List<CommodityRateHistory>> _fetchLatestRates() async {
|
|
try {
|
|
final response = await DioClient().dio.get('/inventory/commodity-rates/latest');
|
|
if (response.statusCode == 200) {
|
|
final List<dynamic> data = response.data;
|
|
return data.map((e) => CommodityRateHistory.fromJson(e)).toList();
|
|
}
|
|
} catch (e) {
|
|
// Fallback if empty or endpoint fails
|
|
}
|
|
return [];
|
|
}
|
|
|
|
Future<List<CommodityRateHistory>> fetchRateHistory(String commodityCode) async {
|
|
try {
|
|
final response = await DioClient().dio.get('/inventory/commodity-rates/$commodityCode');
|
|
if (response.statusCode == 200) {
|
|
final List<dynamic> data = response.data;
|
|
return data.map((e) => CommodityRateHistory.fromJson(e)).toList();
|
|
}
|
|
} catch (e) {
|
|
// Error fetching history
|
|
}
|
|
return [];
|
|
}
|
|
|
|
Future<CommodityRateHistory?> addRate(
|
|
String commodityCode,
|
|
double rate, {
|
|
String? commodityName,
|
|
String? purity,
|
|
String? source,
|
|
}) async {
|
|
try {
|
|
final payload = {
|
|
'commodityCode': commodityCode,
|
|
'commodityName': commodityName ?? commodityCode,
|
|
if (purity != null) 'purity': purity,
|
|
'rate': rate,
|
|
'source': source ?? 'MANUAL',
|
|
};
|
|
|
|
final response = await DioClient().dio.post(
|
|
'/inventory/commodity-rates',
|
|
data: payload,
|
|
);
|
|
|
|
if (response.statusCode == 200 && response.data != null) {
|
|
final newRate = CommodityRateHistory.fromJson(response.data);
|
|
state = await AsyncValue.guard(() => _fetchLatestRates());
|
|
return newRate;
|
|
}
|
|
} catch (e) {
|
|
rethrow;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
Future<int> syncRateToProducts(String commodityCode) async {
|
|
try {
|
|
final response = await DioClient().dio.post(
|
|
'/inventory/commodity-rates/$commodityCode/sync',
|
|
);
|
|
if (response.statusCode == 200 && response.data != null) {
|
|
return (response.data['updatedCount'] as num?)?.toInt() ?? 0;
|
|
}
|
|
} catch (e) {
|
|
rethrow;
|
|
}
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
final commodityRatesProvider =
|
|
AsyncNotifierProvider<CommodityRatesNotifier, List<CommodityRateHistory>>(() {
|
|
return CommodityRatesNotifier();
|
|
});
|