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);
352 FocusInfo fi = focusInfo.getValue();
353 if (fi != null && fi.position == fromIndex)
354 noteFocusChanged(toIndex, fi.element);
356 items.setValue(newList); // same count, same submittable state
358 void moveItemLast(List<Item> list, int index) {
362 3 <-- desired position
365 int itemCount = list.size();
367 if (index < itemCount - 1)
368 list.add(list.remove(index));
370 void toggleCurrencyVisible() {
371 final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
373 // remove currency from all items, or reset currency to the default
374 // no need to clone the list, because the removal of the currency won't lead to
375 // visual changes -- the currency fields will be hidden or reset to default anyway
376 // still, there may be changes in the submittable state
377 final List<Item> list = Objects.requireNonNull(this.items.getValue());
378 for (int i = 1; i < list.size(); i++) {
379 ((TransactionAccount) list.get(i)).setCurrency(newValue ? Data.getProfile()
380 .getDefaultCommodity()
383 checkTransactionSubmittable(null);
384 showCurrency.setValue(newValue);
386 void stopObservingBusyFlag(Observer<Boolean> observer) {
387 busyFlag.removeObserver(observer);
389 void incrementBusyCounter() {
390 int newValue = busyCounter.incrementAndGet();
392 busyFlag.postValue(true);
394 void decrementBusyCounter() {
395 int newValue = busyCounter.decrementAndGet();
397 busyFlag.postValue(false);
399 public LiveData<Boolean> getBusyFlag() {
402 public void toggleShowComments() {
403 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
405 public LedgerTransaction constructLedgerTransaction() {
406 List<Item> list = Objects.requireNonNull(items.getValue());
407 TransactionHead head = list.get(0)
408 .toTransactionHead();
409 SimpleDate date = head.getDate();
410 LedgerTransaction tr = head.asLedgerTransaction();
412 tr.setComment(head.getComment());
413 LedgerTransactionAccount emptyAmountAccount = null;
414 float emptyAmountAccountBalance = 0;
415 for (int i = 1; i < list.size(); i++) {
416 TransactionAccount item = list.get(i)
417 .toTransactionAccount();
418 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
421 if (acc.getAccountName()
425 acc.setComment(item.getComment());
427 if (item.isAmountSet()) {
428 acc.setAmount(item.getAmount());
429 emptyAmountAccountBalance += item.getAmount();
432 emptyAmountAccount = acc;
438 if (emptyAmountAccount != null)
439 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
443 void loadTransactionIntoModel(String profileUUID, int transactionId) {
444 List<Item> newList = new ArrayList<>();
445 LedgerTransaction tr;
446 MobileLedgerProfile profile = Data.getProfile(profileUUID);
448 throw new RuntimeException(String.format(
449 "Unable to find profile %s, which is supposed to contain transaction %d",
450 profileUUID, transactionId));
452 tr = profile.loadTransaction(transactionId);
453 TransactionHead head = new TransactionHead(tr.getDescription());
454 head.setComment(tr.getComment());
458 List<LedgerTransactionAccount> accounts = tr.getAccounts();
460 TransactionAccount firstNegative = null;
461 TransactionAccount firstPositive = null;
462 int singleNegativeIndex = -1;
463 int singlePositiveIndex = -1;
464 int negativeCount = 0;
465 for (int i = 0; i < accounts.size(); i++) {
466 LedgerTransactionAccount acc = accounts.get(i);
467 TransactionAccount item =
468 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
471 item.setAccountName(acc.getAccountName());
472 item.setComment(acc.getComment());
473 if (acc.isAmountSet()) {
474 item.setAmount(acc.getAmount());
475 if (acc.getAmount() < 0) {
476 if (firstNegative == null) {
477 firstNegative = item;
478 singleNegativeIndex = i + 1;
481 singleNegativeIndex = -1;
484 if (firstPositive == null) {
485 firstPositive = item;
486 singlePositiveIndex = i + 1;
489 singlePositiveIndex = -1;
495 if (BuildConfig.DEBUG)
496 dumpItemList("Loaded previous transaction", newList);
498 if (singleNegativeIndex != -1) {
499 firstNegative.resetAmount();
500 moveItemLast(newList, singleNegativeIndex);
502 else if (singlePositiveIndex != -1) {
503 firstPositive.resetAmount();
504 moveItemLast(newList, singlePositiveIndex);
509 noteFocusChanged(1, FocusedElement.Amount);
512 * A transaction is submittable if:
514 * 1) has at least two account names
515 * 2) each row with amount has account name
516 * 3) for each commodity:
517 * 3a) amounts must balance to 0, or
518 * 3b) there must be exactly one empty amount (with account)
519 * 4) empty accounts with empty amounts are ignored
521 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
523 * 6) at least two rows need to be present in the ledger
525 * @param list - the item list to check. Can be the displayed list or a list that will be
528 @SuppressLint("DefaultLocale")
529 void checkTransactionSubmittable(@Nullable List<Item> list) {
530 boolean workingWithLiveList = false;
533 workingWithLiveList = true;
536 if (BuildConfig.DEBUG)
537 dumpItemList(String.format("Before submittable checks (%s)",
538 workingWithLiveList ? "LIVE LIST" : "custom list"), list);
541 final BalanceForCurrency balance = new BalanceForCurrency();
542 final String descriptionText = list.get(0)
545 boolean submittable = true;
546 boolean listChanged = false;
547 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
548 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
549 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
550 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
551 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
552 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
553 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
554 final List<Item> emptyRows = new ArrayList<>();
557 if ((descriptionText == null) || descriptionText.trim()
560 Logger.debug("submittable", "Transaction not submittable: missing description");
564 for (int i = 1; i < list.size(); i++) {
565 TransactionAccount item = list.get(i)
566 .toTransactionAccount();
568 String accName = item.getAccountName()
570 String currName = item.getCurrency();
572 itemsForCurrency.add(currName, item);
574 if (accName.isEmpty()) {
575 itemsWithEmptyAccountForCurrency.add(currName, item);
577 if (item.isAmountSet()) {
578 // 2) each amount has account name
579 Logger.debug("submittable", String.format(
580 "Transaction not submittable: row %d has no account name, but" +
581 " has" + " amount %1.2f", i + 1, item.getAmount()));
585 emptyRowsForCurrency.add(currName, item);
590 itemsWithAccountForCurrency.add(currName, item);
593 if (!item.isAmountValid()) {
594 Logger.debug("submittable",
595 String.format("Not submittable: row %d has an invalid amount", i + 1));
598 else if (item.isAmountSet()) {
599 itemsWithAmountForCurrency.add(currName, item);
600 balance.add(currName, item.getAmount());
603 itemsWithEmptyAmountForCurrency.add(currName, item);
605 if (!accName.isEmpty())
606 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
610 // 1) has at least two account names
613 Logger.debug("submittable", "Transaction not submittable: no account names");
614 else if (accounts == 1)
615 Logger.debug("submittable",
616 "Transaction not submittable: only one account name");
618 Logger.debug("submittable",
619 String.format("Transaction not submittable: only %d account names",
624 // 3) for each commodity:
625 // 3a) amount must balance to 0, or
626 // 3b) there must be exactly one empty amount (with account)
627 for (String balCurrency : itemsForCurrency.currencies()) {
628 float currencyBalance = balance.get(balCurrency);
629 if (Misc.isZero(currencyBalance)) {
630 // remove hints from all amount inputs in that currency
631 for (int i = 1; i < list.size(); i++) {
632 TransactionAccount acc = list.get(i)
633 .toTransactionAccount();
634 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
635 if (BuildConfig.DEBUG)
636 Logger.debug("submittable",
637 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
638 i, Misc.nullIsEmpty(acc.getAccountName()),
640 // skip if the amount is set, in which case the hint is not
642 if (!acc.isAmountSet() && acc.amountHintIsSet &&
643 !TextUtils.isEmpty(acc.getAmountHint()))
645 acc.setAmountHint(null);
653 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
654 int balanceReceiversCount = tmpList.size();
655 if (balanceReceiversCount != 1) {
656 if (BuildConfig.DEBUG) {
657 if (balanceReceiversCount == 0)
658 Logger.debug("submittable", String.format(
659 "Transaction not submittable [%s]: non-zero balance " +
660 "with no empty amounts with accounts", balCurrency));
662 Logger.debug("submittable", String.format(
663 "Transaction not submittable [%s]: non-zero balance " +
664 "with multiple empty amounts with accounts", balCurrency));
669 List<Item> emptyAmountList =
670 itemsWithEmptyAmountForCurrency.getList(balCurrency);
672 // suggest off-balance amount to a row and remove hints on other rows
673 Item receiver = null;
674 if (!tmpList.isEmpty())
675 receiver = tmpList.get(0);
676 else if (!emptyAmountList.isEmpty())
677 receiver = emptyAmountList.get(0);
679 for (int i = 0; i < list.size(); i++) {
680 Item item = list.get(i);
681 if (!(item instanceof TransactionAccount))
684 TransactionAccount acc = item.toTransactionAccount();
685 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
688 if (item == receiver) {
689 final String hint = String.format("%1.2f", -currencyBalance);
690 if (!acc.isAmountHintSet() ||
691 !TextUtils.equals(acc.getAmountHint(), hint))
693 Logger.debug("submittable",
694 String.format("Setting amount hint of {%s} to %s [%s]",
695 acc.toString(), hint, balCurrency));
696 acc.setAmountHint(hint);
701 if (BuildConfig.DEBUG)
702 Logger.debug("submittable",
703 String.format("Resetting hint of '%s' [%s]",
704 Misc.nullIsEmpty(acc.getAccountName()),
706 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
707 acc.setAmountHint(null);
715 // 5) a row with an empty account name or empty amount is guaranteed to exist for
717 for (String balCurrency : balance.currencies()) {
718 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
719 int currRows = itemsForCurrency.size(balCurrency);
720 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
721 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
722 if ((currEmptyRows == 0) &&
723 ((currRows == currAccounts) || (currRows == currAmounts)))
725 // perhaps there already is an unused empty row for another currency that
727 // boolean foundIt = false;
728 // for (Item item : emptyRows) {
729 // Currency itemCurrency = item.getCurrency();
730 // String itemCurrencyName =
731 // (itemCurrency == null) ? "" : itemCurrency.getName();
732 // if (Misc.isZero(balance.get(itemCurrencyName))) {
733 // item.setCurrency(Currency.loadByName(balCurrency));
734 // item.setAmountHint(
735 // String.format("%1.2f", -balance.get(balCurrency)));
742 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
743 final float bal = balance.get(balCurrency);
744 if (!Misc.isZero(bal) && currAmounts == currRows)
745 newAcc.setAmountHint(String.format("%4.2f", -bal));
746 Logger.debug("submittable",
747 String.format("Adding new item with %s for currency %s",
748 newAcc.getAmountHint(), balCurrency));
754 // drop extra empty rows, not needed
755 for (String currName : emptyRowsForCurrency.currencies()) {
756 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
757 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
758 // the list is a copy, so the empty item is no longer present
759 Item itemToRemove = emptyItems.remove(1);
760 removeItemById(list, itemToRemove.id);
764 // unused currency, remove last item (which is also an empty one)
765 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
766 List<Item> currItems = itemsForCurrency.getList(currName);
768 if (currItems.size() == 1) {
769 // the list is a copy, so the empty item is no longer present
770 removeItemById(list, emptyItems.get(0).id);
776 // 6) at least two rows need to be present in the ledger
777 // (the list also contains header and trailer)
778 while (list.size() < MIN_ITEMS) {
779 list.add(new TransactionAccount(""));
783 Logger.debug("submittable", submittable ? "YES" : "NO");
784 isSubmittable.setValue(submittable);
786 if (BuildConfig.DEBUG)
787 dumpItemList("After submittable checks", list);
789 catch (NumberFormatException e) {
790 Logger.debug("submittable", "NO (because of NumberFormatException)");
791 isSubmittable.setValue(false);
793 catch (Exception e) {
795 Logger.debug("submittable", "NO (because of an Exception)");
796 isSubmittable.setValue(false);
799 if (listChanged && workingWithLiveList) {
800 setItemsWithoutSubmittableChecks(list);
803 private void removeItemById(@NotNull List<Item> list, int id) {
804 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
805 list.removeIf(item -> item.id == id);
808 for (Item item : list) {
816 @SuppressLint("DefaultLocale")
817 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
818 Logger.debug("submittable", "== Dump of all items " + msg);
819 for (int i = 1; i < list.size(); i++) {
820 TransactionAccount item = list.get(i)
821 .toTransactionAccount();
822 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
825 public void setItemCurrency(int position, String newCurrency) {
826 TransactionAccount item = Objects.requireNonNull(items.getValue())
828 .toTransactionAccount();
829 final String oldCurrency = item.getCurrency();
831 if (Misc.equalStrings(oldCurrency, newCurrency))
834 List<Item> newList = copyList();
835 newList.get(position)
836 .toTransactionAccount()
837 .setCurrency(newCurrency);
841 public boolean accountListIsEmpty() {
842 List<Item> items = Objects.requireNonNull(this.items.getValue());
844 for (Item item : items) {
845 if (!(item instanceof TransactionAccount))
848 if (!((TransactionAccount) item).isEmpty())
855 public static class FocusInfo {
857 FocusedElement element;
858 public FocusInfo(int position, FocusedElement element) {
859 this.position = position;
860 this.element = element;
864 static abstract class Item {
865 private static int idDispenser = 0;
868 synchronized (Item.class) {
872 public static Item from(Item origin) {
873 if (origin instanceof TransactionHead)
874 return new TransactionHead((TransactionHead) origin);
875 if (origin instanceof TransactionAccount)
876 return new TransactionAccount((TransactionAccount) origin);
877 throw new RuntimeException("Don't know how to handle " + origin);
882 public abstract ItemType getType();
883 public TransactionHead toTransactionHead() {
884 if (this instanceof TransactionHead)
885 return (TransactionHead) this;
887 throw new IllegalStateException("Wrong item type " + this);
889 public TransactionAccount toTransactionAccount() {
890 if (this instanceof TransactionAccount)
891 return (TransactionAccount) this;
893 throw new IllegalStateException("Wrong item type " + this);
895 public boolean equalContents(@Nullable Object item) {
899 if (!getClass().equals(item.getClass()))
902 // shortcut - comparing same instance
906 if (this instanceof TransactionHead)
907 return ((TransactionHead) item).equalContents((TransactionHead) this);
908 if (this instanceof TransactionAccount)
909 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
911 throw new RuntimeException("Don't know how to handle " + this);
916 //==========================================================================================
918 public static class TransactionHead extends Item {
919 private SimpleDate date;
920 private String description;
921 private String comment;
922 TransactionHead(String description) {
924 this.description = description;
926 public TransactionHead(TransactionHead origin) {
929 description = origin.description;
930 comment = origin.comment;
932 public SimpleDate getDate() {
935 public void setDate(SimpleDate date) {
938 public void setDate(String text) throws ParseException {
939 if (Misc.emptyIsNull(text) == null) {
944 date = Globals.parseLedgerDate(text);
949 * @return nicely formatted, shortest available date representation
951 String getFormattedDate() {
955 Calendar today = GregorianCalendar.getInstance();
957 if (today.get(Calendar.YEAR) != date.year) {
958 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
961 if (today.get(Calendar.MONTH) + 1 != date.month) {
962 return String.format(Locale.US, "%d/%02d", date.month, date.day);
965 return String.valueOf(date.day);
969 public String toString() {
970 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
971 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
973 if (TextUtils.isEmpty(description))
974 b.append(" «no description»");
976 b.append(String.format(" '%s'", description));
979 b.append(String.format("@%s", date.toString()));
981 if (!TextUtils.isEmpty(comment))
982 b.append(String.format(" /%s/", comment));
986 public String getDescription() {
989 public void setDescription(String description) {
990 this.description = description;
992 public String getComment() {
995 public void setComment(String comment) {
996 this.comment = comment;
999 public ItemType getType() {
1000 return ItemType.generalData;
1002 public LedgerTransaction asLedgerTransaction() {
1003 return new LedgerTransaction(null, date, description, Data.getProfile());
1005 public boolean equalContents(TransactionHead other) {
1009 return Objects.equals(date, other.date) &&
1010 TextUtils.equals(description, other.description) &&
1011 TextUtils.equals(comment, other.comment);
1015 public static class TransactionAccount extends Item {
1016 private String accountName;
1017 private String amountHint;
1018 private String comment;
1019 private String currency;
1020 private float amount;
1021 private boolean amountSet;
1022 private boolean amountValid = true;
1023 private FocusedElement focusedElement = FocusedElement.Account;
1024 private boolean amountHintIsSet = false;
1025 private boolean isLast = false;
1026 private int accountNameCursorPosition;
1027 public TransactionAccount(TransactionAccount origin) {
1029 accountName = origin.accountName;
1030 amount = origin.amount;
1031 amountSet = origin.amountSet;
1032 amountHint = origin.amountHint;
1033 amountHintIsSet = origin.amountHintIsSet;
1034 comment = origin.comment;
1035 currency = origin.currency;
1036 amountValid = origin.amountValid;
1037 focusedElement = origin.focusedElement;
1038 isLast = origin.isLast;
1039 accountNameCursorPosition = origin.accountNameCursorPosition;
1041 public TransactionAccount(LedgerTransactionAccount account) {
1043 currency = account.getCurrency();
1044 amount = account.getAmount();
1046 public TransactionAccount(String accountName) {
1048 this.accountName = accountName;
1050 public TransactionAccount(String accountName, String currency) {
1052 this.accountName = accountName;
1053 this.currency = currency;
1055 public boolean isLast() {
1058 public boolean isAmountSet() {
1061 public String getAccountName() {
1064 public void setAccountName(String accountName) {
1065 this.accountName = accountName;
1067 public float getAmount() {
1069 throw new IllegalStateException("Amount is not set");
1072 public void setAmount(float amount) {
1073 this.amount = amount;
1076 public void resetAmount() {
1080 public ItemType getType() {
1081 return ItemType.transactionRow;
1083 public String getAmountHint() {
1086 public void setAmountHint(String amountHint) {
1087 this.amountHint = amountHint;
1088 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1090 public String getComment() {
1093 public void setComment(String comment) {
1094 this.comment = comment;
1096 public String getCurrency() {
1099 public void setCurrency(String currency) {
1100 this.currency = currency;
1102 public boolean isAmountValid() {
1105 public void setAmountValid(boolean amountValid) {
1106 this.amountValid = amountValid;
1108 public FocusedElement getFocusedElement() {
1109 return focusedElement;
1111 public void setFocusedElement(FocusedElement focusedElement) {
1112 this.focusedElement = focusedElement;
1114 public boolean isAmountHintSet() {
1115 return amountHintIsSet;
1117 public void setAmountHintIsSet(boolean amountHintIsSet) {
1118 this.amountHintIsSet = amountHintIsSet;
1120 public boolean isEmpty() {
1121 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1122 Misc.emptyIsNull(comment) == null;
1124 @SuppressLint("DefaultLocale")
1126 public String toString() {
1127 StringBuilder b = new StringBuilder();
1128 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1129 if (!TextUtils.isEmpty(accountName))
1130 b.append(String.format(" acc'%s'", accountName));
1133 b.append(String.format(" %4.2f", amount));
1134 else if (amountHintIsSet)
1135 b.append(String.format(" (%s)", amountHint));
1137 if (!TextUtils.isEmpty(currency))
1141 if (!TextUtils.isEmpty(comment))
1142 b.append(String.format(" /%s/", comment));
1147 return b.toString();
1149 public boolean equalContents(TransactionAccount other) {
1153 boolean equal = TextUtils.equals(accountName, other.accountName);
1154 equal = equal && TextUtils.equals(comment, other.comment) &&
1155 (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1157 // compare amount hint only if there is no amount
1159 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1160 TextUtils.equals(amountHint, other.amountHint)
1161 : !other.amountHintIsSet);
1162 equal = equal && TextUtils.equals(currency, other.currency) && isLast == other.isLast;
1164 Logger.debug("new-trans",
1165 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1169 public int getAccountNameCursorPosition() {
1170 return accountNameCursorPosition;
1172 public void setAccountNameCursorPosition(int position) {
1173 this.accountNameCursorPosition = position;
1177 private static class BalanceForCurrency {
1178 private final HashMap<String, Float> hashMap = new HashMap<>();
1179 float get(String currencyName) {
1180 Float f = hashMap.get(currencyName);
1183 hashMap.put(currencyName, f);
1187 void add(String currencyName, float amount) {
1188 hashMap.put(currencyName, get(currencyName) + amount);
1190 Set<String> currencies() {
1191 return hashMap.keySet();
1193 boolean containsCurrency(String currencyName) {
1194 return hashMap.containsKey(currencyName);
1198 private static class ItemsForCurrency {
1199 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1201 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1202 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1204 list = new ArrayList<>();
1205 hashMap.put(currencyName, list);
1209 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1210 getList(currencyName).add(item);
1212 int size(@Nullable String currencyName) {
1213 return this.getList(currencyName)
1216 Set<String> currencies() {
1217 return hashMap.keySet();