2 * Copyright © 2021 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
9 * MoLe is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License terms for details.
14 * You should have received a copy of the GNU General Public License
15 * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.ui.new_transaction;
20 import android.annotation.SuppressLint;
21 import android.text.TextUtils;
23 import androidx.annotation.NonNull;
24 import androidx.annotation.Nullable;
25 import androidx.lifecycle.LifecycleOwner;
26 import androidx.lifecycle.LiveData;
27 import androidx.lifecycle.MutableLiveData;
28 import androidx.lifecycle.Observer;
29 import androidx.lifecycle.ViewModel;
31 import net.ktnx.mobileledger.BuildConfig;
32 import net.ktnx.mobileledger.db.Currency;
33 import net.ktnx.mobileledger.db.DB;
34 import net.ktnx.mobileledger.db.Profile;
35 import net.ktnx.mobileledger.db.TemplateAccount;
36 import net.ktnx.mobileledger.db.TemplateHeader;
37 import net.ktnx.mobileledger.db.TransactionWithAccounts;
38 import net.ktnx.mobileledger.model.Data;
39 import net.ktnx.mobileledger.model.InertMutableLiveData;
40 import net.ktnx.mobileledger.model.LedgerTransaction;
41 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
42 import net.ktnx.mobileledger.model.MatchedTemplate;
43 import net.ktnx.mobileledger.utils.Globals;
44 import net.ktnx.mobileledger.utils.Logger;
45 import net.ktnx.mobileledger.utils.Misc;
46 import net.ktnx.mobileledger.utils.SimpleDate;
48 import org.jetbrains.annotations.NotNull;
50 import java.text.ParseException;
51 import java.util.ArrayList;
52 import java.util.Calendar;
53 import java.util.GregorianCalendar;
54 import java.util.HashMap;
55 import java.util.List;
56 import java.util.Locale;
57 import java.util.Objects;
59 import java.util.concurrent.atomic.AtomicInteger;
60 import java.util.regex.MatchResult;
62 enum ItemType {generalData, transactionRow}
64 enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
67 public class NewTransactionModel extends ViewModel {
68 private static final int MIN_ITEMS = 3;
69 private final MutableLiveData<Boolean> showCurrency = new MutableLiveData<>(false);
70 private final MutableLiveData<Boolean> isSubmittable = new InertMutableLiveData<>(false);
71 private final MutableLiveData<Boolean> showComments = new MutableLiveData<>(true);
72 private final MutableLiveData<List<Item>> items = new MutableLiveData<>();
73 private final MutableLiveData<Boolean> simulateSave = new InertMutableLiveData<>(false);
74 private final AtomicInteger busyCounter = new AtomicInteger(0);
75 private final MutableLiveData<Boolean> busyFlag = new InertMutableLiveData<>(false);
76 private final Observer<Profile> profileObserver = profile -> {
77 showCurrency.postValue(profile.getShowCommodityByDefault());
78 showComments.postValue(profile.getShowCommentsByDefault());
80 private final MutableLiveData<FocusInfo> focusInfo = new MutableLiveData<>();
81 private boolean observingDataProfile;
82 public NewTransactionModel() {
85 public LiveData<Boolean> getShowCurrency() {
88 public LiveData<List<Item>> getItems() {
91 private void setItems(@NonNull List<Item> newList) {
92 checkTransactionSubmittable(newList);
93 setItemsWithoutSubmittableChecks(newList);
95 private void replaceItems(@NonNull List<Item> newList) {
101 * make old items replaceable in-place. makes the new values visually blend in
103 private void renumberItems() {
104 renumberItems(items.getValue());
106 private void renumberItems(List<Item> list) {
112 for (Item item : list)
115 private void setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
116 final int cnt = list.size();
117 for (int i = 1; i < cnt - 1; i++) {
118 final TransactionAccount item = list.get(i)
119 .toTransactionAccount();
121 TransactionAccount replacement = new TransactionAccount(item);
122 replacement.isLast = false;
123 list.set(i, replacement);
126 final TransactionAccount last = list.get(cnt - 1)
127 .toTransactionAccount();
129 TransactionAccount replacement = new TransactionAccount(last);
130 replacement.isLast = true;
131 list.set(cnt - 1, replacement);
134 if (BuildConfig.DEBUG)
135 dumpItemList("Before setValue()", list);
136 items.setValue(list);
138 private List<Item> copyList() {
139 List<Item> copy = new ArrayList<>();
140 List<Item> oldList = items.getValue();
143 for (Item item : oldList) {
144 copy.add(Item.from(item));
149 private List<Item> copyListWithoutItem(int position) {
150 List<Item> copy = new ArrayList<>();
151 List<Item> oldList = items.getValue();
153 if (oldList != null) {
155 for (Item item : oldList) {
158 copy.add(Item.from(item));
164 private List<Item> shallowCopyList() {
165 return new ArrayList<>(items.getValue());
167 LiveData<Boolean> getShowComments() {
170 void observeDataProfile(LifecycleOwner activity) {
171 if (!observingDataProfile)
172 Data.observeProfile(activity, profileObserver);
173 observingDataProfile = true;
175 boolean getSimulateSaveFlag() {
176 Boolean value = simulateSave.getValue();
181 LiveData<Boolean> getSimulateSave() {
184 void toggleSimulateSave() {
185 simulateSave.setValue(!getSimulateSaveFlag());
187 LiveData<Boolean> isSubmittable() {
188 return this.isSubmittable;
191 Logger.debug("new-trans", "Resetting model");
192 List<Item> list = new ArrayList<>();
193 Item.resetIdDispenser();
194 list.add(new TransactionHead(""));
195 final String defaultCurrency = Objects.requireNonNull(Data.getProfile())
196 .getDefaultCommodity();
197 list.add(new TransactionAccount("", defaultCurrency));
198 list.add(new TransactionAccount("", defaultCurrency));
199 noteFocusChanged(0, FocusedElement.Description);
201 isSubmittable.setValue(false);
202 setItemsWithoutSubmittableChecks(list);
204 boolean accountsInInitialState() {
205 final List<Item> list = items.getValue();
210 for (Item item : list) {
211 if (!(item instanceof TransactionAccount))
214 TransactionAccount accRow = (TransactionAccount) item;
215 if (!accRow.isEmpty())
221 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
222 SimpleDate transactionDate = null;
223 final MatchResult matchResult = matchedTemplate.matchResult;
224 final TemplateHeader templateHead = matchedTemplate.templateHead;
226 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
227 templateHead.getDateDay());
228 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
229 templateHead.getDateMonth());
230 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
231 templateHead.getDateYear());
233 if (year > 0 || month > 0 || day > 0) {
234 SimpleDate today = SimpleDate.today();
242 transactionDate = new SimpleDate(year, month, day);
244 Logger.debug("pattern", "setting transaction date to " + transactionDate);
248 List<Item> present = copyList();
250 TransactionHead head = new TransactionHead(present.get(0)
251 .toTransactionHead());
252 if (transactionDate != null)
253 head.setDate(transactionDate);
255 final String transactionDescription = extractStringFromMatches(matchResult,
256 templateHead.getTransactionDescriptionMatchGroup(),
257 templateHead.getTransactionDescription());
258 if (Misc.emptyIsNull(transactionDescription) != null)
259 head.setDescription(transactionDescription);
261 final String transactionComment = extractStringFromMatches(matchResult,
262 templateHead.getTransactionCommentMatchGroup(),
263 templateHead.getTransactionComment());
264 if (Misc.emptyIsNull(transactionComment) != null)
265 head.setComment(transactionComment);
267 List<Item> newItems = new ArrayList<>();
271 for (int i = 1; i < present.size(); i++) {
272 final TransactionAccount row = present.get(i)
273 .toTransactionAccount();
275 newItems.add(new TransactionAccount(row));
280 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
282 final boolean accountsInInitialState = accountsInInitialState();
283 for (TemplateAccount acc : entry.accounts) {
287 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
288 acc.getAccountName());
289 String accountComment =
290 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
291 acc.getAccountComment());
292 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
294 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
297 TransactionAccount accRow = new TransactionAccount(accountName);
298 accRow.setComment(accountComment);
300 accRow.setAmount(amount);
302 extractCurrencyFromMatches(matchResult, acc.getCurrencyMatchGroup(),
303 acc.getCurrencyObject()));
305 newItems.add(accRow);
308 renumberItems(newItems);
309 Misc.onMainThread(() -> replaceItems(newItems));
312 private String extractCurrencyFromMatches(MatchResult m, Integer group, Currency literal) {
313 return extractStringFromMatches(m, group, (literal == null) ? "" : literal.getName());
315 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
321 if (grp > 0 && grp <= m.groupCount())
323 return Integer.parseInt(m.group(grp));
325 catch (NumberFormatException e) {
326 Logger.debug("new-trans", "Error extracting matched number", e);
332 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
338 if (grp > 0 && grp <= m.groupCount())
344 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
350 if (grp > 0 && grp <= m.groupCount())
352 return Float.valueOf(m.group(grp));
354 catch (NumberFormatException e) {
355 Logger.debug("new-trans", "Error extracting matched number", e);
361 void removeItem(int pos) {
362 Logger.debug("new-trans", String.format(Locale.US, "Removing item at position %d", pos));
363 List<Item> newList = copyListWithoutItem(pos);
364 final FocusInfo fi = focusInfo.getValue();
365 if ((fi != null) && (pos < fi.position))
366 noteFocusChanged(fi.position - 1, fi.element);
369 void noteFocusChanged(int position, FocusedElement element) {
370 FocusInfo present = focusInfo.getValue();
371 if (present == null || present.position != position || present.element != element)
372 focusInfo.setValue(new FocusInfo(position, element));
374 public LiveData<FocusInfo> getFocusInfo() {
377 void moveItem(int fromIndex, int toIndex) {
378 List<Item> newList = shallowCopyList();
379 Item item = newList.remove(fromIndex);
380 newList.add(toIndex, item);
382 FocusInfo fi = focusInfo.getValue();
383 if (fi != null && fi.position == fromIndex)
384 noteFocusChanged(toIndex, fi.element);
386 items.setValue(newList); // same count, same submittable state
388 void moveItemLast(List<Item> list, int index) {
392 3 <-- desired position
395 int itemCount = list.size();
397 if (index < itemCount - 1)
398 list.add(list.remove(index));
400 void toggleCurrencyVisible() {
401 final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
403 // remove currency from all items, or reset currency to the default
404 // no need to clone the list, because the removal of the currency won't lead to
405 // visual changes -- the currency fields will be hidden or reset to default anyway
406 // still, there may be changes in the submittable state
407 final List<Item> list = Objects.requireNonNull(this.items.getValue());
408 for (int i = 1; i < list.size(); i++) {
409 ((TransactionAccount) list.get(i)).setCurrency(newValue ? Data.getProfile()
410 .getDefaultCommodity()
413 checkTransactionSubmittable(null);
414 showCurrency.setValue(newValue);
416 void stopObservingBusyFlag(Observer<Boolean> observer) {
417 busyFlag.removeObserver(observer);
419 void incrementBusyCounter() {
420 int newValue = busyCounter.incrementAndGet();
422 busyFlag.postValue(true);
424 void decrementBusyCounter() {
425 int newValue = busyCounter.decrementAndGet();
427 busyFlag.postValue(false);
429 public LiveData<Boolean> getBusyFlag() {
432 public void toggleShowComments() {
433 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
435 public LedgerTransaction constructLedgerTransaction() {
436 List<Item> list = Objects.requireNonNull(items.getValue());
437 TransactionHead head = list.get(0)
438 .toTransactionHead();
439 LedgerTransaction tr = head.asLedgerTransaction();
441 tr.setComment(head.getComment());
442 LedgerTransactionAccount emptyAmountAccount = null;
443 float emptyAmountAccountBalance = 0;
444 for (int i = 1; i < list.size(); i++) {
445 TransactionAccount item = list.get(i)
446 .toTransactionAccount();
447 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
450 if (acc.getAccountName()
454 acc.setComment(item.getComment());
456 if (item.isAmountSet()) {
457 acc.setAmount(item.getAmount());
458 emptyAmountAccountBalance += item.getAmount();
461 emptyAmountAccount = acc;
467 if (emptyAmountAccount != null)
468 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
472 void loadTransactionIntoModel(@NonNull TransactionWithAccounts tr) {
473 List<Item> newList = new ArrayList<>();
474 Item.resetIdDispenser();
476 Item currentHead = items.getValue()
478 TransactionHead head = new TransactionHead(tr.transaction.getDescription());
479 head.setComment(tr.transaction.getComment());
480 if (currentHead instanceof TransactionHead)
481 head.setDate(((TransactionHead) currentHead).date);
485 List<LedgerTransactionAccount> accounts = new ArrayList<>();
486 for (net.ktnx.mobileledger.db.TransactionAccount acc : tr.accounts) {
487 accounts.add(new LedgerTransactionAccount(acc));
490 TransactionAccount firstNegative = null;
491 TransactionAccount firstPositive = null;
492 int singleNegativeIndex = -1;
493 int singlePositiveIndex = -1;
494 int negativeCount = 0;
495 for (int i = 0; i < accounts.size(); i++) {
496 LedgerTransactionAccount acc = accounts.get(i);
497 TransactionAccount item =
498 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
501 item.setAccountName(acc.getAccountName());
502 item.setComment(acc.getComment());
503 if (acc.isAmountSet()) {
504 item.setAmount(acc.getAmount());
505 if (acc.getAmount() < 0) {
506 if (firstNegative == null) {
507 firstNegative = item;
508 singleNegativeIndex = i + 1;
511 singleNegativeIndex = -1;
514 if (firstPositive == null) {
515 firstPositive = item;
516 singlePositiveIndex = i + 1;
519 singlePositiveIndex = -1;
525 if (BuildConfig.DEBUG)
526 dumpItemList("Loaded previous transaction", newList);
528 if (singleNegativeIndex != -1) {
529 firstNegative.resetAmount();
530 moveItemLast(newList, singleNegativeIndex);
532 else if (singlePositiveIndex != -1) {
533 firstPositive.resetAmount();
534 moveItemLast(newList, singlePositiveIndex);
537 Misc.onMainThread(() -> {
539 noteFocusChanged(1, FocusedElement.Amount);
543 * A transaction is submittable if:
545 * 1) has at least two account names
546 * 2) each row with amount has account name
547 * 3) for each commodity:
548 * 3a) amounts must balance to 0, or
549 * 3b) there must be exactly one empty amount (with account)
550 * 4) empty accounts with empty amounts are ignored
552 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
554 * 6) at least two rows need to be present in the ledger
556 * @param list - the item list to check. Can be the displayed list or a list that will be
559 @SuppressLint("DefaultLocale")
560 void checkTransactionSubmittable(@Nullable List<Item> list) {
561 boolean workingWithLiveList = false;
564 workingWithLiveList = true;
567 if (BuildConfig.DEBUG)
568 dumpItemList(String.format("Before submittable checks (%s)",
569 workingWithLiveList ? "LIVE LIST" : "custom list"), list);
572 final BalanceForCurrency balance = new BalanceForCurrency();
573 final String descriptionText = list.get(0)
576 boolean submittable = true;
577 boolean listChanged = false;
578 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
579 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
580 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
581 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
582 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
583 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
584 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
585 final List<Item> emptyRows = new ArrayList<>();
588 if ((descriptionText == null) || descriptionText.trim()
591 Logger.debug("submittable", "Transaction not submittable: missing description");
595 for (int i = 1; i < list.size(); i++) {
596 TransactionAccount item = list.get(i)
597 .toTransactionAccount();
599 String accName = item.getAccountName()
601 String currName = item.getCurrency();
603 itemsForCurrency.add(currName, item);
605 if (accName.isEmpty()) {
606 itemsWithEmptyAccountForCurrency.add(currName, item);
608 if (item.isAmountSet()) {
609 // 2) each amount has account name
610 Logger.debug("submittable", String.format(
611 "Transaction not submittable: row %d has no account name, but" +
612 " has" + " amount %1.2f", i + 1, item.getAmount()));
616 emptyRowsForCurrency.add(currName, item);
621 itemsWithAccountForCurrency.add(currName, item);
624 if (!item.isAmountValid()) {
625 Logger.debug("submittable",
626 String.format("Not submittable: row %d has an invalid amount", i + 1));
629 else if (item.isAmountSet()) {
630 itemsWithAmountForCurrency.add(currName, item);
631 balance.add(currName, item.getAmount());
634 itemsWithEmptyAmountForCurrency.add(currName, item);
636 if (!accName.isEmpty())
637 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
641 // 1) has at least two account names
644 Logger.debug("submittable", "Transaction not submittable: no account names");
645 else if (accounts == 1)
646 Logger.debug("submittable",
647 "Transaction not submittable: only one account name");
649 Logger.debug("submittable",
650 String.format("Transaction not submittable: only %d account names",
655 // 3) for each commodity:
656 // 3a) amount must balance to 0, or
657 // 3b) there must be exactly one empty amount (with account)
658 for (String balCurrency : itemsForCurrency.currencies()) {
659 float currencyBalance = balance.get(balCurrency);
660 if (Misc.isZero(currencyBalance)) {
661 // remove hints from all amount inputs in that currency
662 for (int i = 1; i < list.size(); i++) {
663 TransactionAccount acc = list.get(i)
664 .toTransactionAccount();
665 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
666 if (BuildConfig.DEBUG)
667 Logger.debug("submittable",
668 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
669 i, Misc.nullIsEmpty(acc.getAccountName()),
671 // skip if the amount is set, in which case the hint is not
673 if (!acc.isAmountSet() && acc.amountHintIsSet &&
674 !TextUtils.isEmpty(acc.getAmountHint()))
676 acc.setAmountHint(null);
684 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
685 int balanceReceiversCount = tmpList.size();
686 if (balanceReceiversCount != 1) {
687 if (BuildConfig.DEBUG) {
688 if (balanceReceiversCount == 0)
689 Logger.debug("submittable", String.format(
690 "Transaction not submittable [%s]: non-zero balance " +
691 "with no empty amounts with accounts", balCurrency));
693 Logger.debug("submittable", String.format(
694 "Transaction not submittable [%s]: non-zero balance " +
695 "with multiple empty amounts with accounts", balCurrency));
700 List<Item> emptyAmountList =
701 itemsWithEmptyAmountForCurrency.getList(balCurrency);
703 // suggest off-balance amount to a row and remove hints on other rows
704 Item receiver = null;
705 if (!tmpList.isEmpty())
706 receiver = tmpList.get(0);
707 else if (!emptyAmountList.isEmpty())
708 receiver = emptyAmountList.get(0);
710 for (int i = 0; i < list.size(); i++) {
711 Item item = list.get(i);
712 if (!(item instanceof TransactionAccount))
715 TransactionAccount acc = item.toTransactionAccount();
716 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
719 if (item == receiver) {
720 final String hint = String.format("%1.2f", -currencyBalance);
721 if (!acc.isAmountHintSet() ||
722 !Misc.equalStrings(acc.getAmountHint(), hint))
724 Logger.debug("submittable",
725 String.format("Setting amount hint of {%s} to %s [%s]",
726 acc.toString(), hint, balCurrency));
727 acc.setAmountHint(hint);
732 if (BuildConfig.DEBUG)
733 Logger.debug("submittable",
734 String.format("Resetting hint of '%s' [%s]",
735 Misc.nullIsEmpty(acc.getAccountName()),
737 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
738 acc.setAmountHint(null);
746 // 5) a row with an empty account name or empty amount is guaranteed to exist for
748 for (String balCurrency : balance.currencies()) {
749 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
750 int currRows = itemsForCurrency.size(balCurrency);
751 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
752 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
753 if ((currEmptyRows == 0) &&
754 ((currRows == currAccounts) || (currRows == currAmounts)))
756 // perhaps there already is an unused empty row for another currency that
758 // boolean foundIt = false;
759 // for (Item item : emptyRows) {
760 // Currency itemCurrency = item.getCurrency();
761 // String itemCurrencyName =
762 // (itemCurrency == null) ? "" : itemCurrency.getName();
763 // if (Misc.isZero(balance.get(itemCurrencyName))) {
764 // item.setCurrency(Currency.loadByName(balCurrency));
765 // item.setAmountHint(
766 // String.format("%1.2f", -balance.get(balCurrency)));
773 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
774 final float bal = balance.get(balCurrency);
775 if (!Misc.isZero(bal) && currAmounts == currRows)
776 newAcc.setAmountHint(String.format("%4.2f", -bal));
777 Logger.debug("submittable",
778 String.format("Adding new item with %s for currency %s",
779 newAcc.getAmountHint(), balCurrency));
785 // drop extra empty rows, not needed
786 for (String currName : emptyRowsForCurrency.currencies()) {
787 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
788 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
789 // the list is a copy, so the empty item is no longer present
790 Item itemToRemove = emptyItems.remove(1);
791 removeItemById(list, itemToRemove.id);
795 // unused currency, remove last item (which is also an empty one)
796 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
797 List<Item> currItems = itemsForCurrency.getList(currName);
799 if (currItems.size() == 1) {
800 // the list is a copy, so the empty item is no longer present
801 removeItemById(list, emptyItems.get(0).id);
807 // 6) at least two rows need to be present in the ledger
808 // (the list also contains header and trailer)
809 while (list.size() < MIN_ITEMS) {
810 list.add(new TransactionAccount(""));
814 Logger.debug("submittable", submittable ? "YES" : "NO");
815 isSubmittable.setValue(submittable);
817 if (BuildConfig.DEBUG)
818 dumpItemList("After submittable checks", list);
820 catch (NumberFormatException e) {
821 Logger.debug("submittable", "NO (because of NumberFormatException)");
822 isSubmittable.setValue(false);
824 catch (Exception e) {
826 Logger.debug("submittable", "NO (because of an Exception)");
827 isSubmittable.setValue(false);
830 if (listChanged && workingWithLiveList) {
831 setItemsWithoutSubmittableChecks(list);
834 private void removeItemById(@NotNull List<Item> list, int id) {
835 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
836 list.removeIf(item -> item.id == id);
839 for (Item item : list) {
847 @SuppressLint("DefaultLocale")
848 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
849 Logger.debug("submittable", "== Dump of all items " + msg);
850 for (int i = 1; i < list.size(); i++) {
851 TransactionAccount item = list.get(i)
852 .toTransactionAccount();
853 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
856 public void setItemCurrency(int position, String newCurrency) {
857 TransactionAccount item = Objects.requireNonNull(items.getValue())
859 .toTransactionAccount();
860 final String oldCurrency = item.getCurrency();
862 if (Misc.equalStrings(oldCurrency, newCurrency))
865 List<Item> newList = copyList();
866 newList.get(position)
867 .toTransactionAccount()
868 .setCurrency(newCurrency);
872 public boolean accountListIsEmpty() {
873 List<Item> items = Objects.requireNonNull(this.items.getValue());
875 for (Item item : items) {
876 if (!(item instanceof TransactionAccount))
879 if (!((TransactionAccount) item).isEmpty())
886 public static class FocusInfo {
888 FocusedElement element;
889 public FocusInfo(int position, FocusedElement element) {
890 this.position = position;
891 this.element = element;
895 static abstract class Item {
896 private static int idDispenser = 0;
899 if (this instanceof TransactionHead)
902 synchronized (Item.class) {
906 public Item(int id) {
909 public static Item from(Item origin) {
910 if (origin instanceof TransactionHead)
911 return new TransactionHead((TransactionHead) origin);
912 if (origin instanceof TransactionAccount)
913 return new TransactionAccount((TransactionAccount) origin);
914 throw new RuntimeException("Don't know how to handle " + origin);
916 private static void resetIdDispenser() {
922 public abstract ItemType getType();
923 public TransactionHead toTransactionHead() {
924 if (this instanceof TransactionHead)
925 return (TransactionHead) this;
927 throw new IllegalStateException("Wrong item type " + this);
929 public TransactionAccount toTransactionAccount() {
930 if (this instanceof TransactionAccount)
931 return (TransactionAccount) this;
933 throw new IllegalStateException("Wrong item type " + this);
935 public boolean equalContents(@Nullable Object item) {
939 if (!getClass().equals(item.getClass()))
942 // shortcut - comparing same instance
946 if (this instanceof TransactionHead)
947 return ((TransactionHead) item).equalContents((TransactionHead) this);
948 if (this instanceof TransactionAccount)
949 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
951 throw new RuntimeException("Don't know how to handle " + this);
956 //==========================================================================================
958 public static class TransactionHead extends Item {
959 private SimpleDate date;
960 private String description;
961 private String comment;
962 TransactionHead(String description) {
964 this.description = description;
966 public TransactionHead(TransactionHead origin) {
969 description = origin.description;
970 comment = origin.comment;
972 public SimpleDate getDate() {
975 public void setDate(SimpleDate date) {
978 public void setDate(String text) throws ParseException {
979 if (Misc.emptyIsNull(text) == null) {
984 date = Globals.parseLedgerDate(text);
989 * @return nicely formatted, shortest available date representation
991 String getFormattedDate() {
995 Calendar today = GregorianCalendar.getInstance();
997 if (today.get(Calendar.YEAR) != date.year) {
998 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
1001 if (today.get(Calendar.MONTH) + 1 != date.month) {
1002 return String.format(Locale.US, "%d/%02d", date.month, date.day);
1005 return String.valueOf(date.day);
1009 public String toString() {
1010 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
1011 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1013 if (TextUtils.isEmpty(description))
1014 b.append(" «no description»");
1016 b.append(String.format(" '%s'", description));
1019 b.append(String.format("@%s", date.toString()));
1021 if (!TextUtils.isEmpty(comment))
1022 b.append(String.format(" /%s/", comment));
1024 return b.toString();
1026 public String getDescription() {
1029 public void setDescription(String description) {
1030 this.description = description;
1032 public String getComment() {
1035 public void setComment(String comment) {
1036 this.comment = comment;
1039 public ItemType getType() {
1040 return ItemType.generalData;
1042 public LedgerTransaction asLedgerTransaction() {
1043 return new LedgerTransaction(0, (date == null) ? SimpleDate.today() : date, description,
1046 public boolean equalContents(TransactionHead other) {
1050 return Objects.equals(date, other.date) &&
1051 Misc.equalStrings(description, other.description) &&
1052 Misc.equalStrings(comment, other.comment);
1056 public static class TransactionAccount extends Item {
1057 private String accountName;
1058 private String amountHint;
1059 private String comment;
1060 private String currency;
1061 private float amount;
1062 private boolean amountSet;
1063 private boolean amountValid = true;
1064 private FocusedElement focusedElement = FocusedElement.Account;
1065 private boolean amountHintIsSet = false;
1066 private boolean isLast = false;
1067 private int accountNameCursorPosition;
1068 public TransactionAccount(TransactionAccount origin) {
1070 accountName = origin.accountName;
1071 amount = origin.amount;
1072 amountSet = origin.amountSet;
1073 amountHint = origin.amountHint;
1074 amountHintIsSet = origin.amountHintIsSet;
1075 comment = origin.comment;
1076 currency = origin.currency;
1077 amountValid = origin.amountValid;
1078 focusedElement = origin.focusedElement;
1079 isLast = origin.isLast;
1080 accountNameCursorPosition = origin.accountNameCursorPosition;
1082 public TransactionAccount(LedgerTransactionAccount account) {
1084 currency = account.getCurrency();
1085 amount = account.getAmount();
1087 public TransactionAccount(String accountName) {
1089 this.accountName = accountName;
1091 public TransactionAccount(String accountName, String currency) {
1093 this.accountName = accountName;
1094 this.currency = currency;
1096 public boolean isLast() {
1099 public boolean isAmountSet() {
1102 public String getAccountName() {
1105 public void setAccountName(String accountName) {
1106 this.accountName = accountName;
1108 public float getAmount() {
1110 throw new IllegalStateException("Amount is not set");
1113 public void setAmount(float amount) {
1114 this.amount = amount;
1117 public void resetAmount() {
1121 public ItemType getType() {
1122 return ItemType.transactionRow;
1124 public String getAmountHint() {
1127 public void setAmountHint(String amountHint) {
1128 this.amountHint = amountHint;
1129 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1131 public String getComment() {
1134 public void setComment(String comment) {
1135 this.comment = comment;
1137 public String getCurrency() {
1140 public void setCurrency(String currency) {
1141 this.currency = currency;
1143 public boolean isAmountValid() {
1146 public void setAmountValid(boolean amountValid) {
1147 this.amountValid = amountValid;
1149 public FocusedElement getFocusedElement() {
1150 return focusedElement;
1152 public void setFocusedElement(FocusedElement focusedElement) {
1153 this.focusedElement = focusedElement;
1155 public boolean isAmountHintSet() {
1156 return amountHintIsSet;
1158 public void setAmountHintIsSet(boolean amountHintIsSet) {
1159 this.amountHintIsSet = amountHintIsSet;
1161 public boolean isEmpty() {
1162 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1163 Misc.emptyIsNull(comment) == null;
1165 @SuppressLint("DefaultLocale")
1167 public String toString() {
1168 StringBuilder b = new StringBuilder();
1169 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1170 if (!TextUtils.isEmpty(accountName))
1171 b.append(String.format(" acc'%s'", accountName));
1174 b.append(String.format(" %4.2f", amount));
1175 else if (amountHintIsSet)
1176 b.append(String.format(" (%s)", amountHint));
1178 if (!TextUtils.isEmpty(currency))
1182 if (!TextUtils.isEmpty(comment))
1183 b.append(String.format(" /%s/", comment));
1188 return b.toString();
1190 public boolean equalContents(TransactionAccount other) {
1194 boolean equal = Misc.equalStrings(accountName, other.accountName);
1195 equal = equal && Misc.equalStrings(comment, other.comment) &&
1196 (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1198 // compare amount hint only if there is no amount
1200 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1201 Misc.equalStrings(amountHint, other.amountHint)
1202 : !other.amountHintIsSet);
1203 equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1205 Logger.debug("new-trans",
1206 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1210 public int getAccountNameCursorPosition() {
1211 return accountNameCursorPosition;
1213 public void setAccountNameCursorPosition(int position) {
1214 this.accountNameCursorPosition = position;
1218 private static class BalanceForCurrency {
1219 private final HashMap<String, Float> hashMap = new HashMap<>();
1220 float get(String currencyName) {
1221 Float f = hashMap.get(currencyName);
1224 hashMap.put(currencyName, f);
1228 void add(String currencyName, float amount) {
1229 hashMap.put(currencyName, get(currencyName) + amount);
1231 Set<String> currencies() {
1232 return hashMap.keySet();
1234 boolean containsCurrency(String currencyName) {
1235 return hashMap.containsKey(currencyName);
1239 private static class ItemsForCurrency {
1240 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1242 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1243 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1245 list = new ArrayList<>();
1246 hashMap.put(currencyName, list);
1250 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1251 getList(currencyName).add(item);
1253 int size(@Nullable String currencyName) {
1254 return this.getList(currencyName)
1257 Set<String> currencies() {
1258 return hashMap.keySet();