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