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