]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionModel.java
whitespace
[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     //==========================================================================================
251
252     class Item extends Object {
253         private ItemType type;
254         private MutableLiveData<Date> date = new MutableLiveData<>();
255         private MutableLiveData<String> description = new MutableLiveData<>();
256         private LedgerTransactionAccount account;
257         private MutableLiveData<String> amountHint = new MutableLiveData<>(null);
258         private NewTransactionModel model;
259         private MutableLiveData<Boolean> editable = new MutableLiveData<>(true);
260         public Item(NewTransactionModel model) {
261             this.model = model;
262             type = ItemType.bottomFiller;
263             editable.setValue(false);
264         }
265         public Item(NewTransactionModel model, Date date, String description) {
266             this.model = model;
267             this.type = ItemType.generalData;
268             this.date.setValue(date);
269             this.description.setValue(description);
270             this.editable.setValue(true);
271         }
272         public Item(NewTransactionModel model, LedgerTransactionAccount account) {
273             this.model = model;
274             this.type = ItemType.transactionRow;
275             this.account = account;
276             this.editable.setValue(true);
277         }
278         public NewTransactionModel getModel() {
279             return model;
280         }
281         public void setEditable(boolean editable) {
282             ensureType(ItemType.generalData, ItemType.transactionRow);
283             this.editable.setValue(editable);
284         }
285         private void ensureType(ItemType type1, ItemType type2) {
286             if ((type != type1) && (type != type2)) {
287                 throw new RuntimeException(
288                         String.format("Actual type (%s) differs from wanted (%s or %s)", type,
289                                 type1, type2));
290             }
291         }
292         public String getAmountHint() {
293             ensureType(ItemType.transactionRow);
294             return amountHint.getValue();
295         }
296         public void setAmountHint(String amountHint) {
297             ensureType(ItemType.transactionRow);
298
299             // avoid unnecessary triggers
300             if (amountHint == null) {
301                 if (this.amountHint.getValue() == null)
302                     return;
303             }
304             else {
305                 if (amountHint.equals(this.amountHint.getValue()))
306                     return;
307             }
308
309             this.amountHint.setValue(amountHint);
310         }
311         public void observeAmountHint(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
312                                       @NonNull
313                                               androidx.lifecycle.Observer<? super String> observer) {
314             this.amountHint.observe(owner, observer);
315         }
316         public void stopObservingAmountHint(
317                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
318             this.amountHint.removeObserver(observer);
319         }
320         public ItemType getType() {
321             return type;
322         }
323         public void ensureType(ItemType wantedType) {
324             if (type != wantedType) {
325                 throw new RuntimeException(
326                         String.format("Actual type (%s) differs from wanted (%s)", type,
327                                 wantedType));
328             }
329         }
330         public Date getDate() {
331             ensureType(ItemType.generalData);
332             return date.getValue();
333         }
334         public void setDate(Date date) {
335             ensureType(ItemType.generalData);
336             this.date.setValue(date);
337         }
338         public void setDate(String text) {
339             int year, month, day;
340             final Calendar c = GregorianCalendar.getInstance();
341             Matcher m = reYMD.matcher(text);
342             if (m.matches()) {
343                 year = Integer.parseInt(m.group(1));
344                 month = Integer.parseInt(m.group(2)) - 1;   // month is 0-based
345                 day = Integer.parseInt(m.group(3));
346             }
347             else {
348                 year = c.get(Calendar.YEAR);
349                 m = reMD.matcher(text);
350                 if (m.matches()) {
351                     month = Integer.parseInt(m.group(1)) - 1;
352                     day = Integer.parseInt(m.group(2));
353                 }
354                 else {
355                     month = c.get(Calendar.MONTH);
356                     m = reD.matcher(text);
357                     if (m.matches()) {
358                         day = Integer.parseInt(m.group(1));
359                     }
360                     else {
361                         day = c.get(Calendar.DAY_OF_MONTH);
362                     }
363                 }
364             }
365
366             c.set(year, month, day);
367
368             this.setDate(c.getTime());
369         }
370         public void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
371                                 @NonNull androidx.lifecycle.Observer<? super Date> observer) {
372             this.date.observe(owner, observer);
373         }
374         public void stopObservingDate(@NonNull androidx.lifecycle.Observer<? super Date> observer) {
375             this.date.removeObserver(observer);
376         }
377         public String getDescription() {
378             ensureType(ItemType.generalData);
379             return description.getValue();
380         }
381         public void setDescription(String description) {
382             ensureType(ItemType.generalData);
383             this.description.setValue(description);
384         }
385         public void observeDescription(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
386                                        @NonNull
387                                                androidx.lifecycle.Observer<? super String> observer) {
388             this.description.observe(owner, observer);
389         }
390         public void stopObservingDescription(
391                 @NonNull androidx.lifecycle.Observer<? super String> observer) {
392             this.description.removeObserver(observer);
393         }
394         public LedgerTransactionAccount getAccount() {
395             ensureType(ItemType.transactionRow);
396             return account;
397         }
398         public void setAccountName(String name) {
399             account.setAccountName(name);
400         }
401         /**
402          * getFormattedDate()
403          *
404          * @return nicely formatted, shortest available date representation
405          */
406         public String getFormattedDate() {
407             if (date == null)
408                 return null;
409             Date time = date.getValue();
410             if (time == null)
411                 return null;
412
413             Calendar c = GregorianCalendar.getInstance();
414             c.setTime(time);
415             Calendar today = GregorianCalendar.getInstance();
416
417             final int myYear = c.get(Calendar.YEAR);
418             final int myMonth = c.get(Calendar.MONTH);
419             final int myDay = c.get(Calendar.DAY_OF_MONTH);
420
421             if (today.get(Calendar.YEAR) != myYear) {
422                 return String.format(Locale.US, "%d/%02d/%02d", myYear, myMonth, myDay);
423             }
424
425             if (today.get(Calendar.MONTH) != myMonth) {
426                 return String.format(Locale.US, "%d/%02d", myMonth, myDay);
427             }
428
429             return String.valueOf(myDay);
430         }
431         public void observeEditableFlag(NewTransactionActivity activity,
432                                         Observer<Boolean> observer) {
433             editable.observe(activity, observer);
434         }
435         public void stopObservingEditableFlag(Observer<Boolean> observer) {
436             editable.removeObserver(observer);
437         }
438     }
439 }