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;
454 if (BuildConfig.DEBUG)
455 dumpItemList("Loaded previous transaction", newList);
457 if (singleNegativeIndex != -1) {
458 firstNegative.resetAmount();
459 moveItemLast(newList, singleNegativeIndex);
461 else if (singlePositiveIndex != -1) {
462 firstPositive.resetAmount();
463 moveItemLast(newList, singlePositiveIndex);
466 noteFocusChanged(1, FocusedElement.Description);
471 * A transaction is submittable if:
473 * 1) has at least two account names
474 * 2) each row with amount has account name
475 * 3) for each commodity:
476 * 3a) amounts must balance to 0, or
477 * 3b) there must be exactly one empty amount (with account)
478 * 4) empty accounts with empty amounts are ignored
480 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
482 * 6) at least two rows need to be present in the ledger
484 * @param list - the item list to check. Can be the displayed list or a list that will be
487 @SuppressLint("DefaultLocale")
488 void checkTransactionSubmittable(@Nullable List<Item> list) {
489 boolean workingWithLiveList = false;
490 boolean liveListCopied = false;
492 list = Objects.requireNonNull(items.getValue());
493 workingWithLiveList = true;
496 if (BuildConfig.DEBUG)
497 dumpItemList("Before submittable checks", list);
500 final BalanceForCurrency balance = new BalanceForCurrency();
501 final String descriptionText = list.get(0)
504 boolean submittable = true;
505 boolean listChanged = false;
506 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
507 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
508 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
509 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
510 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
511 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
512 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
513 final List<Item> emptyRows = new ArrayList<>();
516 if ((descriptionText == null) || descriptionText.trim()
519 Logger.debug("submittable", "Transaction not submittable: missing description");
523 for (int i = 1; i < list.size(); i++) {
524 TransactionAccount item = list.get(i)
525 .toTransactionAccount();
527 String accName = item.getAccountName()
529 String currName = item.getCurrency();
531 itemsForCurrency.add(currName, item);
533 if (accName.isEmpty()) {
534 itemsWithEmptyAccountForCurrency.add(currName, item);
536 if (item.isAmountSet()) {
537 // 2) each amount has account name
538 Logger.debug("submittable", String.format(
539 "Transaction not submittable: row %d has no account name, but" +
540 " has" + " amount %1.2f", i + 1, item.getAmount()));
544 emptyRowsForCurrency.add(currName, item);
549 itemsWithAccountForCurrency.add(currName, item);
552 if (!item.isAmountValid()) {
553 Logger.debug("submittable",
554 String.format("Not submittable: row %d has an invalid amount", i + 1));
557 else if (item.isAmountSet()) {
558 itemsWithAmountForCurrency.add(currName, item);
559 balance.add(currName, item.getAmount());
562 itemsWithEmptyAmountForCurrency.add(currName, item);
564 if (!accName.isEmpty())
565 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
569 // 1) has at least two account names
572 Logger.debug("submittable", "Transaction not submittable: no account names");
573 else if (accounts == 1)
574 Logger.debug("submittable",
575 "Transaction not submittable: only one account name");
577 Logger.debug("submittable",
578 String.format("Transaction not submittable: only %d account names",
583 // 3) for each commodity:
584 // 3a) amount must balance to 0, or
585 // 3b) there must be exactly one empty amount (with account)
586 for (String balCurrency : itemsForCurrency.currencies()) {
587 float currencyBalance = balance.get(balCurrency);
588 if (Misc.isZero(currencyBalance)) {
589 // remove hints from all amount inputs in that currency
590 for (int i = 1; i < list.size(); i++) {
591 TransactionAccount acc = list.get(i)
592 .toTransactionAccount();
593 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
594 if (BuildConfig.DEBUG)
595 Logger.debug("submittable",
596 String.format("Resetting hint of '%s' [%s]",
597 Misc.nullIsEmpty(acc.getAccountName()),
599 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
600 if (workingWithLiveList && !liveListCopied) {
601 list = copyList(list);
602 liveListCopied = true;
604 final TransactionAccount newAcc = new TransactionAccount(acc);
605 newAcc.setAmountHint(null);
606 if (!liveListCopied) {
607 list = copyList(list);
608 liveListCopied = true;
618 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
619 int balanceReceiversCount = tmpList.size();
620 if (balanceReceiversCount != 1) {
621 if (BuildConfig.DEBUG) {
622 if (balanceReceiversCount == 0)
623 Logger.debug("submittable", String.format(
624 "Transaction not submittable [%s]: non-zero balance " +
625 "with no empty amounts with accounts", balCurrency));
627 Logger.debug("submittable", String.format(
628 "Transaction not submittable [%s]: non-zero balance " +
629 "with multiple empty amounts with accounts", balCurrency));
634 List<Item> emptyAmountList =
635 itemsWithEmptyAmountForCurrency.getList(balCurrency);
637 // suggest off-balance amount to a row and remove hints on other rows
638 Item receiver = null;
639 if (!tmpList.isEmpty())
640 receiver = tmpList.get(0);
641 else if (!emptyAmountList.isEmpty())
642 receiver = emptyAmountList.get(0);
644 for (int i = 0; i < list.size(); i++) {
645 Item item = list.get(i);
646 if (!(item instanceof TransactionAccount))
649 TransactionAccount acc = item.toTransactionAccount();
650 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
653 if (item == receiver) {
654 final String hint = String.format("%1.2f", -currencyBalance);
655 if (!acc.isAmountHintSet() ||
656 !TextUtils.equals(acc.getAmountHint(), hint))
658 Logger.debug("submittable",
659 String.format("Setting amount hint of {%s} to %s [%s]",
660 acc.toString(), hint, balCurrency));
661 if (workingWithLiveList & !liveListCopied) {
662 list = copyList(list);
663 liveListCopied = true;
665 final TransactionAccount newAcc = new TransactionAccount(acc);
666 newAcc.setAmountHint(hint);
672 if (BuildConfig.DEBUG)
673 Logger.debug("submittable",
674 String.format("Resetting hint of '%s' [%s]",
675 Misc.nullIsEmpty(acc.getAccountName()),
677 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
678 if (workingWithLiveList && !liveListCopied) {
679 list = copyList(list);
680 liveListCopied = true;
682 final TransactionAccount newAcc = new TransactionAccount(acc);
683 newAcc.setAmountHint(null);
692 // 5) a row with an empty account name or empty amount is guaranteed to exist for
694 for (String balCurrency : balance.currencies()) {
695 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
696 int currRows = itemsForCurrency.size(balCurrency);
697 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
698 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
699 if ((currEmptyRows == 0) &&
700 ((currRows == currAccounts) || (currRows == currAmounts)))
702 // perhaps there already is an unused empty row for another currency that
704 // boolean foundIt = false;
705 // for (Item item : emptyRows) {
706 // Currency itemCurrency = item.getCurrency();
707 // String itemCurrencyName =
708 // (itemCurrency == null) ? "" : itemCurrency.getName();
709 // if (Misc.isZero(balance.get(itemCurrencyName))) {
710 // item.setCurrency(Currency.loadByName(balCurrency));
711 // item.setAmountHint(
712 // String.format("%1.2f", -balance.get(balCurrency)));
719 if (workingWithLiveList && !liveListCopied) {
720 list = copyList(list);
721 liveListCopied = true;
723 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
724 final float bal = balance.get(balCurrency);
725 if (!Misc.isZero(bal) && currAmounts == currRows)
726 newAcc.setAmountHint(String.format("%4.2f", -bal));
727 Logger.debug("submittable",
728 String.format("Adding new item with %s for currency %s",
729 newAcc.getAmountHint(), balCurrency));
735 // drop extra empty rows, not needed
736 for (String currName : emptyRowsForCurrency.currencies()) {
737 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
738 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
739 if (workingWithLiveList && !liveListCopied) {
740 list = copyList(list);
741 liveListCopied = true;
743 // the list is a copy, so the empty item is no longer present
744 Item itemToRemove = emptyItems.remove(1);
745 removeItemById(list, itemToRemove.id);
749 // unused currency, remove last item (which is also an empty one)
750 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
751 List<Item> currItems = itemsForCurrency.getList(currName);
753 if (currItems.size() == 1) {
754 if (workingWithLiveList && !liveListCopied) {
755 list = copyList(list);
756 liveListCopied = true;
758 // the list is a copy, so the empty item is no longer present
759 removeItemById(list, emptyItems.get(0).id);
765 // 6) at least two rows need to be present in the ledger
766 // (the list also contains header and trailer)
767 while (list.size() < MIN_ITEMS) {
768 if (workingWithLiveList && !liveListCopied) {
769 list = copyList(list);
770 liveListCopied = true;
772 list.add(new TransactionAccount(""));
777 Logger.debug("submittable", submittable ? "YES" : "NO");
778 isSubmittable.setValue(submittable);
780 if (BuildConfig.DEBUG)
781 dumpItemList("After submittable checks", list);
783 catch (NumberFormatException e) {
784 Logger.debug("submittable", "NO (because of NumberFormatException)");
785 isSubmittable.setValue(false);
787 catch (Exception e) {
789 Logger.debug("submittable", "NO (because of an Exception)");
790 isSubmittable.setValue(false);
793 if (listChanged && workingWithLiveList) {
794 setItemsWithoutSubmittableChecks(list);
797 private void removeItemById(@NotNull List<Item> list, int id) {
798 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
799 list.removeIf(item -> item.id == id);
802 for (Item item : list) {
810 @SuppressLint("DefaultLocale")
811 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
812 Logger.debug("submittable", "== Dump of all items " + msg);
813 for (int i = 1; i < list.size(); i++) {
814 TransactionAccount item = list.get(i)
815 .toTransactionAccount();
816 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
819 public void setItemCurrency(int position, String newCurrency) {
820 TransactionAccount item = Objects.requireNonNull(items.getValue())
822 .toTransactionAccount();
823 final String oldCurrency = item.getCurrency();
825 if (Misc.equalStrings(oldCurrency, newCurrency))
828 List<Item> newList = copyList();
829 newList.get(position)
830 .toTransactionAccount()
831 .setCurrency(newCurrency);
835 public LiveData<Integer> getAccountCount() {
838 public boolean accountListIsEmpty() {
839 List<Item> items = Objects.requireNonNull(this.items.getValue());
841 for (Item item : items) {
842 if (!(item instanceof TransactionAccount))
845 if (!((TransactionAccount) item).isEmpty())
852 public static class FocusInfo {
854 FocusedElement element;
855 public FocusInfo(int position, FocusedElement element) {
856 this.position = position;
857 this.element = element;
861 static abstract class Item {
862 private static int idDispenser = 0;
865 synchronized (Item.class) {
869 public static Item from(Item origin) {
870 if (origin instanceof TransactionHead)
871 return new TransactionHead((TransactionHead) origin);
872 if (origin instanceof TransactionAccount)
873 return new TransactionAccount((TransactionAccount) origin);
874 throw new RuntimeException("Don't know how to handle " + origin);
879 public abstract ItemType getType();
880 public TransactionHead toTransactionHead() {
881 if (this instanceof TransactionHead)
882 return (TransactionHead) this;
884 throw new IllegalStateException("Wrong item type " + this);
886 public TransactionAccount toTransactionAccount() {
887 if (this instanceof TransactionAccount)
888 return (TransactionAccount) this;
890 throw new IllegalStateException("Wrong item type " + this);
892 public boolean equalContents(@Nullable Object item) {
896 if (!getClass().equals(item.getClass()))
899 // shortcut - comparing same instance
903 if (this instanceof TransactionHead)
904 return ((TransactionHead) item).equalContents((TransactionHead) this);
905 if (this instanceof TransactionAccount)
906 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
908 throw new RuntimeException("Don't know how to handle " + this);
913 //==========================================================================================
915 public static class TransactionHead extends Item {
916 private SimpleDate date;
917 private String description;
918 private String comment;
919 TransactionHead(String description) {
921 this.description = description;
923 public TransactionHead(TransactionHead origin) {
926 description = origin.description;
927 comment = origin.comment;
929 public SimpleDate getDate() {
932 public void setDate(SimpleDate date) {
935 public void setDate(String text) throws ParseException {
936 if (Misc.emptyIsNull(text) == null) {
941 date = Globals.parseLedgerDate(text);
946 * @return nicely formatted, shortest available date representation
948 String getFormattedDate() {
952 Calendar today = GregorianCalendar.getInstance();
954 if (today.get(Calendar.YEAR) != date.year) {
955 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
958 if (today.get(Calendar.MONTH) + 1 != date.month) {
959 return String.format(Locale.US, "%d/%02d", date.month, date.day);
962 return String.valueOf(date.day);
966 public String toString() {
967 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
968 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
970 if (TextUtils.isEmpty(description))
971 b.append(" «no description»");
973 b.append(String.format(" descr'%s'", description));
976 b.append(String.format("@%s", date.toString()));
978 if (!TextUtils.isEmpty(comment))
979 b.append(String.format(" /%s/", comment));
983 public String getDescription() {
986 public void setDescription(String description) {
987 this.description = description;
989 public String getComment() {
992 public void setComment(String comment) {
993 this.comment = comment;
996 public ItemType getType() {
997 return ItemType.generalData;
999 public LedgerTransaction asLedgerTransaction() {
1000 return new LedgerTransaction(null, date, description, Data.getProfile());
1002 public boolean equalContents(TransactionHead other) {
1006 return Objects.equals(date, other.date) &&
1007 TextUtils.equals(description, other.description) &&
1008 TextUtils.equals(comment, other.comment);
1012 public static class TransactionAccount extends Item {
1013 private String accountName;
1014 private String amountHint;
1015 private String comment;
1016 private String currency;
1017 private float amount;
1018 private boolean amountSet;
1019 private boolean amountValid = true;
1020 private FocusedElement focusedElement = FocusedElement.Account;
1021 private boolean amountHintIsSet = false;
1022 public TransactionAccount(TransactionAccount origin) {
1024 accountName = origin.accountName;
1025 amount = origin.amount;
1026 amountSet = origin.amountSet;
1027 amountHint = origin.amountHint;
1028 amountHintIsSet = origin.amountHintIsSet;
1029 comment = origin.comment;
1030 currency = origin.currency;
1031 amountValid = origin.amountValid;
1032 focusedElement = origin.focusedElement;
1034 public TransactionAccount(LedgerTransactionAccount account) {
1036 currency = account.getCurrency();
1037 amount = account.getAmount();
1039 public TransactionAccount(String accountName) {
1041 this.accountName = accountName;
1043 public TransactionAccount(String accountName, String currency) {
1045 this.accountName = accountName;
1046 this.currency = currency;
1048 public boolean isAmountSet() {
1051 public String getAccountName() {
1054 public void setAccountName(String accountName) {
1055 this.accountName = accountName;
1057 public float getAmount() {
1059 throw new IllegalStateException("Amount is not set");
1062 public void setAmount(float amount) {
1063 this.amount = amount;
1066 public void resetAmount() {
1070 public ItemType getType() {
1071 return ItemType.transactionRow;
1073 public String getAmountHint() {
1076 public void setAmountHint(String amountHint) {
1077 this.amountHint = amountHint;
1078 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1080 public String getComment() {
1083 public void setComment(String comment) {
1084 this.comment = comment;
1086 public String getCurrency() {
1089 public void setCurrency(String currency) {
1090 this.currency = currency;
1092 public boolean isAmountValid() {
1095 public void setAmountValid(boolean amountValid) {
1096 this.amountValid = amountValid;
1098 public FocusedElement getFocusedElement() {
1099 return focusedElement;
1101 public void setFocusedElement(FocusedElement focusedElement) {
1102 this.focusedElement = focusedElement;
1104 public boolean isAmountHintSet() {
1105 return amountHintIsSet;
1107 public void setAmountHintIsSet(boolean amountHintIsSet) {
1108 this.amountHintIsSet = amountHintIsSet;
1110 public boolean isEmpty() {
1111 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1112 Misc.emptyIsNull(comment) == null;
1114 @SuppressLint("DefaultLocale")
1116 public String toString() {
1117 StringBuilder b = new StringBuilder();
1118 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1119 if (!TextUtils.isEmpty(accountName))
1120 b.append(String.format(" acc'%s'", accountName));
1123 b.append(String.format(" %4.2f", amount));
1124 else if (amountHintIsSet)
1125 b.append(String.format(" (%s)", amountHint));
1127 if (!TextUtils.isEmpty(currency))
1131 if (!TextUtils.isEmpty(comment))
1132 b.append(String.format(" /%s/", comment));
1134 return b.toString();
1136 public boolean equalContents(TransactionAccount other) {
1140 boolean equal = TextUtils.equals(accountName, other.accountName) &&
1141 TextUtils.equals(comment, other.comment) &&
1142 (amountSet ? other.amountSet && amount == other.amount
1143 : !other.amountSet) &&
1144 (amountHintIsSet ? other.amountHintIsSet &&
1145 TextUtils.equals(amountHint, other.amountHint)
1146 : !other.amountHintIsSet) &&
1147 TextUtils.equals(currency, other.currency);
1148 Logger.debug("new-trans",
1149 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1155 private static class BalanceForCurrency {
1156 private final HashMap<String, Float> hashMap = new HashMap<>();
1157 float get(String currencyName) {
1158 Float f = hashMap.get(currencyName);
1161 hashMap.put(currencyName, f);
1165 void add(String currencyName, float amount) {
1166 hashMap.put(currencyName, get(currencyName) + amount);
1168 Set<String> currencies() {
1169 return hashMap.keySet();
1171 boolean containsCurrency(String currencyName) {
1172 return hashMap.containsKey(currencyName);
1176 private static class ItemsForCurrency {
1177 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1179 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1180 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1182 list = new ArrayList<>();
1183 hashMap.put(currencyName, list);
1187 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1188 getList(currencyName).add(item);
1190 int size(@Nullable String currencyName) {
1191 return this.getList(currencyName)
1194 Set<String> currencies() {
1195 return hashMap.keySet();