]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionModel.java
posting-level flag for amount validity; drop custom amount text filter
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionModel.java
1 /*
2  * Copyright © 2019 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.activity;
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
32 import org.jetbrains.annotations.NotNull;
33
34 import java.util.ArrayList;
35 import java.util.Calendar;
36 import java.util.Collections;
37 import java.util.Date;
38 import java.util.GregorianCalendar;
39 import java.util.Locale;
40 import java.util.concurrent.atomic.AtomicInteger;
41 import java.util.regex.Matcher;
42 import java.util.regex.Pattern;
43
44 public class NewTransactionModel extends ViewModel {
45     private static final Pattern reYMD =
46             Pattern.compile("^\\s*(\\d+)\\d*/\\s*(\\d+)\\s*/\\s*(\\d+)\\s*$");
47     private static final Pattern reMD = Pattern.compile("^\\s*(\\d+)\\s*/\\s*(\\d+)\\s*$");
48     private static final Pattern reD = Pattern.compile("\\s*(\\d+)\\s*$");
49     final MutableLiveData<Boolean> showCurrency = new MutableLiveData<>(false);
50     final ArrayList<Item> items = new ArrayList<>();
51     final MutableLiveData<Boolean> isSubmittable = new MutableLiveData<>(false);
52     final MutableLiveData<Boolean> showComments = new MutableLiveData<>(true);
53     private final Item header = new Item(this, null, "");
54     private final Item trailer = new Item(this);
55     private final MutableLiveData<Integer> focusedItem = new MutableLiveData<>(0);
56     private final MutableLiveData<Integer> accountCount = new MutableLiveData<>(0);
57     private final MutableLiveData<Boolean> simulateSave = new MutableLiveData<>(false);
58     private final AtomicInteger busyCounter = new AtomicInteger(0);
59     private final MutableLiveData<Boolean> busyFlag = new MutableLiveData<>(false);
60     private boolean observingDataProfile;
61     private Observer<MobileLedgerProfile> profileObserver = profile -> {
62         showCurrency.postValue(profile.getShowCommodityByDefault());
63         showComments.postValue(profile.getShowCommentsByDefault());
64     };
65     void observeShowComments(LifecycleOwner owner, Observer<? super Boolean> observer) {
66         showComments.observe(owner, observer);
67     }
68     void observeBusyFlag(@NonNull LifecycleOwner owner, Observer<? super Boolean> observer) {
69         busyFlag.observe(owner, observer);
70     }
71     void observeDataProfile(LifecycleOwner activity) {
72         if (!observingDataProfile)
73             Data.profile.observe(activity, profileObserver);
74         observingDataProfile = true;
75     }
76     boolean getSimulateSave() {
77         return simulateSave.getValue();
78     }
79     public void setSimulateSave(boolean simulateSave) {
80         this.simulateSave.setValue(simulateSave);
81     }
82     void toggleSimulateSave() {
83         simulateSave.setValue(!simulateSave.getValue());
84     }
85     void observeSimulateSave(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
86                              @NonNull androidx.lifecycle.Observer<? super Boolean> observer) {
87         this.simulateSave.observe(owner, observer);
88     }
89     int getAccountCount() {
90         return items.size();
91     }
92     public Date getDate() {
93         return header.date.getValue();
94     }
95     public String getDescription() {
96         return header.description.getValue();
97     }
98     public String getComment() {
99         return header.comment.getValue();
100     }
101     LiveData<Boolean> isSubmittable() {
102         return this.isSubmittable;
103     }
104     void reset() {
105         header.date.setValue(null);
106         header.description.setValue(null);
107         header.comment.setValue(null);
108         items.clear();
109         items.add(new Item(this, new LedgerTransactionAccount("")));
110         items.add(new Item(this, new LedgerTransactionAccount("")));
111         focusedItem.setValue(0);
112     }
113     void observeFocusedItem(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
114                             @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
115         this.focusedItem.observe(owner, observer);
116     }
117     void stopObservingFocusedItem(@NonNull androidx.lifecycle.Observer<? super Integer> observer) {
118         this.focusedItem.removeObserver(observer);
119     }
120     void observeAccountCount(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
121                              @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
122         this.accountCount.observe(owner, observer);
123     }
124     void stopObservingAccountCount(@NonNull androidx.lifecycle.Observer<? super Integer> observer) {
125         this.accountCount.removeObserver(observer);
126     }
127     int getFocusedItem() { return focusedItem.getValue(); }
128     void setFocusedItem(int position) {
129         focusedItem.setValue(position);
130     }
131     int addAccount(LedgerTransactionAccount acc) {
132         items.add(new Item(this, acc));
133         accountCount.setValue(getAccountCount());
134         return items.size();
135     }
136     boolean accountsInInitialState() {
137         for (Item item : items) {
138             LedgerTransactionAccount acc = item.getAccount();
139             if (acc.isAmountSet())
140                 return false;
141             if (!acc.getAccountName()
142                     .trim()
143                     .isEmpty())
144                 return false;
145         }
146
147         return true;
148     }
149     LedgerTransactionAccount getAccount(int index) {
150         return items.get(index)
151                     .getAccount();
152     }
153     Item getItem(int index) {
154         if (index == 0) {
155             return header;
156         }
157
158         if (index <= items.size())
159             return items.get(index - 1);
160
161         return trailer;
162     }
163     void removeRow(Item item, NewTransactionItemsAdapter adapter) {
164         int pos = items.indexOf(item);
165         items.remove(pos);
166         if (adapter != null) {
167             adapter.notifyItemRemoved(pos + 1);
168             sendCountNotifications();
169         }
170     }
171     void removeItem(int pos) {
172         items.remove(pos);
173         accountCount.setValue(getAccountCount());
174     }
175     void sendCountNotifications() {
176         accountCount.setValue(getAccountCount());
177     }
178     public void sendFocusedNotification() {
179         focusedItem.setValue(focusedItem.getValue());
180     }
181     void updateFocusedItem(int position) {
182         focusedItem.setValue(position);
183     }
184     void noteFocusChanged(int position, FocusedElement element) {
185         getItem(position).setFocusedElement(element);
186     }
187     void swapItems(int one, int two) {
188         Collections.swap(items, one - 1, two - 1);
189     }
190     void moveItemLast(int index) {
191         /*   0
192              1   <-- index
193              2
194              3   <-- desired position
195          */
196         int itemCount = items.size();
197
198         if (index < itemCount - 1) {
199             Item acc = items.remove(index);
200             items.add(itemCount - 1, acc);
201         }
202     }
203     void toggleCurrencyVisible() {
204         showCurrency.setValue(!showCurrency.getValue());
205     }
206     void stopObservingBusyFlag(Observer<Boolean> observer) {
207         busyFlag.removeObserver(observer);
208     }
209     void incrementBusyCounter() {
210         int newValue = busyCounter.incrementAndGet();
211         if (newValue == 1)
212             busyFlag.postValue(true);
213     }
214     void decrementBusyCounter() {
215         int newValue = busyCounter.decrementAndGet();
216         if (newValue == 0)
217             busyFlag.postValue(false);
218     }
219     public boolean getBusyFlag() {
220         return busyFlag.getValue();
221     }
222     public void toggleShowComments() {
223         showComments.setValue(!showComments.getValue());
224     }
225     enum ItemType {generalData, transactionRow, bottomFiller}
226
227     enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
228
229
230     //==========================================================================================
231
232
233     static class Item {
234         private ItemType type;
235         private MutableLiveData<Date> date = new MutableLiveData<>();
236         private MutableLiveData<String> description = new MutableLiveData<>();
237         private LedgerTransactionAccount account;
238         private MutableLiveData<String> amountHint = new MutableLiveData<>(null);
239         private NewTransactionModel model;
240         private MutableLiveData<Boolean> editable = new MutableLiveData<>(true);
241         private FocusedElement focusedElement = FocusedElement.Account;
242         private MutableLiveData<String> comment = new MutableLiveData<>(null);
243         private MutableLiveData<Currency> currency = new MutableLiveData<>(null);
244         private MutableLiveData<Boolean> amountValid = new MutableLiveData<>(true);
245         private boolean amountHintIsSet = false;
246         Item(NewTransactionModel model) {
247             this.model = model;
248             type = ItemType.bottomFiller;
249             editable.setValue(false);
250         }
251         Item(NewTransactionModel model, Date date, String description) {
252             this.model = model;
253             this.type = ItemType.generalData;
254             this.date.setValue(date);
255             this.description.setValue(description);
256             this.editable.setValue(true);
257         }
258         Item(NewTransactionModel model, LedgerTransactionAccount account) {
259             this.model = model;
260             this.type = ItemType.transactionRow;
261             this.account = account;
262             String currName = account.getCurrency();
263             Currency curr = null;
264             if ((currName != null) && !currName.isEmpty())
265                 curr = Currency.loadByName(currName);
266             this.currency.setValue(curr);
267             this.editable.setValue(true);
268         }
269         FocusedElement getFocusedElement() {
270             return focusedElement;
271         }
272         void setFocusedElement(FocusedElement focusedElement) {
273             this.focusedElement = focusedElement;
274         }
275         public NewTransactionModel getModel() {
276             return model;
277         }
278         void setEditable(boolean editable) {
279             ensureType(ItemType.generalData, ItemType.transactionRow);
280             this.editable.setValue(editable);
281         }
282         private void ensureType(ItemType type1, ItemType type2) {
283             if ((type != type1) && (type != type2)) {
284                 throw new RuntimeException(
285                         String.format("Actual type (%s) differs from wanted (%s or %s)", type,
286                                 type1, type2));
287             }
288         }
289         String getAmountHint() {
290             ensureType(ItemType.transactionRow);
291             return amountHint.getValue();
292         }
293         void setAmountHint(String amountHint) {
294             ensureType(ItemType.transactionRow);
295
296             // avoid unnecessary triggers
297             if (amountHint == null) {
298                 if (this.amountHint.getValue() == null)
299                     return;
300                 amountHintIsSet = false;
301             }
302             else {
303                 if (amountHint.equals(this.amountHint.getValue()))
304                     return;
305                 amountHintIsSet = true;
306             }
307
308             this.amountHint.setValue(amountHint);
309         }
310         void observeAmountHint(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
311                                @NonNull androidx.lifecycle.Observer<? super String> observer) {
312             this.amountHint.observe(owner, observer);
313         }
314         void stopObservingAmountHint(
315                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
316             this.amountHint.removeObserver(observer);
317         }
318         ItemType getType() {
319             return type;
320         }
321         void ensureType(ItemType wantedType) {
322             if (type != wantedType) {
323                 throw new RuntimeException(
324                         String.format("Actual type (%s) differs from wanted (%s)", type,
325                                 wantedType));
326             }
327         }
328         public Date getDate() {
329             ensureType(ItemType.generalData);
330             return date.getValue();
331         }
332         public void setDate(Date date) {
333             ensureType(ItemType.generalData);
334             this.date.setValue(date);
335         }
336         public void setDate(String text) {
337             if ((text == null) || text.trim()
338                                       .isEmpty())
339             {
340                 setDate((Date) null);
341                 return;
342             }
343
344             int year, month, day;
345             final Calendar c = GregorianCalendar.getInstance();
346             Matcher m = reYMD.matcher(text);
347             if (m.matches()) {
348                 year = Integer.parseInt(m.group(1));
349                 month = Integer.parseInt(m.group(2)) - 1;   // month is 0-based
350                 day = Integer.parseInt(m.group(3));
351             }
352             else {
353                 year = c.get(Calendar.YEAR);
354                 m = reMD.matcher(text);
355                 if (m.matches()) {
356                     month = Integer.parseInt(m.group(1)) - 1;
357                     day = Integer.parseInt(m.group(2));
358                 }
359                 else {
360                     month = c.get(Calendar.MONTH);
361                     m = reD.matcher(text);
362                     if (m.matches()) {
363                         day = Integer.parseInt(m.group(1));
364                     }
365                     else {
366                         day = c.get(Calendar.DAY_OF_MONTH);
367                     }
368                 }
369             }
370
371             c.set(year, month, day);
372
373             this.setDate(c.getTime());
374         }
375         void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
376                          @NonNull androidx.lifecycle.Observer<? super Date> observer) {
377             this.date.observe(owner, observer);
378         }
379         void stopObservingDate(@NonNull androidx.lifecycle.Observer<? super Date> observer) {
380             this.date.removeObserver(observer);
381         }
382         public String getDescription() {
383             ensureType(ItemType.generalData);
384             return description.getValue();
385         }
386         public void setDescription(String description) {
387             ensureType(ItemType.generalData);
388             this.description.setValue(description);
389         }
390         void observeDescription(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
391                                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
392             this.description.observe(owner, observer);
393         }
394         void stopObservingDescription(
395                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
396             this.description.removeObserver(observer);
397         }
398         public String getTransactionComment() {
399             ensureType(ItemType.generalData);
400             return comment.getValue();
401         }
402         public void setTransactionComment(String transactionComment) {
403             ensureType(ItemType.generalData);
404             this.comment.setValue(transactionComment);
405         }
406         void observeTransactionComment(@NonNull @NotNull LifecycleOwner owner,
407                                        @NonNull Observer<? super String> observer) {
408             ensureType(ItemType.generalData);
409             this.comment.observe(owner, observer);
410         }
411         void stopObservingTransactionComment(@NonNull Observer<? super String> observer) {
412             this.comment.removeObserver(observer);
413         }
414         public LedgerTransactionAccount getAccount() {
415             ensureType(ItemType.transactionRow);
416             return account;
417         }
418         public void setAccountName(String name) {
419             account.setAccountName(name);
420         }
421         /**
422          * getFormattedDate()
423          *
424          * @return nicely formatted, shortest available date representation
425          */
426         String getFormattedDate() {
427             if (date == null)
428                 return null;
429             Date time = date.getValue();
430             if (time == null)
431                 return null;
432
433             Calendar c = GregorianCalendar.getInstance();
434             c.setTime(time);
435             Calendar today = GregorianCalendar.getInstance();
436
437             final int myYear = c.get(Calendar.YEAR);
438             final int myMonth = c.get(Calendar.MONTH);
439             final int myDay = c.get(Calendar.DAY_OF_MONTH);
440
441             if (today.get(Calendar.YEAR) != myYear) {
442                 return String.format(Locale.US, "%d/%02d/%02d", myYear, myMonth + 1, myDay);
443             }
444
445             if (today.get(Calendar.MONTH) != myMonth) {
446                 return String.format(Locale.US, "%d/%02d", myMonth + 1, myDay);
447             }
448
449             return String.valueOf(myDay);
450         }
451         void observeEditableFlag(NewTransactionActivity activity, Observer<Boolean> observer) {
452             editable.observe(activity, observer);
453         }
454         void stopObservingEditableFlag(Observer<Boolean> observer) {
455             editable.removeObserver(observer);
456         }
457         void observeComment(NewTransactionActivity activity, Observer<String> observer) {
458             comment.observe(activity, observer);
459         }
460         void stopObservingComment(Observer<String> observer) {
461             comment.removeObserver(observer);
462         }
463         public void setComment(String comment) {
464             getAccount().setComment(comment);
465             this.comment.postValue(comment);
466         }
467         public Currency getCurrency() {
468             return this.currency.getValue();
469         }
470         public void setCurrency(Currency currency) {
471             Currency present = this.currency.getValue();
472             if ((currency == null) && (present != null) ||
473                 (currency != null) && !currency.equals(present))
474             {
475                 getAccount().setCurrency((currency != null && !currency.getName()
476                                                                        .isEmpty())
477                                          ? currency.getName() : null);
478                 this.currency.setValue(currency);
479             }
480         }
481         void observeCurrency(NewTransactionActivity activity, Observer<Currency> observer) {
482             currency.observe(activity, observer);
483         }
484         void stopObservingCurrency(Observer<Currency> observer) {
485             currency.removeObserver(observer);
486         }
487         boolean isOfType(ItemType type) {
488             return this.type == type;
489         }
490         boolean isAmountHintSet() {
491             return amountHintIsSet;
492         }
493         void validateAmount() {
494             amountValid.setValue(true);
495         }
496         void invalidateAmount() {
497             amountValid.setValue(false);
498         }
499         void observeAmountValidity(NewTransactionActivity activity, Observer<Boolean> observer) {
500             amountValid.observe(activity, observer);
501         }
502         void stopObservingAmountValidity(Observer<Boolean> observer) {
503             amountValid.removeObserver(observer);
504         }
505     }
506 }