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