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