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.os.Handler;
22 import android.os.Looper;
23 import android.text.TextUtils;
25 import androidx.annotation.NonNull;
26 import androidx.annotation.Nullable;
27 import androidx.lifecycle.LifecycleOwner;
28 import androidx.lifecycle.LiveData;
29 import androidx.lifecycle.MutableLiveData;
30 import androidx.lifecycle.Observer;
31 import androidx.lifecycle.ViewModel;
33 import net.ktnx.mobileledger.BuildConfig;
34 import net.ktnx.mobileledger.db.DB;
35 import net.ktnx.mobileledger.db.TemplateAccount;
36 import net.ktnx.mobileledger.db.TemplateHeader;
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.model.MobileLedgerProfile;
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<MobileLedgerProfile> 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 setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
96 Logger.debug("new-trans", "model: Setting new item list");
97 final int cnt = list.size();
98 for (int i = 1; i < cnt - 1; i++) {
99 final TransactionAccount item = list.get(i)
100 .toTransactionAccount();
102 TransactionAccount replacement = new TransactionAccount(item);
103 replacement.isLast = false;
104 list.set(i, replacement);
107 final TransactionAccount last = list.get(cnt - 1)
108 .toTransactionAccount();
110 TransactionAccount replacement = new TransactionAccount(last);
111 replacement.isLast = true;
112 list.set(cnt - 1, replacement);
115 items.setValue(list);
117 private List<Item> copyList() {
118 return copyList(null);
120 private List<Item> copyList(@Nullable List<Item> source) {
121 List<Item> copy = new ArrayList<>();
122 List<Item> oldList = (source == null) ? items.getValue() : source;
125 for (Item item : oldList) {
126 copy.add(Item.from(item));
131 private List<Item> shallowCopyListWithoutItem(int position) {
132 List<Item> copy = new ArrayList<>();
133 List<Item> oldList = items.getValue();
135 if (oldList != null) {
137 for (Item item : oldList) {
146 private List<Item> shallowCopyList() {
147 return new ArrayList<>(items.getValue());
149 LiveData<Boolean> getShowComments() {
152 void observeDataProfile(LifecycleOwner activity) {
153 if (!observingDataProfile)
154 Data.observeProfile(activity, profileObserver);
155 observingDataProfile = true;
157 boolean getSimulateSaveFlag() {
158 Boolean value = simulateSave.getValue();
163 LiveData<Boolean> getSimulateSave() {
166 void toggleSimulateSave() {
167 simulateSave.setValue(!getSimulateSaveFlag());
169 LiveData<Boolean> isSubmittable() {
170 return this.isSubmittable;
173 Logger.debug("new-trans", "Resetting model");
174 List<Item> list = new ArrayList<>();
175 list.add(new TransactionHead(""));
176 list.add(new TransactionAccount(""));
177 list.add(new TransactionAccount(""));
178 noteFocusChanged(0, FocusedElement.Description);
179 setItemsWithoutSubmittableChecks(list);
181 boolean accountsInInitialState() {
182 final List<Item> list = items.getValue();
187 for (Item item : list) {
188 if (!(item instanceof TransactionAccount))
191 TransactionAccount accRow = (TransactionAccount) item;
192 if (!accRow.isEmpty())
198 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
199 SimpleDate transactionDate = null;
200 final MatchResult matchResult = matchedTemplate.matchResult;
201 final TemplateHeader templateHead = matchedTemplate.templateHead;
203 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
204 templateHead.getDateDay());
205 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
206 templateHead.getDateMonth());
207 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
208 templateHead.getDateYear());
210 if (year > 0 || month > 0 || day > 0) {
211 SimpleDate today = SimpleDate.today();
219 transactionDate = new SimpleDate(year, month, day);
221 Logger.debug("pattern", "setting transaction date to " + transactionDate);
225 List<Item> present = copyList();
227 TransactionHead head = new TransactionHead(present.get(0)
228 .toTransactionHead());
229 if (transactionDate != null)
230 head.setDate(transactionDate);
232 final String transactionDescription = extractStringFromMatches(matchResult,
233 templateHead.getTransactionDescriptionMatchGroup(),
234 templateHead.getTransactionDescription());
235 if (Misc.emptyIsNull(transactionDescription) != null)
236 head.setDescription(transactionDescription);
238 final String transactionComment = extractStringFromMatches(matchResult,
239 templateHead.getTransactionCommentMatchGroup(),
240 templateHead.getTransactionComment());
241 if (Misc.emptyIsNull(transactionComment) != null)
242 head.setComment(transactionComment);
244 List<Item> newItems = new ArrayList<>();
248 for (int i = 1; i < present.size(); i++) {
249 final TransactionAccount row = present.get(i)
250 .toTransactionAccount();
252 newItems.add(new TransactionAccount(row));
257 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
259 final boolean accountsInInitialState = accountsInInitialState();
260 for (TemplateAccount acc : entry.accounts) {
264 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
265 acc.getAccountName());
266 String accountComment =
267 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
268 acc.getAccountComment());
269 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
271 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
275 TransactionAccount accRow = new TransactionAccount(accountName);
276 accRow.setComment(accountComment);
278 accRow.setAmount(amount);
280 newItems.add(accRow);
283 new Handler(Looper.getMainLooper()).post(() -> setItems(newItems));
286 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
292 if (grp > 0 & grp <= m.groupCount())
294 return Integer.parseInt(m.group(grp));
296 catch (NumberFormatException e) {
297 Logger.debug("new-trans", "Error extracting matched number", e);
303 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
309 if (grp > 0 & grp <= m.groupCount())
315 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
321 if (grp > 0 & grp <= m.groupCount())
323 return Float.valueOf(m.group(grp));
325 catch (NumberFormatException e) {
326 Logger.debug("new-trans", "Error extracting matched number", e);
332 void removeItem(int pos) {
333 List<Item> newList = shallowCopyListWithoutItem(pos);
336 void noteFocusChanged(int position, FocusedElement element) {
337 FocusInfo present = focusInfo.getValue();
338 if (present == null || present.position != position || present.element != element)
339 focusInfo.setValue(new FocusInfo(position, element));
341 public LiveData<FocusInfo> getFocusInfo() {
344 void moveItem(int fromIndex, int toIndex) {
345 List<Item> newList = shallowCopyList();
346 Item item = newList.remove(fromIndex);
347 newList.add(toIndex, item);
348 items.setValue(newList); // same count, same submittable state
350 void moveItemLast(List<Item> list, int index) {
354 3 <-- desired position
357 int itemCount = list.size();
359 if (index < itemCount - 1)
360 list.add(list.remove(index));
362 void toggleCurrencyVisible() {
363 showCurrency.setValue(!Objects.requireNonNull(showCurrency.getValue()));
365 void stopObservingBusyFlag(Observer<Boolean> observer) {
366 busyFlag.removeObserver(observer);
368 void incrementBusyCounter() {
369 int newValue = busyCounter.incrementAndGet();
371 busyFlag.postValue(true);
373 void decrementBusyCounter() {
374 int newValue = busyCounter.decrementAndGet();
376 busyFlag.postValue(false);
378 public LiveData<Boolean> getBusyFlag() {
381 public void toggleShowComments() {
382 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
384 public LedgerTransaction constructLedgerTransaction() {
385 List<Item> list = Objects.requireNonNull(items.getValue());
386 TransactionHead head = list.get(0)
387 .toTransactionHead();
388 SimpleDate date = head.getDate();
389 LedgerTransaction tr = head.asLedgerTransaction();
391 tr.setComment(head.getComment());
392 LedgerTransactionAccount emptyAmountAccount = null;
393 float emptyAmountAccountBalance = 0;
394 for (int i = 1; i < list.size(); i++) {
395 TransactionAccount item = list.get(i)
396 .toTransactionAccount();
397 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
400 if (acc.getAccountName()
404 acc.setComment(item.getComment());
406 if (item.isAmountSet()) {
407 acc.setAmount(item.getAmount());
408 emptyAmountAccountBalance += item.getAmount();
411 emptyAmountAccount = acc;
417 if (emptyAmountAccount != null)
418 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
422 void loadTransactionIntoModel(String profileUUID, int transactionId) {
423 List<Item> newList = new ArrayList<>();
424 LedgerTransaction tr;
425 MobileLedgerProfile profile = Data.getProfile(profileUUID);
427 throw new RuntimeException(String.format(
428 "Unable to find profile %s, which is supposed to contain transaction %d",
429 profileUUID, transactionId));
431 tr = profile.loadTransaction(transactionId);
432 TransactionHead head = new TransactionHead(tr.getDescription());
433 head.setComment(tr.getComment());
437 List<LedgerTransactionAccount> accounts = tr.getAccounts();
439 TransactionAccount firstNegative = null;
440 TransactionAccount firstPositive = null;
441 int singleNegativeIndex = -1;
442 int singlePositiveIndex = -1;
443 int negativeCount = 0;
444 for (int i = 0; i < accounts.size(); i++) {
445 LedgerTransactionAccount acc = accounts.get(i);
446 TransactionAccount item =
447 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
450 item.setAccountName(acc.getAccountName());
451 item.setComment(acc.getComment());
452 if (acc.isAmountSet()) {
453 item.setAmount(acc.getAmount());
454 if (acc.getAmount() < 0) {
455 if (firstNegative == null) {
456 firstNegative = item;
457 singleNegativeIndex = i + 1;
460 singleNegativeIndex = -1;
463 if (firstPositive == null) {
464 firstPositive = item;
465 singlePositiveIndex = i + 1;
468 singlePositiveIndex = -1;
474 if (BuildConfig.DEBUG)
475 dumpItemList("Loaded previous transaction", newList);
477 if (singleNegativeIndex != -1) {
478 firstNegative.resetAmount();
479 moveItemLast(newList, singleNegativeIndex);
481 else if (singlePositiveIndex != -1) {
482 firstPositive.resetAmount();
483 moveItemLast(newList, singlePositiveIndex);
488 noteFocusChanged(1, FocusedElement.Amount);
491 * A transaction is submittable if:
493 * 1) has at least two account names
494 * 2) each row with amount has account name
495 * 3) for each commodity:
496 * 3a) amounts must balance to 0, or
497 * 3b) there must be exactly one empty amount (with account)
498 * 4) empty accounts with empty amounts are ignored
500 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
502 * 6) at least two rows need to be present in the ledger
504 * @param list - the item list to check. Can be the displayed list or a list that will be
507 @SuppressLint("DefaultLocale")
508 void checkTransactionSubmittable(@Nullable List<Item> list) {
509 boolean workingWithLiveList = false;
510 boolean liveListCopied = false;
512 list = Objects.requireNonNull(items.getValue());
513 workingWithLiveList = true;
516 if (BuildConfig.DEBUG)
517 dumpItemList("Before submittable checks", list);
520 final BalanceForCurrency balance = new BalanceForCurrency();
521 final String descriptionText = list.get(0)
524 boolean submittable = true;
525 boolean listChanged = false;
526 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
527 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
528 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
529 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
530 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
531 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
532 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
533 final List<Item> emptyRows = new ArrayList<>();
536 if ((descriptionText == null) || descriptionText.trim()
539 Logger.debug("submittable", "Transaction not submittable: missing description");
543 for (int i = 1; i < list.size(); i++) {
544 TransactionAccount item = list.get(i)
545 .toTransactionAccount();
547 String accName = item.getAccountName()
549 String currName = item.getCurrency();
551 itemsForCurrency.add(currName, item);
553 if (accName.isEmpty()) {
554 itemsWithEmptyAccountForCurrency.add(currName, item);
556 if (item.isAmountSet()) {
557 // 2) each amount has account name
558 Logger.debug("submittable", String.format(
559 "Transaction not submittable: row %d has no account name, but" +
560 " has" + " amount %1.2f", i + 1, item.getAmount()));
564 emptyRowsForCurrency.add(currName, item);
569 itemsWithAccountForCurrency.add(currName, item);
572 if (!item.isAmountValid()) {
573 Logger.debug("submittable",
574 String.format("Not submittable: row %d has an invalid amount", i + 1));
577 else if (item.isAmountSet()) {
578 itemsWithAmountForCurrency.add(currName, item);
579 balance.add(currName, item.getAmount());
582 itemsWithEmptyAmountForCurrency.add(currName, item);
584 if (!accName.isEmpty())
585 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
589 // 1) has at least two account names
592 Logger.debug("submittable", "Transaction not submittable: no account names");
593 else if (accounts == 1)
594 Logger.debug("submittable",
595 "Transaction not submittable: only one account name");
597 Logger.debug("submittable",
598 String.format("Transaction not submittable: only %d account names",
603 // 3) for each commodity:
604 // 3a) amount must balance to 0, or
605 // 3b) there must be exactly one empty amount (with account)
606 for (String balCurrency : itemsForCurrency.currencies()) {
607 float currencyBalance = balance.get(balCurrency);
608 if (Misc.isZero(currencyBalance)) {
609 // remove hints from all amount inputs in that currency
610 for (int i = 1; i < list.size(); i++) {
611 TransactionAccount acc = list.get(i)
612 .toTransactionAccount();
613 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
614 if (BuildConfig.DEBUG)
615 Logger.debug("submittable",
616 String.format("Resetting hint of '%s' [%s]",
617 Misc.nullIsEmpty(acc.getAccountName()),
619 // skip if the amount is set, in which case the hint is not
621 if (!acc.isAmountSet() && acc.amountHintIsSet &&
622 !TextUtils.isEmpty(acc.getAmountHint()))
624 if (workingWithLiveList && !liveListCopied) {
625 list = copyList(list);
626 liveListCopied = true;
628 final TransactionAccount newAcc = new TransactionAccount(acc);
629 newAcc.setAmountHint(null);
630 if (!liveListCopied) {
631 list = copyList(list);
632 liveListCopied = true;
642 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
643 int balanceReceiversCount = tmpList.size();
644 if (balanceReceiversCount != 1) {
645 if (BuildConfig.DEBUG) {
646 if (balanceReceiversCount == 0)
647 Logger.debug("submittable", String.format(
648 "Transaction not submittable [%s]: non-zero balance " +
649 "with no empty amounts with accounts", balCurrency));
651 Logger.debug("submittable", String.format(
652 "Transaction not submittable [%s]: non-zero balance " +
653 "with multiple empty amounts with accounts", balCurrency));
658 List<Item> emptyAmountList =
659 itemsWithEmptyAmountForCurrency.getList(balCurrency);
661 // suggest off-balance amount to a row and remove hints on other rows
662 Item receiver = null;
663 if (!tmpList.isEmpty())
664 receiver = tmpList.get(0);
665 else if (!emptyAmountList.isEmpty())
666 receiver = emptyAmountList.get(0);
668 for (int i = 0; i < list.size(); i++) {
669 Item item = list.get(i);
670 if (!(item instanceof TransactionAccount))
673 TransactionAccount acc = item.toTransactionAccount();
674 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
677 if (item == receiver) {
678 final String hint = String.format("%1.2f", -currencyBalance);
679 if (!acc.isAmountHintSet() ||
680 !TextUtils.equals(acc.getAmountHint(), hint))
682 Logger.debug("submittable",
683 String.format("Setting amount hint of {%s} to %s [%s]",
684 acc.toString(), hint, balCurrency));
685 if (workingWithLiveList & !liveListCopied) {
686 list = copyList(list);
687 liveListCopied = true;
689 final TransactionAccount newAcc = new TransactionAccount(acc);
690 newAcc.setAmountHint(hint);
696 if (BuildConfig.DEBUG)
697 Logger.debug("submittable",
698 String.format("Resetting hint of '%s' [%s]",
699 Misc.nullIsEmpty(acc.getAccountName()),
701 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
702 if (workingWithLiveList && !liveListCopied) {
703 list = copyList(list);
704 liveListCopied = true;
706 final TransactionAccount newAcc = new TransactionAccount(acc);
707 newAcc.setAmountHint(null);
716 // 5) a row with an empty account name or empty amount is guaranteed to exist for
718 for (String balCurrency : balance.currencies()) {
719 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
720 int currRows = itemsForCurrency.size(balCurrency);
721 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
722 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
723 if ((currEmptyRows == 0) &&
724 ((currRows == currAccounts) || (currRows == currAmounts)))
726 // perhaps there already is an unused empty row for another currency that
728 // boolean foundIt = false;
729 // for (Item item : emptyRows) {
730 // Currency itemCurrency = item.getCurrency();
731 // String itemCurrencyName =
732 // (itemCurrency == null) ? "" : itemCurrency.getName();
733 // if (Misc.isZero(balance.get(itemCurrencyName))) {
734 // item.setCurrency(Currency.loadByName(balCurrency));
735 // item.setAmountHint(
736 // String.format("%1.2f", -balance.get(balCurrency)));
743 if (workingWithLiveList && !liveListCopied) {
744 list = copyList(list);
745 liveListCopied = true;
747 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
748 final float bal = balance.get(balCurrency);
749 if (!Misc.isZero(bal) && currAmounts == currRows)
750 newAcc.setAmountHint(String.format("%4.2f", -bal));
751 Logger.debug("submittable",
752 String.format("Adding new item with %s for currency %s",
753 newAcc.getAmountHint(), balCurrency));
759 // drop extra empty rows, not needed
760 for (String currName : emptyRowsForCurrency.currencies()) {
761 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
762 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
763 if (workingWithLiveList && !liveListCopied) {
764 list = copyList(list);
765 liveListCopied = true;
767 // the list is a copy, so the empty item is no longer present
768 Item itemToRemove = emptyItems.remove(1);
769 removeItemById(list, itemToRemove.id);
773 // unused currency, remove last item (which is also an empty one)
774 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
775 List<Item> currItems = itemsForCurrency.getList(currName);
777 if (currItems.size() == 1) {
778 if (workingWithLiveList && !liveListCopied) {
779 list = copyList(list);
780 liveListCopied = true;
782 // the list is a copy, so the empty item is no longer present
783 removeItemById(list, emptyItems.get(0).id);
789 // 6) at least two rows need to be present in the ledger
790 // (the list also contains header and trailer)
791 while (list.size() < MIN_ITEMS) {
792 if (workingWithLiveList && !liveListCopied) {
793 list = copyList(list);
794 liveListCopied = true;
796 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 synchronized (Item.class) {
890 public static Item from(Item origin) {
891 if (origin instanceof TransactionHead)
892 return new TransactionHead((TransactionHead) origin);
893 if (origin instanceof TransactionAccount)
894 return new TransactionAccount((TransactionAccount) origin);
895 throw new RuntimeException("Don't know how to handle " + origin);
900 public abstract ItemType getType();
901 public TransactionHead toTransactionHead() {
902 if (this instanceof TransactionHead)
903 return (TransactionHead) this;
905 throw new IllegalStateException("Wrong item type " + this);
907 public TransactionAccount toTransactionAccount() {
908 if (this instanceof TransactionAccount)
909 return (TransactionAccount) this;
911 throw new IllegalStateException("Wrong item type " + this);
913 public boolean equalContents(@Nullable Object item) {
917 if (!getClass().equals(item.getClass()))
920 // shortcut - comparing same instance
924 if (this instanceof TransactionHead)
925 return ((TransactionHead) item).equalContents((TransactionHead) this);
926 if (this instanceof TransactionAccount)
927 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
929 throw new RuntimeException("Don't know how to handle " + this);
934 //==========================================================================================
936 public static class TransactionHead extends Item {
937 private SimpleDate date;
938 private String description;
939 private String comment;
940 TransactionHead(String description) {
942 this.description = description;
944 public TransactionHead(TransactionHead origin) {
947 description = origin.description;
948 comment = origin.comment;
950 public SimpleDate getDate() {
953 public void setDate(SimpleDate date) {
956 public void setDate(String text) throws ParseException {
957 if (Misc.emptyIsNull(text) == null) {
962 date = Globals.parseLedgerDate(text);
967 * @return nicely formatted, shortest available date representation
969 String getFormattedDate() {
973 Calendar today = GregorianCalendar.getInstance();
975 if (today.get(Calendar.YEAR) != date.year) {
976 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
979 if (today.get(Calendar.MONTH) + 1 != date.month) {
980 return String.format(Locale.US, "%d/%02d", date.month, date.day);
983 return String.valueOf(date.day);
987 public String toString() {
988 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
989 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
991 if (TextUtils.isEmpty(description))
992 b.append(" «no description»");
994 b.append(String.format(" descr'%s'", description));
997 b.append(String.format("@%s", date.toString()));
999 if (!TextUtils.isEmpty(comment))
1000 b.append(String.format(" /%s/", comment));
1002 return b.toString();
1004 public String getDescription() {
1007 public void setDescription(String description) {
1008 this.description = description;
1010 public String getComment() {
1013 public void setComment(String comment) {
1014 this.comment = comment;
1017 public ItemType getType() {
1018 return ItemType.generalData;
1020 public LedgerTransaction asLedgerTransaction() {
1021 return new LedgerTransaction(null, date, description, Data.getProfile());
1023 public boolean equalContents(TransactionHead other) {
1027 return Objects.equals(date, other.date) &&
1028 TextUtils.equals(description, other.description) &&
1029 TextUtils.equals(comment, other.comment);
1033 public static class TransactionAccount extends Item {
1034 private String accountName;
1035 private String amountHint;
1036 private String comment;
1037 private String currency;
1038 private float amount;
1039 private boolean amountSet;
1040 private boolean amountValid = true;
1041 private FocusedElement focusedElement = FocusedElement.Account;
1042 private boolean amountHintIsSet = true;
1043 private boolean isLast = false;
1044 private int accountNameCursorPosition;
1045 public TransactionAccount(TransactionAccount origin) {
1047 accountName = origin.accountName;
1048 amount = origin.amount;
1049 amountSet = origin.amountSet;
1050 amountHint = origin.amountHint;
1051 amountHintIsSet = origin.amountHintIsSet;
1052 comment = origin.comment;
1053 currency = origin.currency;
1054 amountValid = origin.amountValid;
1055 focusedElement = origin.focusedElement;
1056 isLast = origin.isLast;
1057 accountNameCursorPosition = origin.accountNameCursorPosition;
1059 public TransactionAccount(LedgerTransactionAccount account) {
1061 currency = account.getCurrency();
1062 amount = account.getAmount();
1064 public TransactionAccount(String accountName) {
1066 this.accountName = accountName;
1068 public TransactionAccount(String accountName, String currency) {
1070 this.accountName = accountName;
1071 this.currency = currency;
1073 public boolean isLast() {
1076 public boolean isAmountSet() {
1079 public String getAccountName() {
1082 public void setAccountName(String accountName) {
1083 this.accountName = accountName;
1085 public float getAmount() {
1087 throw new IllegalStateException("Amount is not set");
1090 public void setAmount(float amount) {
1091 this.amount = amount;
1094 public void resetAmount() {
1098 public ItemType getType() {
1099 return ItemType.transactionRow;
1101 public String getAmountHint() {
1104 public void setAmountHint(String amountHint) {
1105 this.amountHint = amountHint;
1106 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1108 public String getComment() {
1111 public void setComment(String comment) {
1112 this.comment = comment;
1114 public String getCurrency() {
1117 public void setCurrency(String currency) {
1118 this.currency = currency;
1120 public boolean isAmountValid() {
1123 public void setAmountValid(boolean amountValid) {
1124 this.amountValid = amountValid;
1126 public FocusedElement getFocusedElement() {
1127 return focusedElement;
1129 public void setFocusedElement(FocusedElement focusedElement) {
1130 this.focusedElement = focusedElement;
1132 public boolean isAmountHintSet() {
1133 return amountHintIsSet;
1135 public void setAmountHintIsSet(boolean amountHintIsSet) {
1136 this.amountHintIsSet = amountHintIsSet;
1138 public boolean isEmpty() {
1139 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1140 Misc.emptyIsNull(comment) == null;
1142 @SuppressLint("DefaultLocale")
1144 public String toString() {
1145 StringBuilder b = new StringBuilder();
1146 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1147 if (!TextUtils.isEmpty(accountName))
1148 b.append(String.format(" acc'%s'", accountName));
1151 b.append(String.format(" %4.2f", amount));
1152 else if (amountHintIsSet)
1153 b.append(String.format(" (%s)", amountHint));
1155 if (!TextUtils.isEmpty(currency))
1159 if (!TextUtils.isEmpty(comment))
1160 b.append(String.format(" /%s/", comment));
1165 return b.toString();
1167 public boolean equalContents(TransactionAccount other) {
1171 boolean equal = TextUtils.equals(accountName, other.accountName);
1172 equal = equal && TextUtils.equals(comment, other.comment) &&
1173 (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1175 // compare amount hint only if there is no amount
1177 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1178 TextUtils.equals(amountHint, other.amountHint)
1179 : !other.amountHintIsSet);
1180 equal = equal && TextUtils.equals(currency, other.currency) && isLast == other.isLast;
1182 Logger.debug("new-trans",
1183 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1187 public int getAccountNameCursorPosition() {
1188 return accountNameCursorPosition;
1190 public void setAccountNameCursorPosition(int position) {
1191 this.accountNameCursorPosition = position;
1195 private static class BalanceForCurrency {
1196 private final HashMap<String, Float> hashMap = new HashMap<>();
1197 float get(String currencyName) {
1198 Float f = hashMap.get(currencyName);
1201 hashMap.put(currencyName, f);
1205 void add(String currencyName, float amount) {
1206 hashMap.put(currencyName, get(currencyName) + amount);
1208 Set<String> currencies() {
1209 return hashMap.keySet();
1211 boolean containsCurrency(String currencyName) {
1212 return hashMap.containsKey(currencyName);
1216 private static class ItemsForCurrency {
1217 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1219 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1220 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1222 list = new ArrayList<>();
1223 hashMap.put(currencyName, list);
1227 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1228 getList(currencyName).add(item);
1230 int size(@Nullable String currencyName) {
1231 return this.getList(currencyName)
1234 Set<String> currencies() {
1235 return hashMap.keySet();