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.TemplateAccount;
34 import net.ktnx.mobileledger.db.TemplateHeader;
35 import net.ktnx.mobileledger.model.Data;
36 import net.ktnx.mobileledger.model.InertMutableLiveData;
37 import net.ktnx.mobileledger.model.LedgerTransaction;
38 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
39 import net.ktnx.mobileledger.model.MatchedTemplate;
40 import net.ktnx.mobileledger.model.MobileLedgerProfile;
41 import net.ktnx.mobileledger.utils.Globals;
42 import net.ktnx.mobileledger.utils.Logger;
43 import net.ktnx.mobileledger.utils.Misc;
44 import net.ktnx.mobileledger.utils.SimpleDate;
46 import org.jetbrains.annotations.NotNull;
48 import java.text.ParseException;
49 import java.util.ArrayList;
50 import java.util.Calendar;
51 import java.util.GregorianCalendar;
52 import java.util.HashMap;
53 import java.util.List;
54 import java.util.Locale;
55 import java.util.Objects;
57 import java.util.concurrent.atomic.AtomicInteger;
58 import java.util.regex.MatchResult;
60 enum ItemType {generalData, transactionRow}
62 enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
65 public class NewTransactionModel extends ViewModel {
66 private static final int MIN_ITEMS = 3;
67 private final MutableLiveData<Boolean> showCurrency = new MutableLiveData<>(false);
68 private final MutableLiveData<Boolean> isSubmittable = new InertMutableLiveData<>(false);
69 private final MutableLiveData<Boolean> showComments = new MutableLiveData<>(true);
70 private final MutableLiveData<List<Item>> items = new MutableLiveData<>();
71 private final MutableLiveData<Integer> accountCount = new InertMutableLiveData<>(0);
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<MobileLedgerProfile> 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 setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
95 Logger.debug("new-trans", "model: Setting new item list");
97 accountCount.setValue(list.size() - 2);
99 private List<Item> copyList() {
100 return copyList(null);
102 private List<Item> copyList(@Nullable List<Item> source) {
103 List<Item> copy = new ArrayList<>();
104 List<Item> oldList = (source == null) ? items.getValue() : source;
107 for (Item item : oldList) {
108 copy.add(Item.from(item));
113 private List<Item> shallowCopyListWithoutItem(int position) {
114 List<Item> copy = new ArrayList<>();
115 List<Item> oldList = items.getValue();
117 if (oldList != null) {
119 for (Item item : oldList) {
128 private List<Item> shallowCopyList() {
129 return new ArrayList<>(items.getValue());
131 LiveData<Boolean> getShowComments() {
134 void observeDataProfile(LifecycleOwner activity) {
135 if (!observingDataProfile)
136 Data.observeProfile(activity, profileObserver);
137 observingDataProfile = true;
139 boolean getSimulateSaveFlag() {
140 Boolean value = simulateSave.getValue();
145 LiveData<Boolean> getSimulateSave() {
148 void toggleSimulateSave() {
149 simulateSave.setValue(!getSimulateSaveFlag());
151 LiveData<Boolean> isSubmittable() {
152 return this.isSubmittable;
155 List<Item> list = new ArrayList<>();
156 list.add(new TransactionHead(""));
157 list.add(new TransactionAccount(""));
158 list.add(new TransactionAccount(""));
159 items.setValue(list);
161 boolean accountsInInitialState() {
162 final List<Item> list = items.getValue();
167 for (Item item : list) {
168 if (!(item instanceof TransactionAccount))
171 TransactionAccount accRow = (TransactionAccount) item;
172 if (!accRow.isEmpty())
178 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
179 SimpleDate transactionDate = null;
180 final MatchResult matchResult = matchedTemplate.matchResult;
181 final TemplateHeader templateHead = matchedTemplate.templateHead;
183 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
184 templateHead.getDateDay());
185 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
186 templateHead.getDateMonth());
187 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
188 templateHead.getDateYear());
190 if (year > 0 || month > 0 || day > 0) {
191 SimpleDate today = SimpleDate.today();
199 transactionDate = new SimpleDate(year, month, day);
201 Logger.debug("pattern", "setting transaction date to " + transactionDate);
205 List<Item> present = copyList();
207 TransactionHead head = new TransactionHead(present.get(0)
208 .toTransactionHead());
209 if (transactionDate != null)
210 head.setDate(transactionDate);
212 final String transactionDescription = extractStringFromMatches(matchResult,
213 templateHead.getTransactionDescriptionMatchGroup(),
214 templateHead.getTransactionDescription());
215 if (Misc.emptyIsNull(transactionDescription) != null)
216 head.setDescription(transactionDescription);
218 final String transactionComment = extractStringFromMatches(matchResult,
219 templateHead.getTransactionCommentMatchGroup(),
220 templateHead.getTransactionComment());
221 if (Misc.emptyIsNull(transactionComment) != null)
222 head.setComment(transactionComment);
224 List<Item> newItems = new ArrayList<>();
228 for (int i = 1; i < present.size(); i++) {
229 final TransactionAccount row = present.get(i)
230 .toTransactionAccount();
232 newItems.add(new TransactionAccount(row));
237 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
239 final boolean accountsInInitialState = accountsInInitialState();
240 for (TemplateAccount acc : entry.accounts) {
244 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
245 acc.getAccountName());
246 String accountComment =
247 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
248 acc.getAccountComment());
249 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
251 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
255 TransactionAccount accRow = new TransactionAccount(accountName);
256 accRow.setComment(accountComment);
258 accRow.setAmount(amount);
260 newItems.add(accRow);
263 items.postValue(newItems);
266 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
272 if (grp > 0 & grp <= m.groupCount())
274 return Integer.parseInt(m.group(grp));
276 catch (NumberFormatException e) {
277 Logger.debug("new-trans", "Error extracting matched number", e);
283 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
289 if (grp > 0 & grp <= m.groupCount())
295 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
301 if (grp > 0 & grp <= m.groupCount())
303 return Float.valueOf(m.group(grp));
305 catch (NumberFormatException e) {
306 Logger.debug("new-trans", "Error extracting matched number", e);
312 void removeItem(int pos) {
313 List<Item> newList = shallowCopyListWithoutItem(pos);
316 void noteFocusChanged(int position, FocusedElement element) {
317 FocusInfo present = focusInfo.getValue();
318 if (present == null || present.position != position || present.element != element)
319 focusInfo.setValue(new FocusInfo(position, element));
321 public LiveData<FocusInfo> getFocusInfo() {
324 void moveItem(int fromIndex, int toIndex) {
325 List<Item> newList = shallowCopyList();
326 Item item = newList.remove(fromIndex);
327 newList.add(toIndex, item);
328 items.setValue(newList); // same count, same submittable state
330 void moveItemLast(List<Item> list, int index) {
334 3 <-- desired position
337 int itemCount = list.size();
339 if (index < itemCount - 1)
340 list.add(list.remove(index));
342 void toggleCurrencyVisible() {
343 showCurrency.setValue(!Objects.requireNonNull(showCurrency.getValue()));
345 void stopObservingBusyFlag(Observer<Boolean> observer) {
346 busyFlag.removeObserver(observer);
348 void incrementBusyCounter() {
349 int newValue = busyCounter.incrementAndGet();
351 busyFlag.postValue(true);
353 void decrementBusyCounter() {
354 int newValue = busyCounter.decrementAndGet();
356 busyFlag.postValue(false);
358 public LiveData<Boolean> getBusyFlag() {
361 public void toggleShowComments() {
362 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
364 public LedgerTransaction constructLedgerTransaction() {
365 List<Item> list = Objects.requireNonNull(items.getValue());
366 TransactionHead head = list.get(0)
367 .toTransactionHead();
368 SimpleDate date = head.getDate();
369 LedgerTransaction tr = head.asLedgerTransaction();
371 tr.setComment(head.getComment());
372 LedgerTransactionAccount emptyAmountAccount = null;
373 float emptyAmountAccountBalance = 0;
374 for (int i = 1; i < list.size(); i++) {
375 TransactionAccount item = list.get(i)
376 .toTransactionAccount();
377 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
380 if (acc.getAccountName()
384 acc.setComment(item.getComment());
386 if (item.isAmountSet()) {
387 acc.setAmount(item.getAmount());
388 emptyAmountAccountBalance += item.getAmount();
391 emptyAmountAccount = acc;
397 if (emptyAmountAccount != null)
398 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
402 void loadTransactionIntoModel(String profileUUID, int transactionId) {
403 List<Item> newList = new ArrayList<>();
404 LedgerTransaction tr;
405 MobileLedgerProfile profile = Data.getProfile(profileUUID);
407 throw new RuntimeException(String.format(
408 "Unable to find profile %s, which is supposed to contain transaction %d",
409 profileUUID, transactionId));
411 tr = profile.loadTransaction(transactionId);
412 TransactionHead head = new TransactionHead(tr.getDescription());
413 head.setComment(tr.getComment());
417 List<LedgerTransactionAccount> accounts = tr.getAccounts();
419 TransactionAccount firstNegative = null;
420 TransactionAccount firstPositive = null;
421 int singleNegativeIndex = -1;
422 int singlePositiveIndex = -1;
423 int negativeCount = 0;
424 for (int i = 0; i < accounts.size(); i++) {
425 LedgerTransactionAccount acc = accounts.get(i);
426 TransactionAccount item =
427 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
430 item.setAccountName(acc.getAccountName());
431 item.setComment(acc.getComment());
432 if (acc.isAmountSet()) {
433 item.setAmount(acc.getAmount());
434 if (acc.getAmount() < 0) {
435 if (firstNegative == null) {
436 firstNegative = item;
437 singleNegativeIndex = i + 1;
440 singleNegativeIndex = -1;
443 if (firstPositive == null) {
444 firstPositive = item;
445 singlePositiveIndex = i + 1;
448 singlePositiveIndex = -1;
455 if (singleNegativeIndex != -1) {
456 firstNegative.resetAmount();
457 moveItemLast(newList, singleNegativeIndex);
459 else if (singlePositiveIndex != -1) {
460 firstPositive.resetAmount();
461 moveItemLast(newList, singlePositiveIndex);
464 noteFocusChanged(1, FocusedElement.Description);
469 * A transaction is submittable if:
471 * 1) has at least two account names
472 * 2) each row with amount has account name
473 * 3) for each commodity:
474 * 3a) amounts must balance to 0, or
475 * 3b) there must be exactly one empty amount (with account)
476 * 4) empty accounts with empty amounts are ignored
478 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
480 * 6) at least two rows need to be present in the ledger
482 * @param list - the item list to check. Can be the displayed list or a list that will be
485 @SuppressLint("DefaultLocale")
486 void checkTransactionSubmittable(@Nullable List<Item> list) {
487 boolean workingWithLiveList = false;
488 boolean liveListCopied = false;
490 list = Objects.requireNonNull(items.getValue());
491 workingWithLiveList = true;
494 if (BuildConfig.DEBUG)
495 dumpItemList("Before submittable checks", list);
498 final BalanceForCurrency balance = new BalanceForCurrency();
499 final String descriptionText = list.get(0)
502 boolean submittable = true;
503 boolean listChanged = false;
504 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
505 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
506 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
507 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
508 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
509 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
510 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
511 final List<Item> emptyRows = new ArrayList<>();
514 if ((descriptionText == null) || descriptionText.trim()
517 Logger.debug("submittable", "Transaction not submittable: missing description");
521 for (int i = 1; i < list.size(); i++) {
522 TransactionAccount item = list.get(i)
523 .toTransactionAccount();
525 String accName = item.getAccountName()
527 String currName = item.getCurrency();
529 itemsForCurrency.add(currName, item);
531 if (accName.isEmpty()) {
532 itemsWithEmptyAccountForCurrency.add(currName, item);
534 if (item.isAmountSet()) {
535 // 2) each amount has account name
536 Logger.debug("submittable", String.format(
537 "Transaction not submittable: row %d has no account name, but" +
538 " has" + " amount %1.2f", i + 1, item.getAmount()));
542 emptyRowsForCurrency.add(currName, item);
547 itemsWithAccountForCurrency.add(currName, item);
550 if (!item.isAmountValid()) {
551 Logger.debug("submittable",
552 String.format("Not submittable: row %d has an invalid amount", i + 1));
555 else if (item.isAmountSet()) {
556 itemsWithAmountForCurrency.add(currName, item);
557 balance.add(currName, item.getAmount());
560 itemsWithEmptyAmountForCurrency.add(currName, item);
562 if (!accName.isEmpty())
563 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
567 // 1) has at least two account names
570 Logger.debug("submittable", "Transaction not submittable: no account names");
571 else if (accounts == 1)
572 Logger.debug("submittable",
573 "Transaction not submittable: only one account name");
575 Logger.debug("submittable",
576 String.format("Transaction not submittable: only %d account names",
581 // 3) for each commodity:
582 // 3a) amount must balance to 0, or
583 // 3b) there must be exactly one empty amount (with account)
584 for (String balCurrency : itemsForCurrency.currencies()) {
585 float currencyBalance = balance.get(balCurrency);
586 if (Misc.isZero(currencyBalance)) {
587 // remove hints from all amount inputs in that currency
588 for (int i = 1; i < list.size(); i++) {
589 TransactionAccount acc = list.get(i)
590 .toTransactionAccount();
591 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
592 if (BuildConfig.DEBUG)
593 Logger.debug("submittable",
594 String.format("Resetting hint of '%s' [%s]",
595 Misc.nullIsEmpty(acc.getAccountName()),
597 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
598 if (workingWithLiveList && !liveListCopied) {
599 list = copyList(list);
600 liveListCopied = true;
602 final TransactionAccount newAcc = new TransactionAccount(acc);
603 newAcc.setAmountHint(null);
604 if (!liveListCopied) {
605 list = copyList(list);
606 liveListCopied = true;
616 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
617 int balanceReceiversCount = tmpList.size();
618 if (balanceReceiversCount != 1) {
619 if (BuildConfig.DEBUG) {
620 if (balanceReceiversCount == 0)
621 Logger.debug("submittable", String.format(
622 "Transaction not submittable [%s]: non-zero balance " +
623 "with no empty amounts with accounts", balCurrency));
625 Logger.debug("submittable", String.format(
626 "Transaction not submittable [%s]: non-zero balance " +
627 "with multiple empty amounts with accounts", balCurrency));
632 List<Item> emptyAmountList =
633 itemsWithEmptyAmountForCurrency.getList(balCurrency);
635 // suggest off-balance amount to a row and remove hints on other rows
636 Item receiver = null;
637 if (!tmpList.isEmpty())
638 receiver = tmpList.get(0);
639 else if (!emptyAmountList.isEmpty())
640 receiver = emptyAmountList.get(0);
642 for (int i = 0; i < list.size(); i++) {
643 Item item = list.get(i);
644 if (!(item instanceof TransactionAccount))
647 TransactionAccount acc = item.toTransactionAccount();
648 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
651 if (item == receiver) {
652 final String hint = String.format("%1.2f", -currencyBalance);
653 if (!acc.isAmountHintSet() ||
654 !TextUtils.equals(acc.getAmountHint(), hint))
656 Logger.debug("submittable",
657 String.format("Setting amount hint of {%s} to %s [%s]",
658 acc.toString(), hint, balCurrency));
659 if (workingWithLiveList & !liveListCopied) {
660 list = copyList(list);
661 liveListCopied = true;
663 final TransactionAccount newAcc = new TransactionAccount(acc);
664 newAcc.setAmountHint(hint);
670 if (BuildConfig.DEBUG)
671 Logger.debug("submittable",
672 String.format("Resetting hint of '%s' [%s]",
673 Misc.nullIsEmpty(acc.getAccountName()),
675 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
676 if (workingWithLiveList && !liveListCopied) {
677 list = copyList(list);
678 liveListCopied = true;
680 final TransactionAccount newAcc = new TransactionAccount(acc);
681 newAcc.setAmountHint(null);
690 // 5) a row with an empty account name or empty amount is guaranteed to exist for
692 for (String balCurrency : balance.currencies()) {
693 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
694 int currRows = itemsForCurrency.size(balCurrency);
695 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
696 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
697 if ((currEmptyRows == 0) &&
698 ((currRows == currAccounts) || (currRows == currAmounts)))
700 // perhaps there already is an unused empty row for another currency that
702 // boolean foundIt = false;
703 // for (Item item : emptyRows) {
704 // Currency itemCurrency = item.getCurrency();
705 // String itemCurrencyName =
706 // (itemCurrency == null) ? "" : itemCurrency.getName();
707 // if (Misc.isZero(balance.get(itemCurrencyName))) {
708 // item.setCurrency(Currency.loadByName(balCurrency));
709 // item.setAmountHint(
710 // String.format("%1.2f", -balance.get(balCurrency)));
717 if (workingWithLiveList && !liveListCopied) {
718 list = copyList(list);
719 liveListCopied = true;
721 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
722 final float bal = balance.get(balCurrency);
723 if (!Misc.isZero(bal) && currAmounts == currRows)
724 newAcc.setAmountHint(String.format("%4.2f", -bal));
725 Logger.debug("submittable",
726 String.format("Adding new item with %s for currency %s",
727 newAcc.getAmountHint(), balCurrency));
733 // drop extra empty rows, not needed
734 for (String currName : emptyRowsForCurrency.currencies()) {
735 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
736 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
737 if (workingWithLiveList && !liveListCopied) {
738 list = copyList(list);
739 liveListCopied = true;
741 // the list is a copy, so the empty item is no longer present
742 Item itemToRemove = emptyItems.remove(1);
743 removeItemById(list, itemToRemove.id);
747 // unused currency, remove last item (which is also an empty one)
748 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
749 List<Item> currItems = itemsForCurrency.getList(currName);
751 if (currItems.size() == 1) {
752 if (workingWithLiveList && !liveListCopied) {
753 list = copyList(list);
754 liveListCopied = true;
756 // the list is a copy, so the empty item is no longer present
757 removeItemById(list, emptyItems.get(0).id);
763 // 6) at least two rows need to be present in the ledger
764 // (the list also contains header and trailer)
765 while (list.size() < MIN_ITEMS) {
766 if (workingWithLiveList && !liveListCopied) {
767 list = copyList(list);
768 liveListCopied = true;
770 list.add(new TransactionAccount(""));
775 Logger.debug("submittable", submittable ? "YES" : "NO");
776 isSubmittable.setValue(submittable);
778 if (BuildConfig.DEBUG)
779 dumpItemList("After submittable checks", list);
781 catch (NumberFormatException e) {
782 Logger.debug("submittable", "NO (because of NumberFormatException)");
783 isSubmittable.setValue(false);
785 catch (Exception e) {
787 Logger.debug("submittable", "NO (because of an Exception)");
788 isSubmittable.setValue(false);
791 if (listChanged && workingWithLiveList) {
792 setItemsWithoutSubmittableChecks(list);
795 private void removeItemById(@NotNull List<Item> list, int id) {
796 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
797 list.removeIf(item -> item.id == id);
800 for (Item item : list) {
808 @SuppressLint("DefaultLocale")
809 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
810 Logger.debug("submittable", "== Dump of all items " + msg);
811 for (int i = 1; i < list.size(); i++) {
812 TransactionAccount item = list.get(i)
813 .toTransactionAccount();
814 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
817 public void setItemCurrency(int position, String newCurrency) {
818 TransactionAccount item = Objects.requireNonNull(items.getValue())
820 .toTransactionAccount();
821 final String oldCurrency = item.getCurrency();
823 if (Misc.equalStrings(oldCurrency, newCurrency))
826 List<Item> newList = copyList();
827 newList.get(position)
828 .toTransactionAccount()
829 .setCurrency(newCurrency);
833 public LiveData<Integer> getAccountCount() {
836 public boolean accountListIsEmpty() {
837 List<Item> items = Objects.requireNonNull(this.items.getValue());
839 for (Item item : items) {
840 if (!(item instanceof TransactionAccount))
843 if (!((TransactionAccount) item).isEmpty())
850 public static class FocusInfo {
852 FocusedElement element;
853 public FocusInfo(int position, FocusedElement element) {
854 this.position = position;
855 this.element = element;
859 static abstract class Item {
860 private static int idDispenser = 0;
863 synchronized (Item.class) {
867 public static Item from(Item origin) {
868 if (origin instanceof TransactionHead)
869 return new TransactionHead((TransactionHead) origin);
870 if (origin instanceof TransactionAccount)
871 return new TransactionAccount((TransactionAccount) origin);
872 throw new RuntimeException("Don't know how to handle " + origin);
877 public abstract ItemType getType();
878 public TransactionHead toTransactionHead() {
879 if (this instanceof TransactionHead)
880 return (TransactionHead) this;
882 throw new IllegalStateException("Wrong item type " + this);
884 public TransactionAccount toTransactionAccount() {
885 if (this instanceof TransactionAccount)
886 return (TransactionAccount) this;
888 throw new IllegalStateException("Wrong item type " + this);
890 public boolean equalContents(@Nullable Object item) {
894 if (!getClass().equals(item.getClass()))
897 // shortcut - comparing same instance
901 if (this instanceof TransactionHead)
902 return ((TransactionHead) item).equalContents((TransactionHead) this);
903 if (this instanceof TransactionAccount)
904 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
906 throw new RuntimeException("Don't know how to handle " + this);
911 //==========================================================================================
913 public static class TransactionHead extends Item {
914 private SimpleDate date;
915 private String description;
916 private String comment;
917 TransactionHead(String description) {
919 this.description = description;
921 public TransactionHead(TransactionHead origin) {
924 description = origin.description;
925 comment = origin.comment;
927 public SimpleDate getDate() {
930 public void setDate(SimpleDate date) {
933 public void setDate(String text) throws ParseException {
934 if (Misc.emptyIsNull(text) == null) {
939 date = Globals.parseLedgerDate(text);
944 * @return nicely formatted, shortest available date representation
946 String getFormattedDate() {
950 Calendar today = GregorianCalendar.getInstance();
952 if (today.get(Calendar.YEAR) != date.year) {
953 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
956 if (today.get(Calendar.MONTH) + 1 != date.month) {
957 return String.format(Locale.US, "%d/%02d", date.month, date.day);
960 return String.valueOf(date.day);
964 public String toString() {
965 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
966 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
968 if (TextUtils.isEmpty(description))
969 b.append(" «no description»");
971 b.append(String.format(" descr'%s'", description));
974 b.append(String.format("@%s", date.toString()));
976 if (!TextUtils.isEmpty(comment))
977 b.append(String.format(" /%s/", comment));
981 public String getDescription() {
984 public void setDescription(String description) {
985 this.description = description;
987 public String getComment() {
990 public void setComment(String comment) {
991 this.comment = comment;
994 public ItemType getType() {
995 return ItemType.generalData;
997 public LedgerTransaction asLedgerTransaction() {
998 return new LedgerTransaction(null, date, description, Data.getProfile());
1000 public boolean equalContents(TransactionHead other) {
1004 return Objects.equals(date, other.date) &&
1005 TextUtils.equals(description, other.description) &&
1006 TextUtils.equals(comment, other.comment);
1010 public static class TransactionAccount extends Item {
1011 private String accountName;
1012 private String amountHint;
1013 private String comment;
1014 private String currency;
1015 private float amount;
1016 private boolean amountSet;
1017 private boolean amountValid = true;
1018 private FocusedElement focusedElement = FocusedElement.Account;
1019 private boolean amountHintIsSet = false;
1020 public TransactionAccount(TransactionAccount origin) {
1022 accountName = origin.accountName;
1023 amount = origin.amount;
1024 amountSet = origin.amountSet;
1025 amountHint = origin.amountHint;
1026 amountHintIsSet = origin.amountHintIsSet;
1027 comment = origin.comment;
1028 currency = origin.currency;
1029 amountValid = origin.amountValid;
1030 focusedElement = origin.focusedElement;
1032 public TransactionAccount(LedgerTransactionAccount account) {
1034 currency = account.getCurrency();
1035 amount = account.getAmount();
1037 public TransactionAccount(String accountName) {
1039 this.accountName = accountName;
1041 public TransactionAccount(String accountName, String currency) {
1043 this.accountName = accountName;
1044 this.currency = currency;
1046 public boolean isAmountSet() {
1049 public String getAccountName() {
1052 public void setAccountName(String accountName) {
1053 this.accountName = accountName;
1055 public float getAmount() {
1057 throw new IllegalStateException("Amount is not set");
1060 public void setAmount(float amount) {
1061 this.amount = amount;
1064 public void resetAmount() {
1068 public ItemType getType() {
1069 return ItemType.transactionRow;
1071 public String getAmountHint() {
1074 public void setAmountHint(String amountHint) {
1075 this.amountHint = amountHint;
1076 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1078 public String getComment() {
1081 public void setComment(String comment) {
1082 this.comment = comment;
1084 public String getCurrency() {
1087 public void setCurrency(String currency) {
1088 this.currency = currency;
1090 public boolean isAmountValid() {
1093 public void setAmountValid(boolean amountValid) {
1094 this.amountValid = amountValid;
1096 public FocusedElement getFocusedElement() {
1097 return focusedElement;
1099 public void setFocusedElement(FocusedElement focusedElement) {
1100 this.focusedElement = focusedElement;
1102 public boolean isAmountHintSet() {
1103 return amountHintIsSet;
1105 public void setAmountHintIsSet(boolean amountHintIsSet) {
1106 this.amountHintIsSet = amountHintIsSet;
1108 public boolean isEmpty() {
1109 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1110 Misc.emptyIsNull(comment) == null;
1112 @SuppressLint("DefaultLocale")
1114 public String toString() {
1115 StringBuilder b = new StringBuilder();
1116 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1117 if (!TextUtils.isEmpty(accountName))
1118 b.append(String.format(" acc'%s'", accountName));
1121 b.append(String.format(" %4.2f", amount));
1122 else if (amountHintIsSet)
1123 b.append(String.format(" (%s)", amountHint));
1125 if (!TextUtils.isEmpty(currency))
1129 if (!TextUtils.isEmpty(comment))
1130 b.append(String.format(" /%s/", comment));
1132 return b.toString();
1134 public boolean equalContents(TransactionAccount other) {
1138 boolean equal = TextUtils.equals(accountName, other.accountName) &&
1139 TextUtils.equals(comment, other.comment) &&
1140 (amountSet ? other.amountSet && amount == other.amount
1141 : !other.amountSet) &&
1142 (amountHintIsSet ? other.amountHintIsSet &&
1143 TextUtils.equals(amountHint, other.amountHint)
1144 : !other.amountHintIsSet) &&
1145 TextUtils.equals(currency, other.currency);
1146 Logger.debug("new-trans",
1147 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1153 private static class BalanceForCurrency {
1154 private final HashMap<String, Float> hashMap = new HashMap<>();
1155 float get(String currencyName) {
1156 Float f = hashMap.get(currencyName);
1159 hashMap.put(currencyName, f);
1163 void add(String currencyName, float amount) {
1164 hashMap.put(currencyName, get(currencyName) + amount);
1166 Set<String> currencies() {
1167 return hashMap.keySet();
1169 boolean containsCurrency(String currencyName) {
1170 return hashMap.containsKey(currencyName);
1174 private static class ItemsForCurrency {
1175 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1177 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1178 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1180 list = new ArrayList<>();
1181 hashMap.put(currencyName, list);
1185 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1186 getList(currencyName).add(item);
1188 int size(@Nullable String currencyName) {
1189 return this.getList(currencyName)
1192 Set<String> currencies() {
1193 return hashMap.keySet();