]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/new_transaction/NewTransactionModel.java
simplify logic
[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 android.annotation.SuppressLint;
21 import android.text.TextUtils;
22
23 import androidx.annotation.NonNull;
24 import androidx.annotation.Nullable;
25 import androidx.lifecycle.LifecycleOwner;
26 import androidx.lifecycle.LiveData;
27 import androidx.lifecycle.MutableLiveData;
28 import androidx.lifecycle.Observer;
29 import androidx.lifecycle.ViewModel;
30
31 import net.ktnx.mobileledger.BuildConfig;
32 import net.ktnx.mobileledger.db.Currency;
33 import net.ktnx.mobileledger.db.DB;
34 import net.ktnx.mobileledger.db.Profile;
35 import net.ktnx.mobileledger.db.TemplateAccount;
36 import net.ktnx.mobileledger.db.TemplateHeader;
37 import net.ktnx.mobileledger.db.TransactionWithAccounts;
38 import net.ktnx.mobileledger.model.Data;
39 import net.ktnx.mobileledger.model.InertMutableLiveData;
40 import net.ktnx.mobileledger.model.LedgerTransaction;
41 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
42 import net.ktnx.mobileledger.model.MatchedTemplate;
43 import net.ktnx.mobileledger.utils.Globals;
44 import net.ktnx.mobileledger.utils.Logger;
45 import net.ktnx.mobileledger.utils.Misc;
46 import net.ktnx.mobileledger.utils.SimpleDate;
47
48 import org.jetbrains.annotations.NotNull;
49
50 import java.text.ParseException;
51 import java.util.ArrayList;
52 import java.util.Calendar;
53 import java.util.GregorianCalendar;
54 import java.util.HashMap;
55 import java.util.List;
56 import java.util.Locale;
57 import java.util.Objects;
58 import java.util.Set;
59 import java.util.concurrent.atomic.AtomicInteger;
60 import java.util.regex.MatchResult;
61
62 enum ItemType {generalData, transactionRow}
63
64 enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
65
66
67 public class NewTransactionModel extends ViewModel {
68     private static final int MIN_ITEMS = 3;
69     private final MutableLiveData<Boolean> showCurrency = new MutableLiveData<>(false);
70     private final MutableLiveData<Boolean> isSubmittable = new InertMutableLiveData<>(false);
71     private final MutableLiveData<Boolean> showComments = new MutableLiveData<>(true);
72     private final MutableLiveData<List<Item>> items = new MutableLiveData<>();
73     private final MutableLiveData<Boolean> simulateSave = new InertMutableLiveData<>(false);
74     private final AtomicInteger busyCounter = new AtomicInteger(0);
75     private final MutableLiveData<Boolean> busyFlag = new InertMutableLiveData<>(false);
76     private final Observer<Profile> profileObserver = profile -> {
77         showCurrency.postValue(profile.getShowCommodityByDefault());
78         showComments.postValue(profile.getShowCommentsByDefault());
79     };
80     private final MutableLiveData<FocusInfo> focusInfo = new MutableLiveData<>();
81     private boolean observingDataProfile;
82     public NewTransactionModel() {
83         reset();
84     }
85     public LiveData<Boolean> getShowCurrency() {
86         return showCurrency;
87     }
88     public LiveData<List<Item>> getItems() {
89         return items;
90     }
91     private void setItems(@NonNull List<Item> newList) {
92         checkTransactionSubmittable(newList);
93         setItemsWithoutSubmittableChecks(newList);
94     }
95     private void replaceItems(@NonNull List<Item> newList) {
96         renumberItems();
97
98         setItems(newList);
99     }
100     /**
101      * make old items replaceable in-place. makes the new values visually blend in
102      */
103     private void renumberItems() {
104         renumberItems(items.getValue());
105     }
106     private void renumberItems(List<Item> list) {
107         if (list == null) {
108             return;
109         }
110
111         int id = 0;
112         for (Item item : list)
113             item.id = id++;
114     }
115     private void setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
116         final int cnt = list.size();
117         for (int i = 1; i < cnt - 1; i++) {
118             final TransactionAccount item = list.get(i)
119                                                 .toTransactionAccount();
120             if (item.isLast) {
121                 TransactionAccount replacement = new TransactionAccount(item);
122                 replacement.isLast = false;
123                 list.set(i, replacement);
124             }
125         }
126         final TransactionAccount last = list.get(cnt - 1)
127                                             .toTransactionAccount();
128         if (!last.isLast) {
129             TransactionAccount replacement = new TransactionAccount(last);
130             replacement.isLast = true;
131             list.set(cnt - 1, replacement);
132         }
133
134         if (BuildConfig.DEBUG)
135             dumpItemList("Before setValue()", list);
136         items.setValue(list);
137     }
138     private List<Item> copyList() {
139         List<Item> copy = new ArrayList<>();
140         List<Item> oldList = items.getValue();
141
142         if (oldList != null)
143             for (Item item : oldList) {
144                 copy.add(Item.from(item));
145             }
146
147         return copy;
148     }
149     private List<Item> copyListWithoutItem(int position) {
150         List<Item> copy = new ArrayList<>();
151         List<Item> oldList = items.getValue();
152
153         if (oldList != null) {
154             int i = 0;
155             for (Item item : oldList) {
156                 if (i++ == position)
157                     continue;
158                 copy.add(Item.from(item));
159             }
160         }
161
162         return copy;
163     }
164     private List<Item> shallowCopyList() {
165         return new ArrayList<>(items.getValue());
166     }
167     LiveData<Boolean> getShowComments() {
168         return showComments;
169     }
170     void observeDataProfile(LifecycleOwner activity) {
171         if (!observingDataProfile)
172             Data.observeProfile(activity, profileObserver);
173         observingDataProfile = true;
174     }
175     boolean getSimulateSaveFlag() {
176         Boolean value = simulateSave.getValue();
177         if (value == null)
178             return false;
179         return value;
180     }
181     LiveData<Boolean> getSimulateSave() {
182         return simulateSave;
183     }
184     void toggleSimulateSave() {
185         simulateSave.setValue(!getSimulateSaveFlag());
186     }
187     LiveData<Boolean> isSubmittable() {
188         return this.isSubmittable;
189     }
190     void reset() {
191         Logger.debug("new-trans", "Resetting model");
192         List<Item> list = new ArrayList<>();
193         Item.resetIdDispenser();
194         list.add(new TransactionHead(""));
195         final String defaultCurrency = Objects.requireNonNull(Data.getProfile())
196                                               .getDefaultCommodity();
197         list.add(new TransactionAccount("", defaultCurrency));
198         list.add(new TransactionAccount("", defaultCurrency));
199         noteFocusChanged(0, FocusedElement.Description);
200         renumberItems();
201         isSubmittable.setValue(false);
202         setItemsWithoutSubmittableChecks(list);
203     }
204     boolean accountsInInitialState() {
205         final List<Item> list = items.getValue();
206
207         if (list == null)
208             return true;
209
210         for (Item item : list) {
211             if (!(item instanceof TransactionAccount))
212                 continue;
213
214             TransactionAccount accRow = (TransactionAccount) item;
215             if (!accRow.isEmpty())
216                 return false;
217         }
218
219         return true;
220     }
221     void applyTemplate(MatchedTemplate matchedTemplate, String text) {
222         SimpleDate transactionDate = null;
223         final MatchResult matchResult = matchedTemplate.matchResult;
224         final TemplateHeader templateHead = matchedTemplate.templateHead;
225         {
226             int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
227                     templateHead.getDateDay());
228             int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
229                     templateHead.getDateMonth());
230             int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
231                     templateHead.getDateYear());
232
233             if (year > 0 || month > 0 || day > 0) {
234                 SimpleDate today = SimpleDate.today();
235                 if (year <= 0)
236                     year = today.year;
237                 if (month <= 0)
238                     month = today.month;
239                 if (day <= 0)
240                     day = today.day;
241
242                 transactionDate = new SimpleDate(year, month, day);
243
244                 Logger.debug("pattern", "setting transaction date to " + transactionDate);
245             }
246         }
247
248         List<Item> present = copyList();
249
250         TransactionHead head = new TransactionHead(present.get(0)
251                                                           .toTransactionHead());
252         if (transactionDate != null)
253             head.setDate(transactionDate);
254
255         final String transactionDescription = extractStringFromMatches(matchResult,
256                 templateHead.getTransactionDescriptionMatchGroup(),
257                 templateHead.getTransactionDescription());
258         if (Misc.emptyIsNull(transactionDescription) != null)
259             head.setDescription(transactionDescription);
260
261         final String transactionComment = extractStringFromMatches(matchResult,
262                 templateHead.getTransactionCommentMatchGroup(),
263                 templateHead.getTransactionComment());
264         if (Misc.emptyIsNull(transactionComment) != null)
265             head.setComment(transactionComment);
266
267         List<Item> newItems = new ArrayList<>();
268
269         newItems.add(head);
270
271         for (int i = 1; i < present.size(); i++) {
272             final TransactionAccount row = present.get(i)
273                                                   .toTransactionAccount();
274             if (!row.isEmpty())
275                 newItems.add(new TransactionAccount(row));
276         }
277
278         DB.get()
279           .getTemplateDAO()
280           .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
281               int rowIndex = 0;
282               final boolean accountsInInitialState = accountsInInitialState();
283               for (TemplateAccount acc : entry.accounts) {
284                   rowIndex++;
285
286                   String accountName =
287                           extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
288                                   acc.getAccountName());
289                   String accountComment =
290                           extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
291                                   acc.getAccountComment());
292                   Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
293                           acc.getAmount());
294                   if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
295                       amount = -amount;
296
297                   TransactionAccount accRow = new TransactionAccount(accountName);
298                   accRow.setComment(accountComment);
299                   if (amount != null)
300                       accRow.setAmount(amount);
301                   accRow.setCurrency(
302                           extractCurrencyFromMatches(matchResult, acc.getCurrencyMatchGroup(),
303                                   acc.getCurrencyObject()));
304
305                   newItems.add(accRow);
306               }
307
308               renumberItems(newItems);
309               Misc.onMainThread(() -> replaceItems(newItems));
310           });
311     }
312     private String extractCurrencyFromMatches(MatchResult m, Integer group, Currency literal) {
313         return extractStringFromMatches(m, group, (literal == null) ? "" : literal.getName());
314     }
315     private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
316         if (literal != null)
317             return literal;
318
319         if (group != null) {
320             int grp = group;
321             if (grp > 0 && grp <= m.groupCount())
322                 try {
323                     return Integer.parseInt(m.group(grp));
324                 }
325                 catch (NumberFormatException e) {
326                     Logger.debug("new-trans", "Error extracting matched number", e);
327                 }
328         }
329
330         return 0;
331     }
332     private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
333         if (literal != null)
334             return literal;
335
336         if (group != null) {
337             int grp = group;
338             if (grp > 0 && grp <= m.groupCount())
339                 return m.group(grp);
340         }
341
342         return null;
343     }
344     private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
345         if (literal != null)
346             return literal;
347
348         if (group != null) {
349             int grp = group;
350             if (grp > 0 && grp <= m.groupCount())
351                 try {
352                     return Float.valueOf(m.group(grp));
353                 }
354                 catch (NumberFormatException e) {
355                     Logger.debug("new-trans", "Error extracting matched number", e);
356                 }
357         }
358
359         return null;
360     }
361     void removeItem(int pos) {
362         Logger.debug("new-trans", String.format(Locale.US, "Removing item at position %d", pos));
363         List<Item> newList = copyListWithoutItem(pos);
364         final FocusInfo fi = focusInfo.getValue();
365         if ((fi != null) && (pos < fi.position))
366             noteFocusChanged(fi.position - 1, fi.element);
367         setItems(newList);
368     }
369     void noteFocusChanged(int position, FocusedElement element) {
370         FocusInfo present = focusInfo.getValue();
371         if (present == null || present.position != position || present.element != element)
372             focusInfo.setValue(new FocusInfo(position, element));
373     }
374     public LiveData<FocusInfo> getFocusInfo() {
375         return focusInfo;
376     }
377     void moveItem(int fromIndex, int toIndex) {
378         List<Item> newList = shallowCopyList();
379         Item item = newList.remove(fromIndex);
380         newList.add(toIndex, item);
381
382         FocusInfo fi = focusInfo.getValue();
383         if (fi != null && fi.position == fromIndex)
384             noteFocusChanged(toIndex, fi.element);
385
386         items.setValue(newList); // same count, same submittable state
387     }
388     void moveItemLast(List<Item> list, int index) {
389         /*   0
390              1   <-- index
391              2
392              3   <-- desired position
393                  (no bottom filler)
394          */
395         int itemCount = list.size();
396
397         if (index < itemCount - 1)
398             list.add(list.remove(index));
399     }
400     void toggleCurrencyVisible() {
401         final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
402
403         // remove currency from all items, or reset currency to the default
404         // no need to clone the list, because the removal of the currency won't lead to
405         // visual changes -- the currency fields will be hidden or reset to default anyway
406         // still, there may be changes in the submittable state
407         final List<Item> list = Objects.requireNonNull(this.items.getValue());
408         for (int i = 1; i < list.size(); i++) {
409             ((TransactionAccount) list.get(i)).setCurrency(newValue ? Data.getProfile()
410                                                                           .getDefaultCommodity()
411                                                                     : null);
412         }
413         checkTransactionSubmittable(null);
414         showCurrency.setValue(newValue);
415     }
416     void stopObservingBusyFlag(Observer<Boolean> observer) {
417         busyFlag.removeObserver(observer);
418     }
419     void incrementBusyCounter() {
420         int newValue = busyCounter.incrementAndGet();
421         if (newValue == 1)
422             busyFlag.postValue(true);
423     }
424     void decrementBusyCounter() {
425         int newValue = busyCounter.decrementAndGet();
426         if (newValue == 0)
427             busyFlag.postValue(false);
428     }
429     public LiveData<Boolean> getBusyFlag() {
430         return busyFlag;
431     }
432     public void toggleShowComments() {
433         showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
434     }
435     public LedgerTransaction constructLedgerTransaction() {
436         List<Item> list = Objects.requireNonNull(items.getValue());
437         TransactionHead head = list.get(0)
438                                    .toTransactionHead();
439         LedgerTransaction tr = head.asLedgerTransaction();
440
441         tr.setComment(head.getComment());
442         LedgerTransactionAccount emptyAmountAccount = null;
443         float emptyAmountAccountBalance = 0;
444         for (int i = 1; i < list.size(); i++) {
445             TransactionAccount item = list.get(i)
446                                           .toTransactionAccount();
447             LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
448                                                                             .trim(),
449                     item.getCurrency());
450             if (acc.getAccountName()
451                    .isEmpty())
452                 continue;
453
454             acc.setComment(item.getComment());
455
456             if (item.isAmountSet()) {
457                 acc.setAmount(item.getAmount());
458                 emptyAmountAccountBalance += item.getAmount();
459             }
460             else {
461                 emptyAmountAccount = acc;
462             }
463
464             tr.addAccount(acc);
465         }
466
467         if (emptyAmountAccount != null)
468             emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
469
470         return tr;
471     }
472     void loadTransactionIntoModel(@NonNull TransactionWithAccounts tr) {
473         List<Item> newList = new ArrayList<>();
474         Item.resetIdDispenser();
475
476         Item currentHead = items.getValue()
477                                 .get(0);
478         TransactionHead head = new TransactionHead(tr.transaction.getDescription());
479         head.setComment(tr.transaction.getComment());
480         if (currentHead instanceof TransactionHead)
481             head.setDate(((TransactionHead) currentHead).date);
482
483         newList.add(head);
484
485         List<LedgerTransactionAccount> accounts = new ArrayList<>();
486         for (net.ktnx.mobileledger.db.TransactionAccount acc : tr.accounts) {
487             accounts.add(new LedgerTransactionAccount(acc));
488         }
489
490         TransactionAccount firstNegative = null;
491         TransactionAccount firstPositive = null;
492         int singleNegativeIndex = -1;
493         int singlePositiveIndex = -1;
494         int negativeCount = 0;
495         for (int i = 0; i < accounts.size(); i++) {
496             LedgerTransactionAccount acc = accounts.get(i);
497             TransactionAccount item =
498                     new TransactionAccount(acc.getAccountName(), acc.getCurrency());
499             newList.add(item);
500
501             item.setAccountName(acc.getAccountName());
502             item.setComment(acc.getComment());
503             if (acc.isAmountSet()) {
504                 item.setAmount(acc.getAmount());
505                 if (acc.getAmount() < 0) {
506                     if (firstNegative == null) {
507                         firstNegative = item;
508                         singleNegativeIndex = i + 1;
509                     }
510                     else
511                         singleNegativeIndex = -1;
512                 }
513                 else {
514                     if (firstPositive == null) {
515                         firstPositive = item;
516                         singlePositiveIndex = i + 1;
517                     }
518                     else
519                         singlePositiveIndex = -1;
520                 }
521             }
522             else
523                 item.resetAmount();
524         }
525         if (BuildConfig.DEBUG)
526             dumpItemList("Loaded previous transaction", newList);
527
528         if (singleNegativeIndex != -1) {
529             firstNegative.resetAmount();
530             moveItemLast(newList, singleNegativeIndex);
531         }
532         else if (singlePositiveIndex != -1) {
533             firstPositive.resetAmount();
534             moveItemLast(newList, singlePositiveIndex);
535         }
536
537         Misc.onMainThread(() -> {
538             setItems(newList);
539             noteFocusChanged(1, FocusedElement.Amount);
540         });
541     }
542     /**
543      * A transaction is submittable if:
544      * 0) has description
545      * 1) has at least two account names
546      * 2) each row with amount has account name
547      * 3) for each commodity:
548      * 3a) amounts must balance to 0, or
549      * 3b) there must be exactly one empty amount (with account)
550      * 4) empty accounts with empty amounts are ignored
551      * Side effects:
552      * 5) a row with an empty account name or empty amount is guaranteed to exist for each
553      * commodity
554      * 6) at least two rows need to be present in the ledger
555      *
556      * @param list - the item list to check. Can be the displayed list or a list that will be
557      *             displayed soon
558      */
559     @SuppressLint("DefaultLocale")
560     void checkTransactionSubmittable(@Nullable List<Item> list) {
561         boolean workingWithLiveList = false;
562         if (list == null) {
563             list = copyList();
564             workingWithLiveList = true;
565         }
566
567         if (BuildConfig.DEBUG)
568             dumpItemList(String.format("Before submittable checks (%s)",
569                     workingWithLiveList ? "LIVE LIST" : "custom list"), list);
570
571         int accounts = 0;
572         final BalanceForCurrency balance = new BalanceForCurrency();
573         final String descriptionText = list.get(0)
574                                            .toTransactionHead()
575                                            .getDescription();
576         boolean submittable = true;
577         boolean listChanged = false;
578         final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
579         final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
580         final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
581         final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
582         final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
583         final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
584         final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
585         final List<Item> emptyRows = new ArrayList<>();
586
587         try {
588             if ((descriptionText == null) || descriptionText.trim()
589                                                             .isEmpty())
590             {
591                 Logger.debug("submittable", "Transaction not submittable: missing description");
592                 submittable = false;
593             }
594
595             for (int i = 1; i < list.size(); i++) {
596                 TransactionAccount item = list.get(i)
597                                               .toTransactionAccount();
598
599                 String accName = item.getAccountName()
600                                      .trim();
601                 String currName = item.getCurrency();
602
603                 itemsForCurrency.add(currName, item);
604
605                 if (accName.isEmpty()) {
606                     itemsWithEmptyAccountForCurrency.add(currName, item);
607
608                     if (item.isAmountSet()) {
609                         // 2) each amount has account name
610                         Logger.debug("submittable", String.format(
611                                 "Transaction not submittable: row %d has no account name, but" +
612                                 " has" + " amount %1.2f", i + 1, item.getAmount()));
613                         submittable = false;
614                     }
615                     else {
616                         emptyRowsForCurrency.add(currName, item);
617                     }
618                 }
619                 else {
620                     accounts++;
621                     itemsWithAccountForCurrency.add(currName, item);
622                 }
623
624                 if (!item.isAmountValid()) {
625                     Logger.debug("submittable",
626                             String.format("Not submittable: row %d has an invalid amount", i + 1));
627                     submittable = false;
628                 }
629                 else if (item.isAmountSet()) {
630                     itemsWithAmountForCurrency.add(currName, item);
631                     balance.add(currName, item.getAmount());
632                 }
633                 else {
634                     itemsWithEmptyAmountForCurrency.add(currName, item);
635
636                     if (!accName.isEmpty())
637                         itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
638                 }
639             }
640
641             // 1) has at least two account names
642             if (accounts < 2) {
643                 if (accounts == 0)
644                     Logger.debug("submittable", "Transaction not submittable: no account names");
645                 else if (accounts == 1)
646                     Logger.debug("submittable",
647                             "Transaction not submittable: only one account name");
648                 else
649                     Logger.debug("submittable",
650                             String.format("Transaction not submittable: only %d account names",
651                                     accounts));
652                 submittable = false;
653             }
654
655             // 3) for each commodity:
656             // 3a) amount must balance to 0, or
657             // 3b) there must be exactly one empty amount (with account)
658             for (String balCurrency : itemsForCurrency.currencies()) {
659                 float currencyBalance = balance.get(balCurrency);
660                 if (Misc.isZero(currencyBalance)) {
661                     // remove hints from all amount inputs in that currency
662                     for (int i = 1; i < list.size(); i++) {
663                         TransactionAccount acc = list.get(i)
664                                                      .toTransactionAccount();
665                         if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
666                             if (BuildConfig.DEBUG)
667                                 Logger.debug("submittable",
668                                         String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
669                                                 i, Misc.nullIsEmpty(acc.getAccountName()),
670                                                 balCurrency));
671                             // skip if the amount is set, in which case the hint is not
672                             // important/visible
673                             if (!acc.isAmountSet() && acc.amountHintIsSet &&
674                                 !TextUtils.isEmpty(acc.getAmountHint()))
675                             {
676                                 acc.setAmountHint(null);
677                                 listChanged = true;
678                             }
679                         }
680                     }
681                 }
682                 else {
683                     List<Item> tmpList =
684                             itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
685                     int balanceReceiversCount = tmpList.size();
686                     if (balanceReceiversCount != 1) {
687                         if (BuildConfig.DEBUG) {
688                             if (balanceReceiversCount == 0)
689                                 Logger.debug("submittable", String.format(
690                                         "Transaction not submittable [%s]: non-zero balance " +
691                                         "with no empty amounts with accounts", balCurrency));
692                             else
693                                 Logger.debug("submittable", String.format(
694                                         "Transaction not submittable [%s]: non-zero balance " +
695                                         "with multiple empty amounts with accounts", balCurrency));
696                         }
697                         submittable = false;
698                     }
699
700                     List<Item> emptyAmountList =
701                             itemsWithEmptyAmountForCurrency.getList(balCurrency);
702
703                     // suggest off-balance amount to a row and remove hints on other rows
704                     Item receiver = null;
705                     if (!tmpList.isEmpty())
706                         receiver = tmpList.get(0);
707                     else if (!emptyAmountList.isEmpty())
708                         receiver = emptyAmountList.get(0);
709
710                     for (int i = 0; i < list.size(); i++) {
711                         Item item = list.get(i);
712                         if (!(item instanceof TransactionAccount))
713                             continue;
714
715                         TransactionAccount acc = item.toTransactionAccount();
716                         if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
717                             continue;
718
719                         if (item == receiver) {
720                             final String hint = String.format("%1.2f", -currencyBalance);
721                             if (!acc.isAmountHintSet() ||
722                                 !Misc.equalStrings(acc.getAmountHint(), hint))
723                             {
724                                 Logger.debug("submittable",
725                                         String.format("Setting amount hint of {%s} to %s [%s]",
726                                                 acc.toString(), hint, balCurrency));
727                                 acc.setAmountHint(hint);
728                                 listChanged = true;
729                             }
730                         }
731                         else {
732                             if (BuildConfig.DEBUG)
733                                 Logger.debug("submittable",
734                                         String.format("Resetting hint of '%s' [%s]",
735                                                 Misc.nullIsEmpty(acc.getAccountName()),
736                                                 balCurrency));
737                             if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
738                                 acc.setAmountHint(null);
739                                 listChanged = true;
740                             }
741                         }
742                     }
743                 }
744             }
745
746             // 5) a row with an empty account name or empty amount is guaranteed to exist for
747             // each commodity
748             for (String balCurrency : balance.currencies()) {
749                 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
750                 int currRows = itemsForCurrency.size(balCurrency);
751                 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
752                 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
753                 if ((currEmptyRows == 0) &&
754                     ((currRows == currAccounts) || (currRows == currAmounts)))
755                 {
756                     // perhaps there already is an unused empty row for another currency that
757                     // is not used?
758 //                        boolean foundIt = false;
759 //                        for (Item item : emptyRows) {
760 //                            Currency itemCurrency = item.getCurrency();
761 //                            String itemCurrencyName =
762 //                                    (itemCurrency == null) ? "" : itemCurrency.getName();
763 //                            if (Misc.isZero(balance.get(itemCurrencyName))) {
764 //                                item.setCurrency(Currency.loadByName(balCurrency));
765 //                                item.setAmountHint(
766 //                                        String.format("%1.2f", -balance.get(balCurrency)));
767 //                                foundIt = true;
768 //                                break;
769 //                            }
770 //                        }
771 //
772 //                        if (!foundIt)
773                     final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
774                     final float bal = balance.get(balCurrency);
775                     if (!Misc.isZero(bal) && currAmounts == currRows)
776                         newAcc.setAmountHint(String.format("%4.2f", -bal));
777                     Logger.debug("submittable",
778                             String.format("Adding new item with %s for currency %s",
779                                     newAcc.getAmountHint(), balCurrency));
780                     list.add(newAcc);
781                     listChanged = true;
782                 }
783             }
784
785             // drop extra empty rows, not needed
786             for (String currName : emptyRowsForCurrency.currencies()) {
787                 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
788                 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
789                     // the list is a copy, so the empty item is no longer present
790                     Item itemToRemove = emptyItems.remove(1);
791                     removeItemById(list, itemToRemove.id);
792                     listChanged = true;
793                 }
794
795                 // unused currency, remove last item (which is also an empty one)
796                 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
797                     List<Item> currItems = itemsForCurrency.getList(currName);
798
799                     if (currItems.size() == 1) {
800                         // the list is a copy, so the empty item is no longer present
801                         removeItemById(list, emptyItems.get(0).id);
802                         listChanged = true;
803                     }
804                 }
805             }
806
807             // 6) at least two rows need to be present in the ledger
808             //    (the list also contains header and trailer)
809             while (list.size() < MIN_ITEMS) {
810                 list.add(new TransactionAccount(""));
811                 listChanged = true;
812             }
813
814             Logger.debug("submittable", submittable ? "YES" : "NO");
815             isSubmittable.setValue(submittable);
816
817             if (BuildConfig.DEBUG)
818                 dumpItemList("After submittable checks", list);
819         }
820         catch (NumberFormatException e) {
821             Logger.debug("submittable", "NO (because of NumberFormatException)");
822             isSubmittable.setValue(false);
823         }
824         catch (Exception e) {
825             e.printStackTrace();
826             Logger.debug("submittable", "NO (because of an Exception)");
827             isSubmittable.setValue(false);
828         }
829
830         if (listChanged && workingWithLiveList) {
831             setItemsWithoutSubmittableChecks(list);
832         }
833     }
834     private void removeItemById(@NotNull List<Item> list, int id) {
835         if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
836             list.removeIf(item -> item.id == id);
837         }
838         else {
839             for (Item item : list) {
840                 if (item.id == id) {
841                     list.remove(item);
842                     break;
843                 }
844             }
845         }
846     }
847     @SuppressLint("DefaultLocale")
848     private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
849         Logger.debug("submittable", "== Dump of all items " + msg);
850         for (int i = 1; i < list.size(); i++) {
851             TransactionAccount item = list.get(i)
852                                           .toTransactionAccount();
853             Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
854         }
855     }
856     public void setItemCurrency(int position, String newCurrency) {
857         TransactionAccount item = Objects.requireNonNull(items.getValue())
858                                          .get(position)
859                                          .toTransactionAccount();
860         final String oldCurrency = item.getCurrency();
861
862         if (Misc.equalStrings(oldCurrency, newCurrency))
863             return;
864
865         List<Item> newList = copyList();
866         newList.get(position)
867                .toTransactionAccount()
868                .setCurrency(newCurrency);
869
870         setItems(newList);
871     }
872     public boolean accountListIsEmpty() {
873         List<Item> items = Objects.requireNonNull(this.items.getValue());
874
875         for (Item item : items) {
876             if (!(item instanceof TransactionAccount))
877                 continue;
878
879             if (!((TransactionAccount) item).isEmpty())
880                 return false;
881         }
882
883         return true;
884     }
885
886     public static class FocusInfo {
887         int position;
888         FocusedElement element;
889         public FocusInfo(int position, FocusedElement element) {
890             this.position = position;
891             this.element = element;
892         }
893     }
894
895     static abstract class Item {
896         private static int idDispenser = 0;
897         protected int id;
898         private Item() {
899             if (this instanceof TransactionHead)
900                 id = 0;
901             else
902                 synchronized (Item.class) {
903                     id = ++idDispenser;
904                 }
905         }
906         public Item(int id) {
907             this.id = id;
908         }
909         public static Item from(Item origin) {
910             if (origin instanceof TransactionHead)
911                 return new TransactionHead((TransactionHead) origin);
912             if (origin instanceof TransactionAccount)
913                 return new TransactionAccount((TransactionAccount) origin);
914             throw new RuntimeException("Don't know how to handle " + origin);
915         }
916         private static void resetIdDispenser() {
917             idDispenser = 0;
918         }
919         public int getId() {
920             return id;
921         }
922         public abstract ItemType getType();
923         public TransactionHead toTransactionHead() {
924             if (this instanceof TransactionHead)
925                 return (TransactionHead) this;
926
927             throw new IllegalStateException("Wrong item type " + this);
928         }
929         public TransactionAccount toTransactionAccount() {
930             if (this instanceof TransactionAccount)
931                 return (TransactionAccount) this;
932
933             throw new IllegalStateException("Wrong item type " + this);
934         }
935         public boolean equalContents(@Nullable Object item) {
936             if (item == null)
937                 return false;
938
939             if (!getClass().equals(item.getClass()))
940                 return false;
941
942             // shortcut - comparing same instance
943             if (item == this)
944                 return true;
945
946             if (this instanceof TransactionHead)
947                 return ((TransactionHead) item).equalContents((TransactionHead) this);
948             if (this instanceof TransactionAccount)
949                 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
950
951             throw new RuntimeException("Don't know how to handle " + this);
952         }
953     }
954
955
956 //==========================================================================================
957
958     public static class TransactionHead extends Item {
959         private SimpleDate date;
960         private String description;
961         private String comment;
962         TransactionHead(String description) {
963             super();
964             this.description = description;
965         }
966         public TransactionHead(TransactionHead origin) {
967             super(origin.id);
968             date = origin.date;
969             description = origin.description;
970             comment = origin.comment;
971         }
972         public SimpleDate getDate() {
973             return date;
974         }
975         public void setDate(SimpleDate date) {
976             this.date = date;
977         }
978         public void setDate(String text) throws ParseException {
979             if (Misc.emptyIsNull(text) == null) {
980                 date = null;
981                 return;
982             }
983
984             date = Globals.parseLedgerDate(text);
985         }
986         /**
987          * getFormattedDate()
988          *
989          * @return nicely formatted, shortest available date representation
990          */
991         String getFormattedDate() {
992             if (date == null)
993                 return null;
994
995             Calendar today = GregorianCalendar.getInstance();
996
997             if (today.get(Calendar.YEAR) != date.year) {
998                 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
999             }
1000
1001             if (today.get(Calendar.MONTH) + 1 != date.month) {
1002                 return String.format(Locale.US, "%d/%02d", date.month, date.day);
1003             }
1004
1005             return String.valueOf(date.day);
1006         }
1007         @NonNull
1008         @Override
1009         public String toString() {
1010             @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
1011                     String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1012
1013             if (TextUtils.isEmpty(description))
1014                 b.append(" «no description»");
1015             else
1016                 b.append(String.format(" '%s'", description));
1017
1018             if (date != null)
1019                 b.append(String.format("@%s", date.toString()));
1020
1021             if (!TextUtils.isEmpty(comment))
1022                 b.append(String.format(" /%s/", comment));
1023
1024             return b.toString();
1025         }
1026         public String getDescription() {
1027             return description;
1028         }
1029         public void setDescription(String description) {
1030             this.description = description;
1031         }
1032         public String getComment() {
1033             return comment;
1034         }
1035         public void setComment(String comment) {
1036             this.comment = comment;
1037         }
1038         @Override
1039         public ItemType getType() {
1040             return ItemType.generalData;
1041         }
1042         public LedgerTransaction asLedgerTransaction() {
1043             return new LedgerTransaction(0, (date == null) ? SimpleDate.today() : date, description,
1044                     Data.getProfile());
1045         }
1046         public boolean equalContents(TransactionHead other) {
1047             if (other == null)
1048                 return false;
1049
1050             return Objects.equals(date, other.date) &&
1051                    Misc.equalStrings(description, other.description) &&
1052                    Misc.equalStrings(comment, other.comment);
1053         }
1054     }
1055
1056     public static class TransactionAccount extends Item {
1057         private String accountName;
1058         private String amountHint;
1059         private String comment;
1060         private String currency;
1061         private float amount;
1062         private boolean amountSet;
1063         private boolean amountValid = true;
1064         private FocusedElement focusedElement = FocusedElement.Account;
1065         private boolean amountHintIsSet = false;
1066         private boolean isLast = false;
1067         private int accountNameCursorPosition;
1068         public TransactionAccount(TransactionAccount origin) {
1069             super(origin.id);
1070             accountName = origin.accountName;
1071             amount = origin.amount;
1072             amountSet = origin.amountSet;
1073             amountHint = origin.amountHint;
1074             amountHintIsSet = origin.amountHintIsSet;
1075             comment = origin.comment;
1076             currency = origin.currency;
1077             amountValid = origin.amountValid;
1078             focusedElement = origin.focusedElement;
1079             isLast = origin.isLast;
1080             accountNameCursorPosition = origin.accountNameCursorPosition;
1081         }
1082         public TransactionAccount(LedgerTransactionAccount account) {
1083             super();
1084             currency = account.getCurrency();
1085             amount = account.getAmount();
1086         }
1087         public TransactionAccount(String accountName) {
1088             super();
1089             this.accountName = accountName;
1090         }
1091         public TransactionAccount(String accountName, String currency) {
1092             super();
1093             this.accountName = accountName;
1094             this.currency = currency;
1095         }
1096         public boolean isLast() {
1097             return isLast;
1098         }
1099         public boolean isAmountSet() {
1100             return amountSet;
1101         }
1102         public String getAccountName() {
1103             return accountName;
1104         }
1105         public void setAccountName(String accountName) {
1106             this.accountName = accountName;
1107         }
1108         public float getAmount() {
1109             if (!amountSet)
1110                 throw new IllegalStateException("Amount is not set");
1111             return amount;
1112         }
1113         public void setAmount(float amount) {
1114             this.amount = amount;
1115             amountSet = true;
1116         }
1117         public void resetAmount() {
1118             amountSet = false;
1119         }
1120         @Override
1121         public ItemType getType() {
1122             return ItemType.transactionRow;
1123         }
1124         public String getAmountHint() {
1125             return amountHint;
1126         }
1127         public void setAmountHint(String amountHint) {
1128             this.amountHint = amountHint;
1129             amountHintIsSet = !TextUtils.isEmpty(amountHint);
1130         }
1131         public String getComment() {
1132             return comment;
1133         }
1134         public void setComment(String comment) {
1135             this.comment = comment;
1136         }
1137         public String getCurrency() {
1138             return currency;
1139         }
1140         public void setCurrency(String currency) {
1141             this.currency = currency;
1142         }
1143         public boolean isAmountValid() {
1144             return amountValid;
1145         }
1146         public void setAmountValid(boolean amountValid) {
1147             this.amountValid = amountValid;
1148         }
1149         public FocusedElement getFocusedElement() {
1150             return focusedElement;
1151         }
1152         public void setFocusedElement(FocusedElement focusedElement) {
1153             this.focusedElement = focusedElement;
1154         }
1155         public boolean isAmountHintSet() {
1156             return amountHintIsSet;
1157         }
1158         public void setAmountHintIsSet(boolean amountHintIsSet) {
1159             this.amountHintIsSet = amountHintIsSet;
1160         }
1161         public boolean isEmpty() {
1162             return !amountSet && Misc.emptyIsNull(accountName) == null &&
1163                    Misc.emptyIsNull(comment) == null;
1164         }
1165         @SuppressLint("DefaultLocale")
1166         @Override
1167         public String toString() {
1168             StringBuilder b = new StringBuilder();
1169             b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1170             if (!TextUtils.isEmpty(accountName))
1171                 b.append(String.format(" acc'%s'", accountName));
1172
1173             if (amountSet)
1174                 b.append(String.format(" %4.2f", amount));
1175             else if (amountHintIsSet)
1176                 b.append(String.format(" (%s)", amountHint));
1177
1178             if (!TextUtils.isEmpty(currency))
1179                 b.append(" ")
1180                  .append(currency);
1181
1182             if (!TextUtils.isEmpty(comment))
1183                 b.append(String.format(" /%s/", comment));
1184
1185             if (isLast)
1186                 b.append(" last");
1187
1188             return b.toString();
1189         }
1190         public boolean equalContents(TransactionAccount other) {
1191             if (other == null)
1192                 return false;
1193
1194             boolean equal = Misc.equalStrings(accountName, other.accountName);
1195             equal = equal && Misc.equalStrings(comment, other.comment) &&
1196                     (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1197
1198             // compare amount hint only if there is no amount
1199             if (!amountSet)
1200                 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1201                                                     Misc.equalStrings(amountHint, other.amountHint)
1202                                                   : !other.amountHintIsSet);
1203             equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1204
1205             Logger.debug("new-trans",
1206                     String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1207                             equal));
1208             return equal;
1209         }
1210         public int getAccountNameCursorPosition() {
1211             return accountNameCursorPosition;
1212         }
1213         public void setAccountNameCursorPosition(int position) {
1214             this.accountNameCursorPosition = position;
1215         }
1216     }
1217
1218     private static class BalanceForCurrency {
1219         private final HashMap<String, Float> hashMap = new HashMap<>();
1220         float get(String currencyName) {
1221             Float f = hashMap.get(currencyName);
1222             if (f == null) {
1223                 f = 0f;
1224                 hashMap.put(currencyName, f);
1225             }
1226             return f;
1227         }
1228         void add(String currencyName, float amount) {
1229             hashMap.put(currencyName, get(currencyName) + amount);
1230         }
1231         Set<String> currencies() {
1232             return hashMap.keySet();
1233         }
1234         boolean containsCurrency(String currencyName) {
1235             return hashMap.containsKey(currencyName);
1236         }
1237     }
1238
1239     private static class ItemsForCurrency {
1240         private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1241         @NonNull
1242         List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1243             List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1244             if (list == null) {
1245                 list = new ArrayList<>();
1246                 hashMap.put(currencyName, list);
1247             }
1248             return list;
1249         }
1250         void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1251             getList(currencyName).add(item);
1252         }
1253         int size(@Nullable String currencyName) {
1254             return this.getList(currencyName)
1255                        .size();
1256         }
1257         Set<String> currencies() {
1258             return hashMap.keySet();
1259         }
1260     }
1261 }