2 * Copyright © 2021 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
9 * MoLe is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License terms for details.
14 * You should have received a copy of the GNU General Public License
15 * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.ui.new_transaction;
20 import android.annotation.SuppressLint;
21 import android.os.Handler;
22 import android.os.Looper;
23 import android.text.TextUtils;
25 import androidx.annotation.NonNull;
26 import androidx.annotation.Nullable;
27 import androidx.lifecycle.LifecycleOwner;
28 import androidx.lifecycle.LiveData;
29 import androidx.lifecycle.MutableLiveData;
30 import androidx.lifecycle.Observer;
31 import androidx.lifecycle.ViewModel;
33 import net.ktnx.mobileledger.BuildConfig;
34 import net.ktnx.mobileledger.db.DB;
35 import net.ktnx.mobileledger.db.TemplateAccount;
36 import net.ktnx.mobileledger.db.TemplateHeader;
37 import net.ktnx.mobileledger.model.Data;
38 import net.ktnx.mobileledger.model.InertMutableLiveData;
39 import net.ktnx.mobileledger.model.LedgerTransaction;
40 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
41 import net.ktnx.mobileledger.model.MatchedTemplate;
42 import net.ktnx.mobileledger.model.MobileLedgerProfile;
43 import net.ktnx.mobileledger.utils.Globals;
44 import net.ktnx.mobileledger.utils.Logger;
45 import net.ktnx.mobileledger.utils.Misc;
46 import net.ktnx.mobileledger.utils.SimpleDate;
48 import org.jetbrains.annotations.NotNull;
50 import java.text.ParseException;
51 import java.util.ArrayList;
52 import java.util.Calendar;
53 import java.util.GregorianCalendar;
54 import java.util.HashMap;
55 import java.util.List;
56 import java.util.Locale;
57 import java.util.Objects;
59 import java.util.concurrent.atomic.AtomicInteger;
60 import java.util.regex.MatchResult;
62 enum ItemType {generalData, transactionRow}
64 enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
67 public class NewTransactionModel extends ViewModel {
68 private static final int MIN_ITEMS = 3;
69 private final MutableLiveData<Boolean> showCurrency = new MutableLiveData<>(false);
70 private final MutableLiveData<Boolean> isSubmittable = new InertMutableLiveData<>(false);
71 private final MutableLiveData<Boolean> showComments = new MutableLiveData<>(true);
72 private final MutableLiveData<List<Item>> items = new MutableLiveData<>();
73 private final MutableLiveData<Boolean> simulateSave = new InertMutableLiveData<>(false);
74 private final AtomicInteger busyCounter = new AtomicInteger(0);
75 private final MutableLiveData<Boolean> busyFlag = new InertMutableLiveData<>(false);
76 private final Observer<MobileLedgerProfile> profileObserver = profile -> {
77 showCurrency.postValue(profile.getShowCommodityByDefault());
78 showComments.postValue(profile.getShowCommentsByDefault());
80 private final MutableLiveData<FocusInfo> focusInfo = new MutableLiveData<>();
81 private boolean observingDataProfile;
82 public NewTransactionModel() {
85 public LiveData<Boolean> getShowCurrency() {
88 public LiveData<List<Item>> getItems() {
91 private void setItems(@NonNull List<Item> newList) {
92 checkTransactionSubmittable(newList);
93 setItemsWithoutSubmittableChecks(newList);
95 private void setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
96 final int cnt = list.size();
97 for (int i = 1; i < cnt - 1; i++) {
98 final TransactionAccount item = list.get(i)
99 .toTransactionAccount();
101 TransactionAccount replacement = new TransactionAccount(item);
102 replacement.isLast = false;
103 list.set(i, replacement);
106 final TransactionAccount last = list.get(cnt - 1)
107 .toTransactionAccount();
109 TransactionAccount replacement = new TransactionAccount(last);
110 replacement.isLast = true;
111 list.set(cnt - 1, replacement);
114 if (BuildConfig.DEBUG)
115 dumpItemList("Before setValue()", list);
116 items.setValue(list);
118 private List<Item> copyList() {
119 List<Item> copy = new ArrayList<>();
120 List<Item> oldList = items.getValue();
123 for (Item item : oldList) {
124 copy.add(Item.from(item));
129 private List<Item> copyListWithoutItem(int position) {
130 List<Item> copy = new ArrayList<>();
131 List<Item> oldList = items.getValue();
133 if (oldList != null) {
135 for (Item item : oldList) {
138 copy.add(Item.from(item));
144 private List<Item> shallowCopyList() {
145 return new ArrayList<>(items.getValue());
147 LiveData<Boolean> getShowComments() {
150 void observeDataProfile(LifecycleOwner activity) {
151 if (!observingDataProfile)
152 Data.observeProfile(activity, profileObserver);
153 observingDataProfile = true;
155 boolean getSimulateSaveFlag() {
156 Boolean value = simulateSave.getValue();
161 LiveData<Boolean> getSimulateSave() {
164 void toggleSimulateSave() {
165 simulateSave.setValue(!getSimulateSaveFlag());
167 LiveData<Boolean> isSubmittable() {
168 return this.isSubmittable;
171 Logger.debug("new-trans", "Resetting model");
172 List<Item> list = new ArrayList<>();
173 list.add(new TransactionHead(""));
174 list.add(new TransactionAccount(""));
175 list.add(new TransactionAccount(""));
176 noteFocusChanged(0, FocusedElement.Description);
177 isSubmittable.setValue(false);
178 setItemsWithoutSubmittableChecks(list);
180 boolean accountsInInitialState() {
181 final List<Item> list = items.getValue();
186 for (Item item : list) {
187 if (!(item instanceof TransactionAccount))
190 TransactionAccount accRow = (TransactionAccount) item;
191 if (!accRow.isEmpty())
197 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
198 SimpleDate transactionDate = null;
199 final MatchResult matchResult = matchedTemplate.matchResult;
200 final TemplateHeader templateHead = matchedTemplate.templateHead;
202 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
203 templateHead.getDateDay());
204 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
205 templateHead.getDateMonth());
206 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
207 templateHead.getDateYear());
209 if (year > 0 || month > 0 || day > 0) {
210 SimpleDate today = SimpleDate.today();
218 transactionDate = new SimpleDate(year, month, day);
220 Logger.debug("pattern", "setting transaction date to " + transactionDate);
224 List<Item> present = copyList();
226 TransactionHead head = new TransactionHead(present.get(0)
227 .toTransactionHead());
228 if (transactionDate != null)
229 head.setDate(transactionDate);
231 final String transactionDescription = extractStringFromMatches(matchResult,
232 templateHead.getTransactionDescriptionMatchGroup(),
233 templateHead.getTransactionDescription());
234 if (Misc.emptyIsNull(transactionDescription) != null)
235 head.setDescription(transactionDescription);
237 final String transactionComment = extractStringFromMatches(matchResult,
238 templateHead.getTransactionCommentMatchGroup(),
239 templateHead.getTransactionComment());
240 if (Misc.emptyIsNull(transactionComment) != null)
241 head.setComment(transactionComment);
243 List<Item> newItems = new ArrayList<>();
247 for (int i = 1; i < present.size(); i++) {
248 final TransactionAccount row = present.get(i)
249 .toTransactionAccount();
251 newItems.add(new TransactionAccount(row));
256 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
258 final boolean accountsInInitialState = accountsInInitialState();
259 for (TemplateAccount acc : entry.accounts) {
263 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
264 acc.getAccountName());
265 String accountComment =
266 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
267 acc.getAccountComment());
268 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
270 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
274 TransactionAccount accRow = new TransactionAccount(accountName);
275 accRow.setComment(accountComment);
277 accRow.setAmount(amount);
279 newItems.add(accRow);
282 new Handler(Looper.getMainLooper()).post(() -> setItems(newItems));
285 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
291 if (grp > 0 & grp <= m.groupCount())
293 return Integer.parseInt(m.group(grp));
295 catch (NumberFormatException e) {
296 Logger.debug("new-trans", "Error extracting matched number", e);
302 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
308 if (grp > 0 & grp <= m.groupCount())
314 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
320 if (grp > 0 & grp <= m.groupCount())
322 return Float.valueOf(m.group(grp));
324 catch (NumberFormatException e) {
325 Logger.debug("new-trans", "Error extracting matched number", e);
331 void removeItem(int pos) {
332 Logger.debug("new-trans", String.format(Locale.US, "Removing item at position %d", pos));
333 List<Item> newList = copyListWithoutItem(pos);
334 final FocusInfo fi = focusInfo.getValue();
335 if ((fi != null) && (pos < fi.position))
336 noteFocusChanged(fi.position - 1, fi.element);
339 void noteFocusChanged(int position, FocusedElement element) {
340 FocusInfo present = focusInfo.getValue();
341 if (present == null || present.position != position || present.element != element)
342 focusInfo.setValue(new FocusInfo(position, element));
344 public LiveData<FocusInfo> getFocusInfo() {
347 void moveItem(int fromIndex, int toIndex) {
348 List<Item> newList = shallowCopyList();
349 Item item = newList.remove(fromIndex);
350 newList.add(toIndex, item);
351 items.setValue(newList); // same count, same submittable state
353 void moveItemLast(List<Item> list, int index) {
357 3 <-- desired position
360 int itemCount = list.size();
362 if (index < itemCount - 1)
363 list.add(list.remove(index));
365 void toggleCurrencyVisible() {
366 final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
368 // remove currency from all items, or reset currency to the default
369 // no need to clone the list, because the removal of the currency won't lead to
370 // visual changes -- the currency fields will be hidden or reset to default anyway
371 // still, there may be changes in the submittable state
372 final List<Item> list = Objects.requireNonNull(this.items.getValue());
373 for (int i = 1; i < list.size(); i++) {
374 ((TransactionAccount) list.get(i)).setCurrency(newValue ? Data.getProfile()
375 .getDefaultCommodity()
378 checkTransactionSubmittable(null);
379 showCurrency.setValue(newValue);
381 void stopObservingBusyFlag(Observer<Boolean> observer) {
382 busyFlag.removeObserver(observer);
384 void incrementBusyCounter() {
385 int newValue = busyCounter.incrementAndGet();
387 busyFlag.postValue(true);
389 void decrementBusyCounter() {
390 int newValue = busyCounter.decrementAndGet();
392 busyFlag.postValue(false);
394 public LiveData<Boolean> getBusyFlag() {
397 public void toggleShowComments() {
398 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
400 public LedgerTransaction constructLedgerTransaction() {
401 List<Item> list = Objects.requireNonNull(items.getValue());
402 TransactionHead head = list.get(0)
403 .toTransactionHead();
404 SimpleDate date = head.getDate();
405 LedgerTransaction tr = head.asLedgerTransaction();
407 tr.setComment(head.getComment());
408 LedgerTransactionAccount emptyAmountAccount = null;
409 float emptyAmountAccountBalance = 0;
410 for (int i = 1; i < list.size(); i++) {
411 TransactionAccount item = list.get(i)
412 .toTransactionAccount();
413 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
416 if (acc.getAccountName()
420 acc.setComment(item.getComment());
422 if (item.isAmountSet()) {
423 acc.setAmount(item.getAmount());
424 emptyAmountAccountBalance += item.getAmount();
427 emptyAmountAccount = acc;
433 if (emptyAmountAccount != null)
434 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
438 void loadTransactionIntoModel(String profileUUID, int transactionId) {
439 List<Item> newList = new ArrayList<>();
440 LedgerTransaction tr;
441 MobileLedgerProfile profile = Data.getProfile(profileUUID);
443 throw new RuntimeException(String.format(
444 "Unable to find profile %s, which is supposed to contain transaction %d",
445 profileUUID, transactionId));
447 tr = profile.loadTransaction(transactionId);
448 TransactionHead head = new TransactionHead(tr.getDescription());
449 head.setComment(tr.getComment());
453 List<LedgerTransactionAccount> accounts = tr.getAccounts();
455 TransactionAccount firstNegative = null;
456 TransactionAccount firstPositive = null;
457 int singleNegativeIndex = -1;
458 int singlePositiveIndex = -1;
459 int negativeCount = 0;
460 for (int i = 0; i < accounts.size(); i++) {
461 LedgerTransactionAccount acc = accounts.get(i);
462 TransactionAccount item =
463 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
466 item.setAccountName(acc.getAccountName());
467 item.setComment(acc.getComment());
468 if (acc.isAmountSet()) {
469 item.setAmount(acc.getAmount());
470 if (acc.getAmount() < 0) {
471 if (firstNegative == null) {
472 firstNegative = item;
473 singleNegativeIndex = i + 1;
476 singleNegativeIndex = -1;
479 if (firstPositive == null) {
480 firstPositive = item;
481 singlePositiveIndex = i + 1;
484 singlePositiveIndex = -1;
490 if (BuildConfig.DEBUG)
491 dumpItemList("Loaded previous transaction", newList);
493 if (singleNegativeIndex != -1) {
494 firstNegative.resetAmount();
495 moveItemLast(newList, singleNegativeIndex);
497 else if (singlePositiveIndex != -1) {
498 firstPositive.resetAmount();
499 moveItemLast(newList, singlePositiveIndex);
504 noteFocusChanged(1, FocusedElement.Amount);
507 * A transaction is submittable if:
509 * 1) has at least two account names
510 * 2) each row with amount has account name
511 * 3) for each commodity:
512 * 3a) amounts must balance to 0, or
513 * 3b) there must be exactly one empty amount (with account)
514 * 4) empty accounts with empty amounts are ignored
516 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
518 * 6) at least two rows need to be present in the ledger
520 * @param list - the item list to check. Can be the displayed list or a list that will be
523 @SuppressLint("DefaultLocale")
524 void checkTransactionSubmittable(@Nullable List<Item> list) {
525 boolean workingWithLiveList = false;
528 workingWithLiveList = true;
531 if (BuildConfig.DEBUG)
532 dumpItemList("Before submittable checks", list);
535 final BalanceForCurrency balance = new BalanceForCurrency();
536 final String descriptionText = list.get(0)
539 boolean submittable = true;
540 boolean listChanged = false;
541 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
542 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
543 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
544 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
545 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
546 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
547 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
548 final List<Item> emptyRows = new ArrayList<>();
551 if ((descriptionText == null) || descriptionText.trim()
554 Logger.debug("submittable", "Transaction not submittable: missing description");
558 for (int i = 1; i < list.size(); i++) {
559 TransactionAccount item = list.get(i)
560 .toTransactionAccount();
562 String accName = item.getAccountName()
564 String currName = item.getCurrency();
566 itemsForCurrency.add(currName, item);
568 if (accName.isEmpty()) {
569 itemsWithEmptyAccountForCurrency.add(currName, item);
571 if (item.isAmountSet()) {
572 // 2) each amount has account name
573 Logger.debug("submittable", String.format(
574 "Transaction not submittable: row %d has no account name, but" +
575 " has" + " amount %1.2f", i + 1, item.getAmount()));
579 emptyRowsForCurrency.add(currName, item);
584 itemsWithAccountForCurrency.add(currName, item);
587 if (!item.isAmountValid()) {
588 Logger.debug("submittable",
589 String.format("Not submittable: row %d has an invalid amount", i + 1));
592 else if (item.isAmountSet()) {
593 itemsWithAmountForCurrency.add(currName, item);
594 balance.add(currName, item.getAmount());
597 itemsWithEmptyAmountForCurrency.add(currName, item);
599 if (!accName.isEmpty())
600 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
604 // 1) has at least two account names
607 Logger.debug("submittable", "Transaction not submittable: no account names");
608 else if (accounts == 1)
609 Logger.debug("submittable",
610 "Transaction not submittable: only one account name");
612 Logger.debug("submittable",
613 String.format("Transaction not submittable: only %d account names",
618 // 3) for each commodity:
619 // 3a) amount must balance to 0, or
620 // 3b) there must be exactly one empty amount (with account)
621 for (String balCurrency : itemsForCurrency.currencies()) {
622 float currencyBalance = balance.get(balCurrency);
623 if (Misc.isZero(currencyBalance)) {
624 // remove hints from all amount inputs in that currency
625 for (int i = 1; i < list.size(); i++) {
626 TransactionAccount acc = list.get(i)
627 .toTransactionAccount();
628 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
629 if (BuildConfig.DEBUG)
630 Logger.debug("submittable",
631 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
632 i, Misc.nullIsEmpty(acc.getAccountName()),
634 // skip if the amount is set, in which case the hint is not
636 if (!acc.isAmountSet() && acc.amountHintIsSet &&
637 !TextUtils.isEmpty(acc.getAmountHint()))
639 acc.setAmountHint(null);
647 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
648 int balanceReceiversCount = tmpList.size();
649 if (balanceReceiversCount != 1) {
650 if (BuildConfig.DEBUG) {
651 if (balanceReceiversCount == 0)
652 Logger.debug("submittable", String.format(
653 "Transaction not submittable [%s]: non-zero balance " +
654 "with no empty amounts with accounts", balCurrency));
656 Logger.debug("submittable", String.format(
657 "Transaction not submittable [%s]: non-zero balance " +
658 "with multiple empty amounts with accounts", balCurrency));
663 List<Item> emptyAmountList =
664 itemsWithEmptyAmountForCurrency.getList(balCurrency);
666 // suggest off-balance amount to a row and remove hints on other rows
667 Item receiver = null;
668 if (!tmpList.isEmpty())
669 receiver = tmpList.get(0);
670 else if (!emptyAmountList.isEmpty())
671 receiver = emptyAmountList.get(0);
673 for (int i = 0; i < list.size(); i++) {
674 Item item = list.get(i);
675 if (!(item instanceof TransactionAccount))
678 TransactionAccount acc = item.toTransactionAccount();
679 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
682 if (item == receiver) {
683 final String hint = String.format("%1.2f", -currencyBalance);
684 if (!acc.isAmountHintSet() ||
685 !TextUtils.equals(acc.getAmountHint(), hint))
687 Logger.debug("submittable",
688 String.format("Setting amount hint of {%s} to %s [%s]",
689 acc.toString(), hint, balCurrency));
690 acc.setAmountHint(hint);
695 if (BuildConfig.DEBUG)
696 Logger.debug("submittable",
697 String.format("Resetting hint of '%s' [%s]",
698 Misc.nullIsEmpty(acc.getAccountName()),
700 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
701 acc.setAmountHint(null);
709 // 5) a row with an empty account name or empty amount is guaranteed to exist for
711 for (String balCurrency : balance.currencies()) {
712 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
713 int currRows = itemsForCurrency.size(balCurrency);
714 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
715 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
716 if ((currEmptyRows == 0) &&
717 ((currRows == currAccounts) || (currRows == currAmounts)))
719 // perhaps there already is an unused empty row for another currency that
721 // boolean foundIt = false;
722 // for (Item item : emptyRows) {
723 // Currency itemCurrency = item.getCurrency();
724 // String itemCurrencyName =
725 // (itemCurrency == null) ? "" : itemCurrency.getName();
726 // if (Misc.isZero(balance.get(itemCurrencyName))) {
727 // item.setCurrency(Currency.loadByName(balCurrency));
728 // item.setAmountHint(
729 // String.format("%1.2f", -balance.get(balCurrency)));
736 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
737 final float bal = balance.get(balCurrency);
738 if (!Misc.isZero(bal) && currAmounts == currRows)
739 newAcc.setAmountHint(String.format("%4.2f", -bal));
740 Logger.debug("submittable",
741 String.format("Adding new item with %s for currency %s",
742 newAcc.getAmountHint(), balCurrency));
748 // drop extra empty rows, not needed
749 for (String currName : emptyRowsForCurrency.currencies()) {
750 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
751 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
752 // the list is a copy, so the empty item is no longer present
753 Item itemToRemove = emptyItems.remove(1);
754 removeItemById(list, itemToRemove.id);
758 // unused currency, remove last item (which is also an empty one)
759 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
760 List<Item> currItems = itemsForCurrency.getList(currName);
762 if (currItems.size() == 1) {
763 // the list is a copy, so the empty item is no longer present
764 removeItemById(list, emptyItems.get(0).id);
770 // 6) at least two rows need to be present in the ledger
771 // (the list also contains header and trailer)
772 while (list.size() < MIN_ITEMS) {
773 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 boolean accountListIsEmpty() {
836 List<Item> items = Objects.requireNonNull(this.items.getValue());
838 for (Item item : items) {
839 if (!(item instanceof TransactionAccount))
842 if (!((TransactionAccount) item).isEmpty())
849 public static class FocusInfo {
851 FocusedElement element;
852 public FocusInfo(int position, FocusedElement element) {
853 this.position = position;
854 this.element = element;
858 static abstract class Item {
859 private static int idDispenser = 0;
862 synchronized (Item.class) {
866 public static Item from(Item origin) {
867 if (origin instanceof TransactionHead)
868 return new TransactionHead((TransactionHead) origin);
869 if (origin instanceof TransactionAccount)
870 return new TransactionAccount((TransactionAccount) origin);
871 throw new RuntimeException("Don't know how to handle " + origin);
876 public abstract ItemType getType();
877 public TransactionHead toTransactionHead() {
878 if (this instanceof TransactionHead)
879 return (TransactionHead) this;
881 throw new IllegalStateException("Wrong item type " + this);
883 public TransactionAccount toTransactionAccount() {
884 if (this instanceof TransactionAccount)
885 return (TransactionAccount) this;
887 throw new IllegalStateException("Wrong item type " + this);
889 public boolean equalContents(@Nullable Object item) {
893 if (!getClass().equals(item.getClass()))
896 // shortcut - comparing same instance
900 if (this instanceof TransactionHead)
901 return ((TransactionHead) item).equalContents((TransactionHead) this);
902 if (this instanceof TransactionAccount)
903 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
905 throw new RuntimeException("Don't know how to handle " + this);
910 //==========================================================================================
912 public static class TransactionHead extends Item {
913 private SimpleDate date;
914 private String description;
915 private String comment;
916 TransactionHead(String description) {
918 this.description = description;
920 public TransactionHead(TransactionHead origin) {
923 description = origin.description;
924 comment = origin.comment;
926 public SimpleDate getDate() {
929 public void setDate(SimpleDate date) {
932 public void setDate(String text) throws ParseException {
933 if (Misc.emptyIsNull(text) == null) {
938 date = Globals.parseLedgerDate(text);
943 * @return nicely formatted, shortest available date representation
945 String getFormattedDate() {
949 Calendar today = GregorianCalendar.getInstance();
951 if (today.get(Calendar.YEAR) != date.year) {
952 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
955 if (today.get(Calendar.MONTH) + 1 != date.month) {
956 return String.format(Locale.US, "%d/%02d", date.month, date.day);
959 return String.valueOf(date.day);
963 public String toString() {
964 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
965 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
967 if (TextUtils.isEmpty(description))
968 b.append(" «no description»");
970 b.append(String.format(" descr'%s'", description));
973 b.append(String.format("@%s", date.toString()));
975 if (!TextUtils.isEmpty(comment))
976 b.append(String.format(" /%s/", comment));
980 public String getDescription() {
983 public void setDescription(String description) {
984 this.description = description;
986 public String getComment() {
989 public void setComment(String comment) {
990 this.comment = comment;
993 public ItemType getType() {
994 return ItemType.generalData;
996 public LedgerTransaction asLedgerTransaction() {
997 return new LedgerTransaction(null, date, description, Data.getProfile());
999 public boolean equalContents(TransactionHead other) {
1003 return Objects.equals(date, other.date) &&
1004 TextUtils.equals(description, other.description) &&
1005 TextUtils.equals(comment, other.comment);
1009 public static class TransactionAccount extends Item {
1010 private String accountName;
1011 private String amountHint;
1012 private String comment;
1013 private String currency;
1014 private float amount;
1015 private boolean amountSet;
1016 private boolean amountValid = true;
1017 private FocusedElement focusedElement = FocusedElement.Account;
1018 private boolean amountHintIsSet = false;
1019 private boolean isLast = false;
1020 private int accountNameCursorPosition;
1021 public TransactionAccount(TransactionAccount origin) {
1023 accountName = origin.accountName;
1024 amount = origin.amount;
1025 amountSet = origin.amountSet;
1026 amountHint = origin.amountHint;
1027 amountHintIsSet = origin.amountHintIsSet;
1028 comment = origin.comment;
1029 currency = origin.currency;
1030 amountValid = origin.amountValid;
1031 focusedElement = origin.focusedElement;
1032 isLast = origin.isLast;
1033 accountNameCursorPosition = origin.accountNameCursorPosition;
1035 public TransactionAccount(LedgerTransactionAccount account) {
1037 currency = account.getCurrency();
1038 amount = account.getAmount();
1040 public TransactionAccount(String accountName) {
1042 this.accountName = accountName;
1044 public TransactionAccount(String accountName, String currency) {
1046 this.accountName = accountName;
1047 this.currency = currency;
1049 public boolean isLast() {
1052 public boolean isAmountSet() {
1055 public String getAccountName() {
1058 public void setAccountName(String accountName) {
1059 this.accountName = accountName;
1061 public float getAmount() {
1063 throw new IllegalStateException("Amount is not set");
1066 public void setAmount(float amount) {
1067 this.amount = amount;
1070 public void resetAmount() {
1074 public ItemType getType() {
1075 return ItemType.transactionRow;
1077 public String getAmountHint() {
1080 public void setAmountHint(String amountHint) {
1081 this.amountHint = amountHint;
1082 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1084 public String getComment() {
1087 public void setComment(String comment) {
1088 this.comment = comment;
1090 public String getCurrency() {
1093 public void setCurrency(String currency) {
1094 this.currency = currency;
1096 public boolean isAmountValid() {
1099 public void setAmountValid(boolean amountValid) {
1100 this.amountValid = amountValid;
1102 public FocusedElement getFocusedElement() {
1103 return focusedElement;
1105 public void setFocusedElement(FocusedElement focusedElement) {
1106 this.focusedElement = focusedElement;
1108 public boolean isAmountHintSet() {
1109 return amountHintIsSet;
1111 public void setAmountHintIsSet(boolean amountHintIsSet) {
1112 this.amountHintIsSet = amountHintIsSet;
1114 public boolean isEmpty() {
1115 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1116 Misc.emptyIsNull(comment) == null;
1118 @SuppressLint("DefaultLocale")
1120 public String toString() {
1121 StringBuilder b = new StringBuilder();
1122 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1123 if (!TextUtils.isEmpty(accountName))
1124 b.append(String.format(" acc'%s'", accountName));
1127 b.append(String.format(" %4.2f", amount));
1128 else if (amountHintIsSet)
1129 b.append(String.format(" (%s)", amountHint));
1131 if (!TextUtils.isEmpty(currency))
1135 if (!TextUtils.isEmpty(comment))
1136 b.append(String.format(" /%s/", comment));
1141 return b.toString();
1143 public boolean equalContents(TransactionAccount other) {
1147 boolean equal = TextUtils.equals(accountName, other.accountName);
1148 equal = equal && TextUtils.equals(comment, other.comment) &&
1149 (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1151 // compare amount hint only if there is no amount
1153 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1154 TextUtils.equals(amountHint, other.amountHint)
1155 : !other.amountHintIsSet);
1156 equal = equal && TextUtils.equals(currency, other.currency) && isLast == other.isLast;
1158 Logger.debug("new-trans",
1159 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1163 public int getAccountNameCursorPosition() {
1164 return accountNameCursorPosition;
1166 public void setAccountNameCursorPosition(int position) {
1167 this.accountNameCursorPosition = position;
1171 private static class BalanceForCurrency {
1172 private final HashMap<String, Float> hashMap = new HashMap<>();
1173 float get(String currencyName) {
1174 Float f = hashMap.get(currencyName);
1177 hashMap.put(currencyName, f);
1181 void add(String currencyName, float amount) {
1182 hashMap.put(currencyName, get(currencyName) + amount);
1184 Set<String> currencies() {
1185 return hashMap.keySet();
1187 boolean containsCurrency(String currencyName) {
1188 return hashMap.containsKey(currencyName);
1192 private static class ItemsForCurrency {
1193 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1195 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1196 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1198 list = new ArrayList<>();
1199 hashMap.put(currencyName, list);
1203 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1204 getList(currencyName).add(item);
1206 int size(@Nullable String currencyName) {
1207 return this.getList(currencyName)
1210 Set<String> currencies() {
1211 return hashMap.keySet();