]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/new_transaction/NewTransactionModel.java
2bcf82fb8d46ce3d54d193436087eaf4bba83ba4
[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         LedgerTransaction tr = head.asLedgerTransaction();
430
431         tr.setComment(head.getComment());
432         LedgerTransactionAccount emptyAmountAccount = null;
433         float emptyAmountAccountBalance = 0;
434         for (int i = 1; i < list.size(); i++) {
435             TransactionAccount item = list.get(i)
436                                           .toTransactionAccount();
437             LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
438                                                                             .trim(),
439                     item.getCurrency());
440             if (acc.getAccountName()
441                    .isEmpty())
442                 continue;
443
444             acc.setComment(item.getComment());
445
446             if (item.isAmountSet()) {
447                 acc.setAmount(item.getAmount());
448                 emptyAmountAccountBalance += item.getAmount();
449             }
450             else {
451                 emptyAmountAccount = acc;
452             }
453
454             tr.addAccount(acc);
455         }
456
457         if (emptyAmountAccount != null)
458             emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
459
460         return tr;
461     }
462     void loadTransactionIntoModel(@NonNull TransactionWithAccounts tr) {
463         List<Item> newList = new ArrayList<>();
464         Item.resetIdDispenser();
465
466         TransactionHead head = new TransactionHead(tr.transaction.getDescription());
467         head.setComment(tr.transaction.getComment());
468
469         newList.add(head);
470
471         List<LedgerTransactionAccount> accounts = new ArrayList<>();
472         for (net.ktnx.mobileledger.db.TransactionAccount acc : tr.accounts) {
473             accounts.add(new LedgerTransactionAccount(acc));
474         }
475
476         TransactionAccount firstNegative = null;
477         TransactionAccount firstPositive = null;
478         int singleNegativeIndex = -1;
479         int singlePositiveIndex = -1;
480         int negativeCount = 0;
481         for (int i = 0; i < accounts.size(); i++) {
482             LedgerTransactionAccount acc = accounts.get(i);
483             TransactionAccount item =
484                     new TransactionAccount(acc.getAccountName(), acc.getCurrency());
485             newList.add(item);
486
487             item.setAccountName(acc.getAccountName());
488             item.setComment(acc.getComment());
489             if (acc.isAmountSet()) {
490                 item.setAmount(acc.getAmount());
491                 if (acc.getAmount() < 0) {
492                     if (firstNegative == null) {
493                         firstNegative = item;
494                         singleNegativeIndex = i + 1;
495                     }
496                     else
497                         singleNegativeIndex = -1;
498                 }
499                 else {
500                     if (firstPositive == null) {
501                         firstPositive = item;
502                         singlePositiveIndex = i + 1;
503                     }
504                     else
505                         singlePositiveIndex = -1;
506                 }
507             }
508             else
509                 item.resetAmount();
510         }
511         if (BuildConfig.DEBUG)
512             dumpItemList("Loaded previous transaction", newList);
513
514         if (singleNegativeIndex != -1) {
515             firstNegative.resetAmount();
516             moveItemLast(newList, singleNegativeIndex);
517         }
518         else if (singlePositiveIndex != -1) {
519             firstPositive.resetAmount();
520             moveItemLast(newList, singlePositiveIndex);
521         }
522
523         Misc.onMainThread(() -> {
524             setItems(newList);
525             noteFocusChanged(1, FocusedElement.Amount);
526         });
527     }
528     /**
529      * A transaction is submittable if:
530      * 0) has description
531      * 1) has at least two account names
532      * 2) each row with amount has account name
533      * 3) for each commodity:
534      * 3a) amounts must balance to 0, or
535      * 3b) there must be exactly one empty amount (with account)
536      * 4) empty accounts with empty amounts are ignored
537      * Side effects:
538      * 5) a row with an empty account name or empty amount is guaranteed to exist for each
539      * commodity
540      * 6) at least two rows need to be present in the ledger
541      *
542      * @param list - the item list to check. Can be the displayed list or a list that will be
543      *             displayed soon
544      */
545     @SuppressLint("DefaultLocale")
546     void checkTransactionSubmittable(@Nullable List<Item> list) {
547         boolean workingWithLiveList = false;
548         if (list == null) {
549             list = copyList();
550             workingWithLiveList = true;
551         }
552
553         if (BuildConfig.DEBUG)
554             dumpItemList(String.format("Before submittable checks (%s)",
555                     workingWithLiveList ? "LIVE LIST" : "custom list"), list);
556
557         int accounts = 0;
558         final BalanceForCurrency balance = new BalanceForCurrency();
559         final String descriptionText = list.get(0)
560                                            .toTransactionHead()
561                                            .getDescription();
562         boolean submittable = true;
563         boolean listChanged = false;
564         final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
565         final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
566         final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
567         final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
568         final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
569         final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
570         final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
571         final List<Item> emptyRows = new ArrayList<>();
572
573         try {
574             if ((descriptionText == null) || descriptionText.trim()
575                                                             .isEmpty())
576             {
577                 Logger.debug("submittable", "Transaction not submittable: missing description");
578                 submittable = false;
579             }
580
581             for (int i = 1; i < list.size(); i++) {
582                 TransactionAccount item = list.get(i)
583                                               .toTransactionAccount();
584
585                 String accName = item.getAccountName()
586                                      .trim();
587                 String currName = item.getCurrency();
588
589                 itemsForCurrency.add(currName, item);
590
591                 if (accName.isEmpty()) {
592                     itemsWithEmptyAccountForCurrency.add(currName, item);
593
594                     if (item.isAmountSet()) {
595                         // 2) each amount has account name
596                         Logger.debug("submittable", String.format(
597                                 "Transaction not submittable: row %d has no account name, but" +
598                                 " has" + " amount %1.2f", i + 1, item.getAmount()));
599                         submittable = false;
600                     }
601                     else {
602                         emptyRowsForCurrency.add(currName, item);
603                     }
604                 }
605                 else {
606                     accounts++;
607                     itemsWithAccountForCurrency.add(currName, item);
608                 }
609
610                 if (!item.isAmountValid()) {
611                     Logger.debug("submittable",
612                             String.format("Not submittable: row %d has an invalid amount", i + 1));
613                     submittable = false;
614                 }
615                 else if (item.isAmountSet()) {
616                     itemsWithAmountForCurrency.add(currName, item);
617                     balance.add(currName, item.getAmount());
618                 }
619                 else {
620                     itemsWithEmptyAmountForCurrency.add(currName, item);
621
622                     if (!accName.isEmpty())
623                         itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
624                 }
625             }
626
627             // 1) has at least two account names
628             if (accounts < 2) {
629                 if (accounts == 0)
630                     Logger.debug("submittable", "Transaction not submittable: no account names");
631                 else if (accounts == 1)
632                     Logger.debug("submittable",
633                             "Transaction not submittable: only one account name");
634                 else
635                     Logger.debug("submittable",
636                             String.format("Transaction not submittable: only %d account names",
637                                     accounts));
638                 submittable = false;
639             }
640
641             // 3) for each commodity:
642             // 3a) amount must balance to 0, or
643             // 3b) there must be exactly one empty amount (with account)
644             for (String balCurrency : itemsForCurrency.currencies()) {
645                 float currencyBalance = balance.get(balCurrency);
646                 if (Misc.isZero(currencyBalance)) {
647                     // remove hints from all amount inputs in that currency
648                     for (int i = 1; i < list.size(); i++) {
649                         TransactionAccount acc = list.get(i)
650                                                      .toTransactionAccount();
651                         if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
652                             if (BuildConfig.DEBUG)
653                                 Logger.debug("submittable",
654                                         String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
655                                                 i, Misc.nullIsEmpty(acc.getAccountName()),
656                                                 balCurrency));
657                             // skip if the amount is set, in which case the hint is not
658                             // important/visible
659                             if (!acc.isAmountSet() && acc.amountHintIsSet &&
660                                 !TextUtils.isEmpty(acc.getAmountHint()))
661                             {
662                                 acc.setAmountHint(null);
663                                 listChanged = true;
664                             }
665                         }
666                     }
667                 }
668                 else {
669                     List<Item> tmpList =
670                             itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
671                     int balanceReceiversCount = tmpList.size();
672                     if (balanceReceiversCount != 1) {
673                         if (BuildConfig.DEBUG) {
674                             if (balanceReceiversCount == 0)
675                                 Logger.debug("submittable", String.format(
676                                         "Transaction not submittable [%s]: non-zero balance " +
677                                         "with no empty amounts with accounts", balCurrency));
678                             else
679                                 Logger.debug("submittable", String.format(
680                                         "Transaction not submittable [%s]: non-zero balance " +
681                                         "with multiple empty amounts with accounts", balCurrency));
682                         }
683                         submittable = false;
684                     }
685
686                     List<Item> emptyAmountList =
687                             itemsWithEmptyAmountForCurrency.getList(balCurrency);
688
689                     // suggest off-balance amount to a row and remove hints on other rows
690                     Item receiver = null;
691                     if (!tmpList.isEmpty())
692                         receiver = tmpList.get(0);
693                     else if (!emptyAmountList.isEmpty())
694                         receiver = emptyAmountList.get(0);
695
696                     for (int i = 0; i < list.size(); i++) {
697                         Item item = list.get(i);
698                         if (!(item instanceof TransactionAccount))
699                             continue;
700
701                         TransactionAccount acc = item.toTransactionAccount();
702                         if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
703                             continue;
704
705                         if (item == receiver) {
706                             final String hint = String.format("%1.2f", -currencyBalance);
707                             if (!acc.isAmountHintSet() ||
708                                 !Misc.equalStrings(acc.getAmountHint(), hint))
709                             {
710                                 Logger.debug("submittable",
711                                         String.format("Setting amount hint of {%s} to %s [%s]",
712                                                 acc.toString(), hint, balCurrency));
713                                 acc.setAmountHint(hint);
714                                 listChanged = true;
715                             }
716                         }
717                         else {
718                             if (BuildConfig.DEBUG)
719                                 Logger.debug("submittable",
720                                         String.format("Resetting hint of '%s' [%s]",
721                                                 Misc.nullIsEmpty(acc.getAccountName()),
722                                                 balCurrency));
723                             if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
724                                 acc.setAmountHint(null);
725                                 listChanged = true;
726                             }
727                         }
728                     }
729                 }
730             }
731
732             // 5) a row with an empty account name or empty amount is guaranteed to exist for
733             // each commodity
734             for (String balCurrency : balance.currencies()) {
735                 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
736                 int currRows = itemsForCurrency.size(balCurrency);
737                 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
738                 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
739                 if ((currEmptyRows == 0) &&
740                     ((currRows == currAccounts) || (currRows == currAmounts)))
741                 {
742                     // perhaps there already is an unused empty row for another currency that
743                     // is not used?
744 //                        boolean foundIt = false;
745 //                        for (Item item : emptyRows) {
746 //                            Currency itemCurrency = item.getCurrency();
747 //                            String itemCurrencyName =
748 //                                    (itemCurrency == null) ? "" : itemCurrency.getName();
749 //                            if (Misc.isZero(balance.get(itemCurrencyName))) {
750 //                                item.setCurrency(Currency.loadByName(balCurrency));
751 //                                item.setAmountHint(
752 //                                        String.format("%1.2f", -balance.get(balCurrency)));
753 //                                foundIt = true;
754 //                                break;
755 //                            }
756 //                        }
757 //
758 //                        if (!foundIt)
759                     final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
760                     final float bal = balance.get(balCurrency);
761                     if (!Misc.isZero(bal) && currAmounts == currRows)
762                         newAcc.setAmountHint(String.format("%4.2f", -bal));
763                     Logger.debug("submittable",
764                             String.format("Adding new item with %s for currency %s",
765                                     newAcc.getAmountHint(), balCurrency));
766                     list.add(newAcc);
767                     listChanged = true;
768                 }
769             }
770
771             // drop extra empty rows, not needed
772             for (String currName : emptyRowsForCurrency.currencies()) {
773                 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
774                 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
775                     // the list is a copy, so the empty item is no longer present
776                     Item itemToRemove = emptyItems.remove(1);
777                     removeItemById(list, itemToRemove.id);
778                     listChanged = true;
779                 }
780
781                 // unused currency, remove last item (which is also an empty one)
782                 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
783                     List<Item> currItems = itemsForCurrency.getList(currName);
784
785                     if (currItems.size() == 1) {
786                         // the list is a copy, so the empty item is no longer present
787                         removeItemById(list, emptyItems.get(0).id);
788                         listChanged = true;
789                     }
790                 }
791             }
792
793             // 6) at least two rows need to be present in the ledger
794             //    (the list also contains header and trailer)
795             while (list.size() < MIN_ITEMS) {
796                 list.add(new TransactionAccount(""));
797                 listChanged = true;
798             }
799
800             Logger.debug("submittable", submittable ? "YES" : "NO");
801             isSubmittable.setValue(submittable);
802
803             if (BuildConfig.DEBUG)
804                 dumpItemList("After submittable checks", list);
805         }
806         catch (NumberFormatException e) {
807             Logger.debug("submittable", "NO (because of NumberFormatException)");
808             isSubmittable.setValue(false);
809         }
810         catch (Exception e) {
811             e.printStackTrace();
812             Logger.debug("submittable", "NO (because of an Exception)");
813             isSubmittable.setValue(false);
814         }
815
816         if (listChanged && workingWithLiveList) {
817             setItemsWithoutSubmittableChecks(list);
818         }
819     }
820     private void removeItemById(@NotNull List<Item> list, int id) {
821         if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
822             list.removeIf(item -> item.id == id);
823         }
824         else {
825             for (Item item : list) {
826                 if (item.id == id) {
827                     list.remove(item);
828                     break;
829                 }
830             }
831         }
832     }
833     @SuppressLint("DefaultLocale")
834     private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
835         Logger.debug("submittable", "== Dump of all items " + msg);
836         for (int i = 1; i < list.size(); i++) {
837             TransactionAccount item = list.get(i)
838                                           .toTransactionAccount();
839             Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
840         }
841     }
842     public void setItemCurrency(int position, String newCurrency) {
843         TransactionAccount item = Objects.requireNonNull(items.getValue())
844                                          .get(position)
845                                          .toTransactionAccount();
846         final String oldCurrency = item.getCurrency();
847
848         if (Misc.equalStrings(oldCurrency, newCurrency))
849             return;
850
851         List<Item> newList = copyList();
852         newList.get(position)
853                .toTransactionAccount()
854                .setCurrency(newCurrency);
855
856         setItems(newList);
857     }
858     public boolean accountListIsEmpty() {
859         List<Item> items = Objects.requireNonNull(this.items.getValue());
860
861         for (Item item : items) {
862             if (!(item instanceof TransactionAccount))
863                 continue;
864
865             if (!((TransactionAccount) item).isEmpty())
866                 return false;
867         }
868
869         return true;
870     }
871
872     public static class FocusInfo {
873         int position;
874         FocusedElement element;
875         public FocusInfo(int position, FocusedElement element) {
876             this.position = position;
877             this.element = element;
878         }
879     }
880
881     static abstract class Item {
882         private static int idDispenser = 0;
883         protected int id;
884         private Item() {
885             if (this instanceof TransactionHead)
886                 id = 0;
887             else
888                 synchronized (Item.class) {
889                     id = ++idDispenser;
890                 }
891         }
892         public Item(int id) {
893             this.id = id;
894         }
895         public static Item from(Item origin) {
896             if (origin instanceof TransactionHead)
897                 return new TransactionHead((TransactionHead) origin);
898             if (origin instanceof TransactionAccount)
899                 return new TransactionAccount((TransactionAccount) origin);
900             throw new RuntimeException("Don't know how to handle " + origin);
901         }
902         private static void resetIdDispenser() {
903             idDispenser = 0;
904         }
905         public int getId() {
906             return id;
907         }
908         public abstract ItemType getType();
909         public TransactionHead toTransactionHead() {
910             if (this instanceof TransactionHead)
911                 return (TransactionHead) this;
912
913             throw new IllegalStateException("Wrong item type " + this);
914         }
915         public TransactionAccount toTransactionAccount() {
916             if (this instanceof TransactionAccount)
917                 return (TransactionAccount) this;
918
919             throw new IllegalStateException("Wrong item type " + this);
920         }
921         public boolean equalContents(@Nullable Object item) {
922             if (item == null)
923                 return false;
924
925             if (!getClass().equals(item.getClass()))
926                 return false;
927
928             // shortcut - comparing same instance
929             if (item == this)
930                 return true;
931
932             if (this instanceof TransactionHead)
933                 return ((TransactionHead) item).equalContents((TransactionHead) this);
934             if (this instanceof TransactionAccount)
935                 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
936
937             throw new RuntimeException("Don't know how to handle " + this);
938         }
939     }
940
941
942 //==========================================================================================
943
944     public static class TransactionHead extends Item {
945         private SimpleDate date;
946         private String description;
947         private String comment;
948         TransactionHead(String description) {
949             super();
950             this.description = description;
951         }
952         public TransactionHead(TransactionHead origin) {
953             super(origin.id);
954             date = origin.date;
955             description = origin.description;
956             comment = origin.comment;
957         }
958         public SimpleDate getDate() {
959             return date;
960         }
961         public void setDate(SimpleDate date) {
962             this.date = date;
963         }
964         public void setDate(String text) throws ParseException {
965             if (Misc.emptyIsNull(text) == null) {
966                 date = null;
967                 return;
968             }
969
970             date = Globals.parseLedgerDate(text);
971         }
972         /**
973          * getFormattedDate()
974          *
975          * @return nicely formatted, shortest available date representation
976          */
977         String getFormattedDate() {
978             if (date == null)
979                 return null;
980
981             Calendar today = GregorianCalendar.getInstance();
982
983             if (today.get(Calendar.YEAR) != date.year) {
984                 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
985             }
986
987             if (today.get(Calendar.MONTH) + 1 != date.month) {
988                 return String.format(Locale.US, "%d/%02d", date.month, date.day);
989             }
990
991             return String.valueOf(date.day);
992         }
993         @NonNull
994         @Override
995         public String toString() {
996             @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
997                     String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
998
999             if (TextUtils.isEmpty(description))
1000                 b.append(" «no description»");
1001             else
1002                 b.append(String.format(" '%s'", description));
1003
1004             if (date != null)
1005                 b.append(String.format("@%s", date.toString()));
1006
1007             if (!TextUtils.isEmpty(comment))
1008                 b.append(String.format(" /%s/", comment));
1009
1010             return b.toString();
1011         }
1012         public String getDescription() {
1013             return description;
1014         }
1015         public void setDescription(String description) {
1016             this.description = description;
1017         }
1018         public String getComment() {
1019             return comment;
1020         }
1021         public void setComment(String comment) {
1022             this.comment = comment;
1023         }
1024         @Override
1025         public ItemType getType() {
1026             return ItemType.generalData;
1027         }
1028         public LedgerTransaction asLedgerTransaction() {
1029             return new LedgerTransaction(0, (date == null) ? SimpleDate.today() : date, description,
1030                     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 }