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