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