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<>(Objects.requireNonNull(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 = new TransactionAccount(acc.getAccountName(),
501 Misc.nullIsEmpty(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() && item.isAmountValid()) {
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", i));
638 hasInvalidAmount = true;
641 itemsWithEmptyAmountForCurrency.add(currName, item);
643 if (!accName.isEmpty())
644 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
648 // 1) has at least two account names
651 Logger.debug("submittable", "Transaction not submittable: no account names");
652 else if (accounts == 1)
653 Logger.debug("submittable",
654 "Transaction not submittable: only one account name");
656 Logger.debug("submittable",
657 String.format("Transaction not submittable: only %d account names",
662 // 3) for each commodity:
663 // 3a) amount must balance to 0, or
664 // 3b) there must be exactly one empty amount (with account)
665 for (String balCurrency : itemsForCurrency.currencies()) {
666 float currencyBalance = balance.get(balCurrency);
667 if (Misc.isZero(currencyBalance)) {
668 // remove hints from all amount inputs in that currency
669 for (int i = 1; i < list.size(); i++) {
670 TransactionAccount acc = list.get(i)
671 .toTransactionAccount();
672 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
673 if (BuildConfig.DEBUG)
674 Logger.debug("submittable",
675 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
676 i, Misc.nullIsEmpty(acc.getAccountName()),
678 // skip if the amount is set, in which case the hint is not
680 if (!acc.isAmountSet() && acc.amountHintIsSet &&
681 !TextUtils.isEmpty(acc.getAmountHint()))
683 acc.setAmountHint(null);
691 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
692 int balanceReceiversCount = tmpList.size();
693 if (balanceReceiversCount != 1) {
694 if (BuildConfig.DEBUG) {
695 if (balanceReceiversCount == 0)
696 Logger.debug("submittable", String.format(
697 "Transaction not submittable [curr:%s]: non-zero balance " +
698 "with no empty amounts with accounts", balCurrency));
700 Logger.debug("submittable", String.format(
701 "Transaction not submittable [curr:%s]: non-zero balance " +
702 "with multiple empty amounts with accounts", balCurrency));
707 List<Item> emptyAmountList =
708 itemsWithEmptyAmountForCurrency.getList(balCurrency);
710 // suggest off-balance amount to a row and remove hints on other rows
711 Item receiver = null;
712 if (!tmpList.isEmpty())
713 receiver = tmpList.get(0);
714 else if (!emptyAmountList.isEmpty())
715 receiver = emptyAmountList.get(0);
717 for (int i = 0; i < list.size(); i++) {
718 Item item = list.get(i);
719 if (!(item instanceof TransactionAccount))
722 TransactionAccount acc = item.toTransactionAccount();
723 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
726 if (item == receiver) {
727 final String hint = Data.formatNumber(-currencyBalance);
728 if (!acc.isAmountHintSet() ||
729 !Misc.equalStrings(acc.getAmountHint(), hint))
731 Logger.debug("submittable",
732 String.format("Setting amount hint of {%s} to %s [%s]",
733 acc.toString(), hint, balCurrency));
734 acc.setAmountHint(hint);
739 if (BuildConfig.DEBUG)
740 Logger.debug("submittable",
741 String.format("Resetting hint of '%s' [%s]",
742 Misc.nullIsEmpty(acc.getAccountName()),
744 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
745 acc.setAmountHint(null);
753 // 5) a row with an empty account name or empty amount is guaranteed to exist for
755 if (!hasInvalidAmount) {
756 for (String balCurrency : balance.currencies()) {
757 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
758 int currRows = itemsForCurrency.size(balCurrency);
759 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
760 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
761 if ((currEmptyRows == 0) &&
762 ((currRows == currAccounts) || (currRows == currAmounts)))
764 // perhaps there already is an unused empty row for another currency that
766 // boolean foundIt = false;
767 // for (Item item : emptyRows) {
768 // Currency itemCurrency = item.getCurrency();
769 // String itemCurrencyName =
770 // (itemCurrency == null) ? "" : itemCurrency.getName();
771 // if (Misc.isZero(balance.get(itemCurrencyName))) {
772 // item.setCurrency(Currency.loadByName(balCurrency));
773 // item.setAmountHint(
774 // Data.formatNumber(-balance.get(balCurrency)));
781 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
782 final float bal = balance.get(balCurrency);
783 if (!Misc.isZero(bal) && currAmounts == currRows)
784 newAcc.setAmountHint(Data.formatNumber(-bal));
785 Logger.debug("submittable",
786 String.format("Adding new item with %s for currency %s",
787 newAcc.getAmountHint(), balCurrency));
794 // drop extra empty rows, not needed
795 for (String currName : emptyRowsForCurrency.currencies()) {
796 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
797 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
798 // the list is a copy, so the empty item is no longer present
799 Item itemToRemove = emptyItems.remove(1);
800 removeItemById(list, itemToRemove.id);
804 // unused currency, remove last item (which is also an empty one)
805 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
806 List<Item> currItems = itemsForCurrency.getList(currName);
808 if (currItems.size() == 1) {
809 // the list is a copy, so the empty item is no longer present
810 removeItemById(list, emptyItems.get(0).id);
816 // 6) at least two rows need to be present in the ledger
817 // (the list also contains header and trailer)
818 while (list.size() < MIN_ITEMS) {
819 list.add(new TransactionAccount(""));
823 Logger.debug("submittable", submittable ? "YES" : "NO");
824 isSubmittable.setValue(submittable);
826 if (BuildConfig.DEBUG)
827 dumpItemList("After submittable checks", list);
829 catch (NumberFormatException e) {
830 Logger.debug("submittable", "NO (because of NumberFormatException)");
831 isSubmittable.setValue(false);
833 catch (Exception e) {
835 Logger.debug("submittable", "NO (because of an Exception)");
836 isSubmittable.setValue(false);
839 if (listChanged && workingWithLiveList) {
840 setItemsWithoutSubmittableChecks(list);
843 private void removeItemById(@NotNull List<Item> list, int id) {
844 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
845 list.removeIf(item -> item.id == id);
848 for (Item item : list) {
856 @SuppressLint("DefaultLocale")
857 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
858 Logger.debug("submittable", "== Dump of all items " + msg);
859 for (int i = 1; i < list.size(); i++) {
860 TransactionAccount item = list.get(i)
861 .toTransactionAccount();
862 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
865 public void setItemCurrency(int position, String newCurrency) {
866 TransactionAccount item = Objects.requireNonNull(items.getValue())
868 .toTransactionAccount();
869 final String oldCurrency = item.getCurrency();
871 if (Misc.equalStrings(oldCurrency, newCurrency))
874 List<Item> newList = copyList();
875 newList.get(position)
876 .toTransactionAccount()
877 .setCurrency(newCurrency);
881 public boolean accountListIsEmpty() {
882 List<Item> items = Objects.requireNonNull(this.items.getValue());
884 for (Item item : items) {
885 if (!(item instanceof TransactionAccount))
888 if (!((TransactionAccount) item).isEmpty())
895 public static class FocusInfo {
897 FocusedElement element;
898 public FocusInfo(int position, FocusedElement element) {
899 this.position = position;
900 this.element = element;
904 static abstract class Item {
905 private static int idDispenser = 0;
908 if (this instanceof TransactionHead)
911 synchronized (Item.class) {
915 public Item(int id) {
918 public static Item from(Item origin) {
919 if (origin instanceof TransactionHead)
920 return new TransactionHead((TransactionHead) origin);
921 if (origin instanceof TransactionAccount)
922 return new TransactionAccount((TransactionAccount) origin);
923 throw new RuntimeException("Don't know how to handle " + origin);
925 private static void resetIdDispenser() {
931 public abstract ItemType getType();
932 public TransactionHead toTransactionHead() {
933 if (this instanceof TransactionHead)
934 return (TransactionHead) this;
936 throw new IllegalStateException("Wrong item type " + this);
938 public TransactionAccount toTransactionAccount() {
939 if (this instanceof TransactionAccount)
940 return (TransactionAccount) this;
942 throw new IllegalStateException("Wrong item type " + this);
944 public boolean equalContents(@Nullable Object item) {
948 if (!getClass().equals(item.getClass()))
951 // shortcut - comparing same instance
955 if (this instanceof TransactionHead)
956 return ((TransactionHead) item).equalContents((TransactionHead) this);
957 if (this instanceof TransactionAccount)
958 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
960 throw new RuntimeException("Don't know how to handle " + this);
965 //==========================================================================================
967 public static class TransactionHead extends Item {
968 private SimpleDate date;
969 private String description;
970 private String comment;
971 TransactionHead(String description) {
973 this.description = description;
975 public TransactionHead(TransactionHead origin) {
978 description = origin.description;
979 comment = origin.comment;
981 public SimpleDate getDate() {
984 public void setDate(SimpleDate date) {
987 public void setDate(String text) throws ParseException {
988 if (Misc.emptyIsNull(text) == null) {
993 date = Globals.parseLedgerDate(text);
998 * @return nicely formatted, shortest available date representation
1000 String getFormattedDate() {
1004 Calendar today = GregorianCalendar.getInstance();
1006 if (today.get(Calendar.YEAR) != date.year) {
1007 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
1010 if (today.get(Calendar.MONTH) + 1 != date.month) {
1011 return String.format(Locale.US, "%d/%02d", date.month, date.day);
1014 return String.valueOf(date.day);
1018 public String toString() {
1019 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
1020 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1022 if (TextUtils.isEmpty(description))
1023 b.append(" «no description»");
1025 b.append(String.format(" '%s'", description));
1028 b.append(String.format("@%s", date.toString()));
1030 if (!TextUtils.isEmpty(comment))
1031 b.append(String.format(" /%s/", comment));
1033 return b.toString();
1035 public String getDescription() {
1038 public void setDescription(String description) {
1039 this.description = description;
1041 public String getComment() {
1044 public void setComment(String comment) {
1045 this.comment = comment;
1048 public ItemType getType() {
1049 return ItemType.generalData;
1051 public LedgerTransaction asLedgerTransaction() {
1052 return new LedgerTransaction(0, (date == null) ? SimpleDate.today() : date, description,
1053 Objects.requireNonNull(Data.getProfile()));
1055 public boolean equalContents(TransactionHead other) {
1059 return Objects.equals(date, other.date) &&
1060 Misc.equalStrings(description, other.description) &&
1061 Misc.equalStrings(comment, other.comment);
1065 public static class TransactionAccount extends Item {
1066 private String accountName;
1067 private String amountHint;
1068 private String comment;
1070 private String currency = "";
1071 private float amount;
1072 private boolean amountSet;
1073 private boolean amountValid = true;
1075 private String amountText = "";
1076 private FocusedElement focusedElement = FocusedElement.Account;
1077 private boolean amountHintIsSet = false;
1078 private boolean isLast = false;
1079 private int accountNameCursorPosition;
1080 public TransactionAccount(TransactionAccount origin) {
1082 accountName = origin.accountName;
1083 amount = origin.amount;
1084 amountSet = origin.amountSet;
1085 amountHint = origin.amountHint;
1086 amountHintIsSet = origin.amountHintIsSet;
1087 amountText = origin.amountText;
1088 comment = origin.comment;
1089 currency = origin.currency;
1090 amountValid = origin.amountValid;
1091 focusedElement = origin.focusedElement;
1092 isLast = origin.isLast;
1093 accountNameCursorPosition = origin.accountNameCursorPosition;
1095 public TransactionAccount(String accountName) {
1097 this.accountName = accountName;
1099 public TransactionAccount(String accountName, @NotNull String currency) {
1101 this.accountName = accountName;
1102 this.currency = currency;
1104 public @NotNull String getAmountText() {
1107 public void setAmountText(@NotNull String amountText) {
1108 this.amountText = amountText;
1110 public boolean setAndCheckAmountText(@NotNull String amountText) {
1111 String amtText = amountText.trim();
1112 this.amountText = amtText;
1114 boolean significantChange = false;
1116 if (amtText.isEmpty()) {
1118 significantChange = true;
1124 amtText = amtText.replace(Data.getDecimalSeparator(), Data.decimalDot);
1125 final float parsedAmount = Float.parseFloat(amtText);
1126 if (!amountSet || !amountValid || !Misc.equalFloats(parsedAmount, amount))
1127 significantChange = true;
1128 amount = parsedAmount;
1132 catch (NumberFormatException e) {
1133 Logger.debug("new-trans", String.format(
1134 "assuming amount is not set due to number format exception. " +
1135 "input was '%s'", amtText));
1136 if (amountValid) // it was valid and now it's not
1137 significantChange = true;
1138 amountValid = false;
1142 return significantChange;
1144 public boolean isLast() {
1147 public boolean isAmountSet() {
1150 public String getAccountName() {
1153 public void setAccountName(String accountName) {
1154 this.accountName = accountName;
1156 public float getAmount() {
1158 throw new IllegalStateException("Amount is not set");
1161 public void setAmount(float amount) {
1162 this.amount = amount;
1165 amountText = Data.formatNumber(amount);
1167 public void resetAmount() {
1173 public ItemType getType() {
1174 return ItemType.transactionRow;
1176 public String getAmountHint() {
1179 public void setAmountHint(String amountHint) {
1180 this.amountHint = amountHint;
1181 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1183 public String getComment() {
1186 public void setComment(String comment) {
1187 this.comment = comment;
1190 public String getCurrency() {
1193 public void setCurrency(@org.jetbrains.annotations.Nullable String currency) {
1194 this.currency = Misc.nullIsEmpty(currency);
1196 public boolean isAmountValid() {
1199 public void setAmountValid(boolean amountValid) {
1200 this.amountValid = amountValid;
1202 public FocusedElement getFocusedElement() {
1203 return focusedElement;
1205 public void setFocusedElement(FocusedElement focusedElement) {
1206 this.focusedElement = focusedElement;
1208 public boolean isAmountHintSet() {
1209 return amountHintIsSet;
1211 public void setAmountHintIsSet(boolean amountHintIsSet) {
1212 this.amountHintIsSet = amountHintIsSet;
1214 public boolean isEmpty() {
1215 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1216 Misc.emptyIsNull(comment) == null;
1218 @SuppressLint("DefaultLocale")
1221 public String toString() {
1222 StringBuilder b = new StringBuilder();
1223 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1224 if (!TextUtils.isEmpty(accountName))
1225 b.append(String.format(" acc'%s'", accountName));
1228 b.append(amountText)
1230 .append(amountValid ? "valid" : "invalid")
1232 .append(String.format(Locale.ROOT, " {raw %4.2f}", amount));
1233 else if (amountHintIsSet)
1234 b.append(String.format(" (hint %s)", amountHint));
1236 if (!TextUtils.isEmpty(currency))
1240 if (!TextUtils.isEmpty(comment))
1241 b.append(String.format(" /%s/", comment));
1246 return b.toString();
1248 public boolean equalContents(TransactionAccount other) {
1252 boolean equal = Misc.equalStrings(accountName, other.accountName);
1253 equal = equal && Misc.equalStrings(comment, other.comment) &&
1254 (amountSet ? other.amountSet && amountValid == other.amountValid &&
1255 Misc.equalStrings(amountText, other.amountText)
1256 : !other.amountSet);
1258 // compare amount hint only if there is no amount
1260 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1261 Misc.equalStrings(amountHint, other.amountHint)
1262 : !other.amountHintIsSet);
1263 equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1265 Logger.debug("new-trans",
1266 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1270 public int getAccountNameCursorPosition() {
1271 return accountNameCursorPosition;
1273 public void setAccountNameCursorPosition(int position) {
1274 this.accountNameCursorPosition = position;
1278 private static class BalanceForCurrency {
1279 private final HashMap<String, Float> hashMap = new HashMap<>();
1280 float get(String currencyName) {
1281 Float f = hashMap.get(currencyName);
1284 hashMap.put(currencyName, f);
1288 void add(String currencyName, float amount) {
1289 hashMap.put(currencyName, get(currencyName) + amount);
1291 Set<String> currencies() {
1292 return hashMap.keySet();
1294 boolean containsCurrency(String currencyName) {
1295 return hashMap.containsKey(currencyName);
1299 private static class ItemsForCurrency {
1300 private final HashMap<@NotNull String, List<Item>> hashMap = new HashMap<>();
1302 List<NewTransactionModel.Item> getList(@NotNull String currencyName) {
1303 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1305 list = new ArrayList<>();
1306 hashMap.put(currencyName, list);
1310 void add(@NotNull String currencyName, @NonNull NewTransactionModel.Item item) {
1311 getList(Objects.requireNonNull(currencyName)).add(item);
1313 int size(@NotNull String currencyName) {
1314 return this.getList(Objects.requireNonNull(currencyName))
1317 Set<String> currencies() {
1318 return hashMap.keySet();