Line data Source code
1 : // Copyright 2023 The terCAD team. All rights reserved.
2 : // Use of this source code is governed by a CC BY-NC-ND 4.0 license that can be found in the LICENSE file.
3 :
4 : import 'dart:collection';
5 : import 'package:app_finance/_classes/controller/iterator_controller.dart';
6 : import 'package:app_finance/_classes/herald/app_budget_positive.dart';
7 : import 'package:app_finance/_classes/herald/app_start_of_month.dart';
8 : import 'package:app_finance/_classes/herald/app_sync.dart';
9 : import 'package:app_finance/_classes/math/budget_prediction.dart';
10 : import 'package:app_finance/_classes/math/goal_recalculation.dart';
11 : import 'package:app_finance/_classes/math/invoice_recalculation.dart';
12 : import 'package:app_finance/_classes/storage/history_data.dart';
13 : import 'package:app_finance/_classes/structure/account_app_data.dart';
14 : import 'package:app_finance/_classes/structure/bill_app_data.dart';
15 : import 'package:app_finance/_classes/math/bill_recalculation.dart';
16 : import 'package:app_finance/_classes/structure/budget_app_data.dart';
17 : import 'package:app_finance/_classes/math/budget_recalculation.dart';
18 : import 'package:app_finance/_classes/structure/currency_app_data.dart';
19 : import 'package:app_finance/_classes/structure/currency/exchange.dart';
20 : import 'package:app_finance/_classes/structure/goal_app_data.dart';
21 : import 'package:app_finance/_classes/structure/interface_app_data.dart';
22 : import 'package:app_finance/_classes/structure/invoice_app_data.dart';
23 : import 'package:app_finance/_classes/structure/payment_app_data.dart';
24 : import 'package:app_finance/_classes/structure/summary_app_data.dart';
25 : import 'package:app_finance/_classes/math/total_recalculation.dart';
26 : import 'package:app_finance/_classes/storage/transaction_log.dart';
27 : import 'package:app_finance/_ext/iterable_ext.dart';
28 : import 'package:material_ui/material_ui.dart';
29 : import 'package:uuid/uuid.dart';
30 :
31 : enum AppDataType {
32 : goals,
33 : bills,
34 : accounts,
35 : budgets,
36 : currencies,
37 : invoice,
38 : payments,
39 : }
40 :
41 : typedef AppDataGetter = ({
42 : List<dynamic> list,
43 : double total,
44 : InterfaceIterator stream,
45 : });
46 :
47 : class AppData extends ChangeNotifier {
48 : final AppSync appSync;
49 : bool isLoading = false;
50 : final _hashTable = HashMap<String, dynamic>();
51 : final _data = <AppDataType, SummaryAppData>{};
52 3 : late final prediction = BudgetPrediction(isValid: (uuid) {
53 2 : final budget = _hashTable[uuid];
54 2 : return budget is BudgetAppData && !budget.hidden;
55 : });
56 :
57 2 : AppData(this.appSync) : super() {
58 1 : isLoading = true;
59 1 : int startingDay = AppStartOfMonth.get();
60 2 : for (var key in AppDataType.values) {
61 3 : _data[key] = SummaryAppData(startingDay: startingDay);
62 : }
63 2 : Exchange(store: this).getDefaultCurrency();
64 3 : TransactionLog.load(this).then((_) async => await restate()).then((_) => appSync.follow(AppData, _stream));
65 : }
66 :
67 1 : @override
68 : dispose() {
69 1 : super.dispose();
70 2 : appSync.unfollow(AppData);
71 : }
72 :
73 0 : void _stream(String value) {
74 : try {
75 0 : TransactionLog.add(this, value, true, true);
76 : } catch (e) {
77 : //...
78 : }
79 : }
80 :
81 0 : Future<void> flush() async {
82 0 : isLoading = true;
83 0 : int startingDay = AppStartOfMonth.get();
84 0 : _hashTable.clear();
85 0 : _data.updateAll((key, value) => SummaryAppData(startingDay: startingDay));
86 0 : await TransactionLog.load(this);
87 0 : await restate();
88 : }
89 :
90 0 : Future<void> restate() async {
91 0 : await updateTotals(AppDataType.values);
92 0 : isLoading = false;
93 0 : notifyListeners();
94 : }
95 :
96 1 : void _set(AppDataType property, dynamic value) {
97 3 : _hashTable[value.uuid] = value;
98 5 : _data[property]?.add(value.uuid, updatedAt: value.createdAt);
99 1 : if (!isLoading) {
100 1 : TransactionLog.save(value);
101 3 : appSync.send(value.toStream());
102 1 : _notify();
103 : }
104 : }
105 :
106 1 : void _notify() {
107 1 : if (!isLoading) {
108 4 : WidgetsBinding.instance.addPostFrameCallback((_) => notifyListeners());
109 : }
110 : }
111 :
112 1 : dynamic add(InterfaceAppData value, [String? uuid]) {
113 2 : value.uuid = uuid ?? const Uuid().v4();
114 1 : _update(null, value);
115 2 : return getByUuid(value.uuid!);
116 : }
117 :
118 1 : void update(String uuid, InterfaceAppData value, [bool createIfMissing = false]) {
119 1 : var initial = getByUuid(uuid, false);
120 : if (initial != null || createIfMissing) {
121 1 : _update(initial, value);
122 : }
123 : }
124 :
125 1 : Future<void> updateTotals(List<AppDataType> scope) async {
126 1 : final accountTotal = getTotal(AppDataType.accounts);
127 1 : final exchange = Exchange(store: this);
128 1 : int isBudgetPositive = AppBudgetPositive.get();
129 2 : final rec = TotalRecalculation(exchange: exchange, isBudgetPositive: isBudgetPositive != 0);
130 2 : for (AppDataType type in scope) {
131 4 : await rec.updateTotal(type, _data[type], _hashTable);
132 : }
133 1 : if (scope.contains(AppDataType.accounts)) {
134 3 : rec.updateGoals(getList(AppDataType.goals, false), accountTotal, getTotal(AppDataType.accounts));
135 : }
136 1 : _notify();
137 : }
138 :
139 1 : void _update(InterfaceAppData? initial, InterfaceAppData change) {
140 4 : if (change.getType() != AppDataType.budgets && change.getType() != AppDataType.payments) {
141 4 : HistoryData.addLog(change.uuid, change, initial?.details ?? 0.0, change.details);
142 : }
143 1 : switch (change.getType()) {
144 1 : case AppDataType.accounts:
145 1 : _updateAccount(initial as AccountAppData?, change as AccountAppData);
146 : break;
147 1 : case AppDataType.bills:
148 1 : (change as BillAppData).setState(this);
149 1 : _updateBill(initial as BillAppData?, change);
150 : break;
151 1 : case AppDataType.budgets:
152 1 : (change as BudgetAppData).setState(this);
153 1 : _updateBudget(initial as BudgetAppData?, change);
154 3 : HistoryData.addLog(change.uuid, change, initial?.amountLimit ?? 0.0, change.amountLimit);
155 : break;
156 1 : case AppDataType.goals:
157 0 : _updateGoal(initial as GoalAppData?, change as GoalAppData);
158 : break;
159 1 : case AppDataType.currencies:
160 1 : _updateCurrency(initial as CurrencyAppData?, change as CurrencyAppData);
161 : break;
162 0 : case AppDataType.invoice:
163 0 : (change as InvoiceAppData).setState(this);
164 0 : _updateInvoice(initial as InvoiceAppData?, change);
165 : break;
166 0 : case AppDataType.payments:
167 0 : _updatePayment(initial as PaymentAppData?, change as PaymentAppData);
168 : break;
169 : }
170 : }
171 :
172 0 : void _updateInvoice(InvoiceAppData? initial, InvoiceAppData change) {
173 0 : _set(AppDataType.invoice, change);
174 0 : AccountAppData? currAccount = getByUuid(change.account, false);
175 : AccountAppData? prevAccount;
176 : if (initial != null) {
177 0 : prevAccount = getByUuid(initial.account, false);
178 : if (prevAccount != null) {
179 0 : _data[AppDataType.accounts]?.add(initial.account);
180 : }
181 : }
182 : if (currAccount != null) {
183 0 : final rec = InvoiceRecalculation(change, initial)..exchange = Exchange(store: this);
184 0 : rec.updateAccount(currAccount, prevAccount);
185 0 : _data[AppDataType.accounts]?.add(change.account);
186 0 : if (change.accountFrom != null) {
187 0 : rec.updateAccount(getByUuid(change.accountFrom!, false),
188 0 : initial != null && initial.accountFrom != null ? getByUuid(initial.accountFrom!, false) : null, true);
189 0 : _data[AppDataType.accounts]?.add(change.accountFrom!);
190 : }
191 : }
192 0 : if (!isLoading) {
193 0 : updateTotals([AppDataType.accounts]);
194 : }
195 : }
196 :
197 1 : void _updateAccount(AccountAppData? initial, AccountAppData change) {
198 1 : _set(AppDataType.accounts, change);
199 1 : if (!isLoading) {
200 2 : updateTotals([AppDataType.accounts]);
201 : }
202 : }
203 :
204 1 : void _updateBill(BillAppData? initial, BillAppData change) {
205 2 : AccountAppData? currAccount = getByUuid(change.account, false);
206 : AccountAppData? prevAccount;
207 2 : BudgetAppData? currBudget = getByUuid(change.category, false);
208 : BudgetAppData? prevBudget;
209 1 : final exchange = Exchange(store: this);
210 4 : change.exchangeAccount = exchange.reform(1.0, change.currency, currAccount?.currency);
211 4 : change.exchangeCategory = exchange.reform(1.0, change.currency, currBudget?.currency);
212 : if (initial != null) {
213 0 : prevAccount = getByUuid(initial.account, false);
214 : if (prevAccount != null) {
215 0 : _data[AppDataType.accounts]?.add(initial.account);
216 : }
217 0 : prevBudget = getByUuid(initial.category, false);
218 : if (prevBudget != null) {
219 0 : _data[AppDataType.budgets]?.add(initial.category);
220 : }
221 : }
222 2 : prediction.add(change);
223 2 : final rec = BillRecalculation(change: change, initial: initial)..exchange = exchange;
224 : if (currAccount != null) {
225 1 : rec.updateAccount(currAccount, prevAccount);
226 4 : _data[AppDataType.accounts]?.add(change.account);
227 : }
228 : if (currBudget != null) {
229 1 : rec.updateBudget(currBudget, prevBudget);
230 4 : _data[AppDataType.budgets]?.add(change.category);
231 : }
232 1 : _set(AppDataType.bills, change);
233 0 : if (initial?.childOf != null) {
234 0 : BillAppData? parent = getByUuid(initial!.childOf!, false);
235 : if (parent != null) {
236 0 : parent.details -= change.details - (initial.details as double);
237 0 : update(initial.childOf!, parent);
238 : }
239 : }
240 1 : if (!isLoading) {
241 2 : updateTotals([AppDataType.bills, AppDataType.accounts, AppDataType.budgets]);
242 : }
243 : }
244 :
245 1 : void _updateBudget(BudgetAppData? initial, BudgetAppData change) {
246 1 : BudgetRecalculation(change: change, initial: initial)
247 2 : ..exchange = Exchange(store: this)
248 1 : ..updateBudget();
249 1 : _set(AppDataType.budgets, change);
250 1 : if (!isLoading) {
251 2 : updateTotals([AppDataType.budgets]);
252 : }
253 : }
254 :
255 0 : void _updateGoal(GoalAppData? initial, GoalAppData change) {
256 0 : GoalRecalculation(change: change, initial: initial)
257 0 : ..exchange = Exchange(store: this)
258 0 : ..updateGoal();
259 0 : _set(AppDataType.goals, change);
260 0 : if (!isLoading) {
261 0 : updateTotals([AppDataType.goals]);
262 : }
263 : }
264 :
265 1 : void _updateCurrency(CurrencyAppData? initial, CurrencyAppData change) {
266 1 : _set(AppDataType.currencies, change);
267 1 : if (!isLoading) {
268 1 : updateTotals(AppDataType.values);
269 : }
270 : }
271 :
272 0 : void _updatePayment(PaymentAppData? initial, PaymentAppData change) {
273 0 : _set(AppDataType.payments, change);
274 : }
275 :
276 1 : AppDataGetter get(AppDataType property) {
277 : return (
278 1 : list: getList(property),
279 1 : total: getTotal(property),
280 1 : stream: getStream<InterfaceAppData>(property),
281 : );
282 : }
283 :
284 1 : List<dynamic> getList(AppDataType property, [bool isClone = true]) {
285 3 : return (_data[property]?.list ?? [])
286 3 : .map((uuid) => getByUuid(uuid, isClone))
287 3 : .where((element) => !element.hidden)
288 1 : .toList();
289 : }
290 :
291 1 : InterfaceIterator getStream<M extends InterfaceAppData>(AppDataType property,
292 : {bool inverse = true, double? boundary, Function? filter}) {
293 2 : if (_data[property] == null) {
294 0 : return IteratorController<num, dynamic, M>(SplayTreeMap<num, dynamic>(), transform: getByUuid);
295 : }
296 4 : return _data[property]!.origin.toStream<M>(
297 : inverse,
298 1 : transform: getByUuid,
299 : boundary: boundary,
300 4 : filter: (M v) => v.hidden || filter?.call(v) == true,
301 : );
302 : }
303 :
304 0 : List<dynamic> getActualList(AppDataType property, [bool isClone = true]) {
305 0 : return (_data[property]?.listActual ?? [])
306 0 : .map((uuid) => getByUuid(uuid, isClone))
307 0 : .where((element) => !element.hidden)
308 0 : .toList();
309 : }
310 :
311 1 : double getTotal(AppDataType property) {
312 3 : return _data[property]?.total ?? 0.0;
313 : }
314 :
315 1 : dynamic getByUuid(String uuid, [bool isClone = true]) {
316 1 : if (uuid == '') return null;
317 5 : var obj = isClone ? _hashTable[uuid]?.clone() : _hashTable[uuid];
318 3 : if (obj is BillAppData || obj is BudgetAppData || obj is InvoiceAppData) {
319 1 : obj.setState(this);
320 : }
321 : return obj;
322 : }
323 : }
|