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