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 List<LedgerTransactionAccount> emptyAmountAccounts = new ArrayList<>();
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 emptyAmountAccounts.add(acc);
471 if (emptyAmountAccounts.size() > 0) {
472 if (emptyAmountAccounts.size() > 1 && !Misc.isZero(emptyAmountAccountBalance))
473 throw new RuntimeException(String.format(Locale.US,
474 "Should not happen. %d accounts with non zero amount to distribute (%5" +
476 for (LedgerTransactionAccount a : emptyAmountAccounts)
477 a.setAmount(-emptyAmountAccountBalance);
482 void loadTransactionIntoModel(@NonNull TransactionWithAccounts tr) {
483 List<Item> newList = new ArrayList<>();
484 Item.resetIdDispenser();
486 Item currentHead = Objects.requireNonNull(items.getValue())
488 TransactionHead head = new TransactionHead(tr.transaction.getDescription());
489 head.setComment(tr.transaction.getComment());
490 if (currentHead instanceof TransactionHead)
491 head.setDate(((TransactionHead) currentHead).date);
495 List<LedgerTransactionAccount> accounts = new ArrayList<>();
496 for (net.ktnx.mobileledger.db.TransactionAccount acc : tr.accounts) {
497 accounts.add(new LedgerTransactionAccount(acc));
500 TransactionAccount firstNegative = null;
501 TransactionAccount firstPositive = null;
502 int singleNegativeIndex = -1;
503 int singlePositiveIndex = -1;
504 int negativeCount = 0;
505 for (int i = 0; i < accounts.size(); i++) {
506 LedgerTransactionAccount acc = accounts.get(i);
507 TransactionAccount item = new TransactionAccount(acc.getAccountName(),
508 Misc.nullIsEmpty(acc.getCurrency()));
511 item.setAccountName(acc.getAccountName());
512 item.setComment(acc.getComment());
513 if (acc.isAmountSet()) {
514 item.setAmount(acc.getAmount());
515 if (acc.getAmount() < 0) {
516 if (firstNegative == null) {
517 firstNegative = item;
518 singleNegativeIndex = i + 1;
521 singleNegativeIndex = -1;
524 if (firstPositive == null) {
525 firstPositive = item;
526 singlePositiveIndex = i + 1;
529 singlePositiveIndex = -1;
535 if (BuildConfig.DEBUG)
536 dumpItemList("Loaded previous transaction", newList);
538 if (singleNegativeIndex != -1) {
539 firstNegative.resetAmount();
540 moveItemLast(newList, singleNegativeIndex);
542 else if (singlePositiveIndex != -1) {
543 firstPositive.resetAmount();
544 moveItemLast(newList, singlePositiveIndex);
547 Misc.onMainThread(() -> {
549 noteFocusChanged(1, FocusedElement.Amount);
553 * A transaction is submittable if:
555 * 1) has at least two account names
556 * 2) each row with amount has account name
557 * 3) for each commodity:
558 * 3a) amounts must balance to 0, or
559 * 3b) there must be exactly one empty amount (with account)
560 * 4) empty accounts with empty amounts are ignored
562 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
564 * 6) at least two rows need to be present in the ledger
566 * @param list - the item list to check. Can be the displayed list or a list that will be
569 @SuppressLint("DefaultLocale")
570 void checkTransactionSubmittable(@Nullable List<Item> list) {
571 boolean workingWithLiveList = false;
574 workingWithLiveList = true;
577 if (BuildConfig.DEBUG)
578 dumpItemList(String.format("Before submittable checks (%s)",
579 workingWithLiveList ? "LIVE LIST" : "custom list"), list);
582 final BalanceForCurrency balance = new BalanceForCurrency();
583 final String descriptionText = list.get(0)
586 boolean submittable = true;
587 boolean listChanged = false;
588 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
589 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
590 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
591 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
592 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
593 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
594 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
595 final List<Item> emptyRows = new ArrayList<>();
598 if ((descriptionText == null) || descriptionText.trim()
601 Logger.debug("submittable", "Transaction not submittable: missing description");
605 boolean hasInvalidAmount = false;
607 for (int i = 1; i < list.size(); i++) {
608 TransactionAccount item = list.get(i)
609 .toTransactionAccount();
611 String accName = item.getAccountName()
613 String currName = item.getCurrency();
615 itemsForCurrency.add(currName, item);
617 if (accName.isEmpty()) {
618 itemsWithEmptyAccountForCurrency.add(currName, item);
620 if (item.isAmountSet()) {
621 // 2) each amount has account name
622 Logger.debug("submittable", String.format(
623 "Transaction not submittable: row %d has no account name, but" +
624 " has" + " amount %1.2f", i + 1, item.getAmount()));
628 emptyRowsForCurrency.add(currName, item);
633 itemsWithAccountForCurrency.add(currName, item);
636 if (item.isAmountSet() && item.isAmountValid()) {
637 itemsWithAmountForCurrency.add(currName, item);
638 balance.add(currName, item.getAmount());
641 if (!item.isAmountValid()) {
642 Logger.debug("submittable",
643 String.format("Not submittable: row %d has an invalid amount", i));
645 hasInvalidAmount = true;
648 itemsWithEmptyAmountForCurrency.add(currName, item);
650 if (!accName.isEmpty())
651 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
655 // 1) has at least two account names
658 Logger.debug("submittable", "Transaction not submittable: no account names");
659 else if (accounts == 1)
660 Logger.debug("submittable",
661 "Transaction not submittable: only one account name");
663 Logger.debug("submittable",
664 String.format("Transaction not submittable: only %d account names",
669 // 3) for each commodity:
670 // 3a) amount must balance to 0, or
671 // 3b) there must be exactly one empty amount (with account)
672 for (String balCurrency : itemsForCurrency.currencies()) {
673 float currencyBalance = balance.get(balCurrency);
674 if (Misc.isZero(currencyBalance)) {
675 // remove hints from all amount inputs in that currency
676 for (int i = 1; i < list.size(); i++) {
677 TransactionAccount acc = list.get(i)
678 .toTransactionAccount();
679 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
680 if (BuildConfig.DEBUG)
681 Logger.debug("submittable",
682 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
683 i, Misc.nullIsEmpty(acc.getAccountName()),
685 // skip if the amount is set, in which case the hint is not
687 if (!acc.isAmountSet() && acc.amountHintIsSet &&
688 !TextUtils.isEmpty(acc.getAmountHint()))
690 acc.setAmountHint(null);
698 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
699 int balanceReceiversCount = tmpList.size();
700 if (balanceReceiversCount != 1) {
701 if (BuildConfig.DEBUG) {
702 if (balanceReceiversCount == 0)
703 Logger.debug("submittable", String.format(
704 "Transaction not submittable [curr:%s]: non-zero balance " +
705 "with no empty amounts with accounts", balCurrency));
707 Logger.debug("submittable", String.format(
708 "Transaction not submittable [curr:%s]: non-zero balance " +
709 "with multiple empty amounts with accounts", balCurrency));
714 List<Item> emptyAmountList =
715 itemsWithEmptyAmountForCurrency.getList(balCurrency);
717 // suggest off-balance amount to a row and remove hints on other rows
718 Item receiver = null;
719 if (!tmpList.isEmpty())
720 receiver = tmpList.get(0);
721 else if (!emptyAmountList.isEmpty())
722 receiver = emptyAmountList.get(0);
724 for (int i = 0; i < list.size(); i++) {
725 Item item = list.get(i);
726 if (!(item instanceof TransactionAccount))
729 TransactionAccount acc = item.toTransactionAccount();
730 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
733 if (item == receiver) {
734 final String hint = Data.formatNumber(-currencyBalance);
735 if (!acc.isAmountHintSet() ||
736 !Misc.equalStrings(acc.getAmountHint(), hint))
738 Logger.debug("submittable",
739 String.format("Setting amount hint of {%s} to %s [%s]",
740 acc.toString(), hint, balCurrency));
741 acc.setAmountHint(hint);
746 if (BuildConfig.DEBUG)
747 Logger.debug("submittable",
748 String.format("Resetting hint of '%s' [%s]",
749 Misc.nullIsEmpty(acc.getAccountName()),
751 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
752 acc.setAmountHint(null);
760 // 5) a row with an empty account name or empty amount is guaranteed to exist for
762 if (!hasInvalidAmount) {
763 for (String balCurrency : balance.currencies()) {
764 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
765 int currRows = itemsForCurrency.size(balCurrency);
766 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
767 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
768 if ((currEmptyRows == 0) &&
769 ((currRows == currAccounts) || (currRows == currAmounts)))
771 // perhaps there already is an unused empty row for another currency that
773 // boolean foundIt = false;
774 // for (Item item : emptyRows) {
775 // Currency itemCurrency = item.getCurrency();
776 // String itemCurrencyName =
777 // (itemCurrency == null) ? "" : itemCurrency.getName();
778 // if (Misc.isZero(balance.get(itemCurrencyName))) {
779 // item.setCurrency(Currency.loadByName(balCurrency));
780 // item.setAmountHint(
781 // Data.formatNumber(-balance.get(balCurrency)));
788 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
789 final float bal = balance.get(balCurrency);
790 if (!Misc.isZero(bal) && currAmounts == currRows)
791 newAcc.setAmountHint(Data.formatNumber(-bal));
792 Logger.debug("submittable",
793 String.format("Adding new item with %s for currency %s",
794 newAcc.getAmountHint(), balCurrency));
801 // drop extra empty rows, not needed
802 for (String currName : emptyRowsForCurrency.currencies()) {
803 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
804 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
805 // the list is a copy, so the empty item is no longer present
806 Item itemToRemove = emptyItems.remove(1);
807 removeItemById(list, itemToRemove.id);
811 // unused currency, remove last item (which is also an empty one)
812 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
813 List<Item> currItems = itemsForCurrency.getList(currName);
815 if (currItems.size() == 1) {
816 // the list is a copy, so the empty item is no longer present
817 removeItemById(list, emptyItems.get(0).id);
823 // 6) at least two rows need to be present in the ledger
824 // (the list also contains header and trailer)
825 while (list.size() < MIN_ITEMS) {
826 list.add(new TransactionAccount(""));
830 Logger.debug("submittable", submittable ? "YES" : "NO");
831 isSubmittable.setValue(submittable);
833 if (BuildConfig.DEBUG)
834 dumpItemList("After submittable checks", list);
836 catch (NumberFormatException e) {
837 Logger.debug("submittable", "NO (because of NumberFormatException)");
838 isSubmittable.setValue(false);
840 catch (Exception e) {
842 Logger.debug("submittable", "NO (because of an Exception)");
843 isSubmittable.setValue(false);
846 if (listChanged && workingWithLiveList) {
847 setItemsWithoutSubmittableChecks(list);
850 private void removeItemById(@NotNull List<Item> list, int id) {
851 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
852 list.removeIf(item -> item.id == id);
855 for (Item item : list) {
863 @SuppressLint("DefaultLocale")
864 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
865 Logger.debug("submittable", "== Dump of all items " + msg);
866 for (int i = 1; i < list.size(); i++) {
867 TransactionAccount item = list.get(i)
868 .toTransactionAccount();
869 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
872 public void setItemCurrency(int position, String newCurrency) {
873 TransactionAccount item = Objects.requireNonNull(items.getValue())
875 .toTransactionAccount();
876 final String oldCurrency = item.getCurrency();
878 if (Misc.equalStrings(oldCurrency, newCurrency))
881 List<Item> newList = copyList();
882 newList.get(position)
883 .toTransactionAccount()
884 .setCurrency(newCurrency);
888 public boolean accountListIsEmpty() {
889 List<Item> items = Objects.requireNonNull(this.items.getValue());
891 for (Item item : items) {
892 if (!(item instanceof TransactionAccount))
895 if (!((TransactionAccount) item).isEmpty())
902 public static class FocusInfo {
904 FocusedElement element;
905 public FocusInfo(int position, @Nullable FocusedElement element) {
906 this.position = position;
907 this.element = element;
911 static abstract class Item {
912 private static int idDispenser = 0;
915 if (this instanceof TransactionHead)
918 synchronized (Item.class) {
922 public Item(int id) {
925 public static Item from(Item origin) {
926 if (origin instanceof TransactionHead)
927 return new TransactionHead((TransactionHead) origin);
928 if (origin instanceof TransactionAccount)
929 return new TransactionAccount((TransactionAccount) origin);
930 throw new RuntimeException("Don't know how to handle " + origin);
932 private static void resetIdDispenser() {
938 public abstract ItemType getType();
939 public TransactionHead toTransactionHead() {
940 if (this instanceof TransactionHead)
941 return (TransactionHead) this;
943 throw new IllegalStateException("Wrong item type " + this);
945 public TransactionAccount toTransactionAccount() {
946 if (this instanceof TransactionAccount)
947 return (TransactionAccount) this;
949 throw new IllegalStateException("Wrong item type " + this);
951 public boolean equalContents(@Nullable Object item) {
955 if (!getClass().equals(item.getClass()))
958 // shortcut - comparing same instance
962 if (this instanceof TransactionHead)
963 return ((TransactionHead) item).equalContents((TransactionHead) this);
964 if (this instanceof TransactionAccount)
965 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
967 throw new RuntimeException("Don't know how to handle " + this);
972 //==========================================================================================
974 public static class TransactionHead extends Item {
975 private SimpleDate date;
976 private String description;
977 private String comment;
978 TransactionHead(String description) {
980 this.description = description;
982 public TransactionHead(TransactionHead origin) {
985 description = origin.description;
986 comment = origin.comment;
988 public SimpleDate getDate() {
991 public void setDate(SimpleDate date) {
994 public void setDate(String text) throws ParseException {
995 if (Misc.emptyIsNull(text) == null) {
1000 date = Globals.parseLedgerDate(text);
1003 * getFormattedDate()
1005 * @return nicely formatted, shortest available date representation
1007 String getFormattedDate() {
1011 Calendar today = GregorianCalendar.getInstance();
1013 if (today.get(Calendar.YEAR) != date.year) {
1014 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
1017 if (today.get(Calendar.MONTH) + 1 != date.month) {
1018 return String.format(Locale.US, "%d/%02d", date.month, date.day);
1021 return String.valueOf(date.day);
1025 public String toString() {
1026 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
1027 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1029 if (TextUtils.isEmpty(description))
1030 b.append(" «no description»");
1032 b.append(String.format(" '%s'", description));
1035 b.append(String.format("@%s", date.toString()));
1037 if (!TextUtils.isEmpty(comment))
1038 b.append(String.format(" /%s/", comment));
1040 return b.toString();
1042 public String getDescription() {
1045 public void setDescription(String description) {
1046 this.description = description;
1048 public String getComment() {
1051 public void setComment(String comment) {
1052 this.comment = comment;
1055 public ItemType getType() {
1056 return ItemType.generalData;
1058 public LedgerTransaction asLedgerTransaction() {
1059 return new LedgerTransaction(0, (date == null) ? SimpleDate.today() : date, description,
1060 Objects.requireNonNull(Data.getProfile()));
1062 public boolean equalContents(TransactionHead other) {
1066 return Objects.equals(date, other.date) &&
1067 Misc.equalStrings(description, other.description) &&
1068 Misc.equalStrings(comment, other.comment);
1072 public static class TransactionAccount extends Item {
1073 private String accountName;
1074 private String amountHint;
1075 private String comment;
1077 private String currency = "";
1078 private float amount;
1079 private boolean amountSet;
1080 private boolean amountValid = true;
1082 private String amountText = "";
1083 private FocusedElement focusedElement = FocusedElement.Account;
1084 private boolean amountHintIsSet = false;
1085 private boolean isLast = false;
1086 private int accountNameCursorPosition;
1087 public TransactionAccount(TransactionAccount origin) {
1089 accountName = origin.accountName;
1090 amount = origin.amount;
1091 amountSet = origin.amountSet;
1092 amountHint = origin.amountHint;
1093 amountHintIsSet = origin.amountHintIsSet;
1094 amountText = origin.amountText;
1095 comment = origin.comment;
1096 currency = origin.currency;
1097 amountValid = origin.amountValid;
1098 focusedElement = origin.focusedElement;
1099 isLast = origin.isLast;
1100 accountNameCursorPosition = origin.accountNameCursorPosition;
1102 public TransactionAccount(String accountName) {
1104 this.accountName = accountName;
1106 public TransactionAccount(String accountName, @NotNull String currency) {
1108 this.accountName = accountName;
1109 this.currency = currency;
1111 public @NotNull String getAmountText() {
1114 public void setAmountText(@NotNull String amountText) {
1115 this.amountText = amountText;
1117 public boolean setAndCheckAmountText(@NotNull String amountText) {
1118 String amtText = amountText.trim();
1119 this.amountText = amtText;
1121 boolean significantChange = false;
1123 if (amtText.isEmpty()) {
1125 significantChange = true;
1131 amtText = amtText.replace(Data.getDecimalSeparator(), Data.decimalDot);
1132 final float parsedAmount = Float.parseFloat(amtText);
1133 if (!amountSet || !amountValid || !Misc.equalFloats(parsedAmount, amount))
1134 significantChange = true;
1135 amount = parsedAmount;
1139 catch (NumberFormatException e) {
1140 Logger.debug("new-trans", String.format(
1141 "assuming amount is not set due to number format exception. " +
1142 "input was '%s'", amtText));
1143 if (amountValid) // it was valid and now it's not
1144 significantChange = true;
1145 amountValid = false;
1149 return significantChange;
1151 public boolean isLast() {
1154 public boolean isAmountSet() {
1157 public String getAccountName() {
1160 public void setAccountName(String accountName) {
1161 this.accountName = accountName;
1163 public float getAmount() {
1165 throw new IllegalStateException("Amount is not set");
1168 public void setAmount(float amount) {
1169 this.amount = amount;
1172 amountText = Data.formatNumber(amount);
1174 public void resetAmount() {
1180 public ItemType getType() {
1181 return ItemType.transactionRow;
1183 public String getAmountHint() {
1186 public void setAmountHint(String amountHint) {
1187 this.amountHint = amountHint;
1188 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1190 public String getComment() {
1193 public void setComment(String comment) {
1194 this.comment = comment;
1197 public String getCurrency() {
1200 public void setCurrency(@org.jetbrains.annotations.Nullable String currency) {
1201 this.currency = Misc.nullIsEmpty(currency);
1203 public boolean isAmountValid() {
1206 public void setAmountValid(boolean amountValid) {
1207 this.amountValid = amountValid;
1209 public FocusedElement getFocusedElement() {
1210 return focusedElement;
1212 public void setFocusedElement(FocusedElement focusedElement) {
1213 this.focusedElement = focusedElement;
1215 public boolean isAmountHintSet() {
1216 return amountHintIsSet;
1218 public void setAmountHintIsSet(boolean amountHintIsSet) {
1219 this.amountHintIsSet = amountHintIsSet;
1221 public boolean isEmpty() {
1222 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1223 Misc.emptyIsNull(comment) == null;
1225 @SuppressLint("DefaultLocale")
1228 public String toString() {
1229 StringBuilder b = new StringBuilder();
1230 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1231 if (!TextUtils.isEmpty(accountName))
1232 b.append(String.format(" acc'%s'", accountName));
1235 b.append(amountText)
1237 .append(amountValid ? "valid" : "invalid")
1239 .append(String.format(Locale.ROOT, " {raw %4.2f}", amount));
1240 else if (amountHintIsSet)
1241 b.append(String.format(" (hint %s)", amountHint));
1243 if (!TextUtils.isEmpty(currency))
1247 if (!TextUtils.isEmpty(comment))
1248 b.append(String.format(" /%s/", comment));
1253 return b.toString();
1255 public boolean equalContents(TransactionAccount other) {
1259 boolean equal = Misc.equalStrings(accountName, other.accountName);
1260 equal = equal && Misc.equalStrings(comment, other.comment) &&
1261 (amountSet ? other.amountSet && amountValid == other.amountValid &&
1262 Misc.equalStrings(amountText, other.amountText)
1263 : !other.amountSet);
1265 // compare amount hint only if there is no amount
1267 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1268 Misc.equalStrings(amountHint, other.amountHint)
1269 : !other.amountHintIsSet);
1270 equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1272 Logger.debug("new-trans",
1273 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1277 public int getAccountNameCursorPosition() {
1278 return accountNameCursorPosition;
1280 public void setAccountNameCursorPosition(int position) {
1281 this.accountNameCursorPosition = position;
1285 private static class BalanceForCurrency {
1286 private final HashMap<String, Float> hashMap = new HashMap<>();
1287 float get(String currencyName) {
1288 Float f = hashMap.get(currencyName);
1291 hashMap.put(currencyName, f);
1295 void add(String currencyName, float amount) {
1296 hashMap.put(currencyName, get(currencyName) + amount);
1298 Set<String> currencies() {
1299 return hashMap.keySet();
1301 boolean containsCurrency(String currencyName) {
1302 return hashMap.containsKey(currencyName);
1306 private static class ItemsForCurrency {
1307 private final HashMap<@NotNull String, List<Item>> hashMap = new HashMap<>();
1309 List<NewTransactionModel.Item> getList(@NotNull String currencyName) {
1310 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1312 list = new ArrayList<>();
1313 hashMap.put(currencyName, list);
1317 void add(@NotNull String currencyName, @NonNull NewTransactionModel.Item item) {
1318 getList(Objects.requireNonNull(currencyName)).add(item);
1320 int size(@NotNull String currencyName) {
1321 return this.getList(Objects.requireNonNull(currencyName))
1324 Set<String> currencies() {
1325 return hashMap.keySet();