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