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