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, bottomFiller}
62 enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
65 public class NewTransactionModel extends ViewModel {
66 private final MutableLiveData<Boolean> showCurrency = new MutableLiveData<>(false);
67 private final MutableLiveData<Boolean> isSubmittable = new InertMutableLiveData<>(false);
68 private final MutableLiveData<Boolean> showComments = new MutableLiveData<>(true);
69 private final MutableLiveData<List<Item>> items = new MutableLiveData<>();
70 private final MutableLiveData<Integer> accountCount = new InertMutableLiveData<>(0);
71 private final MutableLiveData<Boolean> simulateSave = new InertMutableLiveData<>(false);
72 private final AtomicInteger busyCounter = new AtomicInteger(0);
73 private final MutableLiveData<Boolean> busyFlag = new InertMutableLiveData<>(false);
74 private final Observer<MobileLedgerProfile> profileObserver = profile -> {
75 showCurrency.postValue(profile.getShowCommodityByDefault());
76 showComments.postValue(profile.getShowCommentsByDefault());
78 private final MutableLiveData<FocusInfo> focusInfo = new MutableLiveData<>();
79 private boolean observingDataProfile;
80 public NewTransactionModel() {
83 public LiveData<Boolean> getShowCurrency() {
86 public LiveData<List<Item>> getItems() {
89 private void setItems(@NonNull List<Item> newList) {
90 checkTransactionSubmittable(newList);
91 setItemsWithoutSubmittableChecks(newList);
93 private void setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
94 Logger.debug("new-trans", "model: Setting new item list");
96 accountCount.setValue(list.size() - 2);
98 private List<Item> copyList() {
99 return copyList(null);
101 private List<Item> copyList(@Nullable List<Item> source) {
102 List<Item> copy = new ArrayList<>();
103 List<Item> oldList = (source == null) ? items.getValue() : source;
106 for (Item item : oldList) {
107 copy.add(Item.from(item));
112 private List<Item> shallowCopyListWithoutItem(int position) {
113 List<Item> copy = new ArrayList<>();
114 List<Item> oldList = items.getValue();
116 if (oldList != null) {
118 for (Item item : oldList) {
127 private List<Item> shallowCopyList() {
128 return new ArrayList<>(items.getValue());
130 LiveData<Boolean> getShowComments() {
133 void observeDataProfile(LifecycleOwner activity) {
134 if (!observingDataProfile)
135 Data.observeProfile(activity, profileObserver);
136 observingDataProfile = true;
138 boolean getSimulateSaveFlag() {
139 Boolean value = simulateSave.getValue();
144 LiveData<Boolean> getSimulateSave() {
147 void toggleSimulateSave() {
148 simulateSave.setValue(!getSimulateSaveFlag());
150 LiveData<Boolean> isSubmittable() {
151 return this.isSubmittable;
154 List<Item> list = new ArrayList<>();
155 list.add(new TransactionHead(""));
156 list.add(new TransactionAccount(""));
157 list.add(new TransactionAccount(""));
158 list.add(new BottomFiller());
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() - 1; 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 newItems.add(new BottomFiller());
265 items.postValue(newItems);
268 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
274 if (grp > 0 & grp <= m.groupCount())
276 return Integer.parseInt(m.group(grp));
278 catch (NumberFormatException e) {
279 Logger.debug("new-trans", "Error extracting matched number", e);
285 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
291 if (grp > 0 & grp <= m.groupCount())
297 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
303 if (grp > 0 & grp <= m.groupCount())
305 return Float.valueOf(m.group(grp));
307 catch (NumberFormatException e) {
308 Logger.debug("new-trans", "Error extracting matched number", e);
314 void removeItem(int pos) {
315 List<Item> newList = shallowCopyListWithoutItem(pos);
318 void noteFocusChanged(int position, FocusedElement element) {
319 FocusInfo present = focusInfo.getValue();
320 if (present == null || present.position != position || present.element != element)
321 focusInfo.setValue(new FocusInfo(position, element));
323 public LiveData<FocusInfo> getFocusInfo() {
326 void moveItem(int fromIndex, int toIndex) {
327 List<Item> newList = shallowCopyList();
328 Item item = newList.remove(fromIndex);
329 newList.add(toIndex, item);
330 items.setValue(newList); // same count, same submittable state
332 void moveItemLast(List<Item> list, int index) {
336 3 <-- desired position
339 int itemCount = list.size();
341 if (index < itemCount - 1)
342 list.add(list.remove(index));
344 void toggleCurrencyVisible() {
345 showCurrency.setValue(!Objects.requireNonNull(showCurrency.getValue()));
347 void stopObservingBusyFlag(Observer<Boolean> observer) {
348 busyFlag.removeObserver(observer);
350 void incrementBusyCounter() {
351 int newValue = busyCounter.incrementAndGet();
353 busyFlag.postValue(true);
355 void decrementBusyCounter() {
356 int newValue = busyCounter.decrementAndGet();
358 busyFlag.postValue(false);
360 public LiveData<Boolean> getBusyFlag() {
363 public void toggleShowComments() {
364 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
366 public LedgerTransaction constructLedgerTransaction() {
367 List<Item> list = Objects.requireNonNull(items.getValue());
368 TransactionHead head = list.get(0)
369 .toTransactionHead();
370 SimpleDate date = head.getDate();
371 LedgerTransaction tr = head.asLedgerTransaction();
373 tr.setComment(head.getComment());
374 LedgerTransactionAccount emptyAmountAccount = null;
375 float emptyAmountAccountBalance = 0;
376 for (int i = 1; i < list.size() - 1; i++) {
377 TransactionAccount item = list.get(i)
378 .toTransactionAccount();
379 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
382 if (acc.getAccountName()
386 acc.setComment(item.getComment());
388 if (item.isAmountSet()) {
389 acc.setAmount(item.getAmount());
390 emptyAmountAccountBalance += item.getAmount();
393 emptyAmountAccount = acc;
399 if (emptyAmountAccount != null)
400 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
404 void loadTransactionIntoModel(String profileUUID, int transactionId) {
405 List<Item> newList = new ArrayList<>();
406 LedgerTransaction tr;
407 MobileLedgerProfile profile = Data.getProfile(profileUUID);
409 throw new RuntimeException(String.format(
410 "Unable to find profile %s, which is supposed to contain transaction %d",
411 profileUUID, transactionId));
413 tr = profile.loadTransaction(transactionId);
414 TransactionHead head = new TransactionHead(tr.getDescription());
415 head.setComment(tr.getComment());
419 List<LedgerTransactionAccount> accounts = tr.getAccounts();
421 TransactionAccount firstNegative = null;
422 TransactionAccount firstPositive = null;
423 int singleNegativeIndex = -1;
424 int singlePositiveIndex = -1;
425 int negativeCount = 0;
426 for (int i = 0; i < accounts.size(); i++) {
427 LedgerTransactionAccount acc = accounts.get(i);
428 TransactionAccount item =
429 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
432 item.setAccountName(acc.getAccountName());
433 item.setComment(acc.getComment());
434 if (acc.isAmountSet()) {
435 item.setAmount(acc.getAmount());
436 if (acc.getAmount() < 0) {
437 if (firstNegative == null) {
438 firstNegative = item;
439 singleNegativeIndex = i + 1;
442 singleNegativeIndex = -1;
445 if (firstPositive == null) {
446 firstPositive = item;
447 singlePositiveIndex = i + 1;
450 singlePositiveIndex = -1;
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);
468 newList.add(new BottomFiller());
473 * A transaction is submittable if:
475 * 1) has at least two account names
476 * 2) each row with amount has account name
477 * 3) for each commodity:
478 * 3a) amounts must balance to 0, or
479 * 3b) there must be exactly one empty amount (with account)
480 * 4) empty accounts with empty amounts are ignored
482 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
484 * 6) at least two rows need to be present in the ledger
486 * @param list - the item list to check. Can be the displayed list or a list that will be
489 @SuppressLint("DefaultLocale")
490 void checkTransactionSubmittable(@Nullable List<Item> list) {
491 boolean workingWithLiveList = false;
492 boolean liveListCopied = false;
494 list = Objects.requireNonNull(items.getValue());
495 workingWithLiveList = true;
498 if (BuildConfig.DEBUG)
499 dumpItemList("Before submittable checks", list);
502 final BalanceForCurrency balance = new BalanceForCurrency();
503 final String descriptionText = list.get(0)
506 boolean submittable = true;
507 boolean listChanged = false;
508 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
509 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
510 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
511 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
512 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
513 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
514 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
515 final List<Item> emptyRows = new ArrayList<>();
518 if ((descriptionText == null) || descriptionText.trim()
521 Logger.debug("submittable", "Transaction not submittable: missing description");
525 for (int i = 1; i < list.size() - 1; i++) {
526 TransactionAccount item = list.get(i)
527 .toTransactionAccount();
529 String accName = item.getAccountName()
531 String currName = item.getCurrency();
533 itemsForCurrency.add(currName, item);
535 if (accName.isEmpty()) {
536 itemsWithEmptyAccountForCurrency.add(currName, item);
538 if (item.isAmountSet()) {
539 // 2) each amount has account name
540 Logger.debug("submittable", String.format(
541 "Transaction not submittable: row %d has no account name, but" +
542 " has" + " amount %1.2f", i + 1, item.getAmount()));
546 emptyRowsForCurrency.add(currName, item);
551 itemsWithAccountForCurrency.add(currName, item);
554 if (!item.isAmountValid()) {
555 Logger.debug("submittable",
556 String.format("Not submittable: row %d has an invalid amount", i + 1));
559 else if (item.isAmountSet()) {
560 itemsWithAmountForCurrency.add(currName, item);
561 balance.add(currName, item.getAmount());
564 itemsWithEmptyAmountForCurrency.add(currName, item);
566 if (!accName.isEmpty())
567 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
571 // 1) has at least two account names
574 Logger.debug("submittable", "Transaction not submittable: no account names");
575 else if (accounts == 1)
576 Logger.debug("submittable",
577 "Transaction not submittable: only one account name");
579 Logger.debug("submittable",
580 String.format("Transaction not submittable: only %d account names",
585 // 3) for each commodity:
586 // 3a) amount must balance to 0, or
587 // 3b) there must be exactly one empty amount (with account)
588 for (String balCurrency : itemsForCurrency.currencies()) {
589 float currencyBalance = balance.get(balCurrency);
590 if (Misc.isZero(currencyBalance)) {
591 // remove hints from all amount inputs in that currency
592 for (int i = 1; i < list.size() - 1; i++) {
593 TransactionAccount acc = list.get(i)
594 .toTransactionAccount();
595 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
596 if (BuildConfig.DEBUG)
597 Logger.debug("submittable",
598 String.format("Resetting hint of '%s' [%s]",
599 Misc.nullIsEmpty(acc.getAccountName()),
601 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
602 if (workingWithLiveList && !liveListCopied) {
603 list = copyList(list);
604 liveListCopied = true;
606 final TransactionAccount newAcc = new TransactionAccount(acc);
607 newAcc.setAmountHint(null);
608 if (!liveListCopied) {
609 list = copyList(list);
610 liveListCopied = true;
620 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
621 int balanceReceiversCount = tmpList.size();
622 if (balanceReceiversCount != 1) {
623 if (BuildConfig.DEBUG) {
624 if (balanceReceiversCount == 0)
625 Logger.debug("submittable", String.format(
626 "Transaction not submittable [%s]: non-zero balance " +
627 "with no empty amounts with accounts", balCurrency));
629 Logger.debug("submittable", String.format(
630 "Transaction not submittable [%s]: non-zero balance " +
631 "with multiple empty amounts with accounts", balCurrency));
636 List<Item> emptyAmountList =
637 itemsWithEmptyAmountForCurrency.getList(balCurrency);
639 // suggest off-balance amount to a row and remove hints on other rows
640 Item receiver = null;
641 if (!tmpList.isEmpty())
642 receiver = tmpList.get(0);
643 else if (!emptyAmountList.isEmpty())
644 receiver = emptyAmountList.get(0);
646 for (int i = 0; i < list.size(); i++) {
647 Item item = list.get(i);
648 if (!(item instanceof TransactionAccount))
651 TransactionAccount acc = item.toTransactionAccount();
652 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
655 if (item == receiver) {
656 final String hint = String.format("%1.2f", -currencyBalance);
657 if (!acc.isAmountHintSet() ||
658 !TextUtils.equals(acc.getAmountHint(), hint))
660 Logger.debug("submittable",
661 String.format("Setting amount hint of {%s} to %s [%s]",
662 acc.toString(), hint, balCurrency));
663 if (workingWithLiveList & !liveListCopied) {
664 list = copyList(list);
665 liveListCopied = true;
667 final TransactionAccount newAcc = new TransactionAccount(acc);
668 newAcc.setAmountHint(hint);
674 if (BuildConfig.DEBUG)
675 Logger.debug("submittable",
676 String.format("Resetting hint of '%s' [%s]",
677 Misc.nullIsEmpty(acc.getAccountName()),
679 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
680 if (workingWithLiveList && !liveListCopied) {
681 list = copyList(list);
682 liveListCopied = true;
684 final TransactionAccount newAcc = new TransactionAccount(acc);
685 newAcc.setAmountHint(null);
694 // 5) a row with an empty account name or empty amount is guaranteed to exist for
696 for (String balCurrency : balance.currencies()) {
697 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
698 int currRows = itemsForCurrency.size(balCurrency);
699 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
700 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
701 if ((currEmptyRows == 0) &&
702 ((currRows == currAccounts) || (currRows == currAmounts)))
704 // perhaps there already is an unused empty row for another currency that
706 // boolean foundIt = false;
707 // for (Item item : emptyRows) {
708 // Currency itemCurrency = item.getCurrency();
709 // String itemCurrencyName =
710 // (itemCurrency == null) ? "" : itemCurrency.getName();
711 // if (Misc.isZero(balance.get(itemCurrencyName))) {
712 // item.setCurrency(Currency.loadByName(balCurrency));
713 // item.setAmountHint(
714 // String.format("%1.2f", -balance.get(balCurrency)));
721 if (workingWithLiveList && !liveListCopied) {
722 list = copyList(list);
723 liveListCopied = true;
725 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
726 final float bal = balance.get(balCurrency);
727 if (!Misc.isZero(bal) && currAmounts == currRows)
728 newAcc.setAmountHint(String.format("%4.2f", -bal));
729 Logger.debug("submittable",
730 String.format("Adding new item with %s for currency %s",
731 newAcc.getAmountHint(), balCurrency));
732 list.add(list.size() - 1, newAcc);
737 // drop extra empty rows, not needed
738 for (String currName : emptyRowsForCurrency.currencies()) {
739 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
740 while ((list.size() > 4) && (emptyItems.size() > 1)) {
741 if (workingWithLiveList && !liveListCopied) {
742 list = copyList(list);
743 liveListCopied = true;
745 Item item = emptyItems.remove(1);
750 // unused currency, remove last item (which is also an empty one)
751 if ((list.size() > 4) && (emptyItems.size() == 1)) {
752 List<Item> currItems = itemsForCurrency.getList(currName);
754 if (currItems.size() == 1) {
755 if (workingWithLiveList && !liveListCopied) {
756 list = copyList(list);
757 liveListCopied = true;
759 Item item = emptyItems.get(0);
766 // 6) at least two rows need to be present in the ledger
767 // (the list also contains header and trailer)
768 while (list.size() < 4) {
769 if (workingWithLiveList && !liveListCopied) {
770 list = copyList(list);
771 liveListCopied = true;
773 list.add(list.size() - 1, new TransactionAccount(""));
778 Logger.debug("submittable", submittable ? "YES" : "NO");
779 isSubmittable.setValue(submittable);
781 if (BuildConfig.DEBUG)
782 dumpItemList("After submittable checks", list);
784 catch (NumberFormatException e) {
785 Logger.debug("submittable", "NO (because of NumberFormatException)");
786 isSubmittable.setValue(false);
788 catch (Exception e) {
790 Logger.debug("submittable", "NO (because of an Exception)");
791 isSubmittable.setValue(false);
794 if (listChanged && workingWithLiveList) {
795 setItemsWithoutSubmittableChecks(list);
798 @SuppressLint("DefaultLocale")
799 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
800 Logger.debug("submittable", "== Dump of all items " + msg);
801 for (int i = 1; i < list.size() - 1; i++) {
802 TransactionAccount item = list.get(i)
803 .toTransactionAccount();
804 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
807 public void setItemCurrency(int position, String newCurrency) {
808 TransactionAccount item = Objects.requireNonNull(items.getValue())
810 .toTransactionAccount();
811 final String oldCurrency = item.getCurrency();
813 if (Misc.equalStrings(oldCurrency, newCurrency))
816 List<Item> newList = copyList();
817 newList.get(position)
818 .toTransactionAccount()
819 .setCurrency(newCurrency);
823 public LiveData<Integer> getAccountCount() {
826 public boolean accountListIsEmpty() {
827 List<Item> items = Objects.requireNonNull(this.items.getValue());
829 for (Item item : items) {
830 if (!(item instanceof TransactionAccount))
833 if (!((TransactionAccount) item).isEmpty())
840 public static class FocusInfo {
842 FocusedElement element;
843 public FocusInfo(int position, FocusedElement element) {
844 this.position = position;
845 this.element = element;
849 static abstract class Item {
850 private static int idDispenser = 0;
853 synchronized (Item.class) {
857 public static Item from(Item origin) {
858 if (origin instanceof TransactionHead)
859 return new TransactionHead((TransactionHead) origin);
860 if (origin instanceof TransactionAccount)
861 return new TransactionAccount((TransactionAccount) origin);
862 if (origin instanceof BottomFiller)
863 return new BottomFiller((BottomFiller) origin);
864 throw new RuntimeException("Don't know how to handle " + origin);
869 public abstract ItemType getType();
870 public TransactionHead toTransactionHead() {
871 if (this instanceof TransactionHead)
872 return (TransactionHead) this;
874 throw new IllegalStateException("Wrong item type " + this);
876 public TransactionAccount toTransactionAccount() {
877 if (this instanceof TransactionAccount)
878 return (TransactionAccount) this;
880 throw new IllegalStateException("Wrong item type " + this);
882 public boolean equalContents(@Nullable Object item) {
886 if (!getClass().equals(item.getClass()))
889 // shortcut - comparing same instance
893 if (this instanceof TransactionHead)
894 return ((TransactionHead) item).equalContents((TransactionHead) this);
895 if (this instanceof TransactionAccount)
896 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
897 if (this instanceof BottomFiller)
900 throw new RuntimeException("Don't know how to handle " + this);
905 //==========================================================================================
907 public static class TransactionHead extends Item {
908 private SimpleDate date;
909 private String description;
910 private String comment;
911 TransactionHead(String description) {
913 this.description = description;
915 public TransactionHead(TransactionHead origin) {
918 description = origin.description;
919 comment = origin.comment;
921 public SimpleDate getDate() {
924 public void setDate(SimpleDate date) {
927 public void setDate(String text) throws ParseException {
928 if (Misc.emptyIsNull(text) == null) {
933 date = Globals.parseLedgerDate(text);
938 * @return nicely formatted, shortest available date representation
940 String getFormattedDate() {
944 Calendar today = GregorianCalendar.getInstance();
946 if (today.get(Calendar.YEAR) != date.year) {
947 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
950 if (today.get(Calendar.MONTH) + 1 != date.month) {
951 return String.format(Locale.US, "%d/%02d", date.month, date.day);
954 return String.valueOf(date.day);
958 public String toString() {
959 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
960 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
962 if (TextUtils.isEmpty(description))
963 b.append(" «no description»");
965 b.append(String.format(" descr'%s'", description));
968 b.append(String.format("@%s", date.toString()));
970 if (!TextUtils.isEmpty(comment))
971 b.append(String.format(" /%s/", comment));
975 public String getDescription() {
978 public void setDescription(String description) {
979 this.description = description;
981 public String getComment() {
984 public void setComment(String comment) {
985 this.comment = comment;
988 public ItemType getType() {
989 return ItemType.generalData;
991 public LedgerTransaction asLedgerTransaction() {
992 return new LedgerTransaction(null, date, description, Data.getProfile());
994 public boolean equalContents(TransactionHead other) {
998 return Objects.equals(date, other.date) &&
999 TextUtils.equals(description, other.description) &&
1000 TextUtils.equals(comment, other.comment);
1004 public static class BottomFiller extends Item {
1005 public BottomFiller(BottomFiller origin) {
1009 public BottomFiller() {
1013 public ItemType getType() {
1014 return ItemType.bottomFiller;
1016 @SuppressLint("DefaultLocale")
1019 public String toString() {
1020 return String.format("id:%d «bottom filler»", id);
1024 public static class TransactionAccount extends Item {
1025 private String accountName;
1026 private String amountHint;
1027 private String comment;
1028 private String currency;
1029 private float amount;
1030 private boolean amountSet;
1031 private boolean amountValid = true;
1032 private FocusedElement focusedElement = FocusedElement.Account;
1033 private boolean amountHintIsSet = false;
1034 public TransactionAccount(TransactionAccount origin) {
1036 accountName = origin.accountName;
1037 amount = origin.amount;
1038 amountSet = origin.amountSet;
1039 amountHint = origin.amountHint;
1040 amountHintIsSet = origin.amountHintIsSet;
1041 comment = origin.comment;
1042 currency = origin.currency;
1043 amountValid = origin.amountValid;
1044 focusedElement = origin.focusedElement;
1046 public TransactionAccount(LedgerTransactionAccount account) {
1048 currency = account.getCurrency();
1049 amount = account.getAmount();
1051 public TransactionAccount(String accountName) {
1053 this.accountName = accountName;
1055 public TransactionAccount(String accountName, String currency) {
1057 this.accountName = accountName;
1058 this.currency = currency;
1060 public boolean isAmountSet() {
1063 public String getAccountName() {
1066 public void setAccountName(String accountName) {
1067 this.accountName = accountName;
1069 public float getAmount() {
1071 throw new IllegalStateException("Amount is not set");
1074 public void setAmount(float amount) {
1075 this.amount = amount;
1078 public void resetAmount() {
1082 public ItemType getType() {
1083 return ItemType.transactionRow;
1085 public String getAmountHint() {
1088 public void setAmountHint(String amountHint) {
1089 this.amountHint = amountHint;
1090 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1092 public String getComment() {
1095 public void setComment(String comment) {
1096 this.comment = comment;
1098 public String getCurrency() {
1101 public void setCurrency(String currency) {
1102 this.currency = currency;
1104 public boolean isAmountValid() {
1107 public void setAmountValid(boolean amountValid) {
1108 this.amountValid = amountValid;
1110 public FocusedElement getFocusedElement() {
1111 return focusedElement;
1113 public void setFocusedElement(FocusedElement focusedElement) {
1114 this.focusedElement = focusedElement;
1116 public boolean isAmountHintSet() {
1117 return amountHintIsSet;
1119 public void setAmountHintIsSet(boolean amountHintIsSet) {
1120 this.amountHintIsSet = amountHintIsSet;
1122 public boolean isEmpty() {
1123 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1124 Misc.emptyIsNull(comment) == null;
1126 @SuppressLint("DefaultLocale")
1128 public String toString() {
1129 StringBuilder b = new StringBuilder();
1130 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1131 if (!TextUtils.isEmpty(accountName))
1132 b.append(String.format(" acc'%s'", accountName));
1135 b.append(String.format(" %4.2f", amount));
1136 else if (amountHintIsSet)
1137 b.append(String.format(" (%s)", amountHint));
1139 if (!TextUtils.isEmpty(currency))
1143 if (!TextUtils.isEmpty(comment))
1144 b.append(String.format(" /%s/", comment));
1146 return b.toString();
1148 public boolean equalContents(TransactionAccount other) {
1152 boolean equal = TextUtils.equals(accountName, other.accountName) &&
1153 TextUtils.equals(comment, other.comment) &&
1154 (amountSet ? other.amountSet && amount == other.amount
1155 : !other.amountSet) &&
1156 (amountHintIsSet ? other.amountHintIsSet &&
1157 TextUtils.equals(amountHint, other.amountHint)
1158 : !other.amountHintIsSet) &&
1159 TextUtils.equals(currency, other.currency);
1160 Logger.debug("new-trans",
1161 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1167 private static class BalanceForCurrency {
1168 private final HashMap<String, Float> hashMap = new HashMap<>();
1169 float get(String currencyName) {
1170 Float f = hashMap.get(currencyName);
1173 hashMap.put(currencyName, f);
1177 void add(String currencyName, float amount) {
1178 hashMap.put(currencyName, get(currencyName) + amount);
1180 Set<String> currencies() {
1181 return hashMap.keySet();
1183 boolean containsCurrency(String currencyName) {
1184 return hashMap.containsKey(currencyName);
1188 private static class ItemsForCurrency {
1189 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1191 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1192 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1194 list = new ArrayList<>();
1195 hashMap.put(currencyName, list);
1199 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1200 getList(currencyName).add(item);
1202 int size(@Nullable String currencyName) {
1203 return this.getList(currencyName)
1206 Set<String> currencies() {
1207 return hashMap.keySet();