2 * Copyright © 2022 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.Build;
22 import android.text.TextUtils;
24 import androidx.annotation.NonNull;
25 import androidx.annotation.Nullable;
26 import androidx.lifecycle.LifecycleOwner;
27 import androidx.lifecycle.LiveData;
28 import androidx.lifecycle.MutableLiveData;
29 import androidx.lifecycle.Observer;
30 import androidx.lifecycle.ViewModel;
32 import net.ktnx.mobileledger.BuildConfig;
33 import net.ktnx.mobileledger.db.Currency;
34 import net.ktnx.mobileledger.db.DB;
35 import net.ktnx.mobileledger.db.Profile;
36 import net.ktnx.mobileledger.db.TemplateAccount;
37 import net.ktnx.mobileledger.db.TemplateHeader;
38 import net.ktnx.mobileledger.db.TransactionWithAccounts;
39 import net.ktnx.mobileledger.model.Data;
40 import net.ktnx.mobileledger.model.InertMutableLiveData;
41 import net.ktnx.mobileledger.model.LedgerTransaction;
42 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
43 import net.ktnx.mobileledger.model.MatchedTemplate;
44 import net.ktnx.mobileledger.utils.Globals;
45 import net.ktnx.mobileledger.utils.Logger;
46 import net.ktnx.mobileledger.utils.Misc;
47 import net.ktnx.mobileledger.utils.SimpleDate;
49 import org.jetbrains.annotations.NotNull;
51 import java.text.ParseException;
52 import java.util.ArrayList;
53 import java.util.Calendar;
54 import java.util.GregorianCalendar;
55 import java.util.HashMap;
56 import java.util.List;
57 import java.util.Locale;
58 import java.util.Objects;
60 import java.util.concurrent.atomic.AtomicInteger;
61 import java.util.regex.MatchResult;
63 enum ItemType {generalData, transactionRow}
65 enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
68 public class NewTransactionModel extends ViewModel {
69 private static final int MIN_ITEMS = 3;
70 private final MutableLiveData<Boolean> showCurrency = new MutableLiveData<>(false);
71 private final MutableLiveData<Boolean> isSubmittable = new InertMutableLiveData<>(false);
72 private final MutableLiveData<Boolean> showComments = new MutableLiveData<>(true);
73 private final MutableLiveData<List<Item>> items = new MutableLiveData<>();
74 private final MutableLiveData<Boolean> simulateSave = new InertMutableLiveData<>(false);
75 private final AtomicInteger busyCounter = new AtomicInteger(0);
76 private final MutableLiveData<Boolean> busyFlag = new InertMutableLiveData<>(false);
77 private final Observer<Profile> profileObserver = profile -> {
78 if (profile != null) {
79 showCurrency.postValue(profile.getShowCommodityByDefault());
80 showComments.postValue(profile.getShowCommentsByDefault());
83 private final MutableLiveData<FocusInfo> focusInfo = new MutableLiveData<>();
84 private boolean observingDataProfile;
85 public NewTransactionModel() {
87 public LiveData<Boolean> getShowCurrency() {
90 public LiveData<List<Item>> getItems() {
93 private void setItems(@NonNull List<Item> newList) {
94 checkTransactionSubmittable(newList);
95 setItemsWithoutSubmittableChecks(newList);
97 private void replaceItems(@NonNull List<Item> newList) {
103 * make old items replaceable in-place. makes the new values visually blend in
105 private void renumberItems() {
106 renumberItems(items.getValue());
108 private void renumberItems(List<Item> list) {
114 for (Item item : list)
117 private void setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
118 final int cnt = list.size();
119 for (int i = 1; i < cnt - 1; i++) {
120 final TransactionAccount item = list.get(i)
121 .toTransactionAccount();
123 TransactionAccount replacement = new TransactionAccount(item);
124 replacement.isLast = false;
125 list.set(i, replacement);
128 final TransactionAccount last = list.get(cnt - 1)
129 .toTransactionAccount();
131 TransactionAccount replacement = new TransactionAccount(last);
132 replacement.isLast = true;
133 list.set(cnt - 1, replacement);
136 if (BuildConfig.DEBUG)
137 dumpItemList("Before setValue()", list);
138 items.setValue(list);
140 private List<Item> copyList() {
141 List<Item> copy = new ArrayList<>();
142 List<Item> oldList = items.getValue();
145 for (Item item : oldList) {
146 copy.add(Item.from(item));
151 private List<Item> copyListWithoutItem(int position) {
152 List<Item> copy = new ArrayList<>();
153 List<Item> oldList = items.getValue();
155 if (oldList != null) {
157 for (Item item : oldList) {
160 copy.add(Item.from(item));
166 private List<Item> shallowCopyList() {
167 return new ArrayList<>(Objects.requireNonNull(items.getValue()));
169 LiveData<Boolean> getShowComments() {
172 void observeDataProfile(LifecycleOwner activity) {
173 if (!observingDataProfile)
174 Data.observeProfile(activity, profileObserver);
175 observingDataProfile = true;
177 boolean getSimulateSaveFlag() {
178 Boolean value = simulateSave.getValue();
183 LiveData<Boolean> getSimulateSave() {
186 void toggleSimulateSave() {
187 simulateSave.setValue(!getSimulateSaveFlag());
189 LiveData<Boolean> isSubmittable() {
190 return this.isSubmittable;
193 Logger.debug("new-trans", "Resetting model");
194 List<Item> list = new ArrayList<>();
195 Item.resetIdDispenser();
196 list.add(new TransactionHead(""));
197 final String defaultCurrency = Objects.requireNonNull(Data.getProfile())
198 .getDefaultCommodity();
199 list.add(new TransactionAccount("", defaultCurrency));
200 list.add(new TransactionAccount("", defaultCurrency));
201 noteFocusChanged(0, FocusedElement.Description);
203 isSubmittable.setValue(false);
204 setItemsWithoutSubmittableChecks(list);
206 boolean accountsInInitialState() {
207 final List<Item> list = items.getValue();
212 for (Item item : list) {
213 if (!(item instanceof TransactionAccount))
216 TransactionAccount accRow = (TransactionAccount) item;
217 if (!accRow.isEmpty())
223 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
224 SimpleDate transactionDate = null;
225 final MatchResult matchResult = matchedTemplate.matchResult;
226 final TemplateHeader templateHead = matchedTemplate.templateHead;
228 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
229 templateHead.getDateDay());
230 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
231 templateHead.getDateMonth());
232 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
233 templateHead.getDateYear());
235 if (year > 0 || month > 0 || day > 0) {
236 SimpleDate today = SimpleDate.today();
244 transactionDate = new SimpleDate(year, month, day);
246 Logger.debug("pattern", "setting transaction date to " + transactionDate);
250 List<Item> present = copyList();
252 TransactionHead head = new TransactionHead(present.get(0)
253 .toTransactionHead());
254 if (transactionDate != null)
255 head.setDate(transactionDate);
257 final String transactionDescription = extractStringFromMatches(matchResult,
258 templateHead.getTransactionDescriptionMatchGroup(),
259 templateHead.getTransactionDescription());
260 if (Misc.emptyIsNull(transactionDescription) != null)
261 head.setDescription(transactionDescription);
263 final String transactionComment = extractStringFromMatches(matchResult,
264 templateHead.getTransactionCommentMatchGroup(),
265 templateHead.getTransactionComment());
266 if (Misc.emptyIsNull(transactionComment) != null)
267 head.setComment(transactionComment);
269 List<Item> newItems = new ArrayList<>();
273 for (int i = 1; i < present.size(); i++) {
274 final TransactionAccount row = present.get(i)
275 .toTransactionAccount();
277 newItems.add(new TransactionAccount(row));
282 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
284 final boolean accountsInInitialState = accountsInInitialState();
285 for (TemplateAccount acc : entry.accounts) {
289 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
290 acc.getAccountName());
291 String accountComment =
292 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
293 acc.getAccountComment());
294 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
296 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
299 TransactionAccount accRow = new TransactionAccount(accountName);
300 accRow.setComment(accountComment);
302 accRow.setAmount(amount);
304 extractCurrencyFromMatches(matchResult, acc.getCurrencyMatchGroup(),
305 acc.getCurrencyObject()));
307 newItems.add(accRow);
310 renumberItems(newItems);
311 Misc.onMainThread(() -> replaceItems(newItems));
315 private String extractCurrencyFromMatches(MatchResult m, Integer group, Currency literal) {
316 return Misc.nullIsEmpty(
317 extractStringFromMatches(m, group, (literal == null) ? "" : literal.getName()));
319 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
325 if (grp > 0 && grp <= m.groupCount())
327 return Integer.parseInt(m.group(grp));
329 catch (NumberFormatException e) {
330 Logger.debug("new-trans", "Error extracting matched number", e);
337 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
343 if (grp > 0 && grp <= m.groupCount())
349 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
355 if (grp > 0 && grp <= m.groupCount())
357 return Float.valueOf(m.group(grp));
359 catch (NumberFormatException e) {
360 Logger.debug("new-trans", "Error extracting matched number", e);
366 void removeItem(int pos) {
367 Logger.debug("new-trans", String.format(Locale.US, "Removing item at position %d", pos));
368 List<Item> newList = copyListWithoutItem(pos);
369 final FocusInfo fi = focusInfo.getValue();
370 if ((fi != null) && (pos < fi.position))
371 noteFocusChanged(fi.position - 1, fi.element);
374 void noteFocusChanged(int position, @Nullable FocusedElement element) {
375 FocusInfo present = focusInfo.getValue();
376 if (present == null || present.position != position || present.element != element)
377 focusInfo.setValue(new FocusInfo(position, element));
379 public LiveData<FocusInfo> getFocusInfo() {
382 void moveItem(int fromIndex, int toIndex) {
383 List<Item> newList = shallowCopyList();
384 Item item = newList.remove(fromIndex);
385 newList.add(toIndex, item);
387 FocusInfo fi = focusInfo.getValue();
388 if (fi != null && fi.position == fromIndex)
389 noteFocusChanged(toIndex, fi.element);
391 items.setValue(newList); // same count, same submittable state
393 void moveItemLast(List<Item> list, int index) {
397 3 <-- desired position
400 int itemCount = list.size();
402 if (index < itemCount - 1)
403 list.add(list.remove(index));
405 void toggleCurrencyVisible() {
406 final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
408 // remove currency from all items, or reset currency to the default
409 // no need to clone the list, because the removal of the currency won't lead to
410 // visual changes -- the currency fields will be hidden or reset to default anyway
411 // still, there may be changes in the submittable state
412 final List<Item> list = Objects.requireNonNull(this.items.getValue());
413 final Profile profile = Objects.requireNonNull(Data.getProfile());
414 for (int i = 1; i < list.size(); i++) {
415 ((TransactionAccount) list.get(i)).setCurrency(
416 newValue ? profile.getDefaultCommodity() : "");
418 checkTransactionSubmittable(null);
419 showCurrency.setValue(newValue);
421 void stopObservingBusyFlag(Observer<Boolean> observer) {
422 busyFlag.removeObserver(observer);
424 void incrementBusyCounter() {
425 int newValue = busyCounter.incrementAndGet();
427 busyFlag.postValue(true);
429 void decrementBusyCounter() {
430 int newValue = busyCounter.decrementAndGet();
432 busyFlag.postValue(false);
434 public LiveData<Boolean> getBusyFlag() {
437 public void toggleShowComments() {
438 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
440 public LedgerTransaction constructLedgerTransaction() {
441 List<Item> list = Objects.requireNonNull(items.getValue());
442 TransactionHead head = list.get(0)
443 .toTransactionHead();
444 LedgerTransaction tr = head.asLedgerTransaction();
446 tr.setComment(head.getComment());
447 HashMap<String, List<LedgerTransactionAccount>> emptyAmountAccounts = new HashMap<>();
448 HashMap<String, Float> emptyAmountAccountBalance = new HashMap<>();
449 for (int i = 1; i < list.size(); i++) {
450 TransactionAccount item = list.get(i)
451 .toTransactionAccount();
452 String currency = item.getCurrency();
453 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
455 if (acc.getAccountName()
459 acc.setComment(item.getComment());
461 if (item.isAmountSet()) {
462 acc.setAmount(item.getAmount());
463 Float emptyCurrBalance = emptyAmountAccountBalance.get(currency);
464 if (emptyCurrBalance == null) {
465 emptyAmountAccountBalance.put(currency, item.getAmount());
468 emptyAmountAccountBalance.put(currency, emptyCurrBalance + item.getAmount());
472 List<LedgerTransactionAccount> emptyCurrAccounts =
473 emptyAmountAccounts.get(currency);
474 if (emptyCurrAccounts == null)
475 emptyAmountAccounts.put(currency, emptyCurrAccounts = new ArrayList<>());
476 emptyCurrAccounts.add(acc);
482 if (emptyAmountAccounts.size() > 0) {
483 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
484 emptyAmountAccounts.forEach((currency, accounts) -> {
485 if (accounts.size() != 1)
486 throw new RuntimeException(String.format(Locale.US,
487 "Should not happen: approved transaction has %d accounts for " +
488 "currency %s", accounts.size(), currency));
490 .setAmount(-emptyAmountAccountBalance.get(currency));
494 for (String currency : emptyAmountAccounts.keySet()) {
495 List<LedgerTransactionAccount> accounts =
496 Objects.requireNonNull(emptyAmountAccounts.get(currency));
498 if (accounts.size() != 1)
499 throw new RuntimeException(String.format(Locale.US,
500 "Should not happen: approved transaction has %d accounts for " +
501 "currency %s", accounts.size(), currency));
503 .setAmount(-emptyAmountAccountBalance.get(currency));
510 void loadTransactionIntoModel(@NonNull TransactionWithAccounts tr) {
511 List<Item> newList = new ArrayList<>();
512 Item.resetIdDispenser();
514 Item currentHead = Objects.requireNonNull(items.getValue())
516 TransactionHead head = new TransactionHead(tr.transaction.getDescription());
517 head.setComment(tr.transaction.getComment());
518 if (currentHead instanceof TransactionHead)
519 head.setDate(((TransactionHead) currentHead).date);
523 List<LedgerTransactionAccount> accounts = new ArrayList<>();
524 for (net.ktnx.mobileledger.db.TransactionAccount acc : tr.accounts) {
525 accounts.add(new LedgerTransactionAccount(acc));
528 TransactionAccount firstNegative = null;
529 TransactionAccount firstPositive = null;
530 int singleNegativeIndex = -1;
531 int singlePositiveIndex = -1;
532 int negativeCount = 0;
533 boolean hasCurrency = false;
534 for (int i = 0; i < accounts.size(); i++) {
535 LedgerTransactionAccount acc = accounts.get(i);
536 TransactionAccount item = new TransactionAccount(acc.getAccountName(),
537 Misc.nullIsEmpty(acc.getCurrency()));
540 item.setAccountName(acc.getAccountName());
541 item.setComment(acc.getComment());
542 if (acc.isAmountSet()) {
543 item.setAmount(acc.getAmount());
544 if (acc.getAmount() < 0) {
545 if (firstNegative == null) {
546 firstNegative = item;
547 singleNegativeIndex = i + 1;
550 singleNegativeIndex = -1;
553 if (firstPositive == null) {
554 firstPositive = item;
555 singlePositiveIndex = i + 1;
558 singlePositiveIndex = -1;
564 if (item.getCurrency()
568 if (BuildConfig.DEBUG)
569 dumpItemList("Loaded previous transaction", newList);
571 if (singleNegativeIndex != -1) {
572 firstNegative.resetAmount();
573 moveItemLast(newList, singleNegativeIndex);
575 else if (singlePositiveIndex != -1) {
576 firstPositive.resetAmount();
577 moveItemLast(newList, singlePositiveIndex);
580 final boolean foundTransactionHasCurrency = hasCurrency;
581 Misc.onMainThread(() -> {
583 noteFocusChanged(1, FocusedElement.Amount);
584 if (foundTransactionHasCurrency)
585 showCurrency.setValue(true);
589 * A transaction is submittable if:
591 * 1) has at least two account names
592 * 2) each row with amount has account name
593 * 3) for each commodity:
594 * 3a) amounts must balance to 0, or
595 * 3b) there must be exactly one empty amount (with account)
596 * 4) empty accounts with empty amounts are ignored
598 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
600 * 6) at least two rows need to be present in the ledger
602 * @param list - the item list to check. Can be the displayed list or a list that will be
605 @SuppressLint("DefaultLocale")
606 void checkTransactionSubmittable(@Nullable List<Item> list) {
607 boolean workingWithLiveList = false;
610 workingWithLiveList = true;
613 if (BuildConfig.DEBUG)
614 dumpItemList(String.format("Before submittable checks (%s)",
615 workingWithLiveList ? "LIVE LIST" : "custom list"), list);
618 final BalanceForCurrency balance = new BalanceForCurrency();
619 final String descriptionText = list.get(0)
622 boolean submittable = true;
623 boolean listChanged = false;
624 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
625 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
626 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
627 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
628 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
629 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
630 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
631 final List<Item> emptyRows = new ArrayList<>();
634 if ((descriptionText == null) || descriptionText.trim()
637 Logger.debug("submittable", "Transaction not submittable: missing description");
641 boolean hasInvalidAmount = false;
643 for (int i = 1; i < list.size(); i++) {
644 TransactionAccount item = list.get(i)
645 .toTransactionAccount();
647 String accName = item.getAccountName()
649 String currName = item.getCurrency();
651 itemsForCurrency.add(currName, item);
653 if (accName.isEmpty()) {
654 itemsWithEmptyAccountForCurrency.add(currName, item);
656 if (item.isAmountSet()) {
657 // 2) each amount has account name
658 Logger.debug("submittable", String.format(
659 "Transaction not submittable: row %d has no account name, but" +
660 " has" + " amount %1.2f", i + 1, item.getAmount()));
664 emptyRowsForCurrency.add(currName, item);
669 itemsWithAccountForCurrency.add(currName, item);
672 if (item.isAmountSet() && item.isAmountValid()) {
673 itemsWithAmountForCurrency.add(currName, item);
674 balance.add(currName, item.getAmount());
677 if (!item.isAmountValid()) {
678 Logger.debug("submittable",
679 String.format("Not submittable: row %d has an invalid amount", i));
681 hasInvalidAmount = true;
684 itemsWithEmptyAmountForCurrency.add(currName, item);
686 if (!accName.isEmpty())
687 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
691 // 1) has at least two account names
694 Logger.debug("submittable", "Transaction not submittable: no account names");
695 else if (accounts == 1)
696 Logger.debug("submittable",
697 "Transaction not submittable: only one account name");
699 Logger.debug("submittable",
700 String.format("Transaction not submittable: only %d account names",
705 // 3) for each commodity:
706 // 3a) amount must balance to 0, or
707 // 3b) there must be exactly one empty amount (with account)
708 for (String balCurrency : itemsForCurrency.currencies()) {
709 float currencyBalance = balance.get(balCurrency);
710 if (Misc.isZero(currencyBalance)) {
711 // remove hints from all amount inputs in that currency
712 for (int i = 1; i < list.size(); i++) {
713 TransactionAccount acc = list.get(i)
714 .toTransactionAccount();
715 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
716 if (BuildConfig.DEBUG)
717 Logger.debug("submittable",
718 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
719 i, Misc.nullIsEmpty(acc.getAccountName()),
721 // skip if the amount is set, in which case the hint is not
723 if (!acc.isAmountSet() && acc.amountHintIsSet &&
724 !TextUtils.isEmpty(acc.getAmountHint()))
726 acc.setAmountHint(null);
734 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
735 int balanceReceiversCount = tmpList.size();
736 if (balanceReceiversCount != 1) {
737 if (BuildConfig.DEBUG) {
738 if (balanceReceiversCount == 0)
739 Logger.debug("submittable", String.format(
740 "Transaction not submittable [curr:%s]: non-zero balance " +
741 "with no empty amounts with accounts", balCurrency));
743 Logger.debug("submittable", String.format(
744 "Transaction not submittable [curr:%s]: non-zero balance " +
745 "with multiple empty amounts with accounts", balCurrency));
750 List<Item> emptyAmountList =
751 itemsWithEmptyAmountForCurrency.getList(balCurrency);
753 // suggest off-balance amount to a row and remove hints on other rows
754 Item receiver = null;
755 if (!tmpList.isEmpty())
756 receiver = tmpList.get(0);
757 else if (!emptyAmountList.isEmpty())
758 receiver = emptyAmountList.get(0);
760 for (int i = 0; i < list.size(); i++) {
761 Item item = list.get(i);
762 if (!(item instanceof TransactionAccount))
765 TransactionAccount acc = item.toTransactionAccount();
766 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
769 if (item == receiver) {
770 final String hint = Data.formatNumber(-currencyBalance);
771 if (!acc.isAmountHintSet() ||
772 !Misc.equalStrings(acc.getAmountHint(), hint))
774 Logger.debug("submittable",
775 String.format("Setting amount hint of {%s} to %s [%s]", acc,
777 acc.setAmountHint(hint);
782 if (BuildConfig.DEBUG)
783 Logger.debug("submittable",
784 String.format("Resetting hint of '%s' [%s]",
785 Misc.nullIsEmpty(acc.getAccountName()),
787 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
788 acc.setAmountHint(null);
796 // 5) a row with an empty account name or empty amount is guaranteed to exist for
798 if (!hasInvalidAmount) {
799 for (String balCurrency : balance.currencies()) {
800 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
801 int currRows = itemsForCurrency.size(balCurrency);
802 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
803 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
804 if ((currEmptyRows == 0) &&
805 ((currRows == currAccounts) || (currRows == currAmounts)))
807 // perhaps there already is an unused empty row for another currency that
809 // boolean foundIt = false;
810 // for (Item item : emptyRows) {
811 // Currency itemCurrency = item.getCurrency();
812 // String itemCurrencyName =
813 // (itemCurrency == null) ? "" : itemCurrency.getName();
814 // if (Misc.isZero(balance.get(itemCurrencyName))) {
815 // item.setCurrency(Currency.loadByName(balCurrency));
816 // item.setAmountHint(
817 // Data.formatNumber(-balance.get(balCurrency)));
824 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
825 final float bal = balance.get(balCurrency);
826 if (!Misc.isZero(bal) && currAmounts == currRows)
827 newAcc.setAmountHint(Data.formatNumber(-bal));
828 Logger.debug("submittable",
829 String.format("Adding new item with %s for currency %s",
830 newAcc.getAmountHint(), balCurrency));
837 // drop extra empty rows, not needed
838 for (String currName : emptyRowsForCurrency.currencies()) {
839 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
840 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
841 // the list is a copy, so the empty item is no longer present
842 Item itemToRemove = emptyItems.remove(1);
843 removeItemById(list, itemToRemove.id);
847 // unused currency, remove last item (which is also an empty one)
848 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
849 List<Item> currItems = itemsForCurrency.getList(currName);
851 if (currItems.size() == 1) {
852 // the list is a copy, so the empty item is no longer present
853 removeItemById(list, emptyItems.get(0).id);
859 // 6) at least two rows need to be present in the ledger
860 // (the list also contains header and trailer)
861 while (list.size() < MIN_ITEMS) {
862 list.add(new TransactionAccount(""));
866 Logger.debug("submittable", submittable ? "YES" : "NO");
867 isSubmittable.setValue(submittable);
869 if (BuildConfig.DEBUG)
870 dumpItemList("After submittable checks", list);
872 catch (NumberFormatException e) {
873 Logger.debug("submittable", "NO (because of NumberFormatException)");
874 isSubmittable.setValue(false);
876 catch (Exception e) {
878 Logger.debug("submittable", "NO (because of an Exception)");
879 isSubmittable.setValue(false);
882 if (listChanged && workingWithLiveList) {
883 setItemsWithoutSubmittableChecks(list);
886 private void removeItemById(@NotNull List<Item> list, int id) {
887 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
888 list.removeIf(item -> item.id == id);
891 for (Item item : list) {
899 @SuppressLint("DefaultLocale")
900 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
901 Logger.debug("submittable", "== Dump of all items " + msg);
902 for (int i = 1; i < list.size(); i++) {
903 TransactionAccount item = list.get(i)
904 .toTransactionAccount();
905 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
908 public void setItemCurrency(int position, String newCurrency) {
909 TransactionAccount item = Objects.requireNonNull(items.getValue())
911 .toTransactionAccount();
912 final String oldCurrency = item.getCurrency();
914 if (Misc.equalStrings(oldCurrency, newCurrency))
917 List<Item> newList = copyList();
918 newList.get(position)
919 .toTransactionAccount()
920 .setCurrency(newCurrency);
924 public boolean accountListIsEmpty() {
925 List<Item> items = Objects.requireNonNull(this.items.getValue());
927 for (Item item : items) {
928 if (!(item instanceof TransactionAccount))
931 if (!((TransactionAccount) item).isEmpty())
938 public static class FocusInfo {
940 FocusedElement element;
941 public FocusInfo(int position, @Nullable FocusedElement element) {
942 this.position = position;
943 this.element = element;
947 static abstract class Item {
948 private static int idDispenser = 0;
951 if (this instanceof TransactionHead)
954 synchronized (Item.class) {
958 public Item(int id) {
961 public static Item from(Item origin) {
962 if (origin instanceof TransactionHead)
963 return new TransactionHead((TransactionHead) origin);
964 if (origin instanceof TransactionAccount)
965 return new TransactionAccount((TransactionAccount) origin);
966 throw new RuntimeException("Don't know how to handle " + origin);
968 private static void resetIdDispenser() {
974 public abstract ItemType getType();
975 public TransactionHead toTransactionHead() {
976 if (this instanceof TransactionHead)
977 return (TransactionHead) this;
979 throw new IllegalStateException("Wrong item type " + this);
981 public TransactionAccount toTransactionAccount() {
982 if (this instanceof TransactionAccount)
983 return (TransactionAccount) this;
985 throw new IllegalStateException("Wrong item type " + this);
987 public boolean equalContents(@Nullable Object item) {
991 if (!getClass().equals(item.getClass()))
994 // shortcut - comparing same instance
998 if (this instanceof TransactionHead)
999 return ((TransactionHead) item).equalContents((TransactionHead) this);
1000 if (this instanceof TransactionAccount)
1001 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
1003 throw new RuntimeException("Don't know how to handle " + this);
1008 //==========================================================================================
1010 public static class TransactionHead extends Item {
1011 private SimpleDate date;
1012 private String description;
1013 private String comment;
1014 TransactionHead(String description) {
1016 this.description = description;
1018 public TransactionHead(TransactionHead origin) {
1021 description = origin.description;
1022 comment = origin.comment;
1024 public SimpleDate getDate() {
1027 public void setDate(SimpleDate date) {
1030 public void setDate(String text) throws ParseException {
1031 if (Misc.emptyIsNull(text) == null) {
1036 date = Globals.parseLedgerDate(text);
1039 * getFormattedDate()
1041 * @return nicely formatted, shortest available date representation
1043 String getFormattedDate() {
1047 Calendar today = GregorianCalendar.getInstance();
1049 if (today.get(Calendar.YEAR) != date.year) {
1050 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
1053 if (today.get(Calendar.MONTH) + 1 != date.month) {
1054 return String.format(Locale.US, "%d/%02d", date.month, date.day);
1057 return String.valueOf(date.day);
1061 public String toString() {
1062 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
1063 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1065 if (TextUtils.isEmpty(description))
1066 b.append(" «no description»");
1068 b.append(String.format(" '%s'", description));
1071 b.append(String.format("@%s", date));
1073 if (!TextUtils.isEmpty(comment))
1074 b.append(String.format(" /%s/", comment));
1076 return b.toString();
1078 public String getDescription() {
1081 public void setDescription(String description) {
1082 this.description = description;
1084 public String getComment() {
1087 public void setComment(String comment) {
1088 this.comment = comment;
1091 public ItemType getType() {
1092 return ItemType.generalData;
1094 public LedgerTransaction asLedgerTransaction() {
1095 return new LedgerTransaction(0, (date == null) ? SimpleDate.today() : date, description,
1096 Objects.requireNonNull(Data.getProfile()));
1098 public boolean equalContents(TransactionHead other) {
1102 return Objects.equals(date, other.date) &&
1103 Misc.equalStrings(description, other.description) &&
1104 Misc.equalStrings(comment, other.comment);
1108 public static class TransactionAccount extends Item {
1109 private String accountName;
1110 private String amountHint;
1111 private String comment;
1113 private String currency = "";
1114 private float amount;
1115 private boolean amountSet;
1116 private boolean amountValid = true;
1118 private String amountText = "";
1119 private FocusedElement focusedElement = FocusedElement.Account;
1120 private boolean amountHintIsSet = false;
1121 private boolean isLast = false;
1122 private int accountNameCursorPosition;
1123 public TransactionAccount(TransactionAccount origin) {
1125 accountName = origin.accountName;
1126 amount = origin.amount;
1127 amountSet = origin.amountSet;
1128 amountHint = origin.amountHint;
1129 amountHintIsSet = origin.amountHintIsSet;
1130 amountText = origin.amountText;
1131 comment = origin.comment;
1132 currency = origin.currency;
1133 amountValid = origin.amountValid;
1134 focusedElement = origin.focusedElement;
1135 isLast = origin.isLast;
1136 accountNameCursorPosition = origin.accountNameCursorPosition;
1138 public TransactionAccount(String accountName) {
1140 this.accountName = accountName;
1142 public TransactionAccount(String accountName, @NotNull String currency) {
1144 this.accountName = accountName;
1145 this.currency = currency;
1147 public @NotNull String getAmountText() {
1150 public void setAmountText(@NotNull String amountText) {
1151 this.amountText = amountText;
1153 public boolean setAndCheckAmountText(@NotNull String amountText) {
1154 String amtText = amountText.trim();
1155 this.amountText = amtText;
1157 boolean significantChange = false;
1159 if (amtText.isEmpty()) {
1161 significantChange = true;
1167 amtText = amtText.replace(Data.getDecimalSeparator(), Data.decimalDot);
1168 final float parsedAmount = Float.parseFloat(amtText);
1169 if (!amountSet || !amountValid || !Misc.equalFloats(parsedAmount, amount))
1170 significantChange = true;
1171 amount = parsedAmount;
1175 catch (NumberFormatException e) {
1176 Logger.debug("new-trans", String.format(
1177 "assuming amount is not set due to number format exception. " +
1178 "input was '%s'", amtText));
1179 if (amountValid) // it was valid and now it's not
1180 significantChange = true;
1181 amountValid = false;
1185 return significantChange;
1187 public boolean isLast() {
1190 public boolean isAmountSet() {
1193 public String getAccountName() {
1196 public void setAccountName(String accountName) {
1197 this.accountName = accountName;
1199 public float getAmount() {
1201 throw new IllegalStateException("Amount is not set");
1204 public void setAmount(float amount) {
1205 this.amount = amount;
1208 amountText = Data.formatNumber(amount);
1210 public void resetAmount() {
1216 public ItemType getType() {
1217 return ItemType.transactionRow;
1219 public String getAmountHint() {
1222 public void setAmountHint(String amountHint) {
1223 this.amountHint = amountHint;
1224 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1226 public String getComment() {
1229 public void setComment(String comment) {
1230 this.comment = comment;
1233 public String getCurrency() {
1236 public void setCurrency(@org.jetbrains.annotations.Nullable String currency) {
1237 this.currency = Misc.nullIsEmpty(currency);
1239 public boolean isAmountValid() {
1242 public void setAmountValid(boolean amountValid) {
1243 this.amountValid = amountValid;
1245 public FocusedElement getFocusedElement() {
1246 return focusedElement;
1248 public void setFocusedElement(FocusedElement focusedElement) {
1249 this.focusedElement = focusedElement;
1251 public boolean isAmountHintSet() {
1252 return amountHintIsSet;
1254 public void setAmountHintIsSet(boolean amountHintIsSet) {
1255 this.amountHintIsSet = amountHintIsSet;
1257 public boolean isEmpty() {
1258 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1259 Misc.emptyIsNull(comment) == null;
1261 @SuppressLint("DefaultLocale")
1264 public String toString() {
1265 StringBuilder b = new StringBuilder();
1266 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1267 if (!TextUtils.isEmpty(accountName))
1268 b.append(String.format(" acc'%s'", accountName));
1271 b.append(amountText)
1273 .append(amountValid ? "valid" : "invalid")
1275 .append(String.format(Locale.ROOT, " {raw %4.2f}", amount));
1276 else if (amountHintIsSet)
1277 b.append(String.format(" (hint %s)", amountHint));
1279 if (!TextUtils.isEmpty(currency))
1283 if (!TextUtils.isEmpty(comment))
1284 b.append(String.format(" /%s/", comment));
1289 return b.toString();
1291 public boolean equalContents(TransactionAccount other) {
1295 boolean equal = Misc.equalStrings(accountName, other.accountName);
1296 equal = equal && Misc.equalStrings(comment, other.comment) &&
1297 (amountSet ? other.amountSet && amountValid == other.amountValid &&
1298 Misc.equalStrings(amountText, other.amountText)
1299 : !other.amountSet);
1301 // compare amount hint only if there is no amount
1303 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1304 Misc.equalStrings(amountHint, other.amountHint)
1305 : !other.amountHintIsSet);
1306 equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1308 Logger.debug("new-trans",
1309 String.format("Comparing {%s} and {%s}: %s", this, other, equal));
1312 public int getAccountNameCursorPosition() {
1313 return accountNameCursorPosition;
1315 public void setAccountNameCursorPosition(int position) {
1316 this.accountNameCursorPosition = position;
1320 private static class BalanceForCurrency {
1321 private final HashMap<String, Float> hashMap = new HashMap<>();
1322 float get(String currencyName) {
1323 Float f = hashMap.get(currencyName);
1326 hashMap.put(currencyName, f);
1330 void add(String currencyName, float amount) {
1331 hashMap.put(currencyName, get(currencyName) + amount);
1333 Set<String> currencies() {
1334 return hashMap.keySet();
1336 boolean containsCurrency(String currencyName) {
1337 return hashMap.containsKey(currencyName);
1341 private static class ItemsForCurrency {
1342 private final HashMap<@NotNull String, List<Item>> hashMap = new HashMap<>();
1344 List<NewTransactionModel.Item> getList(@NotNull String currencyName) {
1345 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1347 list = new ArrayList<>();
1348 hashMap.put(currencyName, list);
1352 void add(@NotNull String currencyName, @NonNull NewTransactionModel.Item item) {
1353 getList(Objects.requireNonNull(currencyName)).add(item);
1355 int size(@NotNull String currencyName) {
1356 return this.getList(Objects.requireNonNull(currencyName))
1359 Set<String> currencies() {
1360 return hashMap.keySet();