]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/new_transaction/NewTransactionModel.java
replace TextUtils.equals() usage with Misc.equalStrings()
[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(String.format("Before submittable checks (%s)",
538                     workingWithLiveList ? "LIVE LIST" : "custom list"), list);
539
540         int accounts = 0;
541         final BalanceForCurrency balance = new BalanceForCurrency();
542         final String descriptionText = list.get(0)
543                                            .toTransactionHead()
544                                            .getDescription();
545         boolean submittable = true;
546         boolean listChanged = false;
547         final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
548         final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
549         final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
550         final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
551         final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
552         final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
553         final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
554         final List<Item> emptyRows = new ArrayList<>();
555
556         try {
557             if ((descriptionText == null) || descriptionText.trim()
558                                                             .isEmpty())
559             {
560                 Logger.debug("submittable", "Transaction not submittable: missing description");
561                 submittable = false;
562             }
563
564             for (int i = 1; i < list.size(); i++) {
565                 TransactionAccount item = list.get(i)
566                                               .toTransactionAccount();
567
568                 String accName = item.getAccountName()
569                                      .trim();
570                 String currName = item.getCurrency();
571
572                 itemsForCurrency.add(currName, item);
573
574                 if (accName.isEmpty()) {
575                     itemsWithEmptyAccountForCurrency.add(currName, item);
576
577                     if (item.isAmountSet()) {
578                         // 2) each amount has account name
579                         Logger.debug("submittable", String.format(
580                                 "Transaction not submittable: row %d has no account name, but" +
581                                 " has" + " amount %1.2f", i + 1, item.getAmount()));
582                         submittable = false;
583                     }
584                     else {
585                         emptyRowsForCurrency.add(currName, item);
586                     }
587                 }
588                 else {
589                     accounts++;
590                     itemsWithAccountForCurrency.add(currName, item);
591                 }
592
593                 if (!item.isAmountValid()) {
594                     Logger.debug("submittable",
595                             String.format("Not submittable: row %d has an invalid amount", i + 1));
596                     submittable = false;
597                 }
598                 else if (item.isAmountSet()) {
599                     itemsWithAmountForCurrency.add(currName, item);
600                     balance.add(currName, item.getAmount());
601                 }
602                 else {
603                     itemsWithEmptyAmountForCurrency.add(currName, item);
604
605                     if (!accName.isEmpty())
606                         itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
607                 }
608             }
609
610             // 1) has at least two account names
611             if (accounts < 2) {
612                 if (accounts == 0)
613                     Logger.debug("submittable", "Transaction not submittable: no account names");
614                 else if (accounts == 1)
615                     Logger.debug("submittable",
616                             "Transaction not submittable: only one account name");
617                 else
618                     Logger.debug("submittable",
619                             String.format("Transaction not submittable: only %d account names",
620                                     accounts));
621                 submittable = false;
622             }
623
624             // 3) for each commodity:
625             // 3a) amount must balance to 0, or
626             // 3b) there must be exactly one empty amount (with account)
627             for (String balCurrency : itemsForCurrency.currencies()) {
628                 float currencyBalance = balance.get(balCurrency);
629                 if (Misc.isZero(currencyBalance)) {
630                     // remove hints from all amount inputs in that currency
631                     for (int i = 1; i < list.size(); i++) {
632                         TransactionAccount acc = list.get(i)
633                                                      .toTransactionAccount();
634                         if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
635                             if (BuildConfig.DEBUG)
636                                 Logger.debug("submittable",
637                                         String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
638                                                 i, Misc.nullIsEmpty(acc.getAccountName()),
639                                                 balCurrency));
640                             // skip if the amount is set, in which case the hint is not
641                             // important/visible
642                             if (!acc.isAmountSet() && acc.amountHintIsSet &&
643                                 !TextUtils.isEmpty(acc.getAmountHint()))
644                             {
645                                 acc.setAmountHint(null);
646                                 listChanged = true;
647                             }
648                         }
649                     }
650                 }
651                 else {
652                     List<Item> tmpList =
653                             itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
654                     int balanceReceiversCount = tmpList.size();
655                     if (balanceReceiversCount != 1) {
656                         if (BuildConfig.DEBUG) {
657                             if (balanceReceiversCount == 0)
658                                 Logger.debug("submittable", String.format(
659                                         "Transaction not submittable [%s]: non-zero balance " +
660                                         "with no empty amounts with accounts", balCurrency));
661                             else
662                                 Logger.debug("submittable", String.format(
663                                         "Transaction not submittable [%s]: non-zero balance " +
664                                         "with multiple empty amounts with accounts", balCurrency));
665                         }
666                         submittable = false;
667                     }
668
669                     List<Item> emptyAmountList =
670                             itemsWithEmptyAmountForCurrency.getList(balCurrency);
671
672                     // suggest off-balance amount to a row and remove hints on other rows
673                     Item receiver = null;
674                     if (!tmpList.isEmpty())
675                         receiver = tmpList.get(0);
676                     else if (!emptyAmountList.isEmpty())
677                         receiver = emptyAmountList.get(0);
678
679                     for (int i = 0; i < list.size(); i++) {
680                         Item item = list.get(i);
681                         if (!(item instanceof TransactionAccount))
682                             continue;
683
684                         TransactionAccount acc = item.toTransactionAccount();
685                         if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
686                             continue;
687
688                         if (item == receiver) {
689                             final String hint = String.format("%1.2f", -currencyBalance);
690                             if (!acc.isAmountHintSet() ||
691                                 !Misc.equalStrings(acc.getAmountHint(), hint))
692                             {
693                                 Logger.debug("submittable",
694                                         String.format("Setting amount hint of {%s} to %s [%s]",
695                                                 acc.toString(), hint, balCurrency));
696                                 acc.setAmountHint(hint);
697                                 listChanged = true;
698                             }
699                         }
700                         else {
701                             if (BuildConfig.DEBUG)
702                                 Logger.debug("submittable",
703                                         String.format("Resetting hint of '%s' [%s]",
704                                                 Misc.nullIsEmpty(acc.getAccountName()),
705                                                 balCurrency));
706                             if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
707                                 acc.setAmountHint(null);
708                                 listChanged = true;
709                             }
710                         }
711                     }
712                 }
713             }
714
715             // 5) a row with an empty account name or empty amount is guaranteed to exist for
716             // each commodity
717             for (String balCurrency : balance.currencies()) {
718                 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
719                 int currRows = itemsForCurrency.size(balCurrency);
720                 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
721                 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
722                 if ((currEmptyRows == 0) &&
723                     ((currRows == currAccounts) || (currRows == currAmounts)))
724                 {
725                     // perhaps there already is an unused empty row for another currency that
726                     // is not used?
727 //                        boolean foundIt = false;
728 //                        for (Item item : emptyRows) {
729 //                            Currency itemCurrency = item.getCurrency();
730 //                            String itemCurrencyName =
731 //                                    (itemCurrency == null) ? "" : itemCurrency.getName();
732 //                            if (Misc.isZero(balance.get(itemCurrencyName))) {
733 //                                item.setCurrency(Currency.loadByName(balCurrency));
734 //                                item.setAmountHint(
735 //                                        String.format("%1.2f", -balance.get(balCurrency)));
736 //                                foundIt = true;
737 //                                break;
738 //                            }
739 //                        }
740 //
741 //                        if (!foundIt)
742                     final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
743                     final float bal = balance.get(balCurrency);
744                     if (!Misc.isZero(bal) && currAmounts == currRows)
745                         newAcc.setAmountHint(String.format("%4.2f", -bal));
746                     Logger.debug("submittable",
747                             String.format("Adding new item with %s for currency %s",
748                                     newAcc.getAmountHint(), balCurrency));
749                     list.add(newAcc);
750                     listChanged = true;
751                 }
752             }
753
754             // drop extra empty rows, not needed
755             for (String currName : emptyRowsForCurrency.currencies()) {
756                 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
757                 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
758                     // the list is a copy, so the empty item is no longer present
759                     Item itemToRemove = emptyItems.remove(1);
760                     removeItemById(list, itemToRemove.id);
761                     listChanged = true;
762                 }
763
764                 // unused currency, remove last item (which is also an empty one)
765                 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
766                     List<Item> currItems = itemsForCurrency.getList(currName);
767
768                     if (currItems.size() == 1) {
769                         // the list is a copy, so the empty item is no longer present
770                         removeItemById(list, emptyItems.get(0).id);
771                         listChanged = true;
772                     }
773                 }
774             }
775
776             // 6) at least two rows need to be present in the ledger
777             //    (the list also contains header and trailer)
778             while (list.size() < MIN_ITEMS) {
779                 list.add(new TransactionAccount(""));
780                 listChanged = true;
781             }
782
783             Logger.debug("submittable", submittable ? "YES" : "NO");
784             isSubmittable.setValue(submittable);
785
786             if (BuildConfig.DEBUG)
787                 dumpItemList("After submittable checks", list);
788         }
789         catch (NumberFormatException e) {
790             Logger.debug("submittable", "NO (because of NumberFormatException)");
791             isSubmittable.setValue(false);
792         }
793         catch (Exception e) {
794             e.printStackTrace();
795             Logger.debug("submittable", "NO (because of an Exception)");
796             isSubmittable.setValue(false);
797         }
798
799         if (listChanged && workingWithLiveList) {
800             setItemsWithoutSubmittableChecks(list);
801         }
802     }
803     private void removeItemById(@NotNull List<Item> list, int id) {
804         if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
805             list.removeIf(item -> item.id == id);
806         }
807         else {
808             for (Item item : list) {
809                 if (item.id == id) {
810                     list.remove(item);
811                     break;
812                 }
813             }
814         }
815     }
816     @SuppressLint("DefaultLocale")
817     private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
818         Logger.debug("submittable", "== Dump of all items " + msg);
819         for (int i = 1; i < list.size(); i++) {
820             TransactionAccount item = list.get(i)
821                                           .toTransactionAccount();
822             Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
823         }
824     }
825     public void setItemCurrency(int position, String newCurrency) {
826         TransactionAccount item = Objects.requireNonNull(items.getValue())
827                                          .get(position)
828                                          .toTransactionAccount();
829         final String oldCurrency = item.getCurrency();
830
831         if (Misc.equalStrings(oldCurrency, newCurrency))
832             return;
833
834         List<Item> newList = copyList();
835         newList.get(position)
836                .toTransactionAccount()
837                .setCurrency(newCurrency);
838
839         setItems(newList);
840     }
841     public boolean accountListIsEmpty() {
842         List<Item> items = Objects.requireNonNull(this.items.getValue());
843
844         for (Item item : items) {
845             if (!(item instanceof TransactionAccount))
846                 continue;
847
848             if (!((TransactionAccount) item).isEmpty())
849                 return false;
850         }
851
852         return true;
853     }
854
855     public static class FocusInfo {
856         int position;
857         FocusedElement element;
858         public FocusInfo(int position, FocusedElement element) {
859             this.position = position;
860             this.element = element;
861         }
862     }
863
864     static abstract class Item {
865         private static int idDispenser = 0;
866         protected int id;
867         private Item() {
868             synchronized (Item.class) {
869                 id = ++idDispenser;
870             }
871         }
872         public static Item from(Item origin) {
873             if (origin instanceof TransactionHead)
874                 return new TransactionHead((TransactionHead) origin);
875             if (origin instanceof TransactionAccount)
876                 return new TransactionAccount((TransactionAccount) origin);
877             throw new RuntimeException("Don't know how to handle " + origin);
878         }
879         public int getId() {
880             return id;
881         }
882         public abstract ItemType getType();
883         public TransactionHead toTransactionHead() {
884             if (this instanceof TransactionHead)
885                 return (TransactionHead) this;
886
887             throw new IllegalStateException("Wrong item type " + this);
888         }
889         public TransactionAccount toTransactionAccount() {
890             if (this instanceof TransactionAccount)
891                 return (TransactionAccount) this;
892
893             throw new IllegalStateException("Wrong item type " + this);
894         }
895         public boolean equalContents(@Nullable Object item) {
896             if (item == null)
897                 return false;
898
899             if (!getClass().equals(item.getClass()))
900                 return false;
901
902             // shortcut - comparing same instance
903             if (item == this)
904                 return true;
905
906             if (this instanceof TransactionHead)
907                 return ((TransactionHead) item).equalContents((TransactionHead) this);
908             if (this instanceof TransactionAccount)
909                 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
910
911             throw new RuntimeException("Don't know how to handle " + this);
912         }
913     }
914
915
916 //==========================================================================================
917
918     public static class TransactionHead extends Item {
919         private SimpleDate date;
920         private String description;
921         private String comment;
922         TransactionHead(String description) {
923             super();
924             this.description = description;
925         }
926         public TransactionHead(TransactionHead origin) {
927             id = origin.id;
928             date = origin.date;
929             description = origin.description;
930             comment = origin.comment;
931         }
932         public SimpleDate getDate() {
933             return date;
934         }
935         public void setDate(SimpleDate date) {
936             this.date = date;
937         }
938         public void setDate(String text) throws ParseException {
939             if (Misc.emptyIsNull(text) == null) {
940                 date = null;
941                 return;
942             }
943
944             date = Globals.parseLedgerDate(text);
945         }
946         /**
947          * getFormattedDate()
948          *
949          * @return nicely formatted, shortest available date representation
950          */
951         String getFormattedDate() {
952             if (date == null)
953                 return null;
954
955             Calendar today = GregorianCalendar.getInstance();
956
957             if (today.get(Calendar.YEAR) != date.year) {
958                 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
959             }
960
961             if (today.get(Calendar.MONTH) + 1 != date.month) {
962                 return String.format(Locale.US, "%d/%02d", date.month, date.day);
963             }
964
965             return String.valueOf(date.day);
966         }
967         @NonNull
968         @Override
969         public String toString() {
970             @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
971                     String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
972
973             if (TextUtils.isEmpty(description))
974                 b.append(" «no description»");
975             else
976                 b.append(String.format(" '%s'", description));
977
978             if (date != null)
979                 b.append(String.format("@%s", date.toString()));
980
981             if (!TextUtils.isEmpty(comment))
982                 b.append(String.format(" /%s/", comment));
983
984             return b.toString();
985         }
986         public String getDescription() {
987             return description;
988         }
989         public void setDescription(String description) {
990             this.description = description;
991         }
992         public String getComment() {
993             return comment;
994         }
995         public void setComment(String comment) {
996             this.comment = comment;
997         }
998         @Override
999         public ItemType getType() {
1000             return ItemType.generalData;
1001         }
1002         public LedgerTransaction asLedgerTransaction() {
1003             return new LedgerTransaction(null, date, description, Data.getProfile());
1004         }
1005         public boolean equalContents(TransactionHead other) {
1006             if (other == null)
1007                 return false;
1008
1009             return Objects.equals(date, other.date) &&
1010                    Misc.equalStrings(description, other.description) &&
1011                    Misc.equalStrings(comment, other.comment);
1012         }
1013     }
1014
1015     public static class TransactionAccount extends Item {
1016         private String accountName;
1017         private String amountHint;
1018         private String comment;
1019         private String currency;
1020         private float amount;
1021         private boolean amountSet;
1022         private boolean amountValid = true;
1023         private FocusedElement focusedElement = FocusedElement.Account;
1024         private boolean amountHintIsSet = false;
1025         private boolean isLast = false;
1026         private int accountNameCursorPosition;
1027         public TransactionAccount(TransactionAccount origin) {
1028             id = origin.id;
1029             accountName = origin.accountName;
1030             amount = origin.amount;
1031             amountSet = origin.amountSet;
1032             amountHint = origin.amountHint;
1033             amountHintIsSet = origin.amountHintIsSet;
1034             comment = origin.comment;
1035             currency = origin.currency;
1036             amountValid = origin.amountValid;
1037             focusedElement = origin.focusedElement;
1038             isLast = origin.isLast;
1039             accountNameCursorPosition = origin.accountNameCursorPosition;
1040         }
1041         public TransactionAccount(LedgerTransactionAccount account) {
1042             super();
1043             currency = account.getCurrency();
1044             amount = account.getAmount();
1045         }
1046         public TransactionAccount(String accountName) {
1047             super();
1048             this.accountName = accountName;
1049         }
1050         public TransactionAccount(String accountName, String currency) {
1051             super();
1052             this.accountName = accountName;
1053             this.currency = currency;
1054         }
1055         public boolean isLast() {
1056             return isLast;
1057         }
1058         public boolean isAmountSet() {
1059             return amountSet;
1060         }
1061         public String getAccountName() {
1062             return accountName;
1063         }
1064         public void setAccountName(String accountName) {
1065             this.accountName = accountName;
1066         }
1067         public float getAmount() {
1068             if (!amountSet)
1069                 throw new IllegalStateException("Amount is not set");
1070             return amount;
1071         }
1072         public void setAmount(float amount) {
1073             this.amount = amount;
1074             amountSet = true;
1075         }
1076         public void resetAmount() {
1077             amountSet = false;
1078         }
1079         @Override
1080         public ItemType getType() {
1081             return ItemType.transactionRow;
1082         }
1083         public String getAmountHint() {
1084             return amountHint;
1085         }
1086         public void setAmountHint(String amountHint) {
1087             this.amountHint = amountHint;
1088             amountHintIsSet = !TextUtils.isEmpty(amountHint);
1089         }
1090         public String getComment() {
1091             return comment;
1092         }
1093         public void setComment(String comment) {
1094             this.comment = comment;
1095         }
1096         public String getCurrency() {
1097             return currency;
1098         }
1099         public void setCurrency(String currency) {
1100             this.currency = currency;
1101         }
1102         public boolean isAmountValid() {
1103             return amountValid;
1104         }
1105         public void setAmountValid(boolean amountValid) {
1106             this.amountValid = amountValid;
1107         }
1108         public FocusedElement getFocusedElement() {
1109             return focusedElement;
1110         }
1111         public void setFocusedElement(FocusedElement focusedElement) {
1112             this.focusedElement = focusedElement;
1113         }
1114         public boolean isAmountHintSet() {
1115             return amountHintIsSet;
1116         }
1117         public void setAmountHintIsSet(boolean amountHintIsSet) {
1118             this.amountHintIsSet = amountHintIsSet;
1119         }
1120         public boolean isEmpty() {
1121             return !amountSet && Misc.emptyIsNull(accountName) == null &&
1122                    Misc.emptyIsNull(comment) == null;
1123         }
1124         @SuppressLint("DefaultLocale")
1125         @Override
1126         public String toString() {
1127             StringBuilder b = new StringBuilder();
1128             b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1129             if (!TextUtils.isEmpty(accountName))
1130                 b.append(String.format(" acc'%s'", accountName));
1131
1132             if (amountSet)
1133                 b.append(String.format(" %4.2f", amount));
1134             else if (amountHintIsSet)
1135                 b.append(String.format(" (%s)", amountHint));
1136
1137             if (!TextUtils.isEmpty(currency))
1138                 b.append(" ")
1139                  .append(currency);
1140
1141             if (!TextUtils.isEmpty(comment))
1142                 b.append(String.format(" /%s/", comment));
1143
1144             if (isLast)
1145                 b.append(" last");
1146
1147             return b.toString();
1148         }
1149         public boolean equalContents(TransactionAccount other) {
1150             if (other == null)
1151                 return false;
1152
1153             boolean equal = Misc.equalStrings(accountName, other.accountName);
1154             equal = equal && Misc.equalStrings(comment, other.comment) &&
1155                     (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1156
1157             // compare amount hint only if there is no amount
1158             if (!amountSet)
1159                 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1160                                                     Misc.equalStrings(amountHint, other.amountHint)
1161                                                   : !other.amountHintIsSet);
1162             equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1163
1164             Logger.debug("new-trans",
1165                     String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1166                             equal));
1167             return equal;
1168         }
1169         public int getAccountNameCursorPosition() {
1170             return accountNameCursorPosition;
1171         }
1172         public void setAccountNameCursorPosition(int position) {
1173             this.accountNameCursorPosition = position;
1174         }
1175     }
1176
1177     private static class BalanceForCurrency {
1178         private final HashMap<String, Float> hashMap = new HashMap<>();
1179         float get(String currencyName) {
1180             Float f = hashMap.get(currencyName);
1181             if (f == null) {
1182                 f = 0f;
1183                 hashMap.put(currencyName, f);
1184             }
1185             return f;
1186         }
1187         void add(String currencyName, float amount) {
1188             hashMap.put(currencyName, get(currencyName) + amount);
1189         }
1190         Set<String> currencies() {
1191             return hashMap.keySet();
1192         }
1193         boolean containsCurrency(String currencyName) {
1194             return hashMap.containsKey(currencyName);
1195         }
1196     }
1197
1198     private static class ItemsForCurrency {
1199         private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1200         @NonNull
1201         List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1202             List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1203             if (list == null) {
1204                 list = new ArrayList<>();
1205                 hashMap.put(currencyName, list);
1206             }
1207             return list;
1208         }
1209         void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1210             getList(currencyName).add(item);
1211         }
1212         int size(@Nullable String currencyName) {
1213             return this.getList(currencyName)
1214                        .size();
1215         }
1216         Set<String> currencies() {
1217             return hashMap.keySet();
1218         }
1219     }
1220 }