77 lines
2.3 KiB
Dart
77 lines
2.3 KiB
Dart
import 'dart:convert';
|
|
|
|
import 'package:rxdart/subjects.dart';
|
|
import 'package:tunas/clients/storage/storage_client.dart';
|
|
import 'package:tunas/repositories/account/models/account.dart';
|
|
import 'package:tunas/repositories/account/models/budget.dart';
|
|
import 'package:tunas/repositories/account/models/category.dart';
|
|
import 'package:tunas/repositories/account/models/transaction.dart';
|
|
|
|
class AccountRepository {
|
|
String accountFile = 'tunas_main_account.json';
|
|
Account? currentAccount;
|
|
|
|
final StorageClient _storageClient;
|
|
|
|
final _transactionsController = BehaviorSubject<List<Transaction>>.seeded(const []);
|
|
final _categoriesController = BehaviorSubject<List<Category>>.seeded(const []);
|
|
final _budgetController = BehaviorSubject<List<Budget>>.seeded(const []);
|
|
|
|
AccountRepository({
|
|
required storageClient,
|
|
}) : _storageClient = storageClient {
|
|
init();
|
|
}
|
|
|
|
init() async {
|
|
final account = await getAccount();
|
|
_transactionsController.add(account.transactions);
|
|
_categoriesController.add(account.categories);
|
|
_budgetController.add(account.budgets);
|
|
}
|
|
|
|
Stream<List<Transaction>> getTransactionsStream() {
|
|
return _transactionsController.asBroadcastStream();
|
|
}
|
|
|
|
Stream<List<Category>> getCategoriesStream() {
|
|
return _categoriesController.asBroadcastStream();
|
|
}
|
|
|
|
Stream<List<Budget>> getBudgetsStream() {
|
|
return _budgetController.asBroadcastStream();
|
|
}
|
|
|
|
Future<Account> getAccount() async {
|
|
String json = await _storageClient.load(accountFile);
|
|
Map<String, dynamic> accountJson = jsonDecode(json);
|
|
return Account.fromJson(accountJson);
|
|
}
|
|
|
|
saveAccount(Account account) async {
|
|
await _storageClient.save(accountFile, jsonEncode(account.toJson()));
|
|
_broadcastAccountData(account);
|
|
}
|
|
|
|
saveTransactions(List<Transaction> transactions) async {
|
|
Account? account = currentAccount;
|
|
if (account == null) {
|
|
throw Error();
|
|
} else {account.transactions = transactions;
|
|
await saveAccount(account);
|
|
}
|
|
}
|
|
|
|
deleteAccount() async {
|
|
await _storageClient.delete(accountFile);
|
|
_broadcastAccountData(Account());
|
|
}
|
|
|
|
_broadcastAccountData(Account account) {
|
|
currentAccount = account;
|
|
_transactionsController.add(account.transactions);
|
|
_categoriesController.add(account.categories);
|
|
_budgetController.add(account.budgets);
|
|
}
|
|
}
|