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