]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/new_transaction/NewTransactionModel.java
a87cb22fade82ed0d6c6d5edb5e6983425460879
[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(-emptyAmountAccountBalance.get(currency));
491                 });
492             }
493             else {
494                 for (String currency : emptyAmountAccounts.keySet()) {
495                     List<LedgerTransactionAccount> accounts =
496                             Objects.requireNonNull(emptyAmountAccounts.get(currency));
497
498                     if (accounts.size() != 1)
499                         throw new RuntimeException(String.format(Locale.US,
500                                 "Should not happen: approved transaction has %d accounts for " +
501                                 "currency %s", accounts.size(), currency));
502                     accounts.get(0)
503                             .setAmount(-emptyAmountAccountBalance.get(currency));
504                 }
505             }
506         }
507
508         return tr;
509     }
510     void loadTransactionIntoModel(@NonNull TransactionWithAccounts tr) {
511         List<Item> newList = new ArrayList<>();
512         Item.resetIdDispenser();
513
514         Item currentHead = Objects.requireNonNull(items.getValue())
515                                   .get(0);
516         TransactionHead head = new TransactionHead(tr.transaction.getDescription());
517         head.setComment(tr.transaction.getComment());
518         if (currentHead instanceof TransactionHead)
519             head.setDate(((TransactionHead) currentHead).date);
520
521         newList.add(head);
522
523         List<LedgerTransactionAccount> accounts = new ArrayList<>();
524         for (net.ktnx.mobileledger.db.TransactionAccount acc : tr.accounts) {
525             accounts.add(new LedgerTransactionAccount(acc));
526         }
527
528         TransactionAccount firstNegative = null;
529         TransactionAccount firstPositive = null;
530         int singleNegativeIndex = -1;
531         int singlePositiveIndex = -1;
532         int negativeCount = 0;
533         for (int i = 0; i < accounts.size(); i++) {
534             LedgerTransactionAccount acc = accounts.get(i);
535             TransactionAccount item = new TransactionAccount(acc.getAccountName(),
536                     Misc.nullIsEmpty(acc.getCurrency()));
537             newList.add(item);
538
539             item.setAccountName(acc.getAccountName());
540             item.setComment(acc.getComment());
541             if (acc.isAmountSet()) {
542                 item.setAmount(acc.getAmount());
543                 if (acc.getAmount() < 0) {
544                     if (firstNegative == null) {
545                         firstNegative = item;
546                         singleNegativeIndex = i + 1;
547                     }
548                     else
549                         singleNegativeIndex = -1;
550                 }
551                 else {
552                     if (firstPositive == null) {
553                         firstPositive = item;
554                         singlePositiveIndex = i + 1;
555                     }
556                     else
557                         singlePositiveIndex = -1;
558                 }
559             }
560             else
561                 item.resetAmount();
562         }
563         if (BuildConfig.DEBUG)
564             dumpItemList("Loaded previous transaction", newList);
565
566         if (singleNegativeIndex != -1) {
567             firstNegative.resetAmount();
568             moveItemLast(newList, singleNegativeIndex);
569         }
570         else if (singlePositiveIndex != -1) {
571             firstPositive.resetAmount();
572             moveItemLast(newList, singlePositiveIndex);
573         }
574
575         Misc.onMainThread(() -> {
576             setItems(newList);
577             noteFocusChanged(1, FocusedElement.Amount);
578         });
579     }
580     /**
581      * A transaction is submittable if:
582      * 0) has description
583      * 1) has at least two account names
584      * 2) each row with amount has account name
585      * 3) for each commodity:
586      * 3a) amounts must balance to 0, or
587      * 3b) there must be exactly one empty amount (with account)
588      * 4) empty accounts with empty amounts are ignored
589      * Side effects:
590      * 5) a row with an empty account name or empty amount is guaranteed to exist for each
591      * commodity
592      * 6) at least two rows need to be present in the ledger
593      *
594      * @param list - the item list to check. Can be the displayed list or a list that will be
595      *             displayed soon
596      */
597     @SuppressLint("DefaultLocale")
598     void checkTransactionSubmittable(@Nullable List<Item> list) {
599         boolean workingWithLiveList = false;
600         if (list == null) {
601             list = copyList();
602             workingWithLiveList = true;
603         }
604
605         if (BuildConfig.DEBUG)
606             dumpItemList(String.format("Before submittable checks (%s)",
607                     workingWithLiveList ? "LIVE LIST" : "custom list"), list);
608
609         int accounts = 0;
610         final BalanceForCurrency balance = new BalanceForCurrency();
611         final String descriptionText = list.get(0)
612                                            .toTransactionHead()
613                                            .getDescription();
614         boolean submittable = true;
615         boolean listChanged = false;
616         final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
617         final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
618         final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
619         final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
620         final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
621         final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
622         final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
623         final List<Item> emptyRows = new ArrayList<>();
624
625         try {
626             if ((descriptionText == null) || descriptionText.trim()
627                                                             .isEmpty())
628             {
629                 Logger.debug("submittable", "Transaction not submittable: missing description");
630                 submittable = false;
631             }
632
633             boolean hasInvalidAmount = false;
634
635             for (int i = 1; i < list.size(); i++) {
636                 TransactionAccount item = list.get(i)
637                                               .toTransactionAccount();
638
639                 String accName = item.getAccountName()
640                                      .trim();
641                 String currName = item.getCurrency();
642
643                 itemsForCurrency.add(currName, item);
644
645                 if (accName.isEmpty()) {
646                     itemsWithEmptyAccountForCurrency.add(currName, item);
647
648                     if (item.isAmountSet()) {
649                         // 2) each amount has account name
650                         Logger.debug("submittable", String.format(
651                                 "Transaction not submittable: row %d has no account name, but" +
652                                 " has" + " amount %1.2f", i + 1, item.getAmount()));
653                         submittable = false;
654                     }
655                     else {
656                         emptyRowsForCurrency.add(currName, item);
657                     }
658                 }
659                 else {
660                     accounts++;
661                     itemsWithAccountForCurrency.add(currName, item);
662                 }
663
664                 if (item.isAmountSet() && item.isAmountValid()) {
665                     itemsWithAmountForCurrency.add(currName, item);
666                     balance.add(currName, item.getAmount());
667                 }
668                 else {
669                     if (!item.isAmountValid()) {
670                         Logger.debug("submittable",
671                                 String.format("Not submittable: row %d has an invalid amount", i));
672                         submittable = false;
673                         hasInvalidAmount = true;
674                     }
675
676                     itemsWithEmptyAmountForCurrency.add(currName, item);
677
678                     if (!accName.isEmpty())
679                         itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
680                 }
681             }
682
683             // 1) has at least two account names
684             if (accounts < 2) {
685                 if (accounts == 0)
686                     Logger.debug("submittable", "Transaction not submittable: no account names");
687                 else if (accounts == 1)
688                     Logger.debug("submittable",
689                             "Transaction not submittable: only one account name");
690                 else
691                     Logger.debug("submittable",
692                             String.format("Transaction not submittable: only %d account names",
693                                     accounts));
694                 submittable = false;
695             }
696
697             // 3) for each commodity:
698             // 3a) amount must balance to 0, or
699             // 3b) there must be exactly one empty amount (with account)
700             for (String balCurrency : itemsForCurrency.currencies()) {
701                 float currencyBalance = balance.get(balCurrency);
702                 if (Misc.isZero(currencyBalance)) {
703                     // remove hints from all amount inputs in that currency
704                     for (int i = 1; i < list.size(); i++) {
705                         TransactionAccount acc = list.get(i)
706                                                      .toTransactionAccount();
707                         if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
708                             if (BuildConfig.DEBUG)
709                                 Logger.debug("submittable",
710                                         String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
711                                                 i, Misc.nullIsEmpty(acc.getAccountName()),
712                                                 balCurrency));
713                             // skip if the amount is set, in which case the hint is not
714                             // important/visible
715                             if (!acc.isAmountSet() && acc.amountHintIsSet &&
716                                 !TextUtils.isEmpty(acc.getAmountHint()))
717                             {
718                                 acc.setAmountHint(null);
719                                 listChanged = true;
720                             }
721                         }
722                     }
723                 }
724                 else {
725                     List<Item> tmpList =
726                             itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
727                     int balanceReceiversCount = tmpList.size();
728                     if (balanceReceiversCount != 1) {
729                         if (BuildConfig.DEBUG) {
730                             if (balanceReceiversCount == 0)
731                                 Logger.debug("submittable", String.format(
732                                         "Transaction not submittable [curr:%s]: non-zero balance " +
733                                         "with no empty amounts with accounts", balCurrency));
734                             else
735                                 Logger.debug("submittable", String.format(
736                                         "Transaction not submittable [curr:%s]: non-zero balance " +
737                                         "with multiple empty amounts with accounts", balCurrency));
738                         }
739                         submittable = false;
740                     }
741
742                     List<Item> emptyAmountList =
743                             itemsWithEmptyAmountForCurrency.getList(balCurrency);
744
745                     // suggest off-balance amount to a row and remove hints on other rows
746                     Item receiver = null;
747                     if (!tmpList.isEmpty())
748                         receiver = tmpList.get(0);
749                     else if (!emptyAmountList.isEmpty())
750                         receiver = emptyAmountList.get(0);
751
752                     for (int i = 0; i < list.size(); i++) {
753                         Item item = list.get(i);
754                         if (!(item instanceof TransactionAccount))
755                             continue;
756
757                         TransactionAccount acc = item.toTransactionAccount();
758                         if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
759                             continue;
760
761                         if (item == receiver) {
762                             final String hint = Data.formatNumber(-currencyBalance);
763                             if (!acc.isAmountHintSet() ||
764                                 !Misc.equalStrings(acc.getAmountHint(), hint))
765                             {
766                                 Logger.debug("submittable",
767                                         String.format("Setting amount hint of {%s} to %s [%s]",
768                                                 acc.toString(), hint, balCurrency));
769                                 acc.setAmountHint(hint);
770                                 listChanged = true;
771                             }
772                         }
773                         else {
774                             if (BuildConfig.DEBUG)
775                                 Logger.debug("submittable",
776                                         String.format("Resetting hint of '%s' [%s]",
777                                                 Misc.nullIsEmpty(acc.getAccountName()),
778                                                 balCurrency));
779                             if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
780                                 acc.setAmountHint(null);
781                                 listChanged = true;
782                             }
783                         }
784                     }
785                 }
786             }
787
788             // 5) a row with an empty account name or empty amount is guaranteed to exist for
789             // each commodity
790             if (!hasInvalidAmount) {
791                 for (String balCurrency : balance.currencies()) {
792                     int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
793                     int currRows = itemsForCurrency.size(balCurrency);
794                     int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
795                     int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
796                     if ((currEmptyRows == 0) &&
797                         ((currRows == currAccounts) || (currRows == currAmounts)))
798                     {
799                         // perhaps there already is an unused empty row for another currency that
800                         // is not used?
801 //                        boolean foundIt = false;
802 //                        for (Item item : emptyRows) {
803 //                            Currency itemCurrency = item.getCurrency();
804 //                            String itemCurrencyName =
805 //                                    (itemCurrency == null) ? "" : itemCurrency.getName();
806 //                            if (Misc.isZero(balance.get(itemCurrencyName))) {
807 //                                item.setCurrency(Currency.loadByName(balCurrency));
808 //                                item.setAmountHint(
809 //                                        Data.formatNumber(-balance.get(balCurrency)));
810 //                                foundIt = true;
811 //                                break;
812 //                            }
813 //                        }
814 //
815 //                        if (!foundIt)
816                         final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
817                         final float bal = balance.get(balCurrency);
818                         if (!Misc.isZero(bal) && currAmounts == currRows)
819                             newAcc.setAmountHint(Data.formatNumber(-bal));
820                         Logger.debug("submittable",
821                                 String.format("Adding new item with %s for currency %s",
822                                         newAcc.getAmountHint(), balCurrency));
823                         list.add(newAcc);
824                         listChanged = true;
825                     }
826                 }
827             }
828
829             // drop extra empty rows, not needed
830             for (String currName : emptyRowsForCurrency.currencies()) {
831                 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
832                 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
833                     // the list is a copy, so the empty item is no longer present
834                     Item itemToRemove = emptyItems.remove(1);
835                     removeItemById(list, itemToRemove.id);
836                     listChanged = true;
837                 }
838
839                 // unused currency, remove last item (which is also an empty one)
840                 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
841                     List<Item> currItems = itemsForCurrency.getList(currName);
842
843                     if (currItems.size() == 1) {
844                         // the list is a copy, so the empty item is no longer present
845                         removeItemById(list, emptyItems.get(0).id);
846                         listChanged = true;
847                     }
848                 }
849             }
850
851             // 6) at least two rows need to be present in the ledger
852             //    (the list also contains header and trailer)
853             while (list.size() < MIN_ITEMS) {
854                 list.add(new TransactionAccount(""));
855                 listChanged = true;
856             }
857
858             Logger.debug("submittable", submittable ? "YES" : "NO");
859             isSubmittable.setValue(submittable);
860
861             if (BuildConfig.DEBUG)
862                 dumpItemList("After submittable checks", list);
863         }
864         catch (NumberFormatException e) {
865             Logger.debug("submittable", "NO (because of NumberFormatException)");
866             isSubmittable.setValue(false);
867         }
868         catch (Exception e) {
869             e.printStackTrace();
870             Logger.debug("submittable", "NO (because of an Exception)");
871             isSubmittable.setValue(false);
872         }
873
874         if (listChanged && workingWithLiveList) {
875             setItemsWithoutSubmittableChecks(list);
876         }
877     }
878     private void removeItemById(@NotNull List<Item> list, int id) {
879         if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
880             list.removeIf(item -> item.id == id);
881         }
882         else {
883             for (Item item : list) {
884                 if (item.id == id) {
885                     list.remove(item);
886                     break;
887                 }
888             }
889         }
890     }
891     @SuppressLint("DefaultLocale")
892     private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
893         Logger.debug("submittable", "== Dump of all items " + msg);
894         for (int i = 1; i < list.size(); i++) {
895             TransactionAccount item = list.get(i)
896                                           .toTransactionAccount();
897             Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
898         }
899     }
900     public void setItemCurrency(int position, String newCurrency) {
901         TransactionAccount item = Objects.requireNonNull(items.getValue())
902                                          .get(position)
903                                          .toTransactionAccount();
904         final String oldCurrency = item.getCurrency();
905
906         if (Misc.equalStrings(oldCurrency, newCurrency))
907             return;
908
909         List<Item> newList = copyList();
910         newList.get(position)
911                .toTransactionAccount()
912                .setCurrency(newCurrency);
913
914         setItems(newList);
915     }
916     public boolean accountListIsEmpty() {
917         List<Item> items = Objects.requireNonNull(this.items.getValue());
918
919         for (Item item : items) {
920             if (!(item instanceof TransactionAccount))
921                 continue;
922
923             if (!((TransactionAccount) item).isEmpty())
924                 return false;
925         }
926
927         return true;
928     }
929
930     public static class FocusInfo {
931         int position;
932         FocusedElement element;
933         public FocusInfo(int position, @Nullable FocusedElement element) {
934             this.position = position;
935             this.element = element;
936         }
937     }
938
939     static abstract class Item {
940         private static int idDispenser = 0;
941         protected int id;
942         private Item() {
943             if (this instanceof TransactionHead)
944                 id = 0;
945             else
946                 synchronized (Item.class) {
947                     id = ++idDispenser;
948                 }
949         }
950         public Item(int id) {
951             this.id = id;
952         }
953         public static Item from(Item origin) {
954             if (origin instanceof TransactionHead)
955                 return new TransactionHead((TransactionHead) origin);
956             if (origin instanceof TransactionAccount)
957                 return new TransactionAccount((TransactionAccount) origin);
958             throw new RuntimeException("Don't know how to handle " + origin);
959         }
960         private static void resetIdDispenser() {
961             idDispenser = 0;
962         }
963         public int getId() {
964             return id;
965         }
966         public abstract ItemType getType();
967         public TransactionHead toTransactionHead() {
968             if (this instanceof TransactionHead)
969                 return (TransactionHead) this;
970
971             throw new IllegalStateException("Wrong item type " + this);
972         }
973         public TransactionAccount toTransactionAccount() {
974             if (this instanceof TransactionAccount)
975                 return (TransactionAccount) this;
976
977             throw new IllegalStateException("Wrong item type " + this);
978         }
979         public boolean equalContents(@Nullable Object item) {
980             if (item == null)
981                 return false;
982
983             if (!getClass().equals(item.getClass()))
984                 return false;
985
986             // shortcut - comparing same instance
987             if (item == this)
988                 return true;
989
990             if (this instanceof TransactionHead)
991                 return ((TransactionHead) item).equalContents((TransactionHead) this);
992             if (this instanceof TransactionAccount)
993                 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
994
995             throw new RuntimeException("Don't know how to handle " + this);
996         }
997     }
998
999
1000 //==========================================================================================
1001
1002     public static class TransactionHead extends Item {
1003         private SimpleDate date;
1004         private String description;
1005         private String comment;
1006         TransactionHead(String description) {
1007             super();
1008             this.description = description;
1009         }
1010         public TransactionHead(TransactionHead origin) {
1011             super(origin.id);
1012             date = origin.date;
1013             description = origin.description;
1014             comment = origin.comment;
1015         }
1016         public SimpleDate getDate() {
1017             return date;
1018         }
1019         public void setDate(SimpleDate date) {
1020             this.date = date;
1021         }
1022         public void setDate(String text) throws ParseException {
1023             if (Misc.emptyIsNull(text) == null) {
1024                 date = null;
1025                 return;
1026             }
1027
1028             date = Globals.parseLedgerDate(text);
1029         }
1030         /**
1031          * getFormattedDate()
1032          *
1033          * @return nicely formatted, shortest available date representation
1034          */
1035         String getFormattedDate() {
1036             if (date == null)
1037                 return null;
1038
1039             Calendar today = GregorianCalendar.getInstance();
1040
1041             if (today.get(Calendar.YEAR) != date.year) {
1042                 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
1043             }
1044
1045             if (today.get(Calendar.MONTH) + 1 != date.month) {
1046                 return String.format(Locale.US, "%d/%02d", date.month, date.day);
1047             }
1048
1049             return String.valueOf(date.day);
1050         }
1051         @NonNull
1052         @Override
1053         public String toString() {
1054             @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
1055                     String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1056
1057             if (TextUtils.isEmpty(description))
1058                 b.append(" «no description»");
1059             else
1060                 b.append(String.format(" '%s'", description));
1061
1062             if (date != null)
1063                 b.append(String.format("@%s", date.toString()));
1064
1065             if (!TextUtils.isEmpty(comment))
1066                 b.append(String.format(" /%s/", comment));
1067
1068             return b.toString();
1069         }
1070         public String getDescription() {
1071             return description;
1072         }
1073         public void setDescription(String description) {
1074             this.description = description;
1075         }
1076         public String getComment() {
1077             return comment;
1078         }
1079         public void setComment(String comment) {
1080             this.comment = comment;
1081         }
1082         @Override
1083         public ItemType getType() {
1084             return ItemType.generalData;
1085         }
1086         public LedgerTransaction asLedgerTransaction() {
1087             return new LedgerTransaction(0, (date == null) ? SimpleDate.today() : date, description,
1088                     Objects.requireNonNull(Data.getProfile()));
1089         }
1090         public boolean equalContents(TransactionHead other) {
1091             if (other == null)
1092                 return false;
1093
1094             return Objects.equals(date, other.date) &&
1095                    Misc.equalStrings(description, other.description) &&
1096                    Misc.equalStrings(comment, other.comment);
1097         }
1098     }
1099
1100     public static class TransactionAccount extends Item {
1101         private String accountName;
1102         private String amountHint;
1103         private String comment;
1104         @NotNull
1105         private String currency = "";
1106         private float amount;
1107         private boolean amountSet;
1108         private boolean amountValid = true;
1109         @NotNull
1110         private String amountText = "";
1111         private FocusedElement focusedElement = FocusedElement.Account;
1112         private boolean amountHintIsSet = false;
1113         private boolean isLast = false;
1114         private int accountNameCursorPosition;
1115         public TransactionAccount(TransactionAccount origin) {
1116             super(origin.id);
1117             accountName = origin.accountName;
1118             amount = origin.amount;
1119             amountSet = origin.amountSet;
1120             amountHint = origin.amountHint;
1121             amountHintIsSet = origin.amountHintIsSet;
1122             amountText = origin.amountText;
1123             comment = origin.comment;
1124             currency = origin.currency;
1125             amountValid = origin.amountValid;
1126             focusedElement = origin.focusedElement;
1127             isLast = origin.isLast;
1128             accountNameCursorPosition = origin.accountNameCursorPosition;
1129         }
1130         public TransactionAccount(String accountName) {
1131             super();
1132             this.accountName = accountName;
1133         }
1134         public TransactionAccount(String accountName, @NotNull String currency) {
1135             super();
1136             this.accountName = accountName;
1137             this.currency = currency;
1138         }
1139         public @NotNull String getAmountText() {
1140             return amountText;
1141         }
1142         public void setAmountText(@NotNull String amountText) {
1143             this.amountText = amountText;
1144         }
1145         public boolean setAndCheckAmountText(@NotNull String amountText) {
1146             String amtText = amountText.trim();
1147             this.amountText = amtText;
1148
1149             boolean significantChange = false;
1150
1151             if (amtText.isEmpty()) {
1152                 if (amountSet) {
1153                     significantChange = true;
1154                 }
1155                 resetAmount();
1156             }
1157             else {
1158                 try {
1159                     amtText = amtText.replace(Data.getDecimalSeparator(), Data.decimalDot);
1160                     final float parsedAmount = Float.parseFloat(amtText);
1161                     if (!amountSet || !amountValid || !Misc.equalFloats(parsedAmount, amount))
1162                         significantChange = true;
1163                     amount = parsedAmount;
1164                     amountSet = true;
1165                     amountValid = true;
1166                 }
1167                 catch (NumberFormatException e) {
1168                     Logger.debug("new-trans", String.format(
1169                             "assuming amount is not set due to number format exception. " +
1170                             "input was '%s'", amtText));
1171                     if (amountValid) // it was valid and now it's not
1172                         significantChange = true;
1173                     amountValid = false;
1174                 }
1175             }
1176
1177             return significantChange;
1178         }
1179         public boolean isLast() {
1180             return isLast;
1181         }
1182         public boolean isAmountSet() {
1183             return amountSet;
1184         }
1185         public String getAccountName() {
1186             return accountName;
1187         }
1188         public void setAccountName(String accountName) {
1189             this.accountName = accountName;
1190         }
1191         public float getAmount() {
1192             if (!amountSet)
1193                 throw new IllegalStateException("Amount is not set");
1194             return amount;
1195         }
1196         public void setAmount(float amount) {
1197             this.amount = amount;
1198             amountSet = true;
1199             amountValid = true;
1200             amountText = Data.formatNumber(amount);
1201         }
1202         public void resetAmount() {
1203             amountSet = false;
1204             amountValid = true;
1205             amountText = "";
1206         }
1207         @Override
1208         public ItemType getType() {
1209             return ItemType.transactionRow;
1210         }
1211         public String getAmountHint() {
1212             return amountHint;
1213         }
1214         public void setAmountHint(String amountHint) {
1215             this.amountHint = amountHint;
1216             amountHintIsSet = !TextUtils.isEmpty(amountHint);
1217         }
1218         public String getComment() {
1219             return comment;
1220         }
1221         public void setComment(String comment) {
1222             this.comment = comment;
1223         }
1224         @NotNull
1225         public String getCurrency() {
1226             return currency;
1227         }
1228         public void setCurrency(@org.jetbrains.annotations.Nullable String currency) {
1229             this.currency = Misc.nullIsEmpty(currency);
1230         }
1231         public boolean isAmountValid() {
1232             return amountValid;
1233         }
1234         public void setAmountValid(boolean amountValid) {
1235             this.amountValid = amountValid;
1236         }
1237         public FocusedElement getFocusedElement() {
1238             return focusedElement;
1239         }
1240         public void setFocusedElement(FocusedElement focusedElement) {
1241             this.focusedElement = focusedElement;
1242         }
1243         public boolean isAmountHintSet() {
1244             return amountHintIsSet;
1245         }
1246         public void setAmountHintIsSet(boolean amountHintIsSet) {
1247             this.amountHintIsSet = amountHintIsSet;
1248         }
1249         public boolean isEmpty() {
1250             return !amountSet && Misc.emptyIsNull(accountName) == null &&
1251                    Misc.emptyIsNull(comment) == null;
1252         }
1253         @SuppressLint("DefaultLocale")
1254         @Override
1255         @NotNull
1256         public String toString() {
1257             StringBuilder b = new StringBuilder();
1258             b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1259             if (!TextUtils.isEmpty(accountName))
1260                 b.append(String.format(" acc'%s'", accountName));
1261
1262             if (amountSet)
1263                 b.append(amountText)
1264                  .append(" [")
1265                  .append(amountValid ? "valid" : "invalid")
1266                  .append("] ")
1267                  .append(String.format(Locale.ROOT, " {raw %4.2f}", amount));
1268             else if (amountHintIsSet)
1269                 b.append(String.format(" (hint %s)", amountHint));
1270
1271             if (!TextUtils.isEmpty(currency))
1272                 b.append(" ")
1273                  .append(currency);
1274
1275             if (!TextUtils.isEmpty(comment))
1276                 b.append(String.format(" /%s/", comment));
1277
1278             if (isLast)
1279                 b.append(" last");
1280
1281             return b.toString();
1282         }
1283         public boolean equalContents(TransactionAccount other) {
1284             if (other == null)
1285                 return false;
1286
1287             boolean equal = Misc.equalStrings(accountName, other.accountName);
1288             equal = equal && Misc.equalStrings(comment, other.comment) &&
1289                     (amountSet ? other.amountSet && amountValid == other.amountValid &&
1290                                  Misc.equalStrings(amountText, other.amountText)
1291                                : !other.amountSet);
1292
1293             // compare amount hint only if there is no amount
1294             if (!amountSet)
1295                 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1296                                                     Misc.equalStrings(amountHint, other.amountHint)
1297                                                   : !other.amountHintIsSet);
1298             equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1299
1300             Logger.debug("new-trans",
1301                     String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1302                             equal));
1303             return equal;
1304         }
1305         public int getAccountNameCursorPosition() {
1306             return accountNameCursorPosition;
1307         }
1308         public void setAccountNameCursorPosition(int position) {
1309             this.accountNameCursorPosition = position;
1310         }
1311     }
1312
1313     private static class BalanceForCurrency {
1314         private final HashMap<String, Float> hashMap = new HashMap<>();
1315         float get(String currencyName) {
1316             Float f = hashMap.get(currencyName);
1317             if (f == null) {
1318                 f = 0f;
1319                 hashMap.put(currencyName, f);
1320             }
1321             return f;
1322         }
1323         void add(String currencyName, float amount) {
1324             hashMap.put(currencyName, get(currencyName) + amount);
1325         }
1326         Set<String> currencies() {
1327             return hashMap.keySet();
1328         }
1329         boolean containsCurrency(String currencyName) {
1330             return hashMap.containsKey(currencyName);
1331         }
1332     }
1333
1334     private static class ItemsForCurrency {
1335         private final HashMap<@NotNull String, List<Item>> hashMap = new HashMap<>();
1336         @NonNull
1337         List<NewTransactionModel.Item> getList(@NotNull String currencyName) {
1338             List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1339             if (list == null) {
1340                 list = new ArrayList<>();
1341                 hashMap.put(currencyName, list);
1342             }
1343             return list;
1344         }
1345         void add(@NotNull String currencyName, @NonNull NewTransactionModel.Item item) {
1346             getList(Objects.requireNonNull(currencyName)).add(item);
1347         }
1348         int size(@NotNull String currencyName) {
1349             return this.getList(Objects.requireNonNull(currencyName))
1350                        .size();
1351         }
1352         Set<String> currencies() {
1353             return hashMap.keySet();
1354         }
1355     }
1356 }