]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/new_transaction/NewTransactionModel.java
b3e9eeb3c8b6b26d5a7be7b0aaa911fdb9cb9f92
[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     @NonNull
313     private String extractCurrencyFromMatches(MatchResult m, Integer group, Currency literal) {
314         return Misc.nullIsEmpty(
315                 extractStringFromMatches(m, group, (literal == null) ? "" : literal.getName()));
316     }
317     private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
318         if (literal != null)
319             return literal;
320
321         if (group != null) {
322             int grp = group;
323             if (grp > 0 && grp <= m.groupCount())
324                 try {
325                     return Integer.parseInt(m.group(grp));
326                 }
327                 catch (NumberFormatException e) {
328                     Logger.debug("new-trans", "Error extracting matched number", e);
329                 }
330         }
331
332         return 0;
333     }
334     @Nullable
335     private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
336         if (literal != null)
337             return literal;
338
339         if (group != null) {
340             int grp = group;
341             if (grp > 0 && grp <= m.groupCount())
342                 return m.group(grp);
343         }
344
345         return null;
346     }
347     private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
348         if (literal != null)
349             return literal;
350
351         if (group != null) {
352             int grp = group;
353             if (grp > 0 && grp <= m.groupCount())
354                 try {
355                     return Float.valueOf(m.group(grp));
356                 }
357                 catch (NumberFormatException e) {
358                     Logger.debug("new-trans", "Error extracting matched number", e);
359                 }
360         }
361
362         return null;
363     }
364     void removeItem(int pos) {
365         Logger.debug("new-trans", String.format(Locale.US, "Removing item at position %d", pos));
366         List<Item> newList = copyListWithoutItem(pos);
367         final FocusInfo fi = focusInfo.getValue();
368         if ((fi != null) && (pos < fi.position))
369             noteFocusChanged(fi.position - 1, fi.element);
370         setItems(newList);
371     }
372     void noteFocusChanged(int position, FocusedElement element) {
373         FocusInfo present = focusInfo.getValue();
374         if (present == null || present.position != position || present.element != element)
375             focusInfo.setValue(new FocusInfo(position, element));
376     }
377     public LiveData<FocusInfo> getFocusInfo() {
378         return focusInfo;
379     }
380     void moveItem(int fromIndex, int toIndex) {
381         List<Item> newList = shallowCopyList();
382         Item item = newList.remove(fromIndex);
383         newList.add(toIndex, item);
384
385         FocusInfo fi = focusInfo.getValue();
386         if (fi != null && fi.position == fromIndex)
387             noteFocusChanged(toIndex, fi.element);
388
389         items.setValue(newList); // same count, same submittable state
390     }
391     void moveItemLast(List<Item> list, int index) {
392         /*   0
393              1   <-- index
394              2
395              3   <-- desired position
396                  (no bottom filler)
397          */
398         int itemCount = list.size();
399
400         if (index < itemCount - 1)
401             list.add(list.remove(index));
402     }
403     void toggleCurrencyVisible() {
404         final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
405
406         // remove currency from all items, or reset currency to the default
407         // no need to clone the list, because the removal of the currency won't lead to
408         // visual changes -- the currency fields will be hidden or reset to default anyway
409         // still, there may be changes in the submittable state
410         final List<Item> list = Objects.requireNonNull(this.items.getValue());
411         final Profile profile = Objects.requireNonNull(Data.getProfile());
412         for (int i = 1; i < list.size(); i++) {
413             ((TransactionAccount) list.get(i)).setCurrency(
414                     newValue ? profile.getDefaultCommodity() : "");
415         }
416         checkTransactionSubmittable(null);
417         showCurrency.setValue(newValue);
418     }
419     void stopObservingBusyFlag(Observer<Boolean> observer) {
420         busyFlag.removeObserver(observer);
421     }
422     void incrementBusyCounter() {
423         int newValue = busyCounter.incrementAndGet();
424         if (newValue == 1)
425             busyFlag.postValue(true);
426     }
427     void decrementBusyCounter() {
428         int newValue = busyCounter.decrementAndGet();
429         if (newValue == 0)
430             busyFlag.postValue(false);
431     }
432     public LiveData<Boolean> getBusyFlag() {
433         return busyFlag;
434     }
435     public void toggleShowComments() {
436         showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
437     }
438     public LedgerTransaction constructLedgerTransaction() {
439         List<Item> list = Objects.requireNonNull(items.getValue());
440         TransactionHead head = list.get(0)
441                                    .toTransactionHead();
442         LedgerTransaction tr = head.asLedgerTransaction();
443
444         tr.setComment(head.getComment());
445         LedgerTransactionAccount emptyAmountAccount = null;
446         float emptyAmountAccountBalance = 0;
447         for (int i = 1; i < list.size(); i++) {
448             TransactionAccount item = list.get(i)
449                                           .toTransactionAccount();
450             LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
451                                                                             .trim(),
452                     item.getCurrency());
453             if (acc.getAccountName()
454                    .isEmpty())
455                 continue;
456
457             acc.setComment(item.getComment());
458
459             if (item.isAmountSet()) {
460                 acc.setAmount(item.getAmount());
461                 emptyAmountAccountBalance += item.getAmount();
462             }
463             else {
464                 emptyAmountAccount = acc;
465             }
466
467             tr.addAccount(acc);
468         }
469
470         if (emptyAmountAccount != null)
471             emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
472
473         return tr;
474     }
475     void loadTransactionIntoModel(@NonNull TransactionWithAccounts tr) {
476         List<Item> newList = new ArrayList<>();
477         Item.resetIdDispenser();
478
479         Item currentHead = Objects.requireNonNull(items.getValue())
480                                   .get(0);
481         TransactionHead head = new TransactionHead(tr.transaction.getDescription());
482         head.setComment(tr.transaction.getComment());
483         if (currentHead instanceof TransactionHead)
484             head.setDate(((TransactionHead) currentHead).date);
485
486         newList.add(head);
487
488         List<LedgerTransactionAccount> accounts = new ArrayList<>();
489         for (net.ktnx.mobileledger.db.TransactionAccount acc : tr.accounts) {
490             accounts.add(new LedgerTransactionAccount(acc));
491         }
492
493         TransactionAccount firstNegative = null;
494         TransactionAccount firstPositive = null;
495         int singleNegativeIndex = -1;
496         int singlePositiveIndex = -1;
497         int negativeCount = 0;
498         for (int i = 0; i < accounts.size(); i++) {
499             LedgerTransactionAccount acc = accounts.get(i);
500             TransactionAccount item =
501                     new TransactionAccount(acc.getAccountName(), acc.getCurrency());
502             newList.add(item);
503
504             item.setAccountName(acc.getAccountName());
505             item.setComment(acc.getComment());
506             if (acc.isAmountSet()) {
507                 item.setAmount(acc.getAmount());
508                 if (acc.getAmount() < 0) {
509                     if (firstNegative == null) {
510                         firstNegative = item;
511                         singleNegativeIndex = i + 1;
512                     }
513                     else
514                         singleNegativeIndex = -1;
515                 }
516                 else {
517                     if (firstPositive == null) {
518                         firstPositive = item;
519                         singlePositiveIndex = i + 1;
520                     }
521                     else
522                         singlePositiveIndex = -1;
523                 }
524             }
525             else
526                 item.resetAmount();
527         }
528         if (BuildConfig.DEBUG)
529             dumpItemList("Loaded previous transaction", newList);
530
531         if (singleNegativeIndex != -1) {
532             firstNegative.resetAmount();
533             moveItemLast(newList, singleNegativeIndex);
534         }
535         else if (singlePositiveIndex != -1) {
536             firstPositive.resetAmount();
537             moveItemLast(newList, singlePositiveIndex);
538         }
539
540         Misc.onMainThread(() -> {
541             setItems(newList);
542             noteFocusChanged(1, FocusedElement.Amount);
543         });
544     }
545     /**
546      * A transaction is submittable if:
547      * 0) has description
548      * 1) has at least two account names
549      * 2) each row with amount has account name
550      * 3) for each commodity:
551      * 3a) amounts must balance to 0, or
552      * 3b) there must be exactly one empty amount (with account)
553      * 4) empty accounts with empty amounts are ignored
554      * Side effects:
555      * 5) a row with an empty account name or empty amount is guaranteed to exist for each
556      * commodity
557      * 6) at least two rows need to be present in the ledger
558      *
559      * @param list - the item list to check. Can be the displayed list or a list that will be
560      *             displayed soon
561      */
562     @SuppressLint("DefaultLocale")
563     void checkTransactionSubmittable(@Nullable List<Item> list) {
564         boolean workingWithLiveList = false;
565         if (list == null) {
566             list = copyList();
567             workingWithLiveList = true;
568         }
569
570         if (BuildConfig.DEBUG)
571             dumpItemList(String.format("Before submittable checks (%s)",
572                     workingWithLiveList ? "LIVE LIST" : "custom list"), list);
573
574         int accounts = 0;
575         final BalanceForCurrency balance = new BalanceForCurrency();
576         final String descriptionText = list.get(0)
577                                            .toTransactionHead()
578                                            .getDescription();
579         boolean submittable = true;
580         boolean listChanged = false;
581         final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
582         final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
583         final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
584         final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
585         final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
586         final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
587         final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
588         final List<Item> emptyRows = new ArrayList<>();
589
590         try {
591             if ((descriptionText == null) || descriptionText.trim()
592                                                             .isEmpty())
593             {
594                 Logger.debug("submittable", "Transaction not submittable: missing description");
595                 submittable = false;
596             }
597
598             boolean hasInvalidAmount = false;
599
600             for (int i = 1; i < list.size(); i++) {
601                 TransactionAccount item = list.get(i)
602                                               .toTransactionAccount();
603
604                 String accName = item.getAccountName()
605                                      .trim();
606                 String currName = item.getCurrency();
607
608                 itemsForCurrency.add(currName, item);
609
610                 if (accName.isEmpty()) {
611                     itemsWithEmptyAccountForCurrency.add(currName, item);
612
613                     if (item.isAmountSet()) {
614                         // 2) each amount has account name
615                         Logger.debug("submittable", String.format(
616                                 "Transaction not submittable: row %d has no account name, but" +
617                                 " has" + " amount %1.2f", i + 1, item.getAmount()));
618                         submittable = false;
619                     }
620                     else {
621                         emptyRowsForCurrency.add(currName, item);
622                     }
623                 }
624                 else {
625                     accounts++;
626                     itemsWithAccountForCurrency.add(currName, item);
627                 }
628
629                 if (item.isAmountSet()) {
630                     itemsWithAmountForCurrency.add(currName, item);
631                     balance.add(currName, item.getAmount());
632                 }
633                 else {
634                     if (!item.isAmountValid()) {
635                         Logger.debug("submittable",
636                                 String.format("Not submittable: row %d has an invalid amount",
637                                         i + 1));
638                         submittable = false;
639                         hasInvalidAmount = true;
640                     }
641
642                     itemsWithEmptyAmountForCurrency.add(currName, item);
643
644                     if (!accName.isEmpty())
645                         itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
646                 }
647             }
648
649             // 1) has at least two account names
650             if (accounts < 2) {
651                 if (accounts == 0)
652                     Logger.debug("submittable", "Transaction not submittable: no account names");
653                 else if (accounts == 1)
654                     Logger.debug("submittable",
655                             "Transaction not submittable: only one account name");
656                 else
657                     Logger.debug("submittable",
658                             String.format("Transaction not submittable: only %d account names",
659                                     accounts));
660                 submittable = false;
661             }
662
663             // 3) for each commodity:
664             // 3a) amount must balance to 0, or
665             // 3b) there must be exactly one empty amount (with account)
666             for (String balCurrency : itemsForCurrency.currencies()) {
667                 float currencyBalance = balance.get(balCurrency);
668                 if (Misc.isZero(currencyBalance)) {
669                     // remove hints from all amount inputs in that currency
670                     for (int i = 1; i < list.size(); i++) {
671                         TransactionAccount acc = list.get(i)
672                                                      .toTransactionAccount();
673                         if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
674                             if (BuildConfig.DEBUG)
675                                 Logger.debug("submittable",
676                                         String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
677                                                 i, Misc.nullIsEmpty(acc.getAccountName()),
678                                                 balCurrency));
679                             // skip if the amount is set, in which case the hint is not
680                             // important/visible
681                             if (!acc.isAmountSet() && acc.amountHintIsSet &&
682                                 !TextUtils.isEmpty(acc.getAmountHint()))
683                             {
684                                 acc.setAmountHint(null);
685                                 listChanged = true;
686                             }
687                         }
688                     }
689                 }
690                 else {
691                     List<Item> tmpList =
692                             itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
693                     int balanceReceiversCount = tmpList.size();
694                     if (balanceReceiversCount != 1) {
695                         if (BuildConfig.DEBUG) {
696                             if (balanceReceiversCount == 0)
697                                 Logger.debug("submittable", String.format(
698                                         "Transaction not submittable [curr:%s]: non-zero balance " +
699                                         "with no empty amounts with accounts", balCurrency));
700                             else
701                                 Logger.debug("submittable", String.format(
702                                         "Transaction not submittable [curr:%s]: non-zero balance " +
703                                         "with multiple empty amounts with accounts", balCurrency));
704                         }
705                         submittable = false;
706                     }
707
708                     List<Item> emptyAmountList =
709                             itemsWithEmptyAmountForCurrency.getList(balCurrency);
710
711                     // suggest off-balance amount to a row and remove hints on other rows
712                     Item receiver = null;
713                     if (!tmpList.isEmpty())
714                         receiver = tmpList.get(0);
715                     else if (!emptyAmountList.isEmpty())
716                         receiver = emptyAmountList.get(0);
717
718                     for (int i = 0; i < list.size(); i++) {
719                         Item item = list.get(i);
720                         if (!(item instanceof TransactionAccount))
721                             continue;
722
723                         TransactionAccount acc = item.toTransactionAccount();
724                         if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
725                             continue;
726
727                         if (item == receiver) {
728                             final String hint = String.format("%1.2f", -currencyBalance);
729                             if (!acc.isAmountHintSet() ||
730                                 !Misc.equalStrings(acc.getAmountHint(), hint))
731                             {
732                                 Logger.debug("submittable",
733                                         String.format("Setting amount hint of {%s} to %s [%s]",
734                                                 acc.toString(), hint, balCurrency));
735                                 acc.setAmountHint(hint);
736                                 listChanged = true;
737                             }
738                         }
739                         else {
740                             if (BuildConfig.DEBUG)
741                                 Logger.debug("submittable",
742                                         String.format("Resetting hint of '%s' [%s]",
743                                                 Misc.nullIsEmpty(acc.getAccountName()),
744                                                 balCurrency));
745                             if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
746                                 acc.setAmountHint(null);
747                                 listChanged = true;
748                             }
749                         }
750                     }
751                 }
752             }
753
754             // 5) a row with an empty account name or empty amount is guaranteed to exist for
755             // each commodity
756             if (!hasInvalidAmount) {
757                 for (String balCurrency : balance.currencies()) {
758                     int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
759                     int currRows = itemsForCurrency.size(balCurrency);
760                     int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
761                     int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
762                     if ((currEmptyRows == 0) &&
763                         ((currRows == currAccounts) || (currRows == currAmounts)))
764                     {
765                         // perhaps there already is an unused empty row for another currency that
766                         // is not used?
767 //                        boolean foundIt = false;
768 //                        for (Item item : emptyRows) {
769 //                            Currency itemCurrency = item.getCurrency();
770 //                            String itemCurrencyName =
771 //                                    (itemCurrency == null) ? "" : itemCurrency.getName();
772 //                            if (Misc.isZero(balance.get(itemCurrencyName))) {
773 //                                item.setCurrency(Currency.loadByName(balCurrency));
774 //                                item.setAmountHint(
775 //                                        String.format("%1.2f", -balance.get(balCurrency)));
776 //                                foundIt = true;
777 //                                break;
778 //                            }
779 //                        }
780 //
781 //                        if (!foundIt)
782                         final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
783                         final float bal = balance.get(balCurrency);
784                         if (!Misc.isZero(bal) && currAmounts == currRows)
785                             newAcc.setAmountHint(String.format("%4.2f", -bal));
786                         Logger.debug("submittable",
787                                 String.format("Adding new item with %s for currency %s",
788                                         newAcc.getAmountHint(), balCurrency));
789                         list.add(newAcc);
790                         listChanged = true;
791                     }
792                 }
793             }
794
795             // drop extra empty rows, not needed
796             for (String currName : emptyRowsForCurrency.currencies()) {
797                 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
798                 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
799                     // the list is a copy, so the empty item is no longer present
800                     Item itemToRemove = emptyItems.remove(1);
801                     removeItemById(list, itemToRemove.id);
802                     listChanged = true;
803                 }
804
805                 // unused currency, remove last item (which is also an empty one)
806                 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
807                     List<Item> currItems = itemsForCurrency.getList(currName);
808
809                     if (currItems.size() == 1) {
810                         // the list is a copy, so the empty item is no longer present
811                         removeItemById(list, emptyItems.get(0).id);
812                         listChanged = true;
813                     }
814                 }
815             }
816
817             // 6) at least two rows need to be present in the ledger
818             //    (the list also contains header and trailer)
819             while (list.size() < MIN_ITEMS) {
820                 list.add(new TransactionAccount(""));
821                 listChanged = true;
822             }
823
824             Logger.debug("submittable", submittable ? "YES" : "NO");
825             isSubmittable.setValue(submittable);
826
827             if (BuildConfig.DEBUG)
828                 dumpItemList("After submittable checks", list);
829         }
830         catch (NumberFormatException e) {
831             Logger.debug("submittable", "NO (because of NumberFormatException)");
832             isSubmittable.setValue(false);
833         }
834         catch (Exception e) {
835             e.printStackTrace();
836             Logger.debug("submittable", "NO (because of an Exception)");
837             isSubmittable.setValue(false);
838         }
839
840         if (listChanged && workingWithLiveList) {
841             setItemsWithoutSubmittableChecks(list);
842         }
843     }
844     private void removeItemById(@NotNull List<Item> list, int id) {
845         if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
846             list.removeIf(item -> item.id == id);
847         }
848         else {
849             for (Item item : list) {
850                 if (item.id == id) {
851                     list.remove(item);
852                     break;
853                 }
854             }
855         }
856     }
857     @SuppressLint("DefaultLocale")
858     private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
859         Logger.debug("submittable", "== Dump of all items " + msg);
860         for (int i = 1; i < list.size(); i++) {
861             TransactionAccount item = list.get(i)
862                                           .toTransactionAccount();
863             Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
864         }
865     }
866     public void setItemCurrency(int position, String newCurrency) {
867         TransactionAccount item = Objects.requireNonNull(items.getValue())
868                                          .get(position)
869                                          .toTransactionAccount();
870         final String oldCurrency = item.getCurrency();
871
872         if (Misc.equalStrings(oldCurrency, newCurrency))
873             return;
874
875         List<Item> newList = copyList();
876         newList.get(position)
877                .toTransactionAccount()
878                .setCurrency(newCurrency);
879
880         setItems(newList);
881     }
882     public boolean accountListIsEmpty() {
883         List<Item> items = Objects.requireNonNull(this.items.getValue());
884
885         for (Item item : items) {
886             if (!(item instanceof TransactionAccount))
887                 continue;
888
889             if (!((TransactionAccount) item).isEmpty())
890                 return false;
891         }
892
893         return true;
894     }
895
896     public static class FocusInfo {
897         int position;
898         FocusedElement element;
899         public FocusInfo(int position, FocusedElement element) {
900             this.position = position;
901             this.element = element;
902         }
903     }
904
905     static abstract class Item {
906         private static int idDispenser = 0;
907         protected int id;
908         private Item() {
909             if (this instanceof TransactionHead)
910                 id = 0;
911             else
912                 synchronized (Item.class) {
913                     id = ++idDispenser;
914                 }
915         }
916         public Item(int id) {
917             this.id = id;
918         }
919         public static Item from(Item origin) {
920             if (origin instanceof TransactionHead)
921                 return new TransactionHead((TransactionHead) origin);
922             if (origin instanceof TransactionAccount)
923                 return new TransactionAccount((TransactionAccount) origin);
924             throw new RuntimeException("Don't know how to handle " + origin);
925         }
926         private static void resetIdDispenser() {
927             idDispenser = 0;
928         }
929         public int getId() {
930             return id;
931         }
932         public abstract ItemType getType();
933         public TransactionHead toTransactionHead() {
934             if (this instanceof TransactionHead)
935                 return (TransactionHead) this;
936
937             throw new IllegalStateException("Wrong item type " + this);
938         }
939         public TransactionAccount toTransactionAccount() {
940             if (this instanceof TransactionAccount)
941                 return (TransactionAccount) this;
942
943             throw new IllegalStateException("Wrong item type " + this);
944         }
945         public boolean equalContents(@Nullable Object item) {
946             if (item == null)
947                 return false;
948
949             if (!getClass().equals(item.getClass()))
950                 return false;
951
952             // shortcut - comparing same instance
953             if (item == this)
954                 return true;
955
956             if (this instanceof TransactionHead)
957                 return ((TransactionHead) item).equalContents((TransactionHead) this);
958             if (this instanceof TransactionAccount)
959                 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
960
961             throw new RuntimeException("Don't know how to handle " + this);
962         }
963     }
964
965
966 //==========================================================================================
967
968     public static class TransactionHead extends Item {
969         private SimpleDate date;
970         private String description;
971         private String comment;
972         TransactionHead(String description) {
973             super();
974             this.description = description;
975         }
976         public TransactionHead(TransactionHead origin) {
977             super(origin.id);
978             date = origin.date;
979             description = origin.description;
980             comment = origin.comment;
981         }
982         public SimpleDate getDate() {
983             return date;
984         }
985         public void setDate(SimpleDate date) {
986             this.date = date;
987         }
988         public void setDate(String text) throws ParseException {
989             if (Misc.emptyIsNull(text) == null) {
990                 date = null;
991                 return;
992             }
993
994             date = Globals.parseLedgerDate(text);
995         }
996         /**
997          * getFormattedDate()
998          *
999          * @return nicely formatted, shortest available date representation
1000          */
1001         String getFormattedDate() {
1002             if (date == null)
1003                 return null;
1004
1005             Calendar today = GregorianCalendar.getInstance();
1006
1007             if (today.get(Calendar.YEAR) != date.year) {
1008                 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
1009             }
1010
1011             if (today.get(Calendar.MONTH) + 1 != date.month) {
1012                 return String.format(Locale.US, "%d/%02d", date.month, date.day);
1013             }
1014
1015             return String.valueOf(date.day);
1016         }
1017         @NonNull
1018         @Override
1019         public String toString() {
1020             @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
1021                     String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1022
1023             if (TextUtils.isEmpty(description))
1024                 b.append(" «no description»");
1025             else
1026                 b.append(String.format(" '%s'", description));
1027
1028             if (date != null)
1029                 b.append(String.format("@%s", date.toString()));
1030
1031             if (!TextUtils.isEmpty(comment))
1032                 b.append(String.format(" /%s/", comment));
1033
1034             return b.toString();
1035         }
1036         public String getDescription() {
1037             return description;
1038         }
1039         public void setDescription(String description) {
1040             this.description = description;
1041         }
1042         public String getComment() {
1043             return comment;
1044         }
1045         public void setComment(String comment) {
1046             this.comment = comment;
1047         }
1048         @Override
1049         public ItemType getType() {
1050             return ItemType.generalData;
1051         }
1052         public LedgerTransaction asLedgerTransaction() {
1053             return new LedgerTransaction(0, (date == null) ? SimpleDate.today() : date, description,
1054                     Objects.requireNonNull(Data.getProfile()));
1055         }
1056         public boolean equalContents(TransactionHead other) {
1057             if (other == null)
1058                 return false;
1059
1060             return Objects.equals(date, other.date) &&
1061                    Misc.equalStrings(description, other.description) &&
1062                    Misc.equalStrings(comment, other.comment);
1063         }
1064     }
1065
1066     public static class TransactionAccount extends Item {
1067         private String accountName;
1068         private String amountHint;
1069         private String comment;
1070         private String currency = "";
1071         private float amount;
1072         private boolean amountSet;
1073         private boolean amountValid = true;
1074         private FocusedElement focusedElement = FocusedElement.Account;
1075         private boolean amountHintIsSet = false;
1076         private boolean isLast = false;
1077         private int accountNameCursorPosition;
1078         public TransactionAccount(TransactionAccount origin) {
1079             super(origin.id);
1080             accountName = origin.accountName;
1081             amount = origin.amount;
1082             amountSet = origin.amountSet;
1083             amountHint = origin.amountHint;
1084             amountHintIsSet = origin.amountHintIsSet;
1085             comment = origin.comment;
1086             currency = origin.currency;
1087             amountValid = origin.amountValid;
1088             focusedElement = origin.focusedElement;
1089             isLast = origin.isLast;
1090             accountNameCursorPosition = origin.accountNameCursorPosition;
1091         }
1092         public TransactionAccount(LedgerTransactionAccount account) {
1093             super();
1094             currency = account.getCurrency();
1095             amount = account.getAmount();
1096         }
1097         public TransactionAccount(String accountName) {
1098             super();
1099             this.accountName = accountName;
1100         }
1101         public TransactionAccount(String accountName, @NotNull String currency) {
1102             super();
1103             this.accountName = accountName;
1104             this.currency = currency;
1105         }
1106         public boolean isLast() {
1107             return isLast;
1108         }
1109         public boolean isAmountSet() {
1110             return amountSet;
1111         }
1112         public String getAccountName() {
1113             return accountName;
1114         }
1115         public void setAccountName(String accountName) {
1116             this.accountName = accountName;
1117         }
1118         public float getAmount() {
1119             if (!amountSet)
1120                 throw new IllegalStateException("Amount is not set");
1121             return amount;
1122         }
1123         public void setAmount(float amount) {
1124             this.amount = amount;
1125             amountSet = true;
1126         }
1127         public void resetAmount() {
1128             amountSet = false;
1129         }
1130         @Override
1131         public ItemType getType() {
1132             return ItemType.transactionRow;
1133         }
1134         public String getAmountHint() {
1135             return amountHint;
1136         }
1137         public void setAmountHint(String amountHint) {
1138             this.amountHint = amountHint;
1139             amountHintIsSet = !TextUtils.isEmpty(amountHint);
1140         }
1141         public String getComment() {
1142             return comment;
1143         }
1144         public void setComment(String comment) {
1145             this.comment = comment;
1146         }
1147         @NotNull
1148         public String getCurrency() {
1149             return currency;
1150         }
1151         public void setCurrency(@org.jetbrains.annotations.Nullable String currency) {
1152             this.currency = Misc.nullIsEmpty(currency);
1153         }
1154         public boolean isAmountValid() {
1155             return amountValid;
1156         }
1157         public void setAmountValid(boolean amountValid) {
1158             this.amountValid = amountValid;
1159         }
1160         public FocusedElement getFocusedElement() {
1161             return focusedElement;
1162         }
1163         public void setFocusedElement(FocusedElement focusedElement) {
1164             this.focusedElement = focusedElement;
1165         }
1166         public boolean isAmountHintSet() {
1167             return amountHintIsSet;
1168         }
1169         public void setAmountHintIsSet(boolean amountHintIsSet) {
1170             this.amountHintIsSet = amountHintIsSet;
1171         }
1172         public boolean isEmpty() {
1173             return !amountSet && Misc.emptyIsNull(accountName) == null &&
1174                    Misc.emptyIsNull(comment) == null;
1175         }
1176         @SuppressLint("DefaultLocale")
1177         @Override
1178         public String toString() {
1179             StringBuilder b = new StringBuilder();
1180             b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1181             if (!TextUtils.isEmpty(accountName))
1182                 b.append(String.format(" acc'%s'", accountName));
1183
1184             if (amountSet)
1185                 b.append(String.format(" %4.2f", amount));
1186             else if (amountHintIsSet)
1187                 b.append(String.format(" (%s)", amountHint));
1188
1189             if (!TextUtils.isEmpty(currency))
1190                 b.append(" ")
1191                  .append(currency);
1192
1193             if (!TextUtils.isEmpty(comment))
1194                 b.append(String.format(" /%s/", comment));
1195
1196             if (isLast)
1197                 b.append(" last");
1198
1199             return b.toString();
1200         }
1201         public boolean equalContents(TransactionAccount other) {
1202             if (other == null)
1203                 return false;
1204
1205             boolean equal = Misc.equalStrings(accountName, other.accountName);
1206             equal = equal && Misc.equalStrings(comment, other.comment) &&
1207                     (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1208
1209             // compare amount hint only if there is no amount
1210             if (!amountSet)
1211                 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1212                                                     Misc.equalStrings(amountHint, other.amountHint)
1213                                                   : !other.amountHintIsSet);
1214             equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1215
1216             Logger.debug("new-trans",
1217                     String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1218                             equal));
1219             return equal;
1220         }
1221         public int getAccountNameCursorPosition() {
1222             return accountNameCursorPosition;
1223         }
1224         public void setAccountNameCursorPosition(int position) {
1225             this.accountNameCursorPosition = position;
1226         }
1227     }
1228
1229     private static class BalanceForCurrency {
1230         private final HashMap<String, Float> hashMap = new HashMap<>();
1231         float get(String currencyName) {
1232             Float f = hashMap.get(currencyName);
1233             if (f == null) {
1234                 f = 0f;
1235                 hashMap.put(currencyName, f);
1236             }
1237             return f;
1238         }
1239         void add(String currencyName, float amount) {
1240             hashMap.put(currencyName, get(currencyName) + amount);
1241         }
1242         Set<String> currencies() {
1243             return hashMap.keySet();
1244         }
1245         boolean containsCurrency(String currencyName) {
1246             return hashMap.containsKey(currencyName);
1247         }
1248     }
1249
1250     private static class ItemsForCurrency {
1251         private final HashMap<@NotNull String, List<Item>> hashMap = new HashMap<>();
1252         @NonNull
1253         List<NewTransactionModel.Item> getList(@NotNull String currencyName) {
1254             List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1255             if (list == null) {
1256                 list = new ArrayList<>();
1257                 hashMap.put(currencyName, list);
1258             }
1259             return list;
1260         }
1261         void add(@NotNull String currencyName, @NonNull NewTransactionModel.Item item) {
1262             getList(Objects.requireNonNull(currencyName)).add(item);
1263         }
1264         int size(@NotNull String currencyName) {
1265             return this.getList(Objects.requireNonNull(currencyName))
1266                        .size();
1267         }
1268         Set<String> currencies() {
1269             return hashMap.keySet();
1270         }
1271     }
1272 }