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