2 * Copyright © 2021 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
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.
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/>.
18 package net.ktnx.mobileledger.ui.new_transaction;
20 import android.annotation.SuppressLint;
21 import android.text.TextUtils;
23 import androidx.annotation.NonNull;
24 import androidx.annotation.Nullable;
25 import androidx.lifecycle.LifecycleOwner;
26 import androidx.lifecycle.LiveData;
27 import androidx.lifecycle.MutableLiveData;
28 import androidx.lifecycle.Observer;
29 import androidx.lifecycle.ViewModel;
31 import net.ktnx.mobileledger.BuildConfig;
32 import net.ktnx.mobileledger.db.Currency;
33 import net.ktnx.mobileledger.db.DB;
34 import net.ktnx.mobileledger.db.Profile;
35 import net.ktnx.mobileledger.db.TemplateAccount;
36 import net.ktnx.mobileledger.db.TemplateHeader;
37 import net.ktnx.mobileledger.db.TransactionWithAccounts;
38 import net.ktnx.mobileledger.model.Data;
39 import net.ktnx.mobileledger.model.InertMutableLiveData;
40 import net.ktnx.mobileledger.model.LedgerTransaction;
41 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
42 import net.ktnx.mobileledger.model.MatchedTemplate;
43 import net.ktnx.mobileledger.utils.Globals;
44 import net.ktnx.mobileledger.utils.Logger;
45 import net.ktnx.mobileledger.utils.Misc;
46 import net.ktnx.mobileledger.utils.SimpleDate;
48 import org.jetbrains.annotations.NotNull;
50 import java.text.ParseException;
51 import java.util.ArrayList;
52 import java.util.Calendar;
53 import java.util.GregorianCalendar;
54 import java.util.HashMap;
55 import java.util.List;
56 import java.util.Locale;
57 import java.util.Objects;
59 import java.util.concurrent.atomic.AtomicInteger;
60 import java.util.regex.MatchResult;
62 enum ItemType {generalData, transactionRow}
64 enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
67 public class NewTransactionModel extends ViewModel {
68 private static final int MIN_ITEMS = 3;
69 private final MutableLiveData<Boolean> showCurrency = new MutableLiveData<>(false);
70 private final MutableLiveData<Boolean> isSubmittable = new InertMutableLiveData<>(false);
71 private final MutableLiveData<Boolean> showComments = new MutableLiveData<>(true);
72 private final MutableLiveData<List<Item>> items = new MutableLiveData<>();
73 private final MutableLiveData<Boolean> simulateSave = new InertMutableLiveData<>(false);
74 private final AtomicInteger busyCounter = new AtomicInteger(0);
75 private final MutableLiveData<Boolean> busyFlag = new InertMutableLiveData<>(false);
76 private final Observer<Profile> profileObserver = profile -> {
77 showCurrency.postValue(profile.getShowCommodityByDefault());
78 showComments.postValue(profile.getShowCommentsByDefault());
80 private final MutableLiveData<FocusInfo> focusInfo = new MutableLiveData<>();
81 private boolean observingDataProfile;
82 public NewTransactionModel() {
85 public LiveData<Boolean> getShowCurrency() {
88 public LiveData<List<Item>> getItems() {
91 private void setItems(@NonNull List<Item> newList) {
92 checkTransactionSubmittable(newList);
93 setItemsWithoutSubmittableChecks(newList);
95 private void replaceItems(@NonNull List<Item> newList) {
101 * make old items replaceable in-place. makes the new values visually blend in
103 private void renumberItems() {
104 renumberItems(items.getValue());
106 private void renumberItems(List<Item> list) {
112 for (Item item : list)
115 private void setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
116 final int cnt = list.size();
117 for (int i = 1; i < cnt - 1; i++) {
118 final TransactionAccount item = list.get(i)
119 .toTransactionAccount();
121 TransactionAccount replacement = new TransactionAccount(item);
122 replacement.isLast = false;
123 list.set(i, replacement);
126 final TransactionAccount last = list.get(cnt - 1)
127 .toTransactionAccount();
129 TransactionAccount replacement = new TransactionAccount(last);
130 replacement.isLast = true;
131 list.set(cnt - 1, replacement);
134 if (BuildConfig.DEBUG)
135 dumpItemList("Before setValue()", list);
136 items.setValue(list);
138 private List<Item> copyList() {
139 List<Item> copy = new ArrayList<>();
140 List<Item> oldList = items.getValue();
143 for (Item item : oldList) {
144 copy.add(Item.from(item));
149 private List<Item> copyListWithoutItem(int position) {
150 List<Item> copy = new ArrayList<>();
151 List<Item> oldList = items.getValue();
153 if (oldList != null) {
155 for (Item item : oldList) {
158 copy.add(Item.from(item));
164 private List<Item> shallowCopyList() {
165 return new ArrayList<>(items.getValue());
167 LiveData<Boolean> getShowComments() {
170 void observeDataProfile(LifecycleOwner activity) {
171 if (!observingDataProfile)
172 Data.observeProfile(activity, profileObserver);
173 observingDataProfile = true;
175 boolean getSimulateSaveFlag() {
176 Boolean value = simulateSave.getValue();
181 LiveData<Boolean> getSimulateSave() {
184 void toggleSimulateSave() {
185 simulateSave.setValue(!getSimulateSaveFlag());
187 LiveData<Boolean> isSubmittable() {
188 return this.isSubmittable;
191 Logger.debug("new-trans", "Resetting model");
192 List<Item> list = new ArrayList<>();
193 Item.resetIdDispenser();
194 list.add(new TransactionHead(""));
195 final String defaultCurrency = Objects.requireNonNull(Data.getProfile())
196 .getDefaultCommodity();
197 list.add(new TransactionAccount("", defaultCurrency));
198 list.add(new TransactionAccount("", defaultCurrency));
199 noteFocusChanged(0, FocusedElement.Description);
201 isSubmittable.setValue(false);
202 setItemsWithoutSubmittableChecks(list);
204 boolean accountsInInitialState() {
205 final List<Item> list = items.getValue();
210 for (Item item : list) {
211 if (!(item instanceof TransactionAccount))
214 TransactionAccount accRow = (TransactionAccount) item;
215 if (!accRow.isEmpty())
221 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
222 SimpleDate transactionDate = null;
223 final MatchResult matchResult = matchedTemplate.matchResult;
224 final TemplateHeader templateHead = matchedTemplate.templateHead;
226 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
227 templateHead.getDateDay());
228 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
229 templateHead.getDateMonth());
230 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
231 templateHead.getDateYear());
233 if (year > 0 || month > 0 || day > 0) {
234 SimpleDate today = SimpleDate.today();
242 transactionDate = new SimpleDate(year, month, day);
244 Logger.debug("pattern", "setting transaction date to " + transactionDate);
248 List<Item> present = copyList();
250 TransactionHead head = new TransactionHead(present.get(0)
251 .toTransactionHead());
252 if (transactionDate != null)
253 head.setDate(transactionDate);
255 final String transactionDescription = extractStringFromMatches(matchResult,
256 templateHead.getTransactionDescriptionMatchGroup(),
257 templateHead.getTransactionDescription());
258 if (Misc.emptyIsNull(transactionDescription) != null)
259 head.setDescription(transactionDescription);
261 final String transactionComment = extractStringFromMatches(matchResult,
262 templateHead.getTransactionCommentMatchGroup(),
263 templateHead.getTransactionComment());
264 if (Misc.emptyIsNull(transactionComment) != null)
265 head.setComment(transactionComment);
267 List<Item> newItems = new ArrayList<>();
271 for (int i = 1; i < present.size(); i++) {
272 final TransactionAccount row = present.get(i)
273 .toTransactionAccount();
275 newItems.add(new TransactionAccount(row));
280 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
282 final boolean accountsInInitialState = accountsInInitialState();
283 for (TemplateAccount acc : entry.accounts) {
287 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
288 acc.getAccountName());
289 String accountComment =
290 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
291 acc.getAccountComment());
292 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
294 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
297 TransactionAccount accRow = new TransactionAccount(accountName);
298 accRow.setComment(accountComment);
300 accRow.setAmount(amount);
302 extractCurrencyFromMatches(matchResult, acc.getCurrencyMatchGroup(),
303 acc.getCurrencyObject()));
305 newItems.add(accRow);
308 renumberItems(newItems);
309 Misc.onMainThread(() -> replaceItems(newItems));
313 private String extractCurrencyFromMatches(MatchResult m, Integer group, Currency literal) {
314 return Misc.nullIsEmpty(
315 extractStringFromMatches(m, group, (literal == null) ? "" : literal.getName()));
317 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
323 if (grp > 0 && grp <= m.groupCount())
325 return Integer.parseInt(m.group(grp));
327 catch (NumberFormatException e) {
328 Logger.debug("new-trans", "Error extracting matched number", e);
335 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
341 if (grp > 0 && grp <= m.groupCount())
347 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
353 if (grp > 0 && grp <= m.groupCount())
355 return Float.valueOf(m.group(grp));
357 catch (NumberFormatException e) {
358 Logger.debug("new-trans", "Error extracting matched number", e);
364 void removeItem(int pos) {
365 Logger.debug("new-trans", String.format(Locale.US, "Removing item at position %d", pos));
366 List<Item> newList = copyListWithoutItem(pos);
367 final FocusInfo fi = focusInfo.getValue();
368 if ((fi != null) && (pos < fi.position))
369 noteFocusChanged(fi.position - 1, fi.element);
372 void noteFocusChanged(int position, FocusedElement element) {
373 FocusInfo present = focusInfo.getValue();
374 if (present == null || present.position != position || present.element != element)
375 focusInfo.setValue(new FocusInfo(position, element));
377 public LiveData<FocusInfo> getFocusInfo() {
380 void moveItem(int fromIndex, int toIndex) {
381 List<Item> newList = shallowCopyList();
382 Item item = newList.remove(fromIndex);
383 newList.add(toIndex, item);
385 FocusInfo fi = focusInfo.getValue();
386 if (fi != null && fi.position == fromIndex)
387 noteFocusChanged(toIndex, fi.element);
389 items.setValue(newList); // same count, same submittable state
391 void moveItemLast(List<Item> list, int index) {
395 3 <-- desired position
398 int itemCount = list.size();
400 if (index < itemCount - 1)
401 list.add(list.remove(index));
403 void toggleCurrencyVisible() {
404 final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
406 // remove currency from all items, or reset currency to the default
407 // no need to clone the list, because the removal of the currency won't lead to
408 // visual changes -- the currency fields will be hidden or reset to default anyway
409 // still, there may be changes in the submittable state
410 final List<Item> list = Objects.requireNonNull(this.items.getValue());
411 final Profile profile = Objects.requireNonNull(Data.getProfile());
412 for (int i = 1; i < list.size(); i++) {
413 ((TransactionAccount) list.get(i)).setCurrency(
414 newValue ? profile.getDefaultCommodity() : "");
416 checkTransactionSubmittable(null);
417 showCurrency.setValue(newValue);
419 void stopObservingBusyFlag(Observer<Boolean> observer) {
420 busyFlag.removeObserver(observer);
422 void incrementBusyCounter() {
423 int newValue = busyCounter.incrementAndGet();
425 busyFlag.postValue(true);
427 void decrementBusyCounter() {
428 int newValue = busyCounter.decrementAndGet();
430 busyFlag.postValue(false);
432 public LiveData<Boolean> getBusyFlag() {
435 public void toggleShowComments() {
436 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
438 public LedgerTransaction constructLedgerTransaction() {
439 List<Item> list = Objects.requireNonNull(items.getValue());
440 TransactionHead head = list.get(0)
441 .toTransactionHead();
442 LedgerTransaction tr = head.asLedgerTransaction();
444 tr.setComment(head.getComment());
445 LedgerTransactionAccount emptyAmountAccount = null;
446 float emptyAmountAccountBalance = 0;
447 for (int i = 1; i < list.size(); i++) {
448 TransactionAccount item = list.get(i)
449 .toTransactionAccount();
450 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
453 if (acc.getAccountName()
457 acc.setComment(item.getComment());
459 if (item.isAmountSet()) {
460 acc.setAmount(item.getAmount());
461 emptyAmountAccountBalance += item.getAmount();
464 emptyAmountAccount = acc;
470 if (emptyAmountAccount != null)
471 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
475 void loadTransactionIntoModel(@NonNull TransactionWithAccounts tr) {
476 List<Item> newList = new ArrayList<>();
477 Item.resetIdDispenser();
479 Item currentHead = Objects.requireNonNull(items.getValue())
481 TransactionHead head = new TransactionHead(tr.transaction.getDescription());
482 head.setComment(tr.transaction.getComment());
483 if (currentHead instanceof TransactionHead)
484 head.setDate(((TransactionHead) currentHead).date);
488 List<LedgerTransactionAccount> accounts = new ArrayList<>();
489 for (net.ktnx.mobileledger.db.TransactionAccount acc : tr.accounts) {
490 accounts.add(new LedgerTransactionAccount(acc));
493 TransactionAccount firstNegative = null;
494 TransactionAccount firstPositive = null;
495 int singleNegativeIndex = -1;
496 int singlePositiveIndex = -1;
497 int negativeCount = 0;
498 for (int i = 0; i < accounts.size(); i++) {
499 LedgerTransactionAccount acc = accounts.get(i);
500 TransactionAccount item =
501 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
504 item.setAccountName(acc.getAccountName());
505 item.setComment(acc.getComment());
506 if (acc.isAmountSet()) {
507 item.setAmount(acc.getAmount());
508 if (acc.getAmount() < 0) {
509 if (firstNegative == null) {
510 firstNegative = item;
511 singleNegativeIndex = i + 1;
514 singleNegativeIndex = -1;
517 if (firstPositive == null) {
518 firstPositive = item;
519 singlePositiveIndex = i + 1;
522 singlePositiveIndex = -1;
528 if (BuildConfig.DEBUG)
529 dumpItemList("Loaded previous transaction", newList);
531 if (singleNegativeIndex != -1) {
532 firstNegative.resetAmount();
533 moveItemLast(newList, singleNegativeIndex);
535 else if (singlePositiveIndex != -1) {
536 firstPositive.resetAmount();
537 moveItemLast(newList, singlePositiveIndex);
540 Misc.onMainThread(() -> {
542 noteFocusChanged(1, FocusedElement.Amount);
546 * A transaction is submittable if:
548 * 1) has at least two account names
549 * 2) each row with amount has account name
550 * 3) for each commodity:
551 * 3a) amounts must balance to 0, or
552 * 3b) there must be exactly one empty amount (with account)
553 * 4) empty accounts with empty amounts are ignored
555 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
557 * 6) at least two rows need to be present in the ledger
559 * @param list - the item list to check. Can be the displayed list or a list that will be
562 @SuppressLint("DefaultLocale")
563 void checkTransactionSubmittable(@Nullable List<Item> list) {
564 boolean workingWithLiveList = false;
567 workingWithLiveList = true;
570 if (BuildConfig.DEBUG)
571 dumpItemList(String.format("Before submittable checks (%s)",
572 workingWithLiveList ? "LIVE LIST" : "custom list"), list);
575 final BalanceForCurrency balance = new BalanceForCurrency();
576 final String descriptionText = list.get(0)
579 boolean submittable = true;
580 boolean listChanged = false;
581 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
582 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
583 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
584 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
585 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
586 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
587 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
588 final List<Item> emptyRows = new ArrayList<>();
591 if ((descriptionText == null) || descriptionText.trim()
594 Logger.debug("submittable", "Transaction not submittable: missing description");
598 boolean hasInvalidAmount = false;
600 for (int i = 1; i < list.size(); i++) {
601 TransactionAccount item = list.get(i)
602 .toTransactionAccount();
604 String accName = item.getAccountName()
606 String currName = item.getCurrency();
608 itemsForCurrency.add(currName, item);
610 if (accName.isEmpty()) {
611 itemsWithEmptyAccountForCurrency.add(currName, item);
613 if (item.isAmountSet()) {
614 // 2) each amount has account name
615 Logger.debug("submittable", String.format(
616 "Transaction not submittable: row %d has no account name, but" +
617 " has" + " amount %1.2f", i + 1, item.getAmount()));
621 emptyRowsForCurrency.add(currName, item);
626 itemsWithAccountForCurrency.add(currName, item);
629 if (item.isAmountSet()) {
630 itemsWithAmountForCurrency.add(currName, item);
631 balance.add(currName, item.getAmount());
634 if (!item.isAmountValid()) {
635 Logger.debug("submittable",
636 String.format("Not submittable: row %d has an invalid amount",
639 hasInvalidAmount = true;
642 itemsWithEmptyAmountForCurrency.add(currName, item);
644 if (!accName.isEmpty())
645 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
649 // 1) has at least two account names
652 Logger.debug("submittable", "Transaction not submittable: no account names");
653 else if (accounts == 1)
654 Logger.debug("submittable",
655 "Transaction not submittable: only one account name");
657 Logger.debug("submittable",
658 String.format("Transaction not submittable: only %d account names",
663 // 3) for each commodity:
664 // 3a) amount must balance to 0, or
665 // 3b) there must be exactly one empty amount (with account)
666 for (String balCurrency : itemsForCurrency.currencies()) {
667 float currencyBalance = balance.get(balCurrency);
668 if (Misc.isZero(currencyBalance)) {
669 // remove hints from all amount inputs in that currency
670 for (int i = 1; i < list.size(); i++) {
671 TransactionAccount acc = list.get(i)
672 .toTransactionAccount();
673 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
674 if (BuildConfig.DEBUG)
675 Logger.debug("submittable",
676 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
677 i, Misc.nullIsEmpty(acc.getAccountName()),
679 // skip if the amount is set, in which case the hint is not
681 if (!acc.isAmountSet() && acc.amountHintIsSet &&
682 !TextUtils.isEmpty(acc.getAmountHint()))
684 acc.setAmountHint(null);
692 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
693 int balanceReceiversCount = tmpList.size();
694 if (balanceReceiversCount != 1) {
695 if (BuildConfig.DEBUG) {
696 if (balanceReceiversCount == 0)
697 Logger.debug("submittable", String.format(
698 "Transaction not submittable [curr:%s]: non-zero balance " +
699 "with no empty amounts with accounts", balCurrency));
701 Logger.debug("submittable", String.format(
702 "Transaction not submittable [curr:%s]: non-zero balance " +
703 "with multiple empty amounts with accounts", balCurrency));
708 List<Item> emptyAmountList =
709 itemsWithEmptyAmountForCurrency.getList(balCurrency);
711 // suggest off-balance amount to a row and remove hints on other rows
712 Item receiver = null;
713 if (!tmpList.isEmpty())
714 receiver = tmpList.get(0);
715 else if (!emptyAmountList.isEmpty())
716 receiver = emptyAmountList.get(0);
718 for (int i = 0; i < list.size(); i++) {
719 Item item = list.get(i);
720 if (!(item instanceof TransactionAccount))
723 TransactionAccount acc = item.toTransactionAccount();
724 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
727 if (item == receiver) {
728 final String hint = String.format("%1.2f", -currencyBalance);
729 if (!acc.isAmountHintSet() ||
730 !Misc.equalStrings(acc.getAmountHint(), hint))
732 Logger.debug("submittable",
733 String.format("Setting amount hint of {%s} to %s [%s]",
734 acc.toString(), hint, balCurrency));
735 acc.setAmountHint(hint);
740 if (BuildConfig.DEBUG)
741 Logger.debug("submittable",
742 String.format("Resetting hint of '%s' [%s]",
743 Misc.nullIsEmpty(acc.getAccountName()),
745 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
746 acc.setAmountHint(null);
754 // 5) a row with an empty account name or empty amount is guaranteed to exist for
756 if (!hasInvalidAmount) {
757 for (String balCurrency : balance.currencies()) {
758 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
759 int currRows = itemsForCurrency.size(balCurrency);
760 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
761 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
762 if ((currEmptyRows == 0) &&
763 ((currRows == currAccounts) || (currRows == currAmounts)))
765 // perhaps there already is an unused empty row for another currency that
767 // boolean foundIt = false;
768 // for (Item item : emptyRows) {
769 // Currency itemCurrency = item.getCurrency();
770 // String itemCurrencyName =
771 // (itemCurrency == null) ? "" : itemCurrency.getName();
772 // if (Misc.isZero(balance.get(itemCurrencyName))) {
773 // item.setCurrency(Currency.loadByName(balCurrency));
774 // item.setAmountHint(
775 // String.format("%1.2f", -balance.get(balCurrency)));
782 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
783 final float bal = balance.get(balCurrency);
784 if (!Misc.isZero(bal) && currAmounts == currRows)
785 newAcc.setAmountHint(String.format("%4.2f", -bal));
786 Logger.debug("submittable",
787 String.format("Adding new item with %s for currency %s",
788 newAcc.getAmountHint(), balCurrency));
795 // drop extra empty rows, not needed
796 for (String currName : emptyRowsForCurrency.currencies()) {
797 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
798 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
799 // the list is a copy, so the empty item is no longer present
800 Item itemToRemove = emptyItems.remove(1);
801 removeItemById(list, itemToRemove.id);
805 // unused currency, remove last item (which is also an empty one)
806 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
807 List<Item> currItems = itemsForCurrency.getList(currName);
809 if (currItems.size() == 1) {
810 // the list is a copy, so the empty item is no longer present
811 removeItemById(list, emptyItems.get(0).id);
817 // 6) at least two rows need to be present in the ledger
818 // (the list also contains header and trailer)
819 while (list.size() < MIN_ITEMS) {
820 list.add(new TransactionAccount(""));
824 Logger.debug("submittable", submittable ? "YES" : "NO");
825 isSubmittable.setValue(submittable);
827 if (BuildConfig.DEBUG)
828 dumpItemList("After submittable checks", list);
830 catch (NumberFormatException e) {
831 Logger.debug("submittable", "NO (because of NumberFormatException)");
832 isSubmittable.setValue(false);
834 catch (Exception e) {
836 Logger.debug("submittable", "NO (because of an Exception)");
837 isSubmittable.setValue(false);
840 if (listChanged && workingWithLiveList) {
841 setItemsWithoutSubmittableChecks(list);
844 private void removeItemById(@NotNull List<Item> list, int id) {
845 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
846 list.removeIf(item -> item.id == id);
849 for (Item item : list) {
857 @SuppressLint("DefaultLocale")
858 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
859 Logger.debug("submittable", "== Dump of all items " + msg);
860 for (int i = 1; i < list.size(); i++) {
861 TransactionAccount item = list.get(i)
862 .toTransactionAccount();
863 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
866 public void setItemCurrency(int position, String newCurrency) {
867 TransactionAccount item = Objects.requireNonNull(items.getValue())
869 .toTransactionAccount();
870 final String oldCurrency = item.getCurrency();
872 if (Misc.equalStrings(oldCurrency, newCurrency))
875 List<Item> newList = copyList();
876 newList.get(position)
877 .toTransactionAccount()
878 .setCurrency(newCurrency);
882 public boolean accountListIsEmpty() {
883 List<Item> items = Objects.requireNonNull(this.items.getValue());
885 for (Item item : items) {
886 if (!(item instanceof TransactionAccount))
889 if (!((TransactionAccount) item).isEmpty())
896 public static class FocusInfo {
898 FocusedElement element;
899 public FocusInfo(int position, FocusedElement element) {
900 this.position = position;
901 this.element = element;
905 static abstract class Item {
906 private static int idDispenser = 0;
909 if (this instanceof TransactionHead)
912 synchronized (Item.class) {
916 public Item(int id) {
919 public static Item from(Item origin) {
920 if (origin instanceof TransactionHead)
921 return new TransactionHead((TransactionHead) origin);
922 if (origin instanceof TransactionAccount)
923 return new TransactionAccount((TransactionAccount) origin);
924 throw new RuntimeException("Don't know how to handle " + origin);
926 private static void resetIdDispenser() {
932 public abstract ItemType getType();
933 public TransactionHead toTransactionHead() {
934 if (this instanceof TransactionHead)
935 return (TransactionHead) this;
937 throw new IllegalStateException("Wrong item type " + this);
939 public TransactionAccount toTransactionAccount() {
940 if (this instanceof TransactionAccount)
941 return (TransactionAccount) this;
943 throw new IllegalStateException("Wrong item type " + this);
945 public boolean equalContents(@Nullable Object item) {
949 if (!getClass().equals(item.getClass()))
952 // shortcut - comparing same instance
956 if (this instanceof TransactionHead)
957 return ((TransactionHead) item).equalContents((TransactionHead) this);
958 if (this instanceof TransactionAccount)
959 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
961 throw new RuntimeException("Don't know how to handle " + this);
966 //==========================================================================================
968 public static class TransactionHead extends Item {
969 private SimpleDate date;
970 private String description;
971 private String comment;
972 TransactionHead(String description) {
974 this.description = description;
976 public TransactionHead(TransactionHead origin) {
979 description = origin.description;
980 comment = origin.comment;
982 public SimpleDate getDate() {
985 public void setDate(SimpleDate date) {
988 public void setDate(String text) throws ParseException {
989 if (Misc.emptyIsNull(text) == null) {
994 date = Globals.parseLedgerDate(text);
999 * @return nicely formatted, shortest available date representation
1001 String getFormattedDate() {
1005 Calendar today = GregorianCalendar.getInstance();
1007 if (today.get(Calendar.YEAR) != date.year) {
1008 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
1011 if (today.get(Calendar.MONTH) + 1 != date.month) {
1012 return String.format(Locale.US, "%d/%02d", date.month, date.day);
1015 return String.valueOf(date.day);
1019 public String toString() {
1020 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
1021 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1023 if (TextUtils.isEmpty(description))
1024 b.append(" «no description»");
1026 b.append(String.format(" '%s'", description));
1029 b.append(String.format("@%s", date.toString()));
1031 if (!TextUtils.isEmpty(comment))
1032 b.append(String.format(" /%s/", comment));
1034 return b.toString();
1036 public String getDescription() {
1039 public void setDescription(String description) {
1040 this.description = description;
1042 public String getComment() {
1045 public void setComment(String comment) {
1046 this.comment = comment;
1049 public ItemType getType() {
1050 return ItemType.generalData;
1052 public LedgerTransaction asLedgerTransaction() {
1053 return new LedgerTransaction(0, (date == null) ? SimpleDate.today() : date, description,
1054 Objects.requireNonNull(Data.getProfile()));
1056 public boolean equalContents(TransactionHead other) {
1060 return Objects.equals(date, other.date) &&
1061 Misc.equalStrings(description, other.description) &&
1062 Misc.equalStrings(comment, other.comment);
1066 public static class TransactionAccount extends Item {
1067 private String accountName;
1068 private String amountHint;
1069 private String comment;
1070 private String currency = "";
1071 private float amount;
1072 private boolean amountSet;
1073 private boolean amountValid = true;
1074 private FocusedElement focusedElement = FocusedElement.Account;
1075 private boolean amountHintIsSet = false;
1076 private boolean isLast = false;
1077 private int accountNameCursorPosition;
1078 public TransactionAccount(TransactionAccount origin) {
1080 accountName = origin.accountName;
1081 amount = origin.amount;
1082 amountSet = origin.amountSet;
1083 amountHint = origin.amountHint;
1084 amountHintIsSet = origin.amountHintIsSet;
1085 comment = origin.comment;
1086 currency = origin.currency;
1087 amountValid = origin.amountValid;
1088 focusedElement = origin.focusedElement;
1089 isLast = origin.isLast;
1090 accountNameCursorPosition = origin.accountNameCursorPosition;
1092 public TransactionAccount(LedgerTransactionAccount account) {
1094 currency = account.getCurrency();
1095 amount = account.getAmount();
1097 public TransactionAccount(String accountName) {
1099 this.accountName = accountName;
1101 public TransactionAccount(String accountName, @NotNull String currency) {
1103 this.accountName = accountName;
1104 this.currency = currency;
1106 public boolean isLast() {
1109 public boolean isAmountSet() {
1112 public String getAccountName() {
1115 public void setAccountName(String accountName) {
1116 this.accountName = accountName;
1118 public float getAmount() {
1120 throw new IllegalStateException("Amount is not set");
1123 public void setAmount(float amount) {
1124 this.amount = amount;
1127 public void resetAmount() {
1131 public ItemType getType() {
1132 return ItemType.transactionRow;
1134 public String getAmountHint() {
1137 public void setAmountHint(String amountHint) {
1138 this.amountHint = amountHint;
1139 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1141 public String getComment() {
1144 public void setComment(String comment) {
1145 this.comment = comment;
1148 public String getCurrency() {
1151 public void setCurrency(@org.jetbrains.annotations.Nullable String currency) {
1152 this.currency = Misc.nullIsEmpty(currency);
1154 public boolean isAmountValid() {
1157 public void setAmountValid(boolean amountValid) {
1158 this.amountValid = amountValid;
1160 public FocusedElement getFocusedElement() {
1161 return focusedElement;
1163 public void setFocusedElement(FocusedElement focusedElement) {
1164 this.focusedElement = focusedElement;
1166 public boolean isAmountHintSet() {
1167 return amountHintIsSet;
1169 public void setAmountHintIsSet(boolean amountHintIsSet) {
1170 this.amountHintIsSet = amountHintIsSet;
1172 public boolean isEmpty() {
1173 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1174 Misc.emptyIsNull(comment) == null;
1176 @SuppressLint("DefaultLocale")
1178 public String toString() {
1179 StringBuilder b = new StringBuilder();
1180 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1181 if (!TextUtils.isEmpty(accountName))
1182 b.append(String.format(" acc'%s'", accountName));
1185 b.append(String.format(" %4.2f", amount));
1186 else if (amountHintIsSet)
1187 b.append(String.format(" (%s)", amountHint));
1189 if (!TextUtils.isEmpty(currency))
1193 if (!TextUtils.isEmpty(comment))
1194 b.append(String.format(" /%s/", comment));
1199 return b.toString();
1201 public boolean equalContents(TransactionAccount other) {
1205 boolean equal = Misc.equalStrings(accountName, other.accountName);
1206 equal = equal && Misc.equalStrings(comment, other.comment) &&
1207 (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1209 // compare amount hint only if there is no amount
1211 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1212 Misc.equalStrings(amountHint, other.amountHint)
1213 : !other.amountHintIsSet);
1214 equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1216 Logger.debug("new-trans",
1217 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1221 public int getAccountNameCursorPosition() {
1222 return accountNameCursorPosition;
1224 public void setAccountNameCursorPosition(int position) {
1225 this.accountNameCursorPosition = position;
1229 private static class BalanceForCurrency {
1230 private final HashMap<String, Float> hashMap = new HashMap<>();
1231 float get(String currencyName) {
1232 Float f = hashMap.get(currencyName);
1235 hashMap.put(currencyName, f);
1239 void add(String currencyName, float amount) {
1240 hashMap.put(currencyName, get(currencyName) + amount);
1242 Set<String> currencies() {
1243 return hashMap.keySet();
1245 boolean containsCurrency(String currencyName) {
1246 return hashMap.containsKey(currencyName);
1250 private static class ItemsForCurrency {
1251 private final HashMap<@NotNull String, List<Item>> hashMap = new HashMap<>();
1253 List<NewTransactionModel.Item> getList(@NotNull String currencyName) {
1254 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1256 list = new ArrayList<>();
1257 hashMap.put(currencyName, list);
1261 void add(@NotNull String currencyName, @NonNull NewTransactionModel.Item item) {
1262 getList(Objects.requireNonNull(currencyName)).add(item);
1264 int size(@NotNull String currencyName) {
1265 return this.getList(Objects.requireNonNull(currencyName))
1268 Set<String> currencies() {
1269 return hashMap.keySet();