]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionModel.java
NewTransactionModel/Item: initialize amount hint on creation
[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 android.annotation.SuppressLint;
21
22 import androidx.annotation.NonNull;
23 import androidx.lifecycle.LiveData;
24 import androidx.lifecycle.MutableLiveData;
25 import androidx.lifecycle.Observer;
26 import androidx.lifecycle.ViewModel;
27
28 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
29 import net.ktnx.mobileledger.utils.Misc;
30
31 import org.jetbrains.annotations.NotNull;
32
33 import java.util.ArrayList;
34 import java.util.Calendar;
35 import java.util.Date;
36 import java.util.GregorianCalendar;
37 import java.util.Locale;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
40
41 import static net.ktnx.mobileledger.utils.Logger.debug;
42 import static net.ktnx.mobileledger.utils.Misc.isZero;
43
44 public class NewTransactionModel extends ViewModel {
45     static final Pattern reYMD = Pattern.compile("^\\s*(\\d+)\\d*/\\s*(\\d+)\\s*/\\s*(\\d+)\\s*$");
46     static final Pattern reMD = Pattern.compile("^\\s*(\\d+)\\s*/\\s*(\\d+)\\s*$");
47     static final Pattern reD = Pattern.compile("\\s*(\\d+)\\s*$");
48     private final Item header = new Item(this, null, "");
49     private final Item trailer = new Item(this);
50     private final ArrayList<Item> items = new ArrayList<>();
51     private final MutableLiveData<Boolean> isSubmittable = new MutableLiveData<>(false);
52     private final MutableLiveData<Integer> focusedItem = new MutableLiveData<>(null);
53     private final MutableLiveData<Integer> accountCount = new MutableLiveData<>(0);
54     public int getAccountCount() {
55         return items.size();
56     }
57     public Date getDate() {
58         return header.date.getValue();
59     }
60     public String getDescription() {
61         return header.description.getValue();
62     }
63     public LiveData<Boolean> isSubmittable() {
64         return this.isSubmittable;
65     }
66     void reset() {
67         header.date.setValue(null);
68         header.description.setValue(null);
69         items.clear();
70         items.add(new Item(this, new LedgerTransactionAccount("")));
71         items.add(new Item(this, new LedgerTransactionAccount("")));
72         focusedItem.setValue(0);
73     }
74     public void observeFocusedItem(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
75                                    @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
76         this.focusedItem.observe(owner, observer);
77     }
78     public void stopObservingFocusedItem(
79             @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
80         this.focusedItem.removeObserver(observer);
81     }
82     public void observeAccountCount(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
83                                     @NonNull
84                                             androidx.lifecycle.Observer<? super Integer> observer) {
85         this.accountCount.observe(owner, observer);
86     }
87     public void stopObservingAccountCount(
88             @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
89         this.accountCount.removeObserver(observer);
90     }
91     public void setFocusedItem(int position) {
92         focusedItem.setValue(position);
93     }
94     public int addAccount(LedgerTransactionAccount acc) {
95         items.add(new Item(this, acc));
96         accountCount.setValue(getAccountCount());
97         return items.size();
98     }
99     boolean accountsInInitialState() {
100         for (Item item : items) {
101             LedgerTransactionAccount acc = item.getAccount();
102             if (acc.isAmountSet())
103                 return false;
104             if (!acc.getAccountName()
105                     .trim()
106                     .isEmpty())
107                 return false;
108         }
109
110         return true;
111     }
112     LedgerTransactionAccount getAccount(int index) {
113         return items.get(index)
114                     .getAccount();
115     }
116     public Item getItem(int index) {
117         if (index == 0) {
118             return header;
119         }
120
121         if (index <= items.size())
122             return items.get(index - 1);
123
124         return trailer;
125     }
126     // rules:
127     // 1) at least two account names
128     // 2) each amount must have account name
129     // 3) amounts must balance to 0, or
130     // 3a) there must be exactly one empty amount
131     // 4) empty accounts with empty amounts are ignored
132     // 5) a row with an empty account name or empty amount is guaranteed to exist
133     @SuppressLint("DefaultLocale")
134     public void checkTransactionSubmittable(NewTransactionItemsAdapter adapter) {
135         int accounts = 0;
136         int accounts_with_values = 0;
137         int amounts = 0;
138         int amounts_with_accounts = 0;
139         int empty_rows = 0;
140         Item empty_amount = null;
141         boolean single_empty_amount = false;
142         boolean single_empty_amount_has_account = false;
143         float running_total = 0f;
144         final String descriptionText = getDescription();
145         final boolean have_description = ((descriptionText != null) && !descriptionText.isEmpty());
146
147         try {
148             for (int i = 0; i < this.items.size(); i++) {
149                 Item item = this.items.get(i);
150
151                 LedgerTransactionAccount acc = item.getAccount();
152                 String acc_name = acc.getAccountName()
153                                      .trim();
154                 if (acc_name.isEmpty()) {
155                     empty_rows++;
156                 }
157                 else {
158                     accounts++;
159
160                     if (acc.isAmountSet()) {
161                         accounts_with_values++;
162                     }
163                 }
164
165                 if (acc.isAmountSet()) {
166                     amounts++;
167                     if (!acc_name.isEmpty())
168                         amounts_with_accounts++;
169                     running_total += acc.getAmount();
170                 }
171                 else {
172                     if (empty_amount == null) {
173                         empty_amount = item;
174                         single_empty_amount = true;
175                         single_empty_amount_has_account = !acc_name.isEmpty();
176                     }
177                     else if (!acc_name.isEmpty())
178                         single_empty_amount = false;
179                 }
180             }
181
182             if ((empty_rows == 0) &&
183                 ((this.items.size() == accounts) || (this.items.size() == amounts)))
184             {
185                 adapter.addRow();
186             }
187
188             for (NewTransactionModel.Item item : items) {
189
190                 final LedgerTransactionAccount acc = item.getAccount();
191                 if (acc.isAmountSet())
192                     continue;
193
194                 if (single_empty_amount) {
195                     if (item.equals(empty_amount)) {
196                         empty_amount.setAmountHint(Misc.isZero(running_total) ? null
197                                                                               : String.format(
198                                                                                       "%1.2f",
199                                                                                       -running_total));
200                         continue;
201                     }
202                 }
203                 else {
204                     // no single empty account and this account's amount is not set
205                     // => hint should be '0.00'
206                     item.setAmountHint(null);
207                 }
208
209             }
210
211             debug("submittable", String.format(Locale.US,
212                     "%s, accounts=%d, accounts_with_values=%s, " +
213                     "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
214                     "single_empty_with_acc=%s", have_description ? "description" : "NO description",
215                     accounts, accounts_with_values, amounts_with_accounts, amounts, running_total,
216                     (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
217
218             if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
219                 (amounts_with_accounts == amounts) &&
220                 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
221             {
222                 debug("submittable", "YES");
223                 isSubmittable.setValue(true);
224             }
225             else {
226                 debug("submittable", "NO");
227                 isSubmittable.setValue(false);
228             }
229
230         }
231         catch (NumberFormatException e) {
232             debug("submittable", "NO (because of NumberFormatException)");
233             isSubmittable.setValue(false);
234         }
235         catch (Exception e) {
236             e.printStackTrace();
237             debug("submittable", "NO (because of an Exception)");
238             isSubmittable.setValue(false);
239         }
240     }
241     public void removeItem(int pos) {
242         items.remove(pos);
243         accountCount.setValue(getAccountCount());
244     }
245     public void sendCountNotifications() {
246         accountCount.setValue(getAccountCount());
247     }
248     enum ItemType {generalData, transactionRow, bottomFiller}
249
250     class Item extends Object {
251         private ItemType type;
252         private MutableLiveData<Date> date = new MutableLiveData<>();
253         private MutableLiveData<String> description = new MutableLiveData<>();
254         private LedgerTransactionAccount account;
255         private MutableLiveData<String> amountHint = new MutableLiveData<>(null);
256         private NewTransactionModel model;
257         private MutableLiveData<Boolean> editable = new MutableLiveData<>(true);
258         public Item(NewTransactionModel model) {
259             this.model = model;
260             type = ItemType.bottomFiller;
261             editable.setValue(false);
262         }
263         public Item(NewTransactionModel model, Date date, String description) {
264             this.model = model;
265             this.type = ItemType.generalData;
266             this.date.setValue(date);
267             this.description.setValue(description);
268             this.editable.setValue(true);
269         }
270         public Item(NewTransactionModel model, LedgerTransactionAccount account) {
271             this.model = model;
272             this.type = ItemType.transactionRow;
273             this.account = account;
274             this.editable.setValue(true);
275         }
276         public NewTransactionModel getModel() {
277             return model;
278         }
279         public boolean isEditable() {
280             ensureType(ItemType.transactionRow);
281             return this.editable.getValue();
282         }
283         public void setEditable(boolean editable) {
284             ensureType(ItemType.transactionRow);
285             this.editable.setValue(editable);
286         }
287         public String getAmountHint() {
288             ensureType(ItemType.transactionRow);
289             return amountHint.getValue();
290         }
291         public 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             }
299             else {
300                 if (amountHint.equals(this.amountHint.getValue()))
301                     return;
302             }
303
304             this.amountHint.setValue(amountHint);
305         }
306         public void observeAmountHint(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
307                                       @NonNull
308                                               androidx.lifecycle.Observer<? super String> observer) {
309             this.amountHint.observe(owner, observer);
310         }
311         public void stopObservingAmountHint(
312                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
313             this.amountHint.removeObserver(observer);
314         }
315         public ItemType getType() {
316             return type;
317         }
318         public void ensureType(ItemType wantedType) {
319             if (type != wantedType) {
320                 throw new RuntimeException(
321                         String.format("Actual type (%s) differs from wanted (%s)", type,
322                                 wantedType));
323             }
324         }
325         public Date getDate() {
326             ensureType(ItemType.generalData);
327             return date.getValue();
328         }
329         public void setDate(Date date) {
330             ensureType(ItemType.generalData);
331             this.date.setValue(date);
332         }
333         public void setDate(String text) {
334             int year, month, day;
335             final Calendar c = GregorianCalendar.getInstance();
336             Matcher m = reYMD.matcher(text);
337             if (m.matches()) {
338                 year = Integer.parseInt(m.group(1));
339                 month = Integer.parseInt(m.group(2)) - 1;   // month is 0-based
340                 day = Integer.parseInt(m.group(3));
341             }
342             else {
343                 year = c.get(Calendar.YEAR);
344                 m = reMD.matcher(text);
345                 if (m.matches()) {
346                     month = Integer.parseInt(m.group(1)) - 1;
347                     day = Integer.parseInt(m.group(2));
348                 }
349                 else {
350                     month = c.get(Calendar.MONTH);
351                     m = reD.matcher(text);
352                     if (m.matches()) {
353                         day = Integer.parseInt(m.group(1));
354                     }
355                     else {
356                         day = c.get(Calendar.DAY_OF_MONTH);
357                     }
358                 }
359             }
360
361             c.set(year, month, day);
362
363             this.setDate(c.getTime());
364         }
365         public void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
366                                 @NonNull androidx.lifecycle.Observer<? super Date> observer) {
367             this.date.observe(owner, observer);
368         }
369         public void stopObservingDate(@NonNull androidx.lifecycle.Observer<? super Date> observer) {
370             this.date.removeObserver(observer);
371         }
372         public String getDescription() {
373             ensureType(ItemType.generalData);
374             return description.getValue();
375         }
376         public void setDescription(String description) {
377             ensureType(ItemType.generalData);
378             this.description.setValue(description);
379         }
380         public void observeDescription(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
381                                        @NonNull
382                                                androidx.lifecycle.Observer<? super String> observer) {
383             this.description.observe(owner, observer);
384         }
385         public void stopObservingDescription(
386                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
387             this.description.removeObserver(observer);
388         }
389         public LedgerTransactionAccount getAccount() {
390             ensureType(ItemType.transactionRow);
391             return account;
392         }
393         public void setAccountName(String name) {
394             account.setAccountName(name);
395         }
396         /**
397          * getFormattedDate()
398          *
399          * @return nicely formatted, shortest available date representation
400          */
401         public String getFormattedDate() {
402             if (date == null)
403                 return null;
404             Date time = date.getValue();
405             if (time == null)
406                 return null;
407
408             Calendar c = GregorianCalendar.getInstance();
409             c.setTime(time);
410             Calendar today = GregorianCalendar.getInstance();
411
412             final int myYear = c.get(Calendar.YEAR);
413             final int myMonth = c.get(Calendar.MONTH);
414             final int myDay = c.get(Calendar.DAY_OF_MONTH);
415
416             if (today.get(Calendar.YEAR) != myYear) {
417                 return String.format(Locale.US, "%d/%02d/%02d", myYear, myMonth, myDay);
418             }
419
420             if (today.get(Calendar.MONTH) != myMonth) {
421                 return String.format(Locale.US, "%d/%02d", myMonth, myDay);
422             }
423
424             return String.valueOf(myDay);
425         }
426         public void observeEditableFlag(NewTransactionActivity activity,
427                                         Observer<Boolean> observer) {
428             editable.observe(activity, observer);
429         }
430         public void stopObservingEditableFlag(Observer<Boolean> observer) {
431             editable.removeObserver(observer);
432         }
433     }
434 }