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 Item item = emptyItems.remove(1);
746 // unused currency, remove last item (which is also an empty one)
747 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
748 List<Item> currItems = itemsForCurrency.getList(currName);
750 if (currItems.size() == 1) {
751 if (workingWithLiveList && !liveListCopied) {
752 list = copyList(list);
753 liveListCopied = true;
755 Item item = emptyItems.get(0);
762 // 6) at least two rows need to be present in the ledger
763 // (the list also contains header and trailer)
764 while (list.size() < MIN_ITEMS) {
765 if (workingWithLiveList && !liveListCopied) {
766 list = copyList(list);
767 liveListCopied = true;
769 list.add(new TransactionAccount(""));
774 Logger.debug("submittable", submittable ? "YES" : "NO");
775 isSubmittable.setValue(submittable);
777 if (BuildConfig.DEBUG)
778 dumpItemList("After submittable checks", list);
780 catch (NumberFormatException e) {
781 Logger.debug("submittable", "NO (because of NumberFormatException)");
782 isSubmittable.setValue(false);
784 catch (Exception e) {
786 Logger.debug("submittable", "NO (because of an Exception)");
787 isSubmittable.setValue(false);
790 if (listChanged && workingWithLiveList) {
791 setItemsWithoutSubmittableChecks(list);
794 @SuppressLint("DefaultLocale")
795 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
796 Logger.debug("submittable", "== Dump of all items " + msg);
797 for (int i = 1; i < list.size(); i++) {
798 TransactionAccount item = list.get(i)
799 .toTransactionAccount();
800 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
803 public void setItemCurrency(int position, String newCurrency) {
804 TransactionAccount item = Objects.requireNonNull(items.getValue())
806 .toTransactionAccount();
807 final String oldCurrency = item.getCurrency();
809 if (Misc.equalStrings(oldCurrency, newCurrency))
812 List<Item> newList = copyList();
813 newList.get(position)
814 .toTransactionAccount()
815 .setCurrency(newCurrency);
819 public LiveData<Integer> getAccountCount() {
822 public boolean accountListIsEmpty() {
823 List<Item> items = Objects.requireNonNull(this.items.getValue());
825 for (Item item : items) {
826 if (!(item instanceof TransactionAccount))
829 if (!((TransactionAccount) item).isEmpty())
836 public static class FocusInfo {
838 FocusedElement element;
839 public FocusInfo(int position, FocusedElement element) {
840 this.position = position;
841 this.element = element;
845 static abstract class Item {
846 private static int idDispenser = 0;
849 synchronized (Item.class) {
853 public static Item from(Item origin) {
854 if (origin instanceof TransactionHead)
855 return new TransactionHead((TransactionHead) origin);
856 if (origin instanceof TransactionAccount)
857 return new TransactionAccount((TransactionAccount) origin);
858 throw new RuntimeException("Don't know how to handle " + origin);
863 public abstract ItemType getType();
864 public TransactionHead toTransactionHead() {
865 if (this instanceof TransactionHead)
866 return (TransactionHead) this;
868 throw new IllegalStateException("Wrong item type " + this);
870 public TransactionAccount toTransactionAccount() {
871 if (this instanceof TransactionAccount)
872 return (TransactionAccount) this;
874 throw new IllegalStateException("Wrong item type " + this);
876 public boolean equalContents(@Nullable Object item) {
880 if (!getClass().equals(item.getClass()))
883 // shortcut - comparing same instance
887 if (this instanceof TransactionHead)
888 return ((TransactionHead) item).equalContents((TransactionHead) this);
889 if (this instanceof TransactionAccount)
890 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
892 throw new RuntimeException("Don't know how to handle " + this);
897 //==========================================================================================
899 public static class TransactionHead extends Item {
900 private SimpleDate date;
901 private String description;
902 private String comment;
903 TransactionHead(String description) {
905 this.description = description;
907 public TransactionHead(TransactionHead origin) {
910 description = origin.description;
911 comment = origin.comment;
913 public SimpleDate getDate() {
916 public void setDate(SimpleDate date) {
919 public void setDate(String text) throws ParseException {
920 if (Misc.emptyIsNull(text) == null) {
925 date = Globals.parseLedgerDate(text);
930 * @return nicely formatted, shortest available date representation
932 String getFormattedDate() {
936 Calendar today = GregorianCalendar.getInstance();
938 if (today.get(Calendar.YEAR) != date.year) {
939 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
942 if (today.get(Calendar.MONTH) + 1 != date.month) {
943 return String.format(Locale.US, "%d/%02d", date.month, date.day);
946 return String.valueOf(date.day);
950 public String toString() {
951 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
952 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
954 if (TextUtils.isEmpty(description))
955 b.append(" «no description»");
957 b.append(String.format(" descr'%s'", description));
960 b.append(String.format("@%s", date.toString()));
962 if (!TextUtils.isEmpty(comment))
963 b.append(String.format(" /%s/", comment));
967 public String getDescription() {
970 public void setDescription(String description) {
971 this.description = description;
973 public String getComment() {
976 public void setComment(String comment) {
977 this.comment = comment;
980 public ItemType getType() {
981 return ItemType.generalData;
983 public LedgerTransaction asLedgerTransaction() {
984 return new LedgerTransaction(null, date, description, Data.getProfile());
986 public boolean equalContents(TransactionHead other) {
990 return Objects.equals(date, other.date) &&
991 TextUtils.equals(description, other.description) &&
992 TextUtils.equals(comment, other.comment);
996 public static class TransactionAccount extends Item {
997 private String accountName;
998 private String amountHint;
999 private String comment;
1000 private String currency;
1001 private float amount;
1002 private boolean amountSet;
1003 private boolean amountValid = true;
1004 private FocusedElement focusedElement = FocusedElement.Account;
1005 private boolean amountHintIsSet = false;
1006 public TransactionAccount(TransactionAccount origin) {
1008 accountName = origin.accountName;
1009 amount = origin.amount;
1010 amountSet = origin.amountSet;
1011 amountHint = origin.amountHint;
1012 amountHintIsSet = origin.amountHintIsSet;
1013 comment = origin.comment;
1014 currency = origin.currency;
1015 amountValid = origin.amountValid;
1016 focusedElement = origin.focusedElement;
1018 public TransactionAccount(LedgerTransactionAccount account) {
1020 currency = account.getCurrency();
1021 amount = account.getAmount();
1023 public TransactionAccount(String accountName) {
1025 this.accountName = accountName;
1027 public TransactionAccount(String accountName, String currency) {
1029 this.accountName = accountName;
1030 this.currency = currency;
1032 public boolean isAmountSet() {
1035 public String getAccountName() {
1038 public void setAccountName(String accountName) {
1039 this.accountName = accountName;
1041 public float getAmount() {
1043 throw new IllegalStateException("Amount is not set");
1046 public void setAmount(float amount) {
1047 this.amount = amount;
1050 public void resetAmount() {
1054 public ItemType getType() {
1055 return ItemType.transactionRow;
1057 public String getAmountHint() {
1060 public void setAmountHint(String amountHint) {
1061 this.amountHint = amountHint;
1062 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1064 public String getComment() {
1067 public void setComment(String comment) {
1068 this.comment = comment;
1070 public String getCurrency() {
1073 public void setCurrency(String currency) {
1074 this.currency = currency;
1076 public boolean isAmountValid() {
1079 public void setAmountValid(boolean amountValid) {
1080 this.amountValid = amountValid;
1082 public FocusedElement getFocusedElement() {
1083 return focusedElement;
1085 public void setFocusedElement(FocusedElement focusedElement) {
1086 this.focusedElement = focusedElement;
1088 public boolean isAmountHintSet() {
1089 return amountHintIsSet;
1091 public void setAmountHintIsSet(boolean amountHintIsSet) {
1092 this.amountHintIsSet = amountHintIsSet;
1094 public boolean isEmpty() {
1095 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1096 Misc.emptyIsNull(comment) == null;
1098 @SuppressLint("DefaultLocale")
1100 public String toString() {
1101 StringBuilder b = new StringBuilder();
1102 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1103 if (!TextUtils.isEmpty(accountName))
1104 b.append(String.format(" acc'%s'", accountName));
1107 b.append(String.format(" %4.2f", amount));
1108 else if (amountHintIsSet)
1109 b.append(String.format(" (%s)", amountHint));
1111 if (!TextUtils.isEmpty(currency))
1115 if (!TextUtils.isEmpty(comment))
1116 b.append(String.format(" /%s/", comment));
1118 return b.toString();
1120 public boolean equalContents(TransactionAccount other) {
1124 boolean equal = TextUtils.equals(accountName, other.accountName) &&
1125 TextUtils.equals(comment, other.comment) &&
1126 (amountSet ? other.amountSet && amount == other.amount
1127 : !other.amountSet) &&
1128 (amountHintIsSet ? other.amountHintIsSet &&
1129 TextUtils.equals(amountHint, other.amountHint)
1130 : !other.amountHintIsSet) &&
1131 TextUtils.equals(currency, other.currency);
1132 Logger.debug("new-trans",
1133 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1139 private static class BalanceForCurrency {
1140 private final HashMap<String, Float> hashMap = new HashMap<>();
1141 float get(String currencyName) {
1142 Float f = hashMap.get(currencyName);
1145 hashMap.put(currencyName, f);
1149 void add(String currencyName, float amount) {
1150 hashMap.put(currencyName, get(currencyName) + amount);
1152 Set<String> currencies() {
1153 return hashMap.keySet();
1155 boolean containsCurrency(String currencyName) {
1156 return hashMap.containsKey(currencyName);
1160 private static class ItemsForCurrency {
1161 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1163 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1164 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1166 list = new ArrayList<>();
1167 hashMap.put(currencyName, list);
1171 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1172 getList(currencyName).add(item);
1174 int size(@Nullable String currencyName) {
1175 return this.getList(currencyName)
1178 Set<String> currencies() {
1179 return hashMap.keySet();