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.Currency;
33 import net.ktnx.mobileledger.db.DB;
34 import net.ktnx.mobileledger.db.Profile;
35 import net.ktnx.mobileledger.db.TemplateAccount;
36 import net.ktnx.mobileledger.db.TemplateHeader;
37 import net.ktnx.mobileledger.db.TransactionWithAccounts;
38 import net.ktnx.mobileledger.model.Data;
39 import net.ktnx.mobileledger.model.InertMutableLiveData;
40 import net.ktnx.mobileledger.model.LedgerTransaction;
41 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
42 import net.ktnx.mobileledger.model.MatchedTemplate;
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<Profile> 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 replaceItems(@NonNull List<Item> newList) {
101 * make old items replaceable in-place. makes the new values visually blend in
103 private void renumberItems() {
104 final List<Item> list = items.getValue();
110 for (Item item : list)
113 private void setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
114 final int cnt = list.size();
115 for (int i = 1; i < cnt - 1; i++) {
116 final TransactionAccount item = list.get(i)
117 .toTransactionAccount();
119 TransactionAccount replacement = new TransactionAccount(item);
120 replacement.isLast = false;
121 list.set(i, replacement);
124 final TransactionAccount last = list.get(cnt - 1)
125 .toTransactionAccount();
127 TransactionAccount replacement = new TransactionAccount(last);
128 replacement.isLast = true;
129 list.set(cnt - 1, replacement);
132 if (BuildConfig.DEBUG)
133 dumpItemList("Before setValue()", list);
134 items.setValue(list);
136 private List<Item> copyList() {
137 List<Item> copy = new ArrayList<>();
138 List<Item> oldList = items.getValue();
141 for (Item item : oldList) {
142 copy.add(Item.from(item));
147 private List<Item> copyListWithoutItem(int position) {
148 List<Item> copy = new ArrayList<>();
149 List<Item> oldList = items.getValue();
151 if (oldList != null) {
153 for (Item item : oldList) {
156 copy.add(Item.from(item));
162 private List<Item> shallowCopyList() {
163 return new ArrayList<>(items.getValue());
165 LiveData<Boolean> getShowComments() {
168 void observeDataProfile(LifecycleOwner activity) {
169 if (!observingDataProfile)
170 Data.observeProfile(activity, profileObserver);
171 observingDataProfile = true;
173 boolean getSimulateSaveFlag() {
174 Boolean value = simulateSave.getValue();
179 LiveData<Boolean> getSimulateSave() {
182 void toggleSimulateSave() {
183 simulateSave.setValue(!getSimulateSaveFlag());
185 LiveData<Boolean> isSubmittable() {
186 return this.isSubmittable;
189 Logger.debug("new-trans", "Resetting model");
190 List<Item> list = new ArrayList<>();
191 Item.resetIdDispenser();
192 list.add(new TransactionHead(""));
193 list.add(new TransactionAccount(""));
194 list.add(new TransactionAccount(""));
195 noteFocusChanged(0, FocusedElement.Description);
197 isSubmittable.setValue(false);
198 setItemsWithoutSubmittableChecks(list);
200 boolean accountsInInitialState() {
201 final List<Item> list = items.getValue();
206 for (Item item : list) {
207 if (!(item instanceof TransactionAccount))
210 TransactionAccount accRow = (TransactionAccount) item;
211 if (!accRow.isEmpty())
217 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
218 SimpleDate transactionDate = null;
219 final MatchResult matchResult = matchedTemplate.matchResult;
220 final TemplateHeader templateHead = matchedTemplate.templateHead;
222 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
223 templateHead.getDateDay());
224 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
225 templateHead.getDateMonth());
226 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
227 templateHead.getDateYear());
229 if (year > 0 || month > 0 || day > 0) {
230 SimpleDate today = SimpleDate.today();
238 transactionDate = new SimpleDate(year, month, day);
240 Logger.debug("pattern", "setting transaction date to " + transactionDate);
244 List<Item> present = copyList();
246 TransactionHead head = new TransactionHead(present.get(0)
247 .toTransactionHead());
248 if (transactionDate != null)
249 head.setDate(transactionDate);
251 final String transactionDescription = extractStringFromMatches(matchResult,
252 templateHead.getTransactionDescriptionMatchGroup(),
253 templateHead.getTransactionDescription());
254 if (Misc.emptyIsNull(transactionDescription) != null)
255 head.setDescription(transactionDescription);
257 final String transactionComment = extractStringFromMatches(matchResult,
258 templateHead.getTransactionCommentMatchGroup(),
259 templateHead.getTransactionComment());
260 if (Misc.emptyIsNull(transactionComment) != null)
261 head.setComment(transactionComment);
263 Item.resetIdDispenser();
264 List<Item> newItems = new ArrayList<>();
268 for (int i = 1; i < present.size(); i++) {
269 final TransactionAccount row = present.get(i)
270 .toTransactionAccount();
272 newItems.add(new TransactionAccount(row));
277 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
279 final boolean accountsInInitialState = accountsInInitialState();
280 for (TemplateAccount acc : entry.accounts) {
284 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
285 acc.getAccountName());
286 String accountComment =
287 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
288 acc.getAccountComment());
289 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
291 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
294 TransactionAccount accRow = new TransactionAccount(accountName);
295 accRow.setComment(accountComment);
297 accRow.setAmount(amount);
299 extractCurrencyFromMatches(matchResult, acc.getCurrencyMatchGroup(),
300 acc.getCurrencyObject()));
302 newItems.add(accRow);
305 Misc.onMainThread(() -> replaceItems(newItems));
308 private String extractCurrencyFromMatches(MatchResult m, Integer group, Currency literal) {
309 return extractStringFromMatches(m, group, (literal == null) ? "" : literal.getName());
311 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
317 if (grp > 0 && grp <= m.groupCount())
319 return Integer.parseInt(m.group(grp));
321 catch (NumberFormatException e) {
322 Logger.debug("new-trans", "Error extracting matched number", e);
328 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
334 if (grp > 0 && grp <= m.groupCount())
340 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
346 if (grp > 0 && grp <= m.groupCount())
348 return Float.valueOf(m.group(grp));
350 catch (NumberFormatException e) {
351 Logger.debug("new-trans", "Error extracting matched number", e);
357 void removeItem(int pos) {
358 Logger.debug("new-trans", String.format(Locale.US, "Removing item at position %d", pos));
359 List<Item> newList = copyListWithoutItem(pos);
360 final FocusInfo fi = focusInfo.getValue();
361 if ((fi != null) && (pos < fi.position))
362 noteFocusChanged(fi.position - 1, fi.element);
365 void noteFocusChanged(int position, FocusedElement element) {
366 FocusInfo present = focusInfo.getValue();
367 if (present == null || present.position != position || present.element != element)
368 focusInfo.setValue(new FocusInfo(position, element));
370 public LiveData<FocusInfo> getFocusInfo() {
373 void moveItem(int fromIndex, int toIndex) {
374 List<Item> newList = shallowCopyList();
375 Item item = newList.remove(fromIndex);
376 newList.add(toIndex, item);
378 FocusInfo fi = focusInfo.getValue();
379 if (fi != null && fi.position == fromIndex)
380 noteFocusChanged(toIndex, fi.element);
382 items.setValue(newList); // same count, same submittable state
384 void moveItemLast(List<Item> list, int index) {
388 3 <-- desired position
391 int itemCount = list.size();
393 if (index < itemCount - 1)
394 list.add(list.remove(index));
396 void toggleCurrencyVisible() {
397 final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
399 // remove currency from all items, or reset currency to the default
400 // no need to clone the list, because the removal of the currency won't lead to
401 // visual changes -- the currency fields will be hidden or reset to default anyway
402 // still, there may be changes in the submittable state
403 final List<Item> list = Objects.requireNonNull(this.items.getValue());
404 for (int i = 1; i < list.size(); i++) {
405 ((TransactionAccount) list.get(i)).setCurrency(newValue ? Data.getProfile()
406 .getDefaultCommodity()
409 checkTransactionSubmittable(null);
410 showCurrency.setValue(newValue);
412 void stopObservingBusyFlag(Observer<Boolean> observer) {
413 busyFlag.removeObserver(observer);
415 void incrementBusyCounter() {
416 int newValue = busyCounter.incrementAndGet();
418 busyFlag.postValue(true);
420 void decrementBusyCounter() {
421 int newValue = busyCounter.decrementAndGet();
423 busyFlag.postValue(false);
425 public LiveData<Boolean> getBusyFlag() {
428 public void toggleShowComments() {
429 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
431 public LedgerTransaction constructLedgerTransaction() {
432 List<Item> list = Objects.requireNonNull(items.getValue());
433 TransactionHead head = list.get(0)
434 .toTransactionHead();
435 LedgerTransaction tr = head.asLedgerTransaction();
437 tr.setComment(head.getComment());
438 LedgerTransactionAccount emptyAmountAccount = null;
439 float emptyAmountAccountBalance = 0;
440 for (int i = 1; i < list.size(); i++) {
441 TransactionAccount item = list.get(i)
442 .toTransactionAccount();
443 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
446 if (acc.getAccountName()
450 acc.setComment(item.getComment());
452 if (item.isAmountSet()) {
453 acc.setAmount(item.getAmount());
454 emptyAmountAccountBalance += item.getAmount();
457 emptyAmountAccount = acc;
463 if (emptyAmountAccount != null)
464 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
468 void loadTransactionIntoModel(@NonNull TransactionWithAccounts tr) {
469 List<Item> newList = new ArrayList<>();
470 Item.resetIdDispenser();
472 Item currentHead = items.getValue()
474 TransactionHead head = new TransactionHead(tr.transaction.getDescription());
475 head.setComment(tr.transaction.getComment());
476 if (currentHead instanceof TransactionHead)
477 head.setDate(((TransactionHead) currentHead).date);
481 List<LedgerTransactionAccount> accounts = new ArrayList<>();
482 for (net.ktnx.mobileledger.db.TransactionAccount acc : tr.accounts) {
483 accounts.add(new LedgerTransactionAccount(acc));
486 TransactionAccount firstNegative = null;
487 TransactionAccount firstPositive = null;
488 int singleNegativeIndex = -1;
489 int singlePositiveIndex = -1;
490 int negativeCount = 0;
491 for (int i = 0; i < accounts.size(); i++) {
492 LedgerTransactionAccount acc = accounts.get(i);
493 TransactionAccount item =
494 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
497 item.setAccountName(acc.getAccountName());
498 item.setComment(acc.getComment());
499 if (acc.isAmountSet()) {
500 item.setAmount(acc.getAmount());
501 if (acc.getAmount() < 0) {
502 if (firstNegative == null) {
503 firstNegative = item;
504 singleNegativeIndex = i + 1;
507 singleNegativeIndex = -1;
510 if (firstPositive == null) {
511 firstPositive = item;
512 singlePositiveIndex = i + 1;
515 singlePositiveIndex = -1;
521 if (BuildConfig.DEBUG)
522 dumpItemList("Loaded previous transaction", newList);
524 if (singleNegativeIndex != -1) {
525 firstNegative.resetAmount();
526 moveItemLast(newList, singleNegativeIndex);
528 else if (singlePositiveIndex != -1) {
529 firstPositive.resetAmount();
530 moveItemLast(newList, singlePositiveIndex);
533 Misc.onMainThread(() -> {
535 noteFocusChanged(1, FocusedElement.Amount);
539 * A transaction is submittable if:
541 * 1) has at least two account names
542 * 2) each row with amount has account name
543 * 3) for each commodity:
544 * 3a) amounts must balance to 0, or
545 * 3b) there must be exactly one empty amount (with account)
546 * 4) empty accounts with empty amounts are ignored
548 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
550 * 6) at least two rows need to be present in the ledger
552 * @param list - the item list to check. Can be the displayed list or a list that will be
555 @SuppressLint("DefaultLocale")
556 void checkTransactionSubmittable(@Nullable List<Item> list) {
557 boolean workingWithLiveList = false;
560 workingWithLiveList = true;
563 if (BuildConfig.DEBUG)
564 dumpItemList(String.format("Before submittable checks (%s)",
565 workingWithLiveList ? "LIVE LIST" : "custom list"), list);
568 final BalanceForCurrency balance = new BalanceForCurrency();
569 final String descriptionText = list.get(0)
572 boolean submittable = true;
573 boolean listChanged = false;
574 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
575 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
576 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
577 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
578 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
579 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
580 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
581 final List<Item> emptyRows = new ArrayList<>();
584 if ((descriptionText == null) || descriptionText.trim()
587 Logger.debug("submittable", "Transaction not submittable: missing description");
591 for (int i = 1; i < list.size(); i++) {
592 TransactionAccount item = list.get(i)
593 .toTransactionAccount();
595 String accName = item.getAccountName()
597 String currName = item.getCurrency();
599 itemsForCurrency.add(currName, item);
601 if (accName.isEmpty()) {
602 itemsWithEmptyAccountForCurrency.add(currName, item);
604 if (item.isAmountSet()) {
605 // 2) each amount has account name
606 Logger.debug("submittable", String.format(
607 "Transaction not submittable: row %d has no account name, but" +
608 " has" + " amount %1.2f", i + 1, item.getAmount()));
612 emptyRowsForCurrency.add(currName, item);
617 itemsWithAccountForCurrency.add(currName, item);
620 if (!item.isAmountValid()) {
621 Logger.debug("submittable",
622 String.format("Not submittable: row %d has an invalid amount", i + 1));
625 else if (item.isAmountSet()) {
626 itemsWithAmountForCurrency.add(currName, item);
627 balance.add(currName, item.getAmount());
630 itemsWithEmptyAmountForCurrency.add(currName, item);
632 if (!accName.isEmpty())
633 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
637 // 1) has at least two account names
640 Logger.debug("submittable", "Transaction not submittable: no account names");
641 else if (accounts == 1)
642 Logger.debug("submittable",
643 "Transaction not submittable: only one account name");
645 Logger.debug("submittable",
646 String.format("Transaction not submittable: only %d account names",
651 // 3) for each commodity:
652 // 3a) amount must balance to 0, or
653 // 3b) there must be exactly one empty amount (with account)
654 for (String balCurrency : itemsForCurrency.currencies()) {
655 float currencyBalance = balance.get(balCurrency);
656 if (Misc.isZero(currencyBalance)) {
657 // remove hints from all amount inputs in that currency
658 for (int i = 1; i < list.size(); i++) {
659 TransactionAccount acc = list.get(i)
660 .toTransactionAccount();
661 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
662 if (BuildConfig.DEBUG)
663 Logger.debug("submittable",
664 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
665 i, Misc.nullIsEmpty(acc.getAccountName()),
667 // skip if the amount is set, in which case the hint is not
669 if (!acc.isAmountSet() && acc.amountHintIsSet &&
670 !TextUtils.isEmpty(acc.getAmountHint()))
672 acc.setAmountHint(null);
680 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
681 int balanceReceiversCount = tmpList.size();
682 if (balanceReceiversCount != 1) {
683 if (BuildConfig.DEBUG) {
684 if (balanceReceiversCount == 0)
685 Logger.debug("submittable", String.format(
686 "Transaction not submittable [%s]: non-zero balance " +
687 "with no empty amounts with accounts", balCurrency));
689 Logger.debug("submittable", String.format(
690 "Transaction not submittable [%s]: non-zero balance " +
691 "with multiple empty amounts with accounts", balCurrency));
696 List<Item> emptyAmountList =
697 itemsWithEmptyAmountForCurrency.getList(balCurrency);
699 // suggest off-balance amount to a row and remove hints on other rows
700 Item receiver = null;
701 if (!tmpList.isEmpty())
702 receiver = tmpList.get(0);
703 else if (!emptyAmountList.isEmpty())
704 receiver = emptyAmountList.get(0);
706 for (int i = 0; i < list.size(); i++) {
707 Item item = list.get(i);
708 if (!(item instanceof TransactionAccount))
711 TransactionAccount acc = item.toTransactionAccount();
712 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
715 if (item == receiver) {
716 final String hint = String.format("%1.2f", -currencyBalance);
717 if (!acc.isAmountHintSet() ||
718 !Misc.equalStrings(acc.getAmountHint(), hint))
720 Logger.debug("submittable",
721 String.format("Setting amount hint of {%s} to %s [%s]",
722 acc.toString(), hint, balCurrency));
723 acc.setAmountHint(hint);
728 if (BuildConfig.DEBUG)
729 Logger.debug("submittable",
730 String.format("Resetting hint of '%s' [%s]",
731 Misc.nullIsEmpty(acc.getAccountName()),
733 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
734 acc.setAmountHint(null);
742 // 5) a row with an empty account name or empty amount is guaranteed to exist for
744 for (String balCurrency : balance.currencies()) {
745 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
746 int currRows = itemsForCurrency.size(balCurrency);
747 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
748 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
749 if ((currEmptyRows == 0) &&
750 ((currRows == currAccounts) || (currRows == currAmounts)))
752 // perhaps there already is an unused empty row for another currency that
754 // boolean foundIt = false;
755 // for (Item item : emptyRows) {
756 // Currency itemCurrency = item.getCurrency();
757 // String itemCurrencyName =
758 // (itemCurrency == null) ? "" : itemCurrency.getName();
759 // if (Misc.isZero(balance.get(itemCurrencyName))) {
760 // item.setCurrency(Currency.loadByName(balCurrency));
761 // item.setAmountHint(
762 // String.format("%1.2f", -balance.get(balCurrency)));
769 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
770 final float bal = balance.get(balCurrency);
771 if (!Misc.isZero(bal) && currAmounts == currRows)
772 newAcc.setAmountHint(String.format("%4.2f", -bal));
773 Logger.debug("submittable",
774 String.format("Adding new item with %s for currency %s",
775 newAcc.getAmountHint(), balCurrency));
781 // drop extra empty rows, not needed
782 for (String currName : emptyRowsForCurrency.currencies()) {
783 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
784 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
785 // the list is a copy, so the empty item is no longer present
786 Item itemToRemove = emptyItems.remove(1);
787 removeItemById(list, itemToRemove.id);
791 // unused currency, remove last item (which is also an empty one)
792 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
793 List<Item> currItems = itemsForCurrency.getList(currName);
795 if (currItems.size() == 1) {
796 // the list is a copy, so the empty item is no longer present
797 removeItemById(list, emptyItems.get(0).id);
803 // 6) at least two rows need to be present in the ledger
804 // (the list also contains header and trailer)
805 while (list.size() < MIN_ITEMS) {
806 list.add(new TransactionAccount(""));
810 Logger.debug("submittable", submittable ? "YES" : "NO");
811 isSubmittable.setValue(submittable);
813 if (BuildConfig.DEBUG)
814 dumpItemList("After submittable checks", list);
816 catch (NumberFormatException e) {
817 Logger.debug("submittable", "NO (because of NumberFormatException)");
818 isSubmittable.setValue(false);
820 catch (Exception e) {
822 Logger.debug("submittable", "NO (because of an Exception)");
823 isSubmittable.setValue(false);
826 if (listChanged && workingWithLiveList) {
827 setItemsWithoutSubmittableChecks(list);
830 private void removeItemById(@NotNull List<Item> list, int id) {
831 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
832 list.removeIf(item -> item.id == id);
835 for (Item item : list) {
843 @SuppressLint("DefaultLocale")
844 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
845 Logger.debug("submittable", "== Dump of all items " + msg);
846 for (int i = 1; i < list.size(); i++) {
847 TransactionAccount item = list.get(i)
848 .toTransactionAccount();
849 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
852 public void setItemCurrency(int position, String newCurrency) {
853 TransactionAccount item = Objects.requireNonNull(items.getValue())
855 .toTransactionAccount();
856 final String oldCurrency = item.getCurrency();
858 if (Misc.equalStrings(oldCurrency, newCurrency))
861 List<Item> newList = copyList();
862 newList.get(position)
863 .toTransactionAccount()
864 .setCurrency(newCurrency);
868 public boolean accountListIsEmpty() {
869 List<Item> items = Objects.requireNonNull(this.items.getValue());
871 for (Item item : items) {
872 if (!(item instanceof TransactionAccount))
875 if (!((TransactionAccount) item).isEmpty())
882 public static class FocusInfo {
884 FocusedElement element;
885 public FocusInfo(int position, FocusedElement element) {
886 this.position = position;
887 this.element = element;
891 static abstract class Item {
892 private static int idDispenser = 0;
895 if (this instanceof TransactionHead)
898 synchronized (Item.class) {
902 public Item(int id) {
905 public static Item from(Item origin) {
906 if (origin instanceof TransactionHead)
907 return new TransactionHead((TransactionHead) origin);
908 if (origin instanceof TransactionAccount)
909 return new TransactionAccount((TransactionAccount) origin);
910 throw new RuntimeException("Don't know how to handle " + origin);
912 private static void resetIdDispenser() {
918 public abstract ItemType getType();
919 public TransactionHead toTransactionHead() {
920 if (this instanceof TransactionHead)
921 return (TransactionHead) this;
923 throw new IllegalStateException("Wrong item type " + this);
925 public TransactionAccount toTransactionAccount() {
926 if (this instanceof TransactionAccount)
927 return (TransactionAccount) this;
929 throw new IllegalStateException("Wrong item type " + this);
931 public boolean equalContents(@Nullable Object item) {
935 if (!getClass().equals(item.getClass()))
938 // shortcut - comparing same instance
942 if (this instanceof TransactionHead)
943 return ((TransactionHead) item).equalContents((TransactionHead) this);
944 if (this instanceof TransactionAccount)
945 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
947 throw new RuntimeException("Don't know how to handle " + this);
952 //==========================================================================================
954 public static class TransactionHead extends Item {
955 private SimpleDate date;
956 private String description;
957 private String comment;
958 TransactionHead(String description) {
960 this.description = description;
962 public TransactionHead(TransactionHead origin) {
965 description = origin.description;
966 comment = origin.comment;
968 public SimpleDate getDate() {
971 public void setDate(SimpleDate date) {
974 public void setDate(String text) throws ParseException {
975 if (Misc.emptyIsNull(text) == null) {
980 date = Globals.parseLedgerDate(text);
985 * @return nicely formatted, shortest available date representation
987 String getFormattedDate() {
991 Calendar today = GregorianCalendar.getInstance();
993 if (today.get(Calendar.YEAR) != date.year) {
994 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
997 if (today.get(Calendar.MONTH) + 1 != date.month) {
998 return String.format(Locale.US, "%d/%02d", date.month, date.day);
1001 return String.valueOf(date.day);
1005 public String toString() {
1006 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
1007 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1009 if (TextUtils.isEmpty(description))
1010 b.append(" «no description»");
1012 b.append(String.format(" '%s'", description));
1015 b.append(String.format("@%s", date.toString()));
1017 if (!TextUtils.isEmpty(comment))
1018 b.append(String.format(" /%s/", comment));
1020 return b.toString();
1022 public String getDescription() {
1025 public void setDescription(String description) {
1026 this.description = description;
1028 public String getComment() {
1031 public void setComment(String comment) {
1032 this.comment = comment;
1035 public ItemType getType() {
1036 return ItemType.generalData;
1038 public LedgerTransaction asLedgerTransaction() {
1039 return new LedgerTransaction(0, (date == null) ? SimpleDate.today() : date, description,
1042 public boolean equalContents(TransactionHead other) {
1046 return Objects.equals(date, other.date) &&
1047 Misc.equalStrings(description, other.description) &&
1048 Misc.equalStrings(comment, other.comment);
1052 public static class TransactionAccount extends Item {
1053 private String accountName;
1054 private String amountHint;
1055 private String comment;
1056 private String currency;
1057 private float amount;
1058 private boolean amountSet;
1059 private boolean amountValid = true;
1060 private FocusedElement focusedElement = FocusedElement.Account;
1061 private boolean amountHintIsSet = false;
1062 private boolean isLast = false;
1063 private int accountNameCursorPosition;
1064 public TransactionAccount(TransactionAccount origin) {
1066 accountName = origin.accountName;
1067 amount = origin.amount;
1068 amountSet = origin.amountSet;
1069 amountHint = origin.amountHint;
1070 amountHintIsSet = origin.amountHintIsSet;
1071 comment = origin.comment;
1072 currency = origin.currency;
1073 amountValid = origin.amountValid;
1074 focusedElement = origin.focusedElement;
1075 isLast = origin.isLast;
1076 accountNameCursorPosition = origin.accountNameCursorPosition;
1078 public TransactionAccount(LedgerTransactionAccount account) {
1080 currency = account.getCurrency();
1081 amount = account.getAmount();
1083 public TransactionAccount(String accountName) {
1085 this.accountName = accountName;
1087 public TransactionAccount(String accountName, String currency) {
1089 this.accountName = accountName;
1090 this.currency = currency;
1092 public boolean isLast() {
1095 public boolean isAmountSet() {
1098 public String getAccountName() {
1101 public void setAccountName(String accountName) {
1102 this.accountName = accountName;
1104 public float getAmount() {
1106 throw new IllegalStateException("Amount is not set");
1109 public void setAmount(float amount) {
1110 this.amount = amount;
1113 public void resetAmount() {
1117 public ItemType getType() {
1118 return ItemType.transactionRow;
1120 public String getAmountHint() {
1123 public void setAmountHint(String amountHint) {
1124 this.amountHint = amountHint;
1125 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1127 public String getComment() {
1130 public void setComment(String comment) {
1131 this.comment = comment;
1133 public String getCurrency() {
1136 public void setCurrency(String currency) {
1137 this.currency = currency;
1139 public boolean isAmountValid() {
1142 public void setAmountValid(boolean amountValid) {
1143 this.amountValid = amountValid;
1145 public FocusedElement getFocusedElement() {
1146 return focusedElement;
1148 public void setFocusedElement(FocusedElement focusedElement) {
1149 this.focusedElement = focusedElement;
1151 public boolean isAmountHintSet() {
1152 return amountHintIsSet;
1154 public void setAmountHintIsSet(boolean amountHintIsSet) {
1155 this.amountHintIsSet = amountHintIsSet;
1157 public boolean isEmpty() {
1158 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1159 Misc.emptyIsNull(comment) == null;
1161 @SuppressLint("DefaultLocale")
1163 public String toString() {
1164 StringBuilder b = new StringBuilder();
1165 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1166 if (!TextUtils.isEmpty(accountName))
1167 b.append(String.format(" acc'%s'", accountName));
1170 b.append(String.format(" %4.2f", amount));
1171 else if (amountHintIsSet)
1172 b.append(String.format(" (%s)", amountHint));
1174 if (!TextUtils.isEmpty(currency))
1178 if (!TextUtils.isEmpty(comment))
1179 b.append(String.format(" /%s/", comment));
1184 return b.toString();
1186 public boolean equalContents(TransactionAccount other) {
1190 boolean equal = Misc.equalStrings(accountName, other.accountName);
1191 equal = equal && Misc.equalStrings(comment, other.comment) &&
1192 (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1194 // compare amount hint only if there is no amount
1196 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1197 Misc.equalStrings(amountHint, other.amountHint)
1198 : !other.amountHintIsSet);
1199 equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1201 Logger.debug("new-trans",
1202 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1206 public int getAccountNameCursorPosition() {
1207 return accountNameCursorPosition;
1209 public void setAccountNameCursorPosition(int position) {
1210 this.accountNameCursorPosition = position;
1214 private static class BalanceForCurrency {
1215 private final HashMap<String, Float> hashMap = new HashMap<>();
1216 float get(String currencyName) {
1217 Float f = hashMap.get(currencyName);
1220 hashMap.put(currencyName, f);
1224 void add(String currencyName, float amount) {
1225 hashMap.put(currencyName, get(currencyName) + amount);
1227 Set<String> currencies() {
1228 return hashMap.keySet();
1230 boolean containsCurrency(String currencyName) {
1231 return hashMap.containsKey(currencyName);
1235 private static class ItemsForCurrency {
1236 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1238 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1239 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1241 list = new ArrayList<>();
1242 hashMap.put(currencyName, list);
1246 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1247 getList(currencyName).add(item);
1249 int size(@Nullable String currencyName) {
1250 return this.getList(currencyName)
1253 Set<String> currencies() {
1254 return hashMap.keySet();