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