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 if (profile != null) {
78 showCurrency.postValue(profile.getShowCommodityByDefault());
79 showComments.postValue(profile.getShowCommentsByDefault());
82 private final MutableLiveData<FocusInfo> focusInfo = new MutableLiveData<>();
83 private boolean observingDataProfile;
84 public NewTransactionModel() {
86 public LiveData<Boolean> getShowCurrency() {
89 public LiveData<List<Item>> getItems() {
92 private void setItems(@NonNull List<Item> newList) {
93 checkTransactionSubmittable(newList);
94 setItemsWithoutSubmittableChecks(newList);
96 private void replaceItems(@NonNull List<Item> newList) {
102 * make old items replaceable in-place. makes the new values visually blend in
104 private void renumberItems() {
105 renumberItems(items.getValue());
107 private void renumberItems(List<Item> list) {
113 for (Item item : list)
116 private void setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
117 final int cnt = list.size();
118 for (int i = 1; i < cnt - 1; i++) {
119 final TransactionAccount item = list.get(i)
120 .toTransactionAccount();
122 TransactionAccount replacement = new TransactionAccount(item);
123 replacement.isLast = false;
124 list.set(i, replacement);
127 final TransactionAccount last = list.get(cnt - 1)
128 .toTransactionAccount();
130 TransactionAccount replacement = new TransactionAccount(last);
131 replacement.isLast = true;
132 list.set(cnt - 1, replacement);
135 if (BuildConfig.DEBUG)
136 dumpItemList("Before setValue()", list);
137 items.setValue(list);
139 private List<Item> copyList() {
140 List<Item> copy = new ArrayList<>();
141 List<Item> oldList = items.getValue();
144 for (Item item : oldList) {
145 copy.add(Item.from(item));
150 private List<Item> copyListWithoutItem(int position) {
151 List<Item> copy = new ArrayList<>();
152 List<Item> oldList = items.getValue();
154 if (oldList != null) {
156 for (Item item : oldList) {
159 copy.add(Item.from(item));
165 private List<Item> shallowCopyList() {
166 return new ArrayList<>(Objects.requireNonNull(items.getValue()));
168 LiveData<Boolean> getShowComments() {
171 void observeDataProfile(LifecycleOwner activity) {
172 if (!observingDataProfile)
173 Data.observeProfile(activity, profileObserver);
174 observingDataProfile = true;
176 boolean getSimulateSaveFlag() {
177 Boolean value = simulateSave.getValue();
182 LiveData<Boolean> getSimulateSave() {
185 void toggleSimulateSave() {
186 simulateSave.setValue(!getSimulateSaveFlag());
188 LiveData<Boolean> isSubmittable() {
189 return this.isSubmittable;
192 Logger.debug("new-trans", "Resetting model");
193 List<Item> list = new ArrayList<>();
194 Item.resetIdDispenser();
195 list.add(new TransactionHead(""));
196 final String defaultCurrency = Objects.requireNonNull(Data.getProfile())
197 .getDefaultCommodity();
198 list.add(new TransactionAccount("", defaultCurrency));
199 list.add(new TransactionAccount("", defaultCurrency));
200 noteFocusChanged(0, FocusedElement.Description);
202 isSubmittable.setValue(false);
203 setItemsWithoutSubmittableChecks(list);
205 boolean accountsInInitialState() {
206 final List<Item> list = items.getValue();
211 for (Item item : list) {
212 if (!(item instanceof TransactionAccount))
215 TransactionAccount accRow = (TransactionAccount) item;
216 if (!accRow.isEmpty())
222 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
223 SimpleDate transactionDate = null;
224 final MatchResult matchResult = matchedTemplate.matchResult;
225 final TemplateHeader templateHead = matchedTemplate.templateHead;
227 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
228 templateHead.getDateDay());
229 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
230 templateHead.getDateMonth());
231 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
232 templateHead.getDateYear());
234 if (year > 0 || month > 0 || day > 0) {
235 SimpleDate today = SimpleDate.today();
243 transactionDate = new SimpleDate(year, month, day);
245 Logger.debug("pattern", "setting transaction date to " + transactionDate);
249 List<Item> present = copyList();
251 TransactionHead head = new TransactionHead(present.get(0)
252 .toTransactionHead());
253 if (transactionDate != null)
254 head.setDate(transactionDate);
256 final String transactionDescription = extractStringFromMatches(matchResult,
257 templateHead.getTransactionDescriptionMatchGroup(),
258 templateHead.getTransactionDescription());
259 if (Misc.emptyIsNull(transactionDescription) != null)
260 head.setDescription(transactionDescription);
262 final String transactionComment = extractStringFromMatches(matchResult,
263 templateHead.getTransactionCommentMatchGroup(),
264 templateHead.getTransactionComment());
265 if (Misc.emptyIsNull(transactionComment) != null)
266 head.setComment(transactionComment);
268 List<Item> newItems = new ArrayList<>();
272 for (int i = 1; i < present.size(); i++) {
273 final TransactionAccount row = present.get(i)
274 .toTransactionAccount();
276 newItems.add(new TransactionAccount(row));
281 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
283 final boolean accountsInInitialState = accountsInInitialState();
284 for (TemplateAccount acc : entry.accounts) {
288 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
289 acc.getAccountName());
290 String accountComment =
291 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
292 acc.getAccountComment());
293 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
295 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
298 TransactionAccount accRow = new TransactionAccount(accountName);
299 accRow.setComment(accountComment);
301 accRow.setAmount(amount);
303 extractCurrencyFromMatches(matchResult, acc.getCurrencyMatchGroup(),
304 acc.getCurrencyObject()));
306 newItems.add(accRow);
309 renumberItems(newItems);
310 Misc.onMainThread(() -> replaceItems(newItems));
314 private String extractCurrencyFromMatches(MatchResult m, Integer group, Currency literal) {
315 return Misc.nullIsEmpty(
316 extractStringFromMatches(m, group, (literal == null) ? "" : literal.getName()));
318 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
324 if (grp > 0 && grp <= m.groupCount())
326 return Integer.parseInt(m.group(grp));
328 catch (NumberFormatException e) {
329 Logger.debug("new-trans", "Error extracting matched number", e);
336 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
342 if (grp > 0 && grp <= m.groupCount())
348 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
354 if (grp > 0 && grp <= m.groupCount())
356 return Float.valueOf(m.group(grp));
358 catch (NumberFormatException e) {
359 Logger.debug("new-trans", "Error extracting matched number", e);
365 void removeItem(int pos) {
366 Logger.debug("new-trans", String.format(Locale.US, "Removing item at position %d", pos));
367 List<Item> newList = copyListWithoutItem(pos);
368 final FocusInfo fi = focusInfo.getValue();
369 if ((fi != null) && (pos < fi.position))
370 noteFocusChanged(fi.position - 1, fi.element);
373 void noteFocusChanged(int position, @Nullable FocusedElement element) {
374 FocusInfo present = focusInfo.getValue();
375 if (present == null || present.position != position || present.element != element)
376 focusInfo.setValue(new FocusInfo(position, element));
378 public LiveData<FocusInfo> getFocusInfo() {
381 void moveItem(int fromIndex, int toIndex) {
382 List<Item> newList = shallowCopyList();
383 Item item = newList.remove(fromIndex);
384 newList.add(toIndex, item);
386 FocusInfo fi = focusInfo.getValue();
387 if (fi != null && fi.position == fromIndex)
388 noteFocusChanged(toIndex, fi.element);
390 items.setValue(newList); // same count, same submittable state
392 void moveItemLast(List<Item> list, int index) {
396 3 <-- desired position
399 int itemCount = list.size();
401 if (index < itemCount - 1)
402 list.add(list.remove(index));
404 void toggleCurrencyVisible() {
405 final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
407 // remove currency from all items, or reset currency to the default
408 // no need to clone the list, because the removal of the currency won't lead to
409 // visual changes -- the currency fields will be hidden or reset to default anyway
410 // still, there may be changes in the submittable state
411 final List<Item> list = Objects.requireNonNull(this.items.getValue());
412 final Profile profile = Objects.requireNonNull(Data.getProfile());
413 for (int i = 1; i < list.size(); i++) {
414 ((TransactionAccount) list.get(i)).setCurrency(
415 newValue ? profile.getDefaultCommodity() : "");
417 checkTransactionSubmittable(null);
418 showCurrency.setValue(newValue);
420 void stopObservingBusyFlag(Observer<Boolean> observer) {
421 busyFlag.removeObserver(observer);
423 void incrementBusyCounter() {
424 int newValue = busyCounter.incrementAndGet();
426 busyFlag.postValue(true);
428 void decrementBusyCounter() {
429 int newValue = busyCounter.decrementAndGet();
431 busyFlag.postValue(false);
433 public LiveData<Boolean> getBusyFlag() {
436 public void toggleShowComments() {
437 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
439 public LedgerTransaction constructLedgerTransaction() {
440 List<Item> list = Objects.requireNonNull(items.getValue());
441 TransactionHead head = list.get(0)
442 .toTransactionHead();
443 LedgerTransaction tr = head.asLedgerTransaction();
445 tr.setComment(head.getComment());
446 LedgerTransactionAccount emptyAmountAccount = null;
447 float emptyAmountAccountBalance = 0;
448 for (int i = 1; i < list.size(); i++) {
449 TransactionAccount item = list.get(i)
450 .toTransactionAccount();
451 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
454 if (acc.getAccountName()
458 acc.setComment(item.getComment());
460 if (item.isAmountSet()) {
461 acc.setAmount(item.getAmount());
462 emptyAmountAccountBalance += item.getAmount();
465 emptyAmountAccount = acc;
471 if (emptyAmountAccount != null)
472 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
476 void loadTransactionIntoModel(@NonNull TransactionWithAccounts tr) {
477 List<Item> newList = new ArrayList<>();
478 Item.resetIdDispenser();
480 Item currentHead = Objects.requireNonNull(items.getValue())
482 TransactionHead head = new TransactionHead(tr.transaction.getDescription());
483 head.setComment(tr.transaction.getComment());
484 if (currentHead instanceof TransactionHead)
485 head.setDate(((TransactionHead) currentHead).date);
489 List<LedgerTransactionAccount> accounts = new ArrayList<>();
490 for (net.ktnx.mobileledger.db.TransactionAccount acc : tr.accounts) {
491 accounts.add(new LedgerTransactionAccount(acc));
494 TransactionAccount firstNegative = null;
495 TransactionAccount firstPositive = null;
496 int singleNegativeIndex = -1;
497 int singlePositiveIndex = -1;
498 int negativeCount = 0;
499 for (int i = 0; i < accounts.size(); i++) {
500 LedgerTransactionAccount acc = accounts.get(i);
501 TransactionAccount item = new TransactionAccount(acc.getAccountName(),
502 Misc.nullIsEmpty(acc.getCurrency()));
505 item.setAccountName(acc.getAccountName());
506 item.setComment(acc.getComment());
507 if (acc.isAmountSet()) {
508 item.setAmount(acc.getAmount());
509 if (acc.getAmount() < 0) {
510 if (firstNegative == null) {
511 firstNegative = item;
512 singleNegativeIndex = i + 1;
515 singleNegativeIndex = -1;
518 if (firstPositive == null) {
519 firstPositive = item;
520 singlePositiveIndex = i + 1;
523 singlePositiveIndex = -1;
529 if (BuildConfig.DEBUG)
530 dumpItemList("Loaded previous transaction", newList);
532 if (singleNegativeIndex != -1) {
533 firstNegative.resetAmount();
534 moveItemLast(newList, singleNegativeIndex);
536 else if (singlePositiveIndex != -1) {
537 firstPositive.resetAmount();
538 moveItemLast(newList, singlePositiveIndex);
541 Misc.onMainThread(() -> {
543 noteFocusChanged(1, FocusedElement.Amount);
547 * A transaction is submittable if:
549 * 1) has at least two account names
550 * 2) each row with amount has account name
551 * 3) for each commodity:
552 * 3a) amounts must balance to 0, or
553 * 3b) there must be exactly one empty amount (with account)
554 * 4) empty accounts with empty amounts are ignored
556 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
558 * 6) at least two rows need to be present in the ledger
560 * @param list - the item list to check. Can be the displayed list or a list that will be
563 @SuppressLint("DefaultLocale")
564 void checkTransactionSubmittable(@Nullable List<Item> list) {
565 boolean workingWithLiveList = false;
568 workingWithLiveList = true;
571 if (BuildConfig.DEBUG)
572 dumpItemList(String.format("Before submittable checks (%s)",
573 workingWithLiveList ? "LIVE LIST" : "custom list"), list);
576 final BalanceForCurrency balance = new BalanceForCurrency();
577 final String descriptionText = list.get(0)
580 boolean submittable = true;
581 boolean listChanged = false;
582 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
583 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
584 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
585 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
586 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
587 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
588 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
589 final List<Item> emptyRows = new ArrayList<>();
592 if ((descriptionText == null) || descriptionText.trim()
595 Logger.debug("submittable", "Transaction not submittable: missing description");
599 boolean hasInvalidAmount = false;
601 for (int i = 1; i < list.size(); i++) {
602 TransactionAccount item = list.get(i)
603 .toTransactionAccount();
605 String accName = item.getAccountName()
607 String currName = item.getCurrency();
609 itemsForCurrency.add(currName, item);
611 if (accName.isEmpty()) {
612 itemsWithEmptyAccountForCurrency.add(currName, item);
614 if (item.isAmountSet()) {
615 // 2) each amount has account name
616 Logger.debug("submittable", String.format(
617 "Transaction not submittable: row %d has no account name, but" +
618 " has" + " amount %1.2f", i + 1, item.getAmount()));
622 emptyRowsForCurrency.add(currName, item);
627 itemsWithAccountForCurrency.add(currName, item);
630 if (item.isAmountSet() && item.isAmountValid()) {
631 itemsWithAmountForCurrency.add(currName, item);
632 balance.add(currName, item.getAmount());
635 if (!item.isAmountValid()) {
636 Logger.debug("submittable",
637 String.format("Not submittable: row %d has an invalid amount", i));
639 hasInvalidAmount = true;
642 itemsWithEmptyAmountForCurrency.add(currName, item);
644 if (!accName.isEmpty())
645 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
649 // 1) has at least two account names
652 Logger.debug("submittable", "Transaction not submittable: no account names");
653 else if (accounts == 1)
654 Logger.debug("submittable",
655 "Transaction not submittable: only one account name");
657 Logger.debug("submittable",
658 String.format("Transaction not submittable: only %d account names",
663 // 3) for each commodity:
664 // 3a) amount must balance to 0, or
665 // 3b) there must be exactly one empty amount (with account)
666 for (String balCurrency : itemsForCurrency.currencies()) {
667 float currencyBalance = balance.get(balCurrency);
668 if (Misc.isZero(currencyBalance)) {
669 // remove hints from all amount inputs in that currency
670 for (int i = 1; i < list.size(); i++) {
671 TransactionAccount acc = list.get(i)
672 .toTransactionAccount();
673 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
674 if (BuildConfig.DEBUG)
675 Logger.debug("submittable",
676 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
677 i, Misc.nullIsEmpty(acc.getAccountName()),
679 // skip if the amount is set, in which case the hint is not
681 if (!acc.isAmountSet() && acc.amountHintIsSet &&
682 !TextUtils.isEmpty(acc.getAmountHint()))
684 acc.setAmountHint(null);
692 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
693 int balanceReceiversCount = tmpList.size();
694 if (balanceReceiversCount != 1) {
695 if (BuildConfig.DEBUG) {
696 if (balanceReceiversCount == 0)
697 Logger.debug("submittable", String.format(
698 "Transaction not submittable [curr:%s]: non-zero balance " +
699 "with no empty amounts with accounts", balCurrency));
701 Logger.debug("submittable", String.format(
702 "Transaction not submittable [curr:%s]: non-zero balance " +
703 "with multiple empty amounts with accounts", balCurrency));
708 List<Item> emptyAmountList =
709 itemsWithEmptyAmountForCurrency.getList(balCurrency);
711 // suggest off-balance amount to a row and remove hints on other rows
712 Item receiver = null;
713 if (!tmpList.isEmpty())
714 receiver = tmpList.get(0);
715 else if (!emptyAmountList.isEmpty())
716 receiver = emptyAmountList.get(0);
718 for (int i = 0; i < list.size(); i++) {
719 Item item = list.get(i);
720 if (!(item instanceof TransactionAccount))
723 TransactionAccount acc = item.toTransactionAccount();
724 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
727 if (item == receiver) {
728 final String hint = Data.formatNumber(-currencyBalance);
729 if (!acc.isAmountHintSet() ||
730 !Misc.equalStrings(acc.getAmountHint(), hint))
732 Logger.debug("submittable",
733 String.format("Setting amount hint of {%s} to %s [%s]",
734 acc.toString(), hint, balCurrency));
735 acc.setAmountHint(hint);
740 if (BuildConfig.DEBUG)
741 Logger.debug("submittable",
742 String.format("Resetting hint of '%s' [%s]",
743 Misc.nullIsEmpty(acc.getAccountName()),
745 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
746 acc.setAmountHint(null);
754 // 5) a row with an empty account name or empty amount is guaranteed to exist for
756 if (!hasInvalidAmount) {
757 for (String balCurrency : balance.currencies()) {
758 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
759 int currRows = itemsForCurrency.size(balCurrency);
760 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
761 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
762 if ((currEmptyRows == 0) &&
763 ((currRows == currAccounts) || (currRows == currAmounts)))
765 // perhaps there already is an unused empty row for another currency that
767 // boolean foundIt = false;
768 // for (Item item : emptyRows) {
769 // Currency itemCurrency = item.getCurrency();
770 // String itemCurrencyName =
771 // (itemCurrency == null) ? "" : itemCurrency.getName();
772 // if (Misc.isZero(balance.get(itemCurrencyName))) {
773 // item.setCurrency(Currency.loadByName(balCurrency));
774 // item.setAmountHint(
775 // Data.formatNumber(-balance.get(balCurrency)));
782 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
783 final float bal = balance.get(balCurrency);
784 if (!Misc.isZero(bal) && currAmounts == currRows)
785 newAcc.setAmountHint(Data.formatNumber(-bal));
786 Logger.debug("submittable",
787 String.format("Adding new item with %s for currency %s",
788 newAcc.getAmountHint(), balCurrency));
795 // drop extra empty rows, not needed
796 for (String currName : emptyRowsForCurrency.currencies()) {
797 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
798 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
799 // the list is a copy, so the empty item is no longer present
800 Item itemToRemove = emptyItems.remove(1);
801 removeItemById(list, itemToRemove.id);
805 // unused currency, remove last item (which is also an empty one)
806 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
807 List<Item> currItems = itemsForCurrency.getList(currName);
809 if (currItems.size() == 1) {
810 // the list is a copy, so the empty item is no longer present
811 removeItemById(list, emptyItems.get(0).id);
817 // 6) at least two rows need to be present in the ledger
818 // (the list also contains header and trailer)
819 while (list.size() < MIN_ITEMS) {
820 list.add(new TransactionAccount(""));
824 Logger.debug("submittable", submittable ? "YES" : "NO");
825 isSubmittable.setValue(submittable);
827 if (BuildConfig.DEBUG)
828 dumpItemList("After submittable checks", list);
830 catch (NumberFormatException e) {
831 Logger.debug("submittable", "NO (because of NumberFormatException)");
832 isSubmittable.setValue(false);
834 catch (Exception e) {
836 Logger.debug("submittable", "NO (because of an Exception)");
837 isSubmittable.setValue(false);
840 if (listChanged && workingWithLiveList) {
841 setItemsWithoutSubmittableChecks(list);
844 private void removeItemById(@NotNull List<Item> list, int id) {
845 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
846 list.removeIf(item -> item.id == id);
849 for (Item item : list) {
857 @SuppressLint("DefaultLocale")
858 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
859 Logger.debug("submittable", "== Dump of all items " + msg);
860 for (int i = 1; i < list.size(); i++) {
861 TransactionAccount item = list.get(i)
862 .toTransactionAccount();
863 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
866 public void setItemCurrency(int position, String newCurrency) {
867 TransactionAccount item = Objects.requireNonNull(items.getValue())
869 .toTransactionAccount();
870 final String oldCurrency = item.getCurrency();
872 if (Misc.equalStrings(oldCurrency, newCurrency))
875 List<Item> newList = copyList();
876 newList.get(position)
877 .toTransactionAccount()
878 .setCurrency(newCurrency);
882 public boolean accountListIsEmpty() {
883 List<Item> items = Objects.requireNonNull(this.items.getValue());
885 for (Item item : items) {
886 if (!(item instanceof TransactionAccount))
889 if (!((TransactionAccount) item).isEmpty())
896 public static class FocusInfo {
898 FocusedElement element;
899 public FocusInfo(int position, @Nullable FocusedElement element) {
900 this.position = position;
901 this.element = element;
905 static abstract class Item {
906 private static int idDispenser = 0;
909 if (this instanceof TransactionHead)
912 synchronized (Item.class) {
916 public Item(int id) {
919 public static Item from(Item origin) {
920 if (origin instanceof TransactionHead)
921 return new TransactionHead((TransactionHead) origin);
922 if (origin instanceof TransactionAccount)
923 return new TransactionAccount((TransactionAccount) origin);
924 throw new RuntimeException("Don't know how to handle " + origin);
926 private static void resetIdDispenser() {
932 public abstract ItemType getType();
933 public TransactionHead toTransactionHead() {
934 if (this instanceof TransactionHead)
935 return (TransactionHead) this;
937 throw new IllegalStateException("Wrong item type " + this);
939 public TransactionAccount toTransactionAccount() {
940 if (this instanceof TransactionAccount)
941 return (TransactionAccount) this;
943 throw new IllegalStateException("Wrong item type " + this);
945 public boolean equalContents(@Nullable Object item) {
949 if (!getClass().equals(item.getClass()))
952 // shortcut - comparing same instance
956 if (this instanceof TransactionHead)
957 return ((TransactionHead) item).equalContents((TransactionHead) this);
958 if (this instanceof TransactionAccount)
959 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
961 throw new RuntimeException("Don't know how to handle " + this);
966 //==========================================================================================
968 public static class TransactionHead extends Item {
969 private SimpleDate date;
970 private String description;
971 private String comment;
972 TransactionHead(String description) {
974 this.description = description;
976 public TransactionHead(TransactionHead origin) {
979 description = origin.description;
980 comment = origin.comment;
982 public SimpleDate getDate() {
985 public void setDate(SimpleDate date) {
988 public void setDate(String text) throws ParseException {
989 if (Misc.emptyIsNull(text) == null) {
994 date = Globals.parseLedgerDate(text);
999 * @return nicely formatted, shortest available date representation
1001 String getFormattedDate() {
1005 Calendar today = GregorianCalendar.getInstance();
1007 if (today.get(Calendar.YEAR) != date.year) {
1008 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
1011 if (today.get(Calendar.MONTH) + 1 != date.month) {
1012 return String.format(Locale.US, "%d/%02d", date.month, date.day);
1015 return String.valueOf(date.day);
1019 public String toString() {
1020 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
1021 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1023 if (TextUtils.isEmpty(description))
1024 b.append(" «no description»");
1026 b.append(String.format(" '%s'", description));
1029 b.append(String.format("@%s", date.toString()));
1031 if (!TextUtils.isEmpty(comment))
1032 b.append(String.format(" /%s/", comment));
1034 return b.toString();
1036 public String getDescription() {
1039 public void setDescription(String description) {
1040 this.description = description;
1042 public String getComment() {
1045 public void setComment(String comment) {
1046 this.comment = comment;
1049 public ItemType getType() {
1050 return ItemType.generalData;
1052 public LedgerTransaction asLedgerTransaction() {
1053 return new LedgerTransaction(0, (date == null) ? SimpleDate.today() : date, description,
1054 Objects.requireNonNull(Data.getProfile()));
1056 public boolean equalContents(TransactionHead other) {
1060 return Objects.equals(date, other.date) &&
1061 Misc.equalStrings(description, other.description) &&
1062 Misc.equalStrings(comment, other.comment);
1066 public static class TransactionAccount extends Item {
1067 private String accountName;
1068 private String amountHint;
1069 private String comment;
1071 private String currency = "";
1072 private float amount;
1073 private boolean amountSet;
1074 private boolean amountValid = true;
1076 private String amountText = "";
1077 private FocusedElement focusedElement = FocusedElement.Account;
1078 private boolean amountHintIsSet = false;
1079 private boolean isLast = false;
1080 private int accountNameCursorPosition;
1081 public TransactionAccount(TransactionAccount origin) {
1083 accountName = origin.accountName;
1084 amount = origin.amount;
1085 amountSet = origin.amountSet;
1086 amountHint = origin.amountHint;
1087 amountHintIsSet = origin.amountHintIsSet;
1088 amountText = origin.amountText;
1089 comment = origin.comment;
1090 currency = origin.currency;
1091 amountValid = origin.amountValid;
1092 focusedElement = origin.focusedElement;
1093 isLast = origin.isLast;
1094 accountNameCursorPosition = origin.accountNameCursorPosition;
1096 public TransactionAccount(String accountName) {
1098 this.accountName = accountName;
1100 public TransactionAccount(String accountName, @NotNull String currency) {
1102 this.accountName = accountName;
1103 this.currency = currency;
1105 public @NotNull String getAmountText() {
1108 public void setAmountText(@NotNull String amountText) {
1109 this.amountText = amountText;
1111 public boolean setAndCheckAmountText(@NotNull String amountText) {
1112 String amtText = amountText.trim();
1113 this.amountText = amtText;
1115 boolean significantChange = false;
1117 if (amtText.isEmpty()) {
1119 significantChange = true;
1125 amtText = amtText.replace(Data.getDecimalSeparator(), Data.decimalDot);
1126 final float parsedAmount = Float.parseFloat(amtText);
1127 if (!amountSet || !amountValid || !Misc.equalFloats(parsedAmount, amount))
1128 significantChange = true;
1129 amount = parsedAmount;
1133 catch (NumberFormatException e) {
1134 Logger.debug("new-trans", String.format(
1135 "assuming amount is not set due to number format exception. " +
1136 "input was '%s'", amtText));
1137 if (amountValid) // it was valid and now it's not
1138 significantChange = true;
1139 amountValid = false;
1143 return significantChange;
1145 public boolean isLast() {
1148 public boolean isAmountSet() {
1151 public String getAccountName() {
1154 public void setAccountName(String accountName) {
1155 this.accountName = accountName;
1157 public float getAmount() {
1159 throw new IllegalStateException("Amount is not set");
1162 public void setAmount(float amount) {
1163 this.amount = amount;
1166 amountText = Data.formatNumber(amount);
1168 public void resetAmount() {
1174 public ItemType getType() {
1175 return ItemType.transactionRow;
1177 public String getAmountHint() {
1180 public void setAmountHint(String amountHint) {
1181 this.amountHint = amountHint;
1182 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1184 public String getComment() {
1187 public void setComment(String comment) {
1188 this.comment = comment;
1191 public String getCurrency() {
1194 public void setCurrency(@org.jetbrains.annotations.Nullable String currency) {
1195 this.currency = Misc.nullIsEmpty(currency);
1197 public boolean isAmountValid() {
1200 public void setAmountValid(boolean amountValid) {
1201 this.amountValid = amountValid;
1203 public FocusedElement getFocusedElement() {
1204 return focusedElement;
1206 public void setFocusedElement(FocusedElement focusedElement) {
1207 this.focusedElement = focusedElement;
1209 public boolean isAmountHintSet() {
1210 return amountHintIsSet;
1212 public void setAmountHintIsSet(boolean amountHintIsSet) {
1213 this.amountHintIsSet = amountHintIsSet;
1215 public boolean isEmpty() {
1216 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1217 Misc.emptyIsNull(comment) == null;
1219 @SuppressLint("DefaultLocale")
1222 public String toString() {
1223 StringBuilder b = new StringBuilder();
1224 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1225 if (!TextUtils.isEmpty(accountName))
1226 b.append(String.format(" acc'%s'", accountName));
1229 b.append(amountText)
1231 .append(amountValid ? "valid" : "invalid")
1233 .append(String.format(Locale.ROOT, " {raw %4.2f}", amount));
1234 else if (amountHintIsSet)
1235 b.append(String.format(" (hint %s)", amountHint));
1237 if (!TextUtils.isEmpty(currency))
1241 if (!TextUtils.isEmpty(comment))
1242 b.append(String.format(" /%s/", comment));
1247 return b.toString();
1249 public boolean equalContents(TransactionAccount other) {
1253 boolean equal = Misc.equalStrings(accountName, other.accountName);
1254 equal = equal && Misc.equalStrings(comment, other.comment) &&
1255 (amountSet ? other.amountSet && amountValid == other.amountValid &&
1256 Misc.equalStrings(amountText, other.amountText)
1257 : !other.amountSet);
1259 // compare amount hint only if there is no amount
1261 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1262 Misc.equalStrings(amountHint, other.amountHint)
1263 : !other.amountHintIsSet);
1264 equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1266 Logger.debug("new-trans",
1267 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1271 public int getAccountNameCursorPosition() {
1272 return accountNameCursorPosition;
1274 public void setAccountNameCursorPosition(int position) {
1275 this.accountNameCursorPosition = position;
1279 private static class BalanceForCurrency {
1280 private final HashMap<String, Float> hashMap = new HashMap<>();
1281 float get(String currencyName) {
1282 Float f = hashMap.get(currencyName);
1285 hashMap.put(currencyName, f);
1289 void add(String currencyName, float amount) {
1290 hashMap.put(currencyName, get(currencyName) + amount);
1292 Set<String> currencies() {
1293 return hashMap.keySet();
1295 boolean containsCurrency(String currencyName) {
1296 return hashMap.containsKey(currencyName);
1300 private static class ItemsForCurrency {
1301 private final HashMap<@NotNull String, List<Item>> hashMap = new HashMap<>();
1303 List<NewTransactionModel.Item> getList(@NotNull String currencyName) {
1304 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1306 list = new ArrayList<>();
1307 hashMap.put(currencyName, list);
1311 void add(@NotNull String currencyName, @NonNull NewTransactionModel.Item item) {
1312 getList(Objects.requireNonNull(currencyName)).add(item);
1314 int size(@NotNull String currencyName) {
1315 return this.getList(Objects.requireNonNull(currencyName))
1318 Set<String> currencies() {
1319 return hashMap.keySet();