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