Files

75 lines
2.3 KiB
Dart

import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/api/api_providers.dart';
import '../../../core/api/guarded_api_call.dart';
import '../../auth/data/auth_providers.dart';
import '../domain/inventory_item.dart';
import '../domain/inventory_consumption.dart';
import 'inventory_repository.dart';
class InventoryQuery {
final String location;
final String sort;
const InventoryQuery({required this.location, required this.sort});
}
class _StringNotifier extends Notifier<String> {
_StringNotifier(this._initial);
final String _initial;
@override
String build() => _initial;
void setValue(String value) {
state = value;
}
}
final inventoryLocationFilterProvider =
NotifierProvider<_StringNotifier, String>(() => _StringNotifier(''));
final inventorySortFilterProvider =
NotifierProvider<_StringNotifier, String>(() => _StringNotifier(''));
final inventoryQueryProvider = Provider<InventoryQuery>((ref) {
final location = ref.watch(inventoryLocationFilterProvider);
final sort = ref.watch(inventorySortFilterProvider);
return InventoryQuery(location: location, sort: sort);
});
final inventoryRepositoryProvider = Provider<InventoryRepository>((ref) {
return InventoryRepository(ref.watch(apiClientProvider));
});
final inventoryProvider = FutureProvider<List<InventoryItem>>((ref) async {
final token = await ref.watch(authStateProvider.future);
final query = ref.watch(inventoryQueryProvider);
return guardedApiCall(
ref,
() => ref.read(inventoryRepositoryProvider).fetchInventory(
location: query.location,
sort: query.sort,
token: token,
),
);
});
final inventoryDetailProvider =
FutureProvider.family<InventoryItem, int>((ref, id) async {
final token = await ref.watch(authStateProvider.future);
return guardedApiCall(
ref,
() => ref.read(inventoryRepositoryProvider).fetchInventoryItem(id, token: token),
);
});
final consumptionHistoryProvider =
FutureProvider.family<List<InventoryConsumption>, int>((ref, id) async {
final token = await ref.watch(authStateProvider.future);
return guardedApiCall(
ref,
() => ref
.read(inventoryRepositoryProvider)
.fetchConsumptionHistory(id, token: token),
);
});