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