]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/new_transaction/NewTransactionModel.java
add icon to the dialog for choosing a template
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / new_transaction / NewTransactionModel.java
1 /*
2  * Copyright © 2021 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * MoLe is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.ui.new_transaction;
19
20 import androidx.annotation.NonNull;
21 import androidx.lifecycle.LifecycleOwner;
22 import androidx.lifecycle.LiveData;
23 import androidx.lifecycle.MutableLiveData;
24 import androidx.lifecycle.Observer;
25 import androidx.lifecycle.ViewModel;
26
27 import net.ktnx.mobileledger.model.Currency;
28 import net.ktnx.mobileledger.model.Data;
29 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
30 import net.ktnx.mobileledger.model.MobileLedgerProfile;
31 import net.ktnx.mobileledger.utils.Globals;
32 import net.ktnx.mobileledger.utils.SimpleDate;
33
34 import org.jetbrains.annotations.NotNull;
35
36 import java.text.ParseException;
37 import java.util.ArrayList;
38 import java.util.Calendar;
39 import java.util.Collections;
40 import java.util.GregorianCalendar;
41 import java.util.Locale;
42 import java.util.concurrent.atomic.AtomicInteger;
43
44 public class NewTransactionModel extends ViewModel {
45     final MutableLiveData<Boolean> showCurrency = new MutableLiveData<>(false);
46     final ArrayList<Item> items = new ArrayList<>();
47     final MutableLiveData<Boolean> isSubmittable = new MutableLiveData<>(false);
48     final MutableLiveData<Boolean> showComments = new MutableLiveData<>(true);
49     private final Item header = new Item(this, "");
50     private final Item trailer = new Item(this);
51     private final MutableLiveData<Integer> focusedItem = new MutableLiveData<>(0);
52     private final MutableLiveData<Integer> accountCount = new MutableLiveData<>(0);
53     private final MutableLiveData<Boolean> simulateSave = new MutableLiveData<>(false);
54     private final AtomicInteger busyCounter = new AtomicInteger(0);
55     private final MutableLiveData<Boolean> busyFlag = new MutableLiveData<>(false);
56     private final Observer<MobileLedgerProfile> profileObserver = profile -> {
57         showCurrency.postValue(profile.getShowCommodityByDefault());
58         showComments.postValue(profile.getShowCommentsByDefault());
59     };
60     private boolean observingDataProfile;
61     void observeShowComments(LifecycleOwner owner, Observer<? super Boolean> observer) {
62         showComments.observe(owner, observer);
63     }
64     void observeBusyFlag(@NonNull LifecycleOwner owner, Observer<? super Boolean> observer) {
65         busyFlag.observe(owner, observer);
66     }
67     void observeDataProfile(LifecycleOwner activity) {
68         if (!observingDataProfile)
69             Data.observeProfile(activity, profileObserver);
70         observingDataProfile = true;
71     }
72     boolean getSimulateSave() {
73         return simulateSave.getValue();
74     }
75     public void setSimulateSave(boolean simulateSave) {
76         this.simulateSave.setValue(simulateSave);
77     }
78     void toggleSimulateSave() {
79         simulateSave.setValue(!simulateSave.getValue());
80     }
81     void observeSimulateSave(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
82                              @NonNull androidx.lifecycle.Observer<? super Boolean> observer) {
83         this.simulateSave.observe(owner, observer);
84     }
85     int getAccountCount() {
86         return items.size();
87     }
88     public SimpleDate getDate() {
89         return header.date.getValue();
90     }
91     public void setDate(SimpleDate date) {
92         header.date.setValue(date);
93     }
94     public String getDescription() {
95         return header.description.getValue();
96     }
97     public String getComment() {
98         return header.comment.getValue();
99     }
100     LiveData<Boolean> isSubmittable() {
101         return this.isSubmittable;
102     }
103     void reset() {
104         header.date.setValue(null);
105         header.description.setValue(null);
106         header.comment.setValue(null);
107         items.clear();
108         items.add(new Item(this, new LedgerTransactionAccount("")));
109         items.add(new Item(this, new LedgerTransactionAccount("")));
110         focusedItem.setValue(0);
111     }
112     void observeFocusedItem(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
113                             @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
114         this.focusedItem.observe(owner, observer);
115     }
116     void stopObservingFocusedItem(@NonNull androidx.lifecycle.Observer<? super Integer> observer) {
117         this.focusedItem.removeObserver(observer);
118     }
119     void observeAccountCount(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
120                              @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
121         this.accountCount.observe(owner, observer);
122     }
123     void stopObservingAccountCount(@NonNull androidx.lifecycle.Observer<? super Integer> observer) {
124         this.accountCount.removeObserver(observer);
125     }
126     int getFocusedItem() { return focusedItem.getValue(); }
127     void setFocusedItem(int position) {
128         focusedItem.setValue(position);
129     }
130     int addAccount(LedgerTransactionAccount acc) {
131         items.add(new Item(this, acc));
132         accountCount.setValue(getAccountCount());
133         return items.size();
134     }
135     boolean accountsInInitialState() {
136         for (Item item : items) {
137             LedgerTransactionAccount acc = item.getAccount();
138             if (acc.isAmountSet())
139                 return false;
140             if (!acc.getAccountName()
141                     .trim()
142                     .isEmpty())
143                 return false;
144         }
145
146         return true;
147     }
148     LedgerTransactionAccount getAccount(int index) {
149         return items.get(index)
150                     .getAccount();
151     }
152     Item getItem(int index) {
153         if (index == 0) {
154             return header;
155         }
156
157         if (index <= items.size())
158             return items.get(index - 1);
159
160         return trailer;
161     }
162     void removeRow(Item item, NewTransactionItemsAdapter adapter) {
163         int pos = items.indexOf(item);
164         items.remove(pos);
165         if (adapter != null) {
166             adapter.notifyItemRemoved(pos + 1);
167             sendCountNotifications();
168         }
169     }
170     void removeItem(int pos) {
171         items.remove(pos);
172         accountCount.setValue(getAccountCount());
173     }
174     void sendCountNotifications() {
175         accountCount.setValue(getAccountCount());
176     }
177     public void sendFocusedNotification() {
178         focusedItem.setValue(focusedItem.getValue());
179     }
180     void updateFocusedItem(int position) {
181         focusedItem.setValue(position);
182     }
183     void noteFocusChanged(int position, FocusedElement element) {
184         getItem(position).setFocusedElement(element);
185     }
186     void swapItems(int one, int two) {
187         Collections.swap(items, one - 1, two - 1);
188     }
189     void moveItemLast(int index) {
190         /*   0
191              1   <-- index
192              2
193              3   <-- desired position
194          */
195         int itemCount = items.size();
196
197         if (index < itemCount - 1) {
198             Item acc = items.remove(index);
199             items.add(itemCount - 1, acc);
200         }
201     }
202     void toggleCurrencyVisible() {
203         showCurrency.setValue(!showCurrency.getValue());
204     }
205     void stopObservingBusyFlag(Observer<Boolean> observer) {
206         busyFlag.removeObserver(observer);
207     }
208     void incrementBusyCounter() {
209         int newValue = busyCounter.incrementAndGet();
210         if (newValue == 1)
211             busyFlag.postValue(true);
212     }
213     void decrementBusyCounter() {
214         int newValue = busyCounter.decrementAndGet();
215         if (newValue == 0)
216             busyFlag.postValue(false);
217     }
218     public boolean getBusyFlag() {
219         return busyFlag.getValue();
220     }
221     public void toggleShowComments() {
222         showComments.setValue(!showComments.getValue());
223     }
224     enum ItemType {generalData, transactionRow, bottomFiller}
225
226     enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
227
228
229     //==========================================================================================
230
231
232     static class Item {
233         private final ItemType type;
234         private final MutableLiveData<SimpleDate> date = new MutableLiveData<>();
235         private final MutableLiveData<String> description = new MutableLiveData<>();
236         private final MutableLiveData<String> amountHint = new MutableLiveData<>(null);
237         private final NewTransactionModel model;
238         private final MutableLiveData<Boolean> editable = new MutableLiveData<>(true);
239         private final MutableLiveData<String> comment = new MutableLiveData<>(null);
240         private final MutableLiveData<Currency> currency = new MutableLiveData<>(null);
241         private final MutableLiveData<Boolean> amountValid = new MutableLiveData<>(true);
242         private LedgerTransactionAccount account;
243         private FocusedElement focusedElement = FocusedElement.Account;
244         private boolean amountHintIsSet = false;
245         Item(NewTransactionModel model) {
246             this.model = model;
247             type = ItemType.bottomFiller;
248             editable.setValue(false);
249         }
250         Item(NewTransactionModel model, String description) {
251             this.model = model;
252             this.type = ItemType.generalData;
253             this.description.setValue(description);
254             this.editable.setValue(true);
255         }
256         Item(NewTransactionModel model, LedgerTransactionAccount account) {
257             this.model = model;
258             this.type = ItemType.transactionRow;
259             this.account = account;
260             String currName = account.getCurrency();
261             Currency curr = null;
262             if ((currName != null) && !currName.isEmpty())
263                 curr = Currency.loadByName(currName);
264             this.currency.setValue(curr);
265             this.editable.setValue(true);
266         }
267         FocusedElement getFocusedElement() {
268             return focusedElement;
269         }
270         void setFocusedElement(FocusedElement focusedElement) {
271             this.focusedElement = focusedElement;
272         }
273         public NewTransactionModel getModel() {
274             return model;
275         }
276         void setEditable(boolean editable) {
277             ensureTypeIsGeneralDataOrTransactionRow();
278             this.editable.setValue(editable);
279         }
280         private void ensureTypeIsGeneralDataOrTransactionRow() {
281             if ((type != ItemType.generalData) && (type != ItemType.transactionRow)) {
282                 throw new RuntimeException(
283                         String.format("Actual type (%s) differs from wanted (%s or %s)", type,
284                                 ItemType.generalData, ItemType.transactionRow));
285             }
286         }
287         String getAmountHint() {
288             ensureType(ItemType.transactionRow);
289             return amountHint.getValue();
290         }
291         void setAmountHint(String amountHint) {
292             ensureType(ItemType.transactionRow);
293
294             // avoid unnecessary triggers
295             if (amountHint == null) {
296                 if (this.amountHint.getValue() == null)
297                     return;
298                 amountHintIsSet = false;
299             }
300             else {
301                 if (amountHint.equals(this.amountHint.getValue()))
302                     return;
303                 amountHintIsSet = true;
304             }
305
306             this.amountHint.setValue(amountHint);
307         }
308         void observeAmountHint(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
309                                @NonNull androidx.lifecycle.Observer<? super String> observer) {
310             this.amountHint.observe(owner, observer);
311         }
312         void stopObservingAmountHint(
313                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
314             this.amountHint.removeObserver(observer);
315         }
316         ItemType getType() {
317             return type;
318         }
319         void ensureType(ItemType wantedType) {
320             if (type != wantedType) {
321                 throw new RuntimeException(
322                         String.format("Actual type (%s) differs from wanted (%s)", type,
323                                 wantedType));
324             }
325         }
326         public SimpleDate getDate() {
327             ensureType(ItemType.generalData);
328             return date.getValue();
329         }
330         public void setDate(SimpleDate date) {
331             ensureType(ItemType.generalData);
332             this.date.setValue(date);
333         }
334         public void setDate(String text) throws ParseException {
335             if ((text == null) || text.trim()
336                                       .isEmpty())
337             {
338                 setDate((SimpleDate) null);
339                 return;
340             }
341
342             SimpleDate date = Globals.parseLedgerDate(text);
343             this.setDate(date);
344         }
345         void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
346                          @NonNull androidx.lifecycle.Observer<? super SimpleDate> observer) {
347             this.date.observe(owner, observer);
348         }
349         void stopObservingDate(@NonNull androidx.lifecycle.Observer<? super SimpleDate> observer) {
350             this.date.removeObserver(observer);
351         }
352         public String getDescription() {
353             ensureType(ItemType.generalData);
354             return description.getValue();
355         }
356         public void setDescription(String description) {
357             ensureType(ItemType.generalData);
358             this.description.setValue(description);
359         }
360         void observeDescription(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
361                                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
362             this.description.observe(owner, observer);
363         }
364         void stopObservingDescription(
365                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
366             this.description.removeObserver(observer);
367         }
368         public String getTransactionComment() {
369             ensureType(ItemType.generalData);
370             return comment.getValue();
371         }
372         public void setTransactionComment(String transactionComment) {
373             ensureType(ItemType.generalData);
374             this.comment.setValue(transactionComment);
375         }
376         void observeTransactionComment(@NonNull @NotNull LifecycleOwner owner,
377                                        @NonNull Observer<? super String> observer) {
378             ensureType(ItemType.generalData);
379             this.comment.observe(owner, observer);
380         }
381         void stopObservingTransactionComment(@NonNull Observer<? super String> observer) {
382             this.comment.removeObserver(observer);
383         }
384         public LedgerTransactionAccount getAccount() {
385             ensureType(ItemType.transactionRow);
386             return account;
387         }
388         public void setAccountName(String name) {
389             account.setAccountName(name);
390         }
391         /**
392          * getFormattedDate()
393          *
394          * @return nicely formatted, shortest available date representation
395          */
396         String getFormattedDate() {
397             if (date == null)
398                 return null;
399             SimpleDate d = date.getValue();
400             if (d == null)
401                 return null;
402
403             Calendar today = GregorianCalendar.getInstance();
404
405             if (today.get(Calendar.YEAR) != d.year) {
406                 return String.format(Locale.US, "%d/%02d/%02d", d.year, d.month, d.day);
407             }
408
409             if (today.get(Calendar.MONTH) != d.month - 1) {
410                 return String.format(Locale.US, "%d/%02d", d.month, d.day);
411             }
412
413             return String.valueOf(d.day);
414         }
415         void observeEditableFlag(NewTransactionActivity activity, Observer<Boolean> observer) {
416             editable.observe(activity, observer);
417         }
418         void stopObservingEditableFlag(Observer<Boolean> observer) {
419             editable.removeObserver(observer);
420         }
421         void observeComment(NewTransactionActivity activity, Observer<String> observer) {
422             comment.observe(activity, observer);
423         }
424         void stopObservingComment(Observer<String> observer) {
425             comment.removeObserver(observer);
426         }
427         public void setComment(String comment) {
428             getAccount().setComment(comment);
429             this.comment.postValue(comment);
430         }
431         public Currency getCurrency() {
432             return this.currency.getValue();
433         }
434         public void setCurrency(Currency currency) {
435             Currency present = this.currency.getValue();
436             if ((currency == null) && (present != null) ||
437                 (currency != null) && !currency.equals(present))
438             {
439                 getAccount().setCurrency((currency != null && !currency.getName()
440                                                                        .isEmpty())
441                                          ? currency.getName() : null);
442                 this.currency.setValue(currency);
443             }
444         }
445         void observeCurrency(NewTransactionActivity activity, Observer<Currency> observer) {
446             currency.observe(activity, observer);
447         }
448         void stopObservingCurrency(Observer<Currency> observer) {
449             currency.removeObserver(observer);
450         }
451         boolean isBottomFiller() {
452             return this.type == ItemType.bottomFiller;
453         }
454         boolean isAmountHintSet() {
455             return amountHintIsSet;
456         }
457         void validateAmount() {
458             amountValid.setValue(true);
459         }
460         void invalidateAmount() {
461             amountValid.setValue(false);
462         }
463         void observeAmountValidity(NewTransactionActivity activity, Observer<Boolean> observer) {
464             amountValid.observe(activity, observer);
465         }
466         void stopObservingAmountValidity(Observer<Boolean> observer) {
467             amountValid.removeObserver(observer);
468         }
469     }
470 }