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