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