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