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