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 SimpleDate date = head.getDate();
430 LedgerTransaction tr = head.asLedgerTransaction();
432 tr.setComment(head.getComment());
433 LedgerTransactionAccount emptyAmountAccount = null;
434 float emptyAmountAccountBalance = 0;
435 for (int i = 1; i < list.size(); i++) {
436 TransactionAccount item = list.get(i)
437 .toTransactionAccount();
438 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
441 if (acc.getAccountName()
445 acc.setComment(item.getComment());
447 if (item.isAmountSet()) {
448 acc.setAmount(item.getAmount());
449 emptyAmountAccountBalance += item.getAmount();
452 emptyAmountAccount = acc;
458 if (emptyAmountAccount != null)
459 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
463 void loadTransactionIntoModel(@NonNull TransactionWithAccounts tr) {
464 List<Item> newList = new ArrayList<>();
465 Item.resetIdDispenser();
467 TransactionHead head = new TransactionHead(tr.transaction.getDescription());
468 head.setComment(tr.transaction.getComment());
472 List<LedgerTransactionAccount> accounts = new ArrayList<>();
473 for (net.ktnx.mobileledger.db.TransactionAccount acc : tr.accounts) {
474 accounts.add(new LedgerTransactionAccount(acc));
477 TransactionAccount firstNegative = null;
478 TransactionAccount firstPositive = null;
479 int singleNegativeIndex = -1;
480 int singlePositiveIndex = -1;
481 int negativeCount = 0;
482 for (int i = 0; i < accounts.size(); i++) {
483 LedgerTransactionAccount acc = accounts.get(i);
484 TransactionAccount item =
485 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
488 item.setAccountName(acc.getAccountName());
489 item.setComment(acc.getComment());
490 if (acc.isAmountSet()) {
491 item.setAmount(acc.getAmount());
492 if (acc.getAmount() < 0) {
493 if (firstNegative == null) {
494 firstNegative = item;
495 singleNegativeIndex = i + 1;
498 singleNegativeIndex = -1;
501 if (firstPositive == null) {
502 firstPositive = item;
503 singlePositiveIndex = i + 1;
506 singlePositiveIndex = -1;
512 if (BuildConfig.DEBUG)
513 dumpItemList("Loaded previous transaction", newList);
515 if (singleNegativeIndex != -1) {
516 firstNegative.resetAmount();
517 moveItemLast(newList, singleNegativeIndex);
519 else if (singlePositiveIndex != -1) {
520 firstPositive.resetAmount();
521 moveItemLast(newList, singlePositiveIndex);
524 Misc.onMainThread(() -> {
526 noteFocusChanged(1, FocusedElement.Amount);
530 * A transaction is submittable if:
532 * 1) has at least two account names
533 * 2) each row with amount has account name
534 * 3) for each commodity:
535 * 3a) amounts must balance to 0, or
536 * 3b) there must be exactly one empty amount (with account)
537 * 4) empty accounts with empty amounts are ignored
539 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
541 * 6) at least two rows need to be present in the ledger
543 * @param list - the item list to check. Can be the displayed list or a list that will be
546 @SuppressLint("DefaultLocale")
547 void checkTransactionSubmittable(@Nullable List<Item> list) {
548 boolean workingWithLiveList = false;
551 workingWithLiveList = true;
554 if (BuildConfig.DEBUG)
555 dumpItemList(String.format("Before submittable checks (%s)",
556 workingWithLiveList ? "LIVE LIST" : "custom list"), list);
559 final BalanceForCurrency balance = new BalanceForCurrency();
560 final String descriptionText = list.get(0)
563 boolean submittable = true;
564 boolean listChanged = false;
565 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
566 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
567 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
568 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
569 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
570 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
571 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
572 final List<Item> emptyRows = new ArrayList<>();
575 if ((descriptionText == null) || descriptionText.trim()
578 Logger.debug("submittable", "Transaction not submittable: missing description");
582 for (int i = 1; i < list.size(); i++) {
583 TransactionAccount item = list.get(i)
584 .toTransactionAccount();
586 String accName = item.getAccountName()
588 String currName = item.getCurrency();
590 itemsForCurrency.add(currName, item);
592 if (accName.isEmpty()) {
593 itemsWithEmptyAccountForCurrency.add(currName, item);
595 if (item.isAmountSet()) {
596 // 2) each amount has account name
597 Logger.debug("submittable", String.format(
598 "Transaction not submittable: row %d has no account name, but" +
599 " has" + " amount %1.2f", i + 1, item.getAmount()));
603 emptyRowsForCurrency.add(currName, item);
608 itemsWithAccountForCurrency.add(currName, item);
611 if (!item.isAmountValid()) {
612 Logger.debug("submittable",
613 String.format("Not submittable: row %d has an invalid amount", i + 1));
616 else if (item.isAmountSet()) {
617 itemsWithAmountForCurrency.add(currName, item);
618 balance.add(currName, item.getAmount());
621 itemsWithEmptyAmountForCurrency.add(currName, item);
623 if (!accName.isEmpty())
624 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
628 // 1) has at least two account names
631 Logger.debug("submittable", "Transaction not submittable: no account names");
632 else if (accounts == 1)
633 Logger.debug("submittable",
634 "Transaction not submittable: only one account name");
636 Logger.debug("submittable",
637 String.format("Transaction not submittable: only %d account names",
642 // 3) for each commodity:
643 // 3a) amount must balance to 0, or
644 // 3b) there must be exactly one empty amount (with account)
645 for (String balCurrency : itemsForCurrency.currencies()) {
646 float currencyBalance = balance.get(balCurrency);
647 if (Misc.isZero(currencyBalance)) {
648 // remove hints from all amount inputs in that currency
649 for (int i = 1; i < list.size(); i++) {
650 TransactionAccount acc = list.get(i)
651 .toTransactionAccount();
652 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
653 if (BuildConfig.DEBUG)
654 Logger.debug("submittable",
655 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
656 i, Misc.nullIsEmpty(acc.getAccountName()),
658 // skip if the amount is set, in which case the hint is not
660 if (!acc.isAmountSet() && acc.amountHintIsSet &&
661 !TextUtils.isEmpty(acc.getAmountHint()))
663 acc.setAmountHint(null);
671 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
672 int balanceReceiversCount = tmpList.size();
673 if (balanceReceiversCount != 1) {
674 if (BuildConfig.DEBUG) {
675 if (balanceReceiversCount == 0)
676 Logger.debug("submittable", String.format(
677 "Transaction not submittable [%s]: non-zero balance " +
678 "with no empty amounts with accounts", balCurrency));
680 Logger.debug("submittable", String.format(
681 "Transaction not submittable [%s]: non-zero balance " +
682 "with multiple empty amounts with accounts", balCurrency));
687 List<Item> emptyAmountList =
688 itemsWithEmptyAmountForCurrency.getList(balCurrency);
690 // suggest off-balance amount to a row and remove hints on other rows
691 Item receiver = null;
692 if (!tmpList.isEmpty())
693 receiver = tmpList.get(0);
694 else if (!emptyAmountList.isEmpty())
695 receiver = emptyAmountList.get(0);
697 for (int i = 0; i < list.size(); i++) {
698 Item item = list.get(i);
699 if (!(item instanceof TransactionAccount))
702 TransactionAccount acc = item.toTransactionAccount();
703 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
706 if (item == receiver) {
707 final String hint = String.format("%1.2f", -currencyBalance);
708 if (!acc.isAmountHintSet() ||
709 !Misc.equalStrings(acc.getAmountHint(), hint))
711 Logger.debug("submittable",
712 String.format("Setting amount hint of {%s} to %s [%s]",
713 acc.toString(), hint, balCurrency));
714 acc.setAmountHint(hint);
719 if (BuildConfig.DEBUG)
720 Logger.debug("submittable",
721 String.format("Resetting hint of '%s' [%s]",
722 Misc.nullIsEmpty(acc.getAccountName()),
724 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
725 acc.setAmountHint(null);
733 // 5) a row with an empty account name or empty amount is guaranteed to exist for
735 for (String balCurrency : balance.currencies()) {
736 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
737 int currRows = itemsForCurrency.size(balCurrency);
738 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
739 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
740 if ((currEmptyRows == 0) &&
741 ((currRows == currAccounts) || (currRows == currAmounts)))
743 // perhaps there already is an unused empty row for another currency that
745 // boolean foundIt = false;
746 // for (Item item : emptyRows) {
747 // Currency itemCurrency = item.getCurrency();
748 // String itemCurrencyName =
749 // (itemCurrency == null) ? "" : itemCurrency.getName();
750 // if (Misc.isZero(balance.get(itemCurrencyName))) {
751 // item.setCurrency(Currency.loadByName(balCurrency));
752 // item.setAmountHint(
753 // String.format("%1.2f", -balance.get(balCurrency)));
760 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
761 final float bal = balance.get(balCurrency);
762 if (!Misc.isZero(bal) && currAmounts == currRows)
763 newAcc.setAmountHint(String.format("%4.2f", -bal));
764 Logger.debug("submittable",
765 String.format("Adding new item with %s for currency %s",
766 newAcc.getAmountHint(), balCurrency));
772 // drop extra empty rows, not needed
773 for (String currName : emptyRowsForCurrency.currencies()) {
774 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
775 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
776 // the list is a copy, so the empty item is no longer present
777 Item itemToRemove = emptyItems.remove(1);
778 removeItemById(list, itemToRemove.id);
782 // unused currency, remove last item (which is also an empty one)
783 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
784 List<Item> currItems = itemsForCurrency.getList(currName);
786 if (currItems.size() == 1) {
787 // the list is a copy, so the empty item is no longer present
788 removeItemById(list, emptyItems.get(0).id);
794 // 6) at least two rows need to be present in the ledger
795 // (the list also contains header and trailer)
796 while (list.size() < MIN_ITEMS) {
797 list.add(new TransactionAccount(""));
801 Logger.debug("submittable", submittable ? "YES" : "NO");
802 isSubmittable.setValue(submittable);
804 if (BuildConfig.DEBUG)
805 dumpItemList("After submittable checks", list);
807 catch (NumberFormatException e) {
808 Logger.debug("submittable", "NO (because of NumberFormatException)");
809 isSubmittable.setValue(false);
811 catch (Exception e) {
813 Logger.debug("submittable", "NO (because of an Exception)");
814 isSubmittable.setValue(false);
817 if (listChanged && workingWithLiveList) {
818 setItemsWithoutSubmittableChecks(list);
821 private void removeItemById(@NotNull List<Item> list, int id) {
822 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
823 list.removeIf(item -> item.id == id);
826 for (Item item : list) {
834 @SuppressLint("DefaultLocale")
835 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
836 Logger.debug("submittable", "== Dump of all items " + msg);
837 for (int i = 1; i < list.size(); i++) {
838 TransactionAccount item = list.get(i)
839 .toTransactionAccount();
840 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
843 public void setItemCurrency(int position, String newCurrency) {
844 TransactionAccount item = Objects.requireNonNull(items.getValue())
846 .toTransactionAccount();
847 final String oldCurrency = item.getCurrency();
849 if (Misc.equalStrings(oldCurrency, newCurrency))
852 List<Item> newList = copyList();
853 newList.get(position)
854 .toTransactionAccount()
855 .setCurrency(newCurrency);
859 public boolean accountListIsEmpty() {
860 List<Item> items = Objects.requireNonNull(this.items.getValue());
862 for (Item item : items) {
863 if (!(item instanceof TransactionAccount))
866 if (!((TransactionAccount) item).isEmpty())
873 public static class FocusInfo {
875 FocusedElement element;
876 public FocusInfo(int position, FocusedElement element) {
877 this.position = position;
878 this.element = element;
882 static abstract class Item {
883 private static int idDispenser = 0;
886 if (this instanceof TransactionHead)
889 synchronized (Item.class) {
893 public Item(int id) {
896 public static Item from(Item origin) {
897 if (origin instanceof TransactionHead)
898 return new TransactionHead((TransactionHead) origin);
899 if (origin instanceof TransactionAccount)
900 return new TransactionAccount((TransactionAccount) origin);
901 throw new RuntimeException("Don't know how to handle " + origin);
903 private static void resetIdDispenser() {
909 public abstract ItemType getType();
910 public TransactionHead toTransactionHead() {
911 if (this instanceof TransactionHead)
912 return (TransactionHead) this;
914 throw new IllegalStateException("Wrong item type " + this);
916 public TransactionAccount toTransactionAccount() {
917 if (this instanceof TransactionAccount)
918 return (TransactionAccount) this;
920 throw new IllegalStateException("Wrong item type " + this);
922 public boolean equalContents(@Nullable Object item) {
926 if (!getClass().equals(item.getClass()))
929 // shortcut - comparing same instance
933 if (this instanceof TransactionHead)
934 return ((TransactionHead) item).equalContents((TransactionHead) this);
935 if (this instanceof TransactionAccount)
936 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
938 throw new RuntimeException("Don't know how to handle " + this);
943 //==========================================================================================
945 public static class TransactionHead extends Item {
946 private SimpleDate date;
947 private String description;
948 private String comment;
949 TransactionHead(String description) {
951 this.description = description;
953 public TransactionHead(TransactionHead origin) {
956 description = origin.description;
957 comment = origin.comment;
959 public SimpleDate getDate() {
962 public void setDate(SimpleDate date) {
965 public void setDate(String text) throws ParseException {
966 if (Misc.emptyIsNull(text) == null) {
971 date = Globals.parseLedgerDate(text);
976 * @return nicely formatted, shortest available date representation
978 String getFormattedDate() {
982 Calendar today = GregorianCalendar.getInstance();
984 if (today.get(Calendar.YEAR) != date.year) {
985 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
988 if (today.get(Calendar.MONTH) + 1 != date.month) {
989 return String.format(Locale.US, "%d/%02d", date.month, date.day);
992 return String.valueOf(date.day);
996 public String toString() {
997 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
998 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1000 if (TextUtils.isEmpty(description))
1001 b.append(" «no description»");
1003 b.append(String.format(" '%s'", description));
1006 b.append(String.format("@%s", date.toString()));
1008 if (!TextUtils.isEmpty(comment))
1009 b.append(String.format(" /%s/", comment));
1011 return b.toString();
1013 public String getDescription() {
1016 public void setDescription(String description) {
1017 this.description = description;
1019 public String getComment() {
1022 public void setComment(String comment) {
1023 this.comment = comment;
1026 public ItemType getType() {
1027 return ItemType.generalData;
1029 public LedgerTransaction asLedgerTransaction() {
1030 return new LedgerTransaction(0, date, description, Data.getProfile());
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();