]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/new_transaction/NewTransactionModel.java
maintain amount text independent from the amount
[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<>(Objects.requireNonNull(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 = new TransactionAccount(acc.getAccountName(),
501                     Misc.nullIsEmpty(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() && item.isAmountValid()) {
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", i));
637                         submittable = false;
638                         hasInvalidAmount = true;
639                     }
640
641                     itemsWithEmptyAmountForCurrency.add(currName, item);
642
643                     if (!accName.isEmpty())
644                         itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
645                 }
646             }
647
648             // 1) has at least two account names
649             if (accounts < 2) {
650                 if (accounts == 0)
651                     Logger.debug("submittable", "Transaction not submittable: no account names");
652                 else if (accounts == 1)
653                     Logger.debug("submittable",
654                             "Transaction not submittable: only one account name");
655                 else
656                     Logger.debug("submittable",
657                             String.format("Transaction not submittable: only %d account names",
658                                     accounts));
659                 submittable = false;
660             }
661
662             // 3) for each commodity:
663             // 3a) amount must balance to 0, or
664             // 3b) there must be exactly one empty amount (with account)
665             for (String balCurrency : itemsForCurrency.currencies()) {
666                 float currencyBalance = balance.get(balCurrency);
667                 if (Misc.isZero(currencyBalance)) {
668                     // remove hints from all amount inputs in that currency
669                     for (int i = 1; i < list.size(); i++) {
670                         TransactionAccount acc = list.get(i)
671                                                      .toTransactionAccount();
672                         if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
673                             if (BuildConfig.DEBUG)
674                                 Logger.debug("submittable",
675                                         String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
676                                                 i, Misc.nullIsEmpty(acc.getAccountName()),
677                                                 balCurrency));
678                             // skip if the amount is set, in which case the hint is not
679                             // important/visible
680                             if (!acc.isAmountSet() && acc.amountHintIsSet &&
681                                 !TextUtils.isEmpty(acc.getAmountHint()))
682                             {
683                                 acc.setAmountHint(null);
684                                 listChanged = true;
685                             }
686                         }
687                     }
688                 }
689                 else {
690                     List<Item> tmpList =
691                             itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
692                     int balanceReceiversCount = tmpList.size();
693                     if (balanceReceiversCount != 1) {
694                         if (BuildConfig.DEBUG) {
695                             if (balanceReceiversCount == 0)
696                                 Logger.debug("submittable", String.format(
697                                         "Transaction not submittable [curr:%s]: non-zero balance " +
698                                         "with no empty amounts with accounts", balCurrency));
699                             else
700                                 Logger.debug("submittable", String.format(
701                                         "Transaction not submittable [curr:%s]: non-zero balance " +
702                                         "with multiple empty amounts with accounts", balCurrency));
703                         }
704                         submittable = false;
705                     }
706
707                     List<Item> emptyAmountList =
708                             itemsWithEmptyAmountForCurrency.getList(balCurrency);
709
710                     // suggest off-balance amount to a row and remove hints on other rows
711                     Item receiver = null;
712                     if (!tmpList.isEmpty())
713                         receiver = tmpList.get(0);
714                     else if (!emptyAmountList.isEmpty())
715                         receiver = emptyAmountList.get(0);
716
717                     for (int i = 0; i < list.size(); i++) {
718                         Item item = list.get(i);
719                         if (!(item instanceof TransactionAccount))
720                             continue;
721
722                         TransactionAccount acc = item.toTransactionAccount();
723                         if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
724                             continue;
725
726                         if (item == receiver) {
727                             final String hint = Data.formatNumber(-currencyBalance);
728                             if (!acc.isAmountHintSet() ||
729                                 !Misc.equalStrings(acc.getAmountHint(), hint))
730                             {
731                                 Logger.debug("submittable",
732                                         String.format("Setting amount hint of {%s} to %s [%s]",
733                                                 acc.toString(), hint, balCurrency));
734                                 acc.setAmountHint(hint);
735                                 listChanged = true;
736                             }
737                         }
738                         else {
739                             if (BuildConfig.DEBUG)
740                                 Logger.debug("submittable",
741                                         String.format("Resetting hint of '%s' [%s]",
742                                                 Misc.nullIsEmpty(acc.getAccountName()),
743                                                 balCurrency));
744                             if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
745                                 acc.setAmountHint(null);
746                                 listChanged = true;
747                             }
748                         }
749                     }
750                 }
751             }
752
753             // 5) a row with an empty account name or empty amount is guaranteed to exist for
754             // each commodity
755             if (!hasInvalidAmount) {
756                 for (String balCurrency : balance.currencies()) {
757                     int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
758                     int currRows = itemsForCurrency.size(balCurrency);
759                     int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
760                     int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
761                     if ((currEmptyRows == 0) &&
762                         ((currRows == currAccounts) || (currRows == currAmounts)))
763                     {
764                         // perhaps there already is an unused empty row for another currency that
765                         // is not used?
766 //                        boolean foundIt = false;
767 //                        for (Item item : emptyRows) {
768 //                            Currency itemCurrency = item.getCurrency();
769 //                            String itemCurrencyName =
770 //                                    (itemCurrency == null) ? "" : itemCurrency.getName();
771 //                            if (Misc.isZero(balance.get(itemCurrencyName))) {
772 //                                item.setCurrency(Currency.loadByName(balCurrency));
773 //                                item.setAmountHint(
774 //                                        Data.formatNumber(-balance.get(balCurrency)));
775 //                                foundIt = true;
776 //                                break;
777 //                            }
778 //                        }
779 //
780 //                        if (!foundIt)
781                         final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
782                         final float bal = balance.get(balCurrency);
783                         if (!Misc.isZero(bal) && currAmounts == currRows)
784                             newAcc.setAmountHint(Data.formatNumber(-bal));
785                         Logger.debug("submittable",
786                                 String.format("Adding new item with %s for currency %s",
787                                         newAcc.getAmountHint(), balCurrency));
788                         list.add(newAcc);
789                         listChanged = true;
790                     }
791                 }
792             }
793
794             // drop extra empty rows, not needed
795             for (String currName : emptyRowsForCurrency.currencies()) {
796                 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
797                 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
798                     // the list is a copy, so the empty item is no longer present
799                     Item itemToRemove = emptyItems.remove(1);
800                     removeItemById(list, itemToRemove.id);
801                     listChanged = true;
802                 }
803
804                 // unused currency, remove last item (which is also an empty one)
805                 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
806                     List<Item> currItems = itemsForCurrency.getList(currName);
807
808                     if (currItems.size() == 1) {
809                         // the list is a copy, so the empty item is no longer present
810                         removeItemById(list, emptyItems.get(0).id);
811                         listChanged = true;
812                     }
813                 }
814             }
815
816             // 6) at least two rows need to be present in the ledger
817             //    (the list also contains header and trailer)
818             while (list.size() < MIN_ITEMS) {
819                 list.add(new TransactionAccount(""));
820                 listChanged = true;
821             }
822
823             Logger.debug("submittable", submittable ? "YES" : "NO");
824             isSubmittable.setValue(submittable);
825
826             if (BuildConfig.DEBUG)
827                 dumpItemList("After submittable checks", list);
828         }
829         catch (NumberFormatException e) {
830             Logger.debug("submittable", "NO (because of NumberFormatException)");
831             isSubmittable.setValue(false);
832         }
833         catch (Exception e) {
834             e.printStackTrace();
835             Logger.debug("submittable", "NO (because of an Exception)");
836             isSubmittable.setValue(false);
837         }
838
839         if (listChanged && workingWithLiveList) {
840             setItemsWithoutSubmittableChecks(list);
841         }
842     }
843     private void removeItemById(@NotNull List<Item> list, int id) {
844         if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
845             list.removeIf(item -> item.id == id);
846         }
847         else {
848             for (Item item : list) {
849                 if (item.id == id) {
850                     list.remove(item);
851                     break;
852                 }
853             }
854         }
855     }
856     @SuppressLint("DefaultLocale")
857     private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
858         Logger.debug("submittable", "== Dump of all items " + msg);
859         for (int i = 1; i < list.size(); i++) {
860             TransactionAccount item = list.get(i)
861                                           .toTransactionAccount();
862             Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
863         }
864     }
865     public void setItemCurrency(int position, String newCurrency) {
866         TransactionAccount item = Objects.requireNonNull(items.getValue())
867                                          .get(position)
868                                          .toTransactionAccount();
869         final String oldCurrency = item.getCurrency();
870
871         if (Misc.equalStrings(oldCurrency, newCurrency))
872             return;
873
874         List<Item> newList = copyList();
875         newList.get(position)
876                .toTransactionAccount()
877                .setCurrency(newCurrency);
878
879         setItems(newList);
880     }
881     public boolean accountListIsEmpty() {
882         List<Item> items = Objects.requireNonNull(this.items.getValue());
883
884         for (Item item : items) {
885             if (!(item instanceof TransactionAccount))
886                 continue;
887
888             if (!((TransactionAccount) item).isEmpty())
889                 return false;
890         }
891
892         return true;
893     }
894
895     public static class FocusInfo {
896         int position;
897         FocusedElement element;
898         public FocusInfo(int position, FocusedElement element) {
899             this.position = position;
900             this.element = element;
901         }
902     }
903
904     static abstract class Item {
905         private static int idDispenser = 0;
906         protected int id;
907         private Item() {
908             if (this instanceof TransactionHead)
909                 id = 0;
910             else
911                 synchronized (Item.class) {
912                     id = ++idDispenser;
913                 }
914         }
915         public Item(int id) {
916             this.id = id;
917         }
918         public static Item from(Item origin) {
919             if (origin instanceof TransactionHead)
920                 return new TransactionHead((TransactionHead) origin);
921             if (origin instanceof TransactionAccount)
922                 return new TransactionAccount((TransactionAccount) origin);
923             throw new RuntimeException("Don't know how to handle " + origin);
924         }
925         private static void resetIdDispenser() {
926             idDispenser = 0;
927         }
928         public int getId() {
929             return id;
930         }
931         public abstract ItemType getType();
932         public TransactionHead toTransactionHead() {
933             if (this instanceof TransactionHead)
934                 return (TransactionHead) this;
935
936             throw new IllegalStateException("Wrong item type " + this);
937         }
938         public TransactionAccount toTransactionAccount() {
939             if (this instanceof TransactionAccount)
940                 return (TransactionAccount) this;
941
942             throw new IllegalStateException("Wrong item type " + this);
943         }
944         public boolean equalContents(@Nullable Object item) {
945             if (item == null)
946                 return false;
947
948             if (!getClass().equals(item.getClass()))
949                 return false;
950
951             // shortcut - comparing same instance
952             if (item == this)
953                 return true;
954
955             if (this instanceof TransactionHead)
956                 return ((TransactionHead) item).equalContents((TransactionHead) this);
957             if (this instanceof TransactionAccount)
958                 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
959
960             throw new RuntimeException("Don't know how to handle " + this);
961         }
962     }
963
964
965 //==========================================================================================
966
967     public static class TransactionHead extends Item {
968         private SimpleDate date;
969         private String description;
970         private String comment;
971         TransactionHead(String description) {
972             super();
973             this.description = description;
974         }
975         public TransactionHead(TransactionHead origin) {
976             super(origin.id);
977             date = origin.date;
978             description = origin.description;
979             comment = origin.comment;
980         }
981         public SimpleDate getDate() {
982             return date;
983         }
984         public void setDate(SimpleDate date) {
985             this.date = date;
986         }
987         public void setDate(String text) throws ParseException {
988             if (Misc.emptyIsNull(text) == null) {
989                 date = null;
990                 return;
991             }
992
993             date = Globals.parseLedgerDate(text);
994         }
995         /**
996          * getFormattedDate()
997          *
998          * @return nicely formatted, shortest available date representation
999          */
1000         String getFormattedDate() {
1001             if (date == null)
1002                 return null;
1003
1004             Calendar today = GregorianCalendar.getInstance();
1005
1006             if (today.get(Calendar.YEAR) != date.year) {
1007                 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
1008             }
1009
1010             if (today.get(Calendar.MONTH) + 1 != date.month) {
1011                 return String.format(Locale.US, "%d/%02d", date.month, date.day);
1012             }
1013
1014             return String.valueOf(date.day);
1015         }
1016         @NonNull
1017         @Override
1018         public String toString() {
1019             @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
1020                     String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1021
1022             if (TextUtils.isEmpty(description))
1023                 b.append(" «no description»");
1024             else
1025                 b.append(String.format(" '%s'", description));
1026
1027             if (date != null)
1028                 b.append(String.format("@%s", date.toString()));
1029
1030             if (!TextUtils.isEmpty(comment))
1031                 b.append(String.format(" /%s/", comment));
1032
1033             return b.toString();
1034         }
1035         public String getDescription() {
1036             return description;
1037         }
1038         public void setDescription(String description) {
1039             this.description = description;
1040         }
1041         public String getComment() {
1042             return comment;
1043         }
1044         public void setComment(String comment) {
1045             this.comment = comment;
1046         }
1047         @Override
1048         public ItemType getType() {
1049             return ItemType.generalData;
1050         }
1051         public LedgerTransaction asLedgerTransaction() {
1052             return new LedgerTransaction(0, (date == null) ? SimpleDate.today() : date, description,
1053                     Objects.requireNonNull(Data.getProfile()));
1054         }
1055         public boolean equalContents(TransactionHead other) {
1056             if (other == null)
1057                 return false;
1058
1059             return Objects.equals(date, other.date) &&
1060                    Misc.equalStrings(description, other.description) &&
1061                    Misc.equalStrings(comment, other.comment);
1062         }
1063     }
1064
1065     public static class TransactionAccount extends Item {
1066         private String accountName;
1067         private String amountHint;
1068         private String comment;
1069         @NotNull
1070         private String currency = "";
1071         private float amount;
1072         private boolean amountSet;
1073         private boolean amountValid = true;
1074         @NotNull
1075         private String amountText = "";
1076         private FocusedElement focusedElement = FocusedElement.Account;
1077         private boolean amountHintIsSet = false;
1078         private boolean isLast = false;
1079         private int accountNameCursorPosition;
1080         public TransactionAccount(TransactionAccount origin) {
1081             super(origin.id);
1082             accountName = origin.accountName;
1083             amount = origin.amount;
1084             amountSet = origin.amountSet;
1085             amountHint = origin.amountHint;
1086             amountHintIsSet = origin.amountHintIsSet;
1087             amountText = origin.amountText;
1088             comment = origin.comment;
1089             currency = origin.currency;
1090             amountValid = origin.amountValid;
1091             focusedElement = origin.focusedElement;
1092             isLast = origin.isLast;
1093             accountNameCursorPosition = origin.accountNameCursorPosition;
1094         }
1095         public TransactionAccount(String accountName) {
1096             super();
1097             this.accountName = accountName;
1098         }
1099         public TransactionAccount(String accountName, @NotNull String currency) {
1100             super();
1101             this.accountName = accountName;
1102             this.currency = currency;
1103         }
1104         public @NotNull String getAmountText() {
1105             return amountText;
1106         }
1107         public void setAmountText(@NotNull String amountText) {
1108             this.amountText = amountText;
1109         }
1110         public boolean setAndCheckAmountText(@NotNull String amountText) {
1111             String amtText = amountText.trim();
1112             this.amountText = amtText;
1113
1114             boolean significantChange = false;
1115
1116             if (amtText.isEmpty()) {
1117                 if (amountSet) {
1118                     significantChange = true;
1119                 }
1120                 resetAmount();
1121             }
1122             else {
1123                 try {
1124                     amtText = amtText.replace(Data.getDecimalSeparator(), Data.decimalDot);
1125                     final float parsedAmount = Float.parseFloat(amtText);
1126                     if (!amountSet || !amountValid || !Misc.equalFloats(parsedAmount, amount))
1127                         significantChange = true;
1128                     amount = parsedAmount;
1129                     amountSet = true;
1130                     amountValid = true;
1131                 }
1132                 catch (NumberFormatException e) {
1133                     Logger.debug("new-trans", String.format(
1134                             "assuming amount is not set due to number format exception. " +
1135                             "input was '%s'", amtText));
1136                     if (amountValid) // it was valid and now it's not
1137                         significantChange = true;
1138                     amountValid = false;
1139                 }
1140             }
1141
1142             return significantChange;
1143         }
1144         public boolean isLast() {
1145             return isLast;
1146         }
1147         public boolean isAmountSet() {
1148             return amountSet;
1149         }
1150         public String getAccountName() {
1151             return accountName;
1152         }
1153         public void setAccountName(String accountName) {
1154             this.accountName = accountName;
1155         }
1156         public float getAmount() {
1157             if (!amountSet)
1158                 throw new IllegalStateException("Amount is not set");
1159             return amount;
1160         }
1161         public void setAmount(float amount) {
1162             this.amount = amount;
1163             amountSet = true;
1164             amountValid = true;
1165             amountText = Data.formatNumber(amount);
1166         }
1167         public void resetAmount() {
1168             amountSet = false;
1169             amountValid = true;
1170             amountText = "";
1171         }
1172         @Override
1173         public ItemType getType() {
1174             return ItemType.transactionRow;
1175         }
1176         public String getAmountHint() {
1177             return amountHint;
1178         }
1179         public void setAmountHint(String amountHint) {
1180             this.amountHint = amountHint;
1181             amountHintIsSet = !TextUtils.isEmpty(amountHint);
1182         }
1183         public String getComment() {
1184             return comment;
1185         }
1186         public void setComment(String comment) {
1187             this.comment = comment;
1188         }
1189         @NotNull
1190         public String getCurrency() {
1191             return currency;
1192         }
1193         public void setCurrency(@org.jetbrains.annotations.Nullable String currency) {
1194             this.currency = Misc.nullIsEmpty(currency);
1195         }
1196         public boolean isAmountValid() {
1197             return amountValid;
1198         }
1199         public void setAmountValid(boolean amountValid) {
1200             this.amountValid = amountValid;
1201         }
1202         public FocusedElement getFocusedElement() {
1203             return focusedElement;
1204         }
1205         public void setFocusedElement(FocusedElement focusedElement) {
1206             this.focusedElement = focusedElement;
1207         }
1208         public boolean isAmountHintSet() {
1209             return amountHintIsSet;
1210         }
1211         public void setAmountHintIsSet(boolean amountHintIsSet) {
1212             this.amountHintIsSet = amountHintIsSet;
1213         }
1214         public boolean isEmpty() {
1215             return !amountSet && Misc.emptyIsNull(accountName) == null &&
1216                    Misc.emptyIsNull(comment) == null;
1217         }
1218         @SuppressLint("DefaultLocale")
1219         @Override
1220         @NotNull
1221         public String toString() {
1222             StringBuilder b = new StringBuilder();
1223             b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1224             if (!TextUtils.isEmpty(accountName))
1225                 b.append(String.format(" acc'%s'", accountName));
1226
1227             if (amountSet)
1228                 b.append(amountText)
1229                  .append(" [")
1230                  .append(amountValid ? "valid" : "invalid")
1231                  .append("] ")
1232                  .append(String.format(Locale.ROOT, " {raw %4.2f}", amount));
1233             else if (amountHintIsSet)
1234                 b.append(String.format(" (hint %s)", amountHint));
1235
1236             if (!TextUtils.isEmpty(currency))
1237                 b.append(" ")
1238                  .append(currency);
1239
1240             if (!TextUtils.isEmpty(comment))
1241                 b.append(String.format(" /%s/", comment));
1242
1243             if (isLast)
1244                 b.append(" last");
1245
1246             return b.toString();
1247         }
1248         public boolean equalContents(TransactionAccount other) {
1249             if (other == null)
1250                 return false;
1251
1252             boolean equal = Misc.equalStrings(accountName, other.accountName);
1253             equal = equal && Misc.equalStrings(comment, other.comment) &&
1254                     (amountSet ? other.amountSet && amountValid == other.amountValid &&
1255                                  Misc.equalStrings(amountText, other.amountText)
1256                                : !other.amountSet);
1257
1258             // compare amount hint only if there is no amount
1259             if (!amountSet)
1260                 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1261                                                     Misc.equalStrings(amountHint, other.amountHint)
1262                                                   : !other.amountHintIsSet);
1263             equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1264
1265             Logger.debug("new-trans",
1266                     String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1267                             equal));
1268             return equal;
1269         }
1270         public int getAccountNameCursorPosition() {
1271             return accountNameCursorPosition;
1272         }
1273         public void setAccountNameCursorPosition(int position) {
1274             this.accountNameCursorPosition = position;
1275         }
1276     }
1277
1278     private static class BalanceForCurrency {
1279         private final HashMap<String, Float> hashMap = new HashMap<>();
1280         float get(String currencyName) {
1281             Float f = hashMap.get(currencyName);
1282             if (f == null) {
1283                 f = 0f;
1284                 hashMap.put(currencyName, f);
1285             }
1286             return f;
1287         }
1288         void add(String currencyName, float amount) {
1289             hashMap.put(currencyName, get(currencyName) + amount);
1290         }
1291         Set<String> currencies() {
1292             return hashMap.keySet();
1293         }
1294         boolean containsCurrency(String currencyName) {
1295             return hashMap.containsKey(currencyName);
1296         }
1297     }
1298
1299     private static class ItemsForCurrency {
1300         private final HashMap<@NotNull String, List<Item>> hashMap = new HashMap<>();
1301         @NonNull
1302         List<NewTransactionModel.Item> getList(@NotNull String currencyName) {
1303             List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1304             if (list == null) {
1305                 list = new ArrayList<>();
1306                 hashMap.put(currencyName, list);
1307             }
1308             return list;
1309         }
1310         void add(@NotNull String currencyName, @NonNull NewTransactionModel.Item item) {
1311             getList(Objects.requireNonNull(currencyName)).add(item);
1312         }
1313         int size(@NotNull String currencyName) {
1314             return this.getList(Objects.requireNonNull(currencyName))
1315                        .size();
1316         }
1317         Set<String> currencies() {
1318             return hashMap.keySet();
1319         }
1320     }
1321 }