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