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.DB;
33 import net.ktnx.mobileledger.db.Profile;
34 import net.ktnx.mobileledger.db.TemplateAccount;
35 import net.ktnx.mobileledger.db.TemplateHeader;
36 import net.ktnx.mobileledger.db.TransactionWithAccounts;
37 import net.ktnx.mobileledger.model.Data;
38 import net.ktnx.mobileledger.model.InertMutableLiveData;
39 import net.ktnx.mobileledger.model.LedgerTransaction;
40 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
41 import net.ktnx.mobileledger.model.MatchedTemplate;
42 import net.ktnx.mobileledger.utils.Globals;
43 import net.ktnx.mobileledger.utils.Logger;
44 import net.ktnx.mobileledger.utils.Misc;
45 import net.ktnx.mobileledger.utils.SimpleDate;
47 import org.jetbrains.annotations.NotNull;
49 import java.text.ParseException;
50 import java.util.ArrayList;
51 import java.util.Calendar;
52 import java.util.GregorianCalendar;
53 import java.util.HashMap;
54 import java.util.List;
55 import java.util.Locale;
56 import java.util.Objects;
58 import java.util.concurrent.atomic.AtomicInteger;
59 import java.util.regex.MatchResult;
61 enum ItemType {generalData, transactionRow}
63 enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
66 public class NewTransactionModel extends ViewModel {
67 private static final int MIN_ITEMS = 3;
68 private final MutableLiveData<Boolean> showCurrency = new MutableLiveData<>(false);
69 private final MutableLiveData<Boolean> isSubmittable = new InertMutableLiveData<>(false);
70 private final MutableLiveData<Boolean> showComments = new MutableLiveData<>(true);
71 private final MutableLiveData<List<Item>> items = new MutableLiveData<>();
72 private final MutableLiveData<Boolean> simulateSave = new InertMutableLiveData<>(false);
73 private final AtomicInteger busyCounter = new AtomicInteger(0);
74 private final MutableLiveData<Boolean> busyFlag = new InertMutableLiveData<>(false);
75 private final Observer<Profile> profileObserver = profile -> {
76 showCurrency.postValue(profile.getShowCommodityByDefault());
77 showComments.postValue(profile.getShowCommentsByDefault());
79 private final MutableLiveData<FocusInfo> focusInfo = new MutableLiveData<>();
80 private boolean observingDataProfile;
81 public NewTransactionModel() {
84 public LiveData<Boolean> getShowCurrency() {
87 public LiveData<List<Item>> getItems() {
90 private void setItems(@NonNull List<Item> newList) {
91 checkTransactionSubmittable(newList);
92 setItemsWithoutSubmittableChecks(newList);
94 private void replaceItems(@NonNull List<Item> newList) {
100 * make old items replaceable in-place. makes the new values visually blend in
102 private void renumberItems() {
103 final List<Item> list = items.getValue();
109 for (Item item : list)
112 private void setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
113 final int cnt = list.size();
114 for (int i = 1; i < cnt - 1; i++) {
115 final TransactionAccount item = list.get(i)
116 .toTransactionAccount();
118 TransactionAccount replacement = new TransactionAccount(item);
119 replacement.isLast = false;
120 list.set(i, replacement);
123 final TransactionAccount last = list.get(cnt - 1)
124 .toTransactionAccount();
126 TransactionAccount replacement = new TransactionAccount(last);
127 replacement.isLast = true;
128 list.set(cnt - 1, replacement);
131 if (BuildConfig.DEBUG)
132 dumpItemList("Before setValue()", list);
133 items.setValue(list);
135 private List<Item> copyList() {
136 List<Item> copy = new ArrayList<>();
137 List<Item> oldList = items.getValue();
140 for (Item item : oldList) {
141 copy.add(Item.from(item));
146 private List<Item> copyListWithoutItem(int position) {
147 List<Item> copy = new ArrayList<>();
148 List<Item> oldList = items.getValue();
150 if (oldList != null) {
152 for (Item item : oldList) {
155 copy.add(Item.from(item));
161 private List<Item> shallowCopyList() {
162 return new ArrayList<>(items.getValue());
164 LiveData<Boolean> getShowComments() {
167 void observeDataProfile(LifecycleOwner activity) {
168 if (!observingDataProfile)
169 Data.observeProfile(activity, profileObserver);
170 observingDataProfile = true;
172 boolean getSimulateSaveFlag() {
173 Boolean value = simulateSave.getValue();
178 LiveData<Boolean> getSimulateSave() {
181 void toggleSimulateSave() {
182 simulateSave.setValue(!getSimulateSaveFlag());
184 LiveData<Boolean> isSubmittable() {
185 return this.isSubmittable;
188 Logger.debug("new-trans", "Resetting model");
189 List<Item> list = new ArrayList<>();
190 Item.resetIdDispenser();
191 list.add(new TransactionHead(""));
192 list.add(new TransactionAccount(""));
193 list.add(new TransactionAccount(""));
194 noteFocusChanged(0, FocusedElement.Description);
196 isSubmittable.setValue(false);
197 setItemsWithoutSubmittableChecks(list);
199 boolean accountsInInitialState() {
200 final List<Item> list = items.getValue();
205 for (Item item : list) {
206 if (!(item instanceof TransactionAccount))
209 TransactionAccount accRow = (TransactionAccount) item;
210 if (!accRow.isEmpty())
216 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
217 SimpleDate transactionDate = null;
218 final MatchResult matchResult = matchedTemplate.matchResult;
219 final TemplateHeader templateHead = matchedTemplate.templateHead;
221 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
222 templateHead.getDateDay());
223 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
224 templateHead.getDateMonth());
225 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
226 templateHead.getDateYear());
228 if (year > 0 || month > 0 || day > 0) {
229 SimpleDate today = SimpleDate.today();
237 transactionDate = new SimpleDate(year, month, day);
239 Logger.debug("pattern", "setting transaction date to " + transactionDate);
243 List<Item> present = copyList();
245 TransactionHead head = new TransactionHead(present.get(0)
246 .toTransactionHead());
247 if (transactionDate != null)
248 head.setDate(transactionDate);
250 final String transactionDescription = extractStringFromMatches(matchResult,
251 templateHead.getTransactionDescriptionMatchGroup(),
252 templateHead.getTransactionDescription());
253 if (Misc.emptyIsNull(transactionDescription) != null)
254 head.setDescription(transactionDescription);
256 final String transactionComment = extractStringFromMatches(matchResult,
257 templateHead.getTransactionCommentMatchGroup(),
258 templateHead.getTransactionComment());
259 if (Misc.emptyIsNull(transactionComment) != null)
260 head.setComment(transactionComment);
262 Item.resetIdDispenser();
263 List<Item> newItems = new ArrayList<>();
267 for (int i = 1; i < present.size(); i++) {
268 final TransactionAccount row = present.get(i)
269 .toTransactionAccount();
271 newItems.add(new TransactionAccount(row));
276 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
278 final boolean accountsInInitialState = accountsInInitialState();
279 for (TemplateAccount acc : entry.accounts) {
283 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
284 acc.getAccountName());
285 String accountComment =
286 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
287 acc.getAccountComment());
288 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
290 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
294 TransactionAccount accRow = new TransactionAccount(accountName);
295 accRow.setComment(accountComment);
297 accRow.setAmount(amount);
299 newItems.add(accRow);
302 Misc.onMainThread(() -> replaceItems(newItems));
305 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
311 if (grp > 0 & grp <= m.groupCount())
313 return Integer.parseInt(m.group(grp));
315 catch (NumberFormatException e) {
316 Logger.debug("new-trans", "Error extracting matched number", e);
322 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
328 if (grp > 0 & grp <= m.groupCount())
334 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
340 if (grp > 0 & grp <= m.groupCount())
342 return Float.valueOf(m.group(grp));
344 catch (NumberFormatException e) {
345 Logger.debug("new-trans", "Error extracting matched number", e);
351 void removeItem(int pos) {
352 Logger.debug("new-trans", String.format(Locale.US, "Removing item at position %d", pos));
353 List<Item> newList = copyListWithoutItem(pos);
354 final FocusInfo fi = focusInfo.getValue();
355 if ((fi != null) && (pos < fi.position))
356 noteFocusChanged(fi.position - 1, fi.element);
359 void noteFocusChanged(int position, FocusedElement element) {
360 FocusInfo present = focusInfo.getValue();
361 if (present == null || present.position != position || present.element != element)
362 focusInfo.setValue(new FocusInfo(position, element));
364 public LiveData<FocusInfo> getFocusInfo() {
367 void moveItem(int fromIndex, int toIndex) {
368 List<Item> newList = shallowCopyList();
369 Item item = newList.remove(fromIndex);
370 newList.add(toIndex, item);
372 FocusInfo fi = focusInfo.getValue();
373 if (fi != null && fi.position == fromIndex)
374 noteFocusChanged(toIndex, fi.element);
376 items.setValue(newList); // same count, same submittable state
378 void moveItemLast(List<Item> list, int index) {
382 3 <-- desired position
385 int itemCount = list.size();
387 if (index < itemCount - 1)
388 list.add(list.remove(index));
390 void toggleCurrencyVisible() {
391 final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
393 // remove currency from all items, or reset currency to the default
394 // no need to clone the list, because the removal of the currency won't lead to
395 // visual changes -- the currency fields will be hidden or reset to default anyway
396 // still, there may be changes in the submittable state
397 final List<Item> list = Objects.requireNonNull(this.items.getValue());
398 for (int i = 1; i < list.size(); i++) {
399 ((TransactionAccount) list.get(i)).setCurrency(newValue ? Data.getProfile()
400 .getDefaultCommodity()
403 checkTransactionSubmittable(null);
404 showCurrency.setValue(newValue);
406 void stopObservingBusyFlag(Observer<Boolean> observer) {
407 busyFlag.removeObserver(observer);
409 void incrementBusyCounter() {
410 int newValue = busyCounter.incrementAndGet();
412 busyFlag.postValue(true);
414 void decrementBusyCounter() {
415 int newValue = busyCounter.decrementAndGet();
417 busyFlag.postValue(false);
419 public LiveData<Boolean> getBusyFlag() {
422 public void toggleShowComments() {
423 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
425 public LedgerTransaction constructLedgerTransaction() {
426 List<Item> list = Objects.requireNonNull(items.getValue());
427 TransactionHead head = list.get(0)
428 .toTransactionHead();
429 LedgerTransaction tr = head.asLedgerTransaction();
431 tr.setComment(head.getComment());
432 LedgerTransactionAccount emptyAmountAccount = null;
433 float emptyAmountAccountBalance = 0;
434 for (int i = 1; i < list.size(); i++) {
435 TransactionAccount item = list.get(i)
436 .toTransactionAccount();
437 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
440 if (acc.getAccountName()
444 acc.setComment(item.getComment());
446 if (item.isAmountSet()) {
447 acc.setAmount(item.getAmount());
448 emptyAmountAccountBalance += item.getAmount();
451 emptyAmountAccount = acc;
457 if (emptyAmountAccount != null)
458 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
462 void loadTransactionIntoModel(@NonNull TransactionWithAccounts tr) {
463 List<Item> newList = new ArrayList<>();
464 Item.resetIdDispenser();
466 TransactionHead head = new TransactionHead(tr.transaction.getDescription());
467 head.setComment(tr.transaction.getComment());
471 List<LedgerTransactionAccount> accounts = new ArrayList<>();
472 for (net.ktnx.mobileledger.db.TransactionAccount acc : tr.accounts) {
473 accounts.add(new LedgerTransactionAccount(acc));
476 TransactionAccount firstNegative = null;
477 TransactionAccount firstPositive = null;
478 int singleNegativeIndex = -1;
479 int singlePositiveIndex = -1;
480 int negativeCount = 0;
481 for (int i = 0; i < accounts.size(); i++) {
482 LedgerTransactionAccount acc = accounts.get(i);
483 TransactionAccount item =
484 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
487 item.setAccountName(acc.getAccountName());
488 item.setComment(acc.getComment());
489 if (acc.isAmountSet()) {
490 item.setAmount(acc.getAmount());
491 if (acc.getAmount() < 0) {
492 if (firstNegative == null) {
493 firstNegative = item;
494 singleNegativeIndex = i + 1;
497 singleNegativeIndex = -1;
500 if (firstPositive == null) {
501 firstPositive = item;
502 singlePositiveIndex = i + 1;
505 singlePositiveIndex = -1;
511 if (BuildConfig.DEBUG)
512 dumpItemList("Loaded previous transaction", newList);
514 if (singleNegativeIndex != -1) {
515 firstNegative.resetAmount();
516 moveItemLast(newList, singleNegativeIndex);
518 else if (singlePositiveIndex != -1) {
519 firstPositive.resetAmount();
520 moveItemLast(newList, singlePositiveIndex);
523 Misc.onMainThread(() -> {
525 noteFocusChanged(1, FocusedElement.Amount);
529 * A transaction is submittable if:
531 * 1) has at least two account names
532 * 2) each row with amount has account name
533 * 3) for each commodity:
534 * 3a) amounts must balance to 0, or
535 * 3b) there must be exactly one empty amount (with account)
536 * 4) empty accounts with empty amounts are ignored
538 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
540 * 6) at least two rows need to be present in the ledger
542 * @param list - the item list to check. Can be the displayed list or a list that will be
545 @SuppressLint("DefaultLocale")
546 void checkTransactionSubmittable(@Nullable List<Item> list) {
547 boolean workingWithLiveList = false;
550 workingWithLiveList = true;
553 if (BuildConfig.DEBUG)
554 dumpItemList(String.format("Before submittable checks (%s)",
555 workingWithLiveList ? "LIVE LIST" : "custom list"), list);
558 final BalanceForCurrency balance = new BalanceForCurrency();
559 final String descriptionText = list.get(0)
562 boolean submittable = true;
563 boolean listChanged = false;
564 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
565 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
566 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
567 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
568 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
569 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
570 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
571 final List<Item> emptyRows = new ArrayList<>();
574 if ((descriptionText == null) || descriptionText.trim()
577 Logger.debug("submittable", "Transaction not submittable: missing description");
581 for (int i = 1; i < list.size(); i++) {
582 TransactionAccount item = list.get(i)
583 .toTransactionAccount();
585 String accName = item.getAccountName()
587 String currName = item.getCurrency();
589 itemsForCurrency.add(currName, item);
591 if (accName.isEmpty()) {
592 itemsWithEmptyAccountForCurrency.add(currName, item);
594 if (item.isAmountSet()) {
595 // 2) each amount has account name
596 Logger.debug("submittable", String.format(
597 "Transaction not submittable: row %d has no account name, but" +
598 " has" + " amount %1.2f", i + 1, item.getAmount()));
602 emptyRowsForCurrency.add(currName, item);
607 itemsWithAccountForCurrency.add(currName, item);
610 if (!item.isAmountValid()) {
611 Logger.debug("submittable",
612 String.format("Not submittable: row %d has an invalid amount", i + 1));
615 else if (item.isAmountSet()) {
616 itemsWithAmountForCurrency.add(currName, item);
617 balance.add(currName, item.getAmount());
620 itemsWithEmptyAmountForCurrency.add(currName, item);
622 if (!accName.isEmpty())
623 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
627 // 1) has at least two account names
630 Logger.debug("submittable", "Transaction not submittable: no account names");
631 else if (accounts == 1)
632 Logger.debug("submittable",
633 "Transaction not submittable: only one account name");
635 Logger.debug("submittable",
636 String.format("Transaction not submittable: only %d account names",
641 // 3) for each commodity:
642 // 3a) amount must balance to 0, or
643 // 3b) there must be exactly one empty amount (with account)
644 for (String balCurrency : itemsForCurrency.currencies()) {
645 float currencyBalance = balance.get(balCurrency);
646 if (Misc.isZero(currencyBalance)) {
647 // remove hints from all amount inputs in that currency
648 for (int i = 1; i < list.size(); i++) {
649 TransactionAccount acc = list.get(i)
650 .toTransactionAccount();
651 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
652 if (BuildConfig.DEBUG)
653 Logger.debug("submittable",
654 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
655 i, Misc.nullIsEmpty(acc.getAccountName()),
657 // skip if the amount is set, in which case the hint is not
659 if (!acc.isAmountSet() && acc.amountHintIsSet &&
660 !TextUtils.isEmpty(acc.getAmountHint()))
662 acc.setAmountHint(null);
670 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
671 int balanceReceiversCount = tmpList.size();
672 if (balanceReceiversCount != 1) {
673 if (BuildConfig.DEBUG) {
674 if (balanceReceiversCount == 0)
675 Logger.debug("submittable", String.format(
676 "Transaction not submittable [%s]: non-zero balance " +
677 "with no empty amounts with accounts", balCurrency));
679 Logger.debug("submittable", String.format(
680 "Transaction not submittable [%s]: non-zero balance " +
681 "with multiple empty amounts with accounts", balCurrency));
686 List<Item> emptyAmountList =
687 itemsWithEmptyAmountForCurrency.getList(balCurrency);
689 // suggest off-balance amount to a row and remove hints on other rows
690 Item receiver = null;
691 if (!tmpList.isEmpty())
692 receiver = tmpList.get(0);
693 else if (!emptyAmountList.isEmpty())
694 receiver = emptyAmountList.get(0);
696 for (int i = 0; i < list.size(); i++) {
697 Item item = list.get(i);
698 if (!(item instanceof TransactionAccount))
701 TransactionAccount acc = item.toTransactionAccount();
702 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
705 if (item == receiver) {
706 final String hint = String.format("%1.2f", -currencyBalance);
707 if (!acc.isAmountHintSet() ||
708 !Misc.equalStrings(acc.getAmountHint(), hint))
710 Logger.debug("submittable",
711 String.format("Setting amount hint of {%s} to %s [%s]",
712 acc.toString(), hint, balCurrency));
713 acc.setAmountHint(hint);
718 if (BuildConfig.DEBUG)
719 Logger.debug("submittable",
720 String.format("Resetting hint of '%s' [%s]",
721 Misc.nullIsEmpty(acc.getAccountName()),
723 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
724 acc.setAmountHint(null);
732 // 5) a row with an empty account name or empty amount is guaranteed to exist for
734 for (String balCurrency : balance.currencies()) {
735 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
736 int currRows = itemsForCurrency.size(balCurrency);
737 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
738 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
739 if ((currEmptyRows == 0) &&
740 ((currRows == currAccounts) || (currRows == currAmounts)))
742 // perhaps there already is an unused empty row for another currency that
744 // boolean foundIt = false;
745 // for (Item item : emptyRows) {
746 // Currency itemCurrency = item.getCurrency();
747 // String itemCurrencyName =
748 // (itemCurrency == null) ? "" : itemCurrency.getName();
749 // if (Misc.isZero(balance.get(itemCurrencyName))) {
750 // item.setCurrency(Currency.loadByName(balCurrency));
751 // item.setAmountHint(
752 // String.format("%1.2f", -balance.get(balCurrency)));
759 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
760 final float bal = balance.get(balCurrency);
761 if (!Misc.isZero(bal) && currAmounts == currRows)
762 newAcc.setAmountHint(String.format("%4.2f", -bal));
763 Logger.debug("submittable",
764 String.format("Adding new item with %s for currency %s",
765 newAcc.getAmountHint(), balCurrency));
771 // drop extra empty rows, not needed
772 for (String currName : emptyRowsForCurrency.currencies()) {
773 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
774 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
775 // the list is a copy, so the empty item is no longer present
776 Item itemToRemove = emptyItems.remove(1);
777 removeItemById(list, itemToRemove.id);
781 // unused currency, remove last item (which is also an empty one)
782 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
783 List<Item> currItems = itemsForCurrency.getList(currName);
785 if (currItems.size() == 1) {
786 // the list is a copy, so the empty item is no longer present
787 removeItemById(list, emptyItems.get(0).id);
793 // 6) at least two rows need to be present in the ledger
794 // (the list also contains header and trailer)
795 while (list.size() < MIN_ITEMS) {
796 list.add(new TransactionAccount(""));
800 Logger.debug("submittable", submittable ? "YES" : "NO");
801 isSubmittable.setValue(submittable);
803 if (BuildConfig.DEBUG)
804 dumpItemList("After submittable checks", list);
806 catch (NumberFormatException e) {
807 Logger.debug("submittable", "NO (because of NumberFormatException)");
808 isSubmittable.setValue(false);
810 catch (Exception e) {
812 Logger.debug("submittable", "NO (because of an Exception)");
813 isSubmittable.setValue(false);
816 if (listChanged && workingWithLiveList) {
817 setItemsWithoutSubmittableChecks(list);
820 private void removeItemById(@NotNull List<Item> list, int id) {
821 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
822 list.removeIf(item -> item.id == id);
825 for (Item item : list) {
833 @SuppressLint("DefaultLocale")
834 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
835 Logger.debug("submittable", "== Dump of all items " + msg);
836 for (int i = 1; i < list.size(); i++) {
837 TransactionAccount item = list.get(i)
838 .toTransactionAccount();
839 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
842 public void setItemCurrency(int position, String newCurrency) {
843 TransactionAccount item = Objects.requireNonNull(items.getValue())
845 .toTransactionAccount();
846 final String oldCurrency = item.getCurrency();
848 if (Misc.equalStrings(oldCurrency, newCurrency))
851 List<Item> newList = copyList();
852 newList.get(position)
853 .toTransactionAccount()
854 .setCurrency(newCurrency);
858 public boolean accountListIsEmpty() {
859 List<Item> items = Objects.requireNonNull(this.items.getValue());
861 for (Item item : items) {
862 if (!(item instanceof TransactionAccount))
865 if (!((TransactionAccount) item).isEmpty())
872 public static class FocusInfo {
874 FocusedElement element;
875 public FocusInfo(int position, FocusedElement element) {
876 this.position = position;
877 this.element = element;
881 static abstract class Item {
882 private static int idDispenser = 0;
885 if (this instanceof TransactionHead)
888 synchronized (Item.class) {
892 public Item(int id) {
895 public static Item from(Item origin) {
896 if (origin instanceof TransactionHead)
897 return new TransactionHead((TransactionHead) origin);
898 if (origin instanceof TransactionAccount)
899 return new TransactionAccount((TransactionAccount) origin);
900 throw new RuntimeException("Don't know how to handle " + origin);
902 private static void resetIdDispenser() {
908 public abstract ItemType getType();
909 public TransactionHead toTransactionHead() {
910 if (this instanceof TransactionHead)
911 return (TransactionHead) this;
913 throw new IllegalStateException("Wrong item type " + this);
915 public TransactionAccount toTransactionAccount() {
916 if (this instanceof TransactionAccount)
917 return (TransactionAccount) this;
919 throw new IllegalStateException("Wrong item type " + this);
921 public boolean equalContents(@Nullable Object item) {
925 if (!getClass().equals(item.getClass()))
928 // shortcut - comparing same instance
932 if (this instanceof TransactionHead)
933 return ((TransactionHead) item).equalContents((TransactionHead) this);
934 if (this instanceof TransactionAccount)
935 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
937 throw new RuntimeException("Don't know how to handle " + this);
942 //==========================================================================================
944 public static class TransactionHead extends Item {
945 private SimpleDate date;
946 private String description;
947 private String comment;
948 TransactionHead(String description) {
950 this.description = description;
952 public TransactionHead(TransactionHead origin) {
955 description = origin.description;
956 comment = origin.comment;
958 public SimpleDate getDate() {
961 public void setDate(SimpleDate date) {
964 public void setDate(String text) throws ParseException {
965 if (Misc.emptyIsNull(text) == null) {
970 date = Globals.parseLedgerDate(text);
975 * @return nicely formatted, shortest available date representation
977 String getFormattedDate() {
981 Calendar today = GregorianCalendar.getInstance();
983 if (today.get(Calendar.YEAR) != date.year) {
984 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
987 if (today.get(Calendar.MONTH) + 1 != date.month) {
988 return String.format(Locale.US, "%d/%02d", date.month, date.day);
991 return String.valueOf(date.day);
995 public String toString() {
996 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
997 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
999 if (TextUtils.isEmpty(description))
1000 b.append(" «no description»");
1002 b.append(String.format(" '%s'", description));
1005 b.append(String.format("@%s", date.toString()));
1007 if (!TextUtils.isEmpty(comment))
1008 b.append(String.format(" /%s/", comment));
1010 return b.toString();
1012 public String getDescription() {
1015 public void setDescription(String description) {
1016 this.description = description;
1018 public String getComment() {
1021 public void setComment(String comment) {
1022 this.comment = comment;
1025 public ItemType getType() {
1026 return ItemType.generalData;
1028 public LedgerTransaction asLedgerTransaction() {
1029 return new LedgerTransaction(0, (date == null) ? SimpleDate.today() : date, description,
1032 public boolean equalContents(TransactionHead other) {
1036 return Objects.equals(date, other.date) &&
1037 Misc.equalStrings(description, other.description) &&
1038 Misc.equalStrings(comment, other.comment);
1042 public static class TransactionAccount extends Item {
1043 private String accountName;
1044 private String amountHint;
1045 private String comment;
1046 private String currency;
1047 private float amount;
1048 private boolean amountSet;
1049 private boolean amountValid = true;
1050 private FocusedElement focusedElement = FocusedElement.Account;
1051 private boolean amountHintIsSet = false;
1052 private boolean isLast = false;
1053 private int accountNameCursorPosition;
1054 public TransactionAccount(TransactionAccount origin) {
1056 accountName = origin.accountName;
1057 amount = origin.amount;
1058 amountSet = origin.amountSet;
1059 amountHint = origin.amountHint;
1060 amountHintIsSet = origin.amountHintIsSet;
1061 comment = origin.comment;
1062 currency = origin.currency;
1063 amountValid = origin.amountValid;
1064 focusedElement = origin.focusedElement;
1065 isLast = origin.isLast;
1066 accountNameCursorPosition = origin.accountNameCursorPosition;
1068 public TransactionAccount(LedgerTransactionAccount account) {
1070 currency = account.getCurrency();
1071 amount = account.getAmount();
1073 public TransactionAccount(String accountName) {
1075 this.accountName = accountName;
1077 public TransactionAccount(String accountName, String currency) {
1079 this.accountName = accountName;
1080 this.currency = currency;
1082 public boolean isLast() {
1085 public boolean isAmountSet() {
1088 public String getAccountName() {
1091 public void setAccountName(String accountName) {
1092 this.accountName = accountName;
1094 public float getAmount() {
1096 throw new IllegalStateException("Amount is not set");
1099 public void setAmount(float amount) {
1100 this.amount = amount;
1103 public void resetAmount() {
1107 public ItemType getType() {
1108 return ItemType.transactionRow;
1110 public String getAmountHint() {
1113 public void setAmountHint(String amountHint) {
1114 this.amountHint = amountHint;
1115 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1117 public String getComment() {
1120 public void setComment(String comment) {
1121 this.comment = comment;
1123 public String getCurrency() {
1126 public void setCurrency(String currency) {
1127 this.currency = currency;
1129 public boolean isAmountValid() {
1132 public void setAmountValid(boolean amountValid) {
1133 this.amountValid = amountValid;
1135 public FocusedElement getFocusedElement() {
1136 return focusedElement;
1138 public void setFocusedElement(FocusedElement focusedElement) {
1139 this.focusedElement = focusedElement;
1141 public boolean isAmountHintSet() {
1142 return amountHintIsSet;
1144 public void setAmountHintIsSet(boolean amountHintIsSet) {
1145 this.amountHintIsSet = amountHintIsSet;
1147 public boolean isEmpty() {
1148 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1149 Misc.emptyIsNull(comment) == null;
1151 @SuppressLint("DefaultLocale")
1153 public String toString() {
1154 StringBuilder b = new StringBuilder();
1155 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1156 if (!TextUtils.isEmpty(accountName))
1157 b.append(String.format(" acc'%s'", accountName));
1160 b.append(String.format(" %4.2f", amount));
1161 else if (amountHintIsSet)
1162 b.append(String.format(" (%s)", amountHint));
1164 if (!TextUtils.isEmpty(currency))
1168 if (!TextUtils.isEmpty(comment))
1169 b.append(String.format(" /%s/", comment));
1174 return b.toString();
1176 public boolean equalContents(TransactionAccount other) {
1180 boolean equal = Misc.equalStrings(accountName, other.accountName);
1181 equal = equal && Misc.equalStrings(comment, other.comment) &&
1182 (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1184 // compare amount hint only if there is no amount
1186 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1187 Misc.equalStrings(amountHint, other.amountHint)
1188 : !other.amountHintIsSet);
1189 equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1191 Logger.debug("new-trans",
1192 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1196 public int getAccountNameCursorPosition() {
1197 return accountNameCursorPosition;
1199 public void setAccountNameCursorPosition(int position) {
1200 this.accountNameCursorPosition = position;
1204 private static class BalanceForCurrency {
1205 private final HashMap<String, Float> hashMap = new HashMap<>();
1206 float get(String currencyName) {
1207 Float f = hashMap.get(currencyName);
1210 hashMap.put(currencyName, f);
1214 void add(String currencyName, float amount) {
1215 hashMap.put(currencyName, get(currencyName) + amount);
1217 Set<String> currencies() {
1218 return hashMap.keySet();
1220 boolean containsCurrency(String currencyName) {
1221 return hashMap.containsKey(currencyName);
1225 private static class ItemsForCurrency {
1226 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1228 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1229 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1231 list = new ArrayList<>();
1232 hashMap.put(currencyName, list);
1236 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1237 getList(currencyName).add(item);
1239 int size(@Nullable String currencyName) {
1240 return this.getList(currencyName)
1243 Set<String> currencies() {
1244 return hashMap.keySet();