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