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