4ed8a65d6298c118c208e6dbfbb5a4ec2b8b459f
[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 int id;
869         private Item() {
870             synchronized (Item.class) {
871                 id = ++idDispenser;
872             }
873         }
874         public static Item from(Item origin) {
875             if (origin instanceof TransactionHead)
876                 return new TransactionHead((TransactionHead) origin);
877             if (origin instanceof TransactionAccount)
878                 return new TransactionAccount((TransactionAccount) origin);
879             throw new RuntimeException("Don't know how to handle " + origin);
880         }
881         private static void resetIdDispenser() {
882             idDispenser = 0;
883         }
884         public int getId() {
885             return id;
886         }
887         public abstract ItemType getType();
888         public TransactionHead toTransactionHead() {
889             if (this instanceof TransactionHead)
890                 return (TransactionHead) this;
891
892             throw new IllegalStateException("Wrong item type " + this);
893         }
894         public TransactionAccount toTransactionAccount() {
895             if (this instanceof TransactionAccount)
896                 return (TransactionAccount) this;
897
898             throw new IllegalStateException("Wrong item type " + this);
899         }
900         public boolean equalContents(@Nullable Object item) {
901             if (item == null)
902                 return false;
903
904             if (!getClass().equals(item.getClass()))
905                 return false;
906
907             // shortcut - comparing same instance
908             if (item == this)
909                 return true;
910
911             if (this instanceof TransactionHead)
912                 return ((TransactionHead) item).equalContents((TransactionHead) this);
913             if (this instanceof TransactionAccount)
914                 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
915
916             throw new RuntimeException("Don't know how to handle " + this);
917         }
918     }
919
920
921 //==========================================================================================
922
923     public static class TransactionHead extends Item {
924         private SimpleDate date;
925         private String description;
926         private String comment;
927         TransactionHead(String description) {
928             super();
929             this.description = description;
930         }
931         public TransactionHead(TransactionHead origin) {
932             id = origin.id;
933             date = origin.date;
934             description = origin.description;
935             comment = origin.comment;
936         }
937         public SimpleDate getDate() {
938             return date;
939         }
940         public void setDate(SimpleDate date) {
941             this.date = date;
942         }
943         public void setDate(String text) throws ParseException {
944             if (Misc.emptyIsNull(text) == null) {
945                 date = null;
946                 return;
947             }
948
949             date = Globals.parseLedgerDate(text);
950         }
951         /**
952          * getFormattedDate()
953          *
954          * @return nicely formatted, shortest available date representation
955          */
956         String getFormattedDate() {
957             if (date == null)
958                 return null;
959
960             Calendar today = GregorianCalendar.getInstance();
961
962             if (today.get(Calendar.YEAR) != date.year) {
963                 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
964             }
965
966             if (today.get(Calendar.MONTH) + 1 != date.month) {
967                 return String.format(Locale.US, "%d/%02d", date.month, date.day);
968             }
969
970             return String.valueOf(date.day);
971         }
972         @NonNull
973         @Override
974         public String toString() {
975             @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
976                     String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
977
978             if (TextUtils.isEmpty(description))
979                 b.append(" «no description»");
980             else
981                 b.append(String.format(" '%s'", description));
982
983             if (date != null)
984                 b.append(String.format("@%s", date.toString()));
985
986             if (!TextUtils.isEmpty(comment))
987                 b.append(String.format(" /%s/", comment));
988
989             return b.toString();
990         }
991         public String getDescription() {
992             return description;
993         }
994         public void setDescription(String description) {
995             this.description = description;
996         }
997         public String getComment() {
998             return comment;
999         }
1000         public void setComment(String comment) {
1001             this.comment = comment;
1002         }
1003         @Override
1004         public ItemType getType() {
1005             return ItemType.generalData;
1006         }
1007         public LedgerTransaction asLedgerTransaction() {
1008             return new LedgerTransaction(null, date, description, Data.getProfile());
1009         }
1010         public boolean equalContents(TransactionHead other) {
1011             if (other == null)
1012                 return false;
1013
1014             return Objects.equals(date, other.date) &&
1015                    Misc.equalStrings(description, other.description) &&
1016                    Misc.equalStrings(comment, other.comment);
1017         }
1018     }
1019
1020     public static class TransactionAccount extends Item {
1021         private String accountName;
1022         private String amountHint;
1023         private String comment;
1024         private String currency;
1025         private float amount;
1026         private boolean amountSet;
1027         private boolean amountValid = true;
1028         private FocusedElement focusedElement = FocusedElement.Account;
1029         private boolean amountHintIsSet = false;
1030         private boolean isLast = false;
1031         private int accountNameCursorPosition;
1032         public TransactionAccount(TransactionAccount origin) {
1033             id = origin.id;
1034             accountName = origin.accountName;
1035             amount = origin.amount;
1036             amountSet = origin.amountSet;
1037             amountHint = origin.amountHint;
1038             amountHintIsSet = origin.amountHintIsSet;
1039             comment = origin.comment;
1040             currency = origin.currency;
1041             amountValid = origin.amountValid;
1042             focusedElement = origin.focusedElement;
1043             isLast = origin.isLast;
1044             accountNameCursorPosition = origin.accountNameCursorPosition;
1045         }
1046         public TransactionAccount(LedgerTransactionAccount account) {
1047             super();
1048             currency = account.getCurrency();
1049             amount = account.getAmount();
1050         }
1051         public TransactionAccount(String accountName) {
1052             super();
1053             this.accountName = accountName;
1054         }
1055         public TransactionAccount(String accountName, String currency) {
1056             super();
1057             this.accountName = accountName;
1058             this.currency = currency;
1059         }
1060         public boolean isLast() {
1061             return isLast;
1062         }
1063         public boolean isAmountSet() {
1064             return amountSet;
1065         }
1066         public String getAccountName() {
1067             return accountName;
1068         }
1069         public void setAccountName(String accountName) {
1070             this.accountName = accountName;
1071         }
1072         public float getAmount() {
1073             if (!amountSet)
1074                 throw new IllegalStateException("Amount is not set");
1075             return amount;
1076         }
1077         public void setAmount(float amount) {
1078             this.amount = amount;
1079             amountSet = true;
1080         }
1081         public void resetAmount() {
1082             amountSet = false;
1083         }
1084         @Override
1085         public ItemType getType() {
1086             return ItemType.transactionRow;
1087         }
1088         public String getAmountHint() {
1089             return amountHint;
1090         }
1091         public void setAmountHint(String amountHint) {
1092             this.amountHint = amountHint;
1093             amountHintIsSet = !TextUtils.isEmpty(amountHint);
1094         }
1095         public String getComment() {
1096             return comment;
1097         }
1098         public void setComment(String comment) {
1099             this.comment = comment;
1100         }
1101         public String getCurrency() {
1102             return currency;
1103         }
1104         public void setCurrency(String currency) {
1105             this.currency = currency;
1106         }
1107         public boolean isAmountValid() {
1108             return amountValid;
1109         }
1110         public void setAmountValid(boolean amountValid) {
1111             this.amountValid = amountValid;
1112         }
1113         public FocusedElement getFocusedElement() {
1114             return focusedElement;
1115         }
1116         public void setFocusedElement(FocusedElement focusedElement) {
1117             this.focusedElement = focusedElement;
1118         }
1119         public boolean isAmountHintSet() {
1120             return amountHintIsSet;
1121         }
1122         public void setAmountHintIsSet(boolean amountHintIsSet) {
1123             this.amountHintIsSet = amountHintIsSet;
1124         }
1125         public boolean isEmpty() {
1126             return !amountSet && Misc.emptyIsNull(accountName) == null &&
1127                    Misc.emptyIsNull(comment) == null;
1128         }
1129         @SuppressLint("DefaultLocale")
1130         @Override
1131         public String toString() {
1132             StringBuilder b = new StringBuilder();
1133             b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1134             if (!TextUtils.isEmpty(accountName))
1135                 b.append(String.format(" acc'%s'", accountName));
1136
1137             if (amountSet)
1138                 b.append(String.format(" %4.2f", amount));
1139             else if (amountHintIsSet)
1140                 b.append(String.format(" (%s)", amountHint));
1141
1142             if (!TextUtils.isEmpty(currency))
1143                 b.append(" ")
1144                  .append(currency);
1145
1146             if (!TextUtils.isEmpty(comment))
1147                 b.append(String.format(" /%s/", comment));
1148
1149             if (isLast)
1150                 b.append(" last");
1151
1152             return b.toString();
1153         }
1154         public boolean equalContents(TransactionAccount other) {
1155             if (other == null)
1156                 return false;
1157
1158             boolean equal = Misc.equalStrings(accountName, other.accountName);
1159             equal = equal && Misc.equalStrings(comment, other.comment) &&
1160                     (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1161
1162             // compare amount hint only if there is no amount
1163             if (!amountSet)
1164                 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1165                                                     Misc.equalStrings(amountHint, other.amountHint)
1166                                                   : !other.amountHintIsSet);
1167             equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1168
1169             Logger.debug("new-trans",
1170                     String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1171                             equal));
1172             return equal;
1173         }
1174         public int getAccountNameCursorPosition() {
1175             return accountNameCursorPosition;
1176         }
1177         public void setAccountNameCursorPosition(int position) {
1178             this.accountNameCursorPosition = position;
1179         }
1180     }
1181
1182     private static class BalanceForCurrency {
1183         private final HashMap<String, Float> hashMap = new HashMap<>();
1184         float get(String currencyName) {
1185             Float f = hashMap.get(currencyName);
1186             if (f == null) {
1187                 f = 0f;
1188                 hashMap.put(currencyName, f);
1189             }
1190             return f;
1191         }
1192         void add(String currencyName, float amount) {
1193             hashMap.put(currencyName, get(currencyName) + amount);
1194         }
1195         Set<String> currencies() {
1196             return hashMap.keySet();
1197         }
1198         boolean containsCurrency(String currencyName) {
1199             return hashMap.containsKey(currencyName);
1200         }
1201     }
1202
1203     private static class ItemsForCurrency {
1204         private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1205         @NonNull
1206         List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1207             List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1208             if (list == null) {
1209                 list = new ArrayList<>();
1210                 hashMap.put(currencyName, list);
1211             }
1212             return list;
1213         }
1214         void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1215             getList(currencyName).add(item);
1216         }
1217         int size(@Nullable String currencyName) {
1218             return this.getList(currencyName)
1219                        .size();
1220         }
1221         Set<String> currencies() {
1222             return hashMap.keySet();
1223         }
1224     }
1225 }