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.os.Handler;
22 import android.os.Looper;
23 import android.text.TextUtils;
25 import androidx.annotation.NonNull;
26 import androidx.annotation.Nullable;
27 import androidx.lifecycle.LifecycleOwner;
28 import androidx.lifecycle.LiveData;
29 import androidx.lifecycle.MutableLiveData;
30 import androidx.lifecycle.Observer;
31 import androidx.lifecycle.ViewModel;
33 import net.ktnx.mobileledger.BuildConfig;
34 import net.ktnx.mobileledger.db.DB;
35 import net.ktnx.mobileledger.db.TemplateAccount;
36 import net.ktnx.mobileledger.db.TemplateHeader;
37 import net.ktnx.mobileledger.model.Data;
38 import net.ktnx.mobileledger.model.InertMutableLiveData;
39 import net.ktnx.mobileledger.model.LedgerTransaction;
40 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
41 import net.ktnx.mobileledger.model.MatchedTemplate;
42 import net.ktnx.mobileledger.model.MobileLedgerProfile;
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<MobileLedgerProfile> 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 setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
96 Logger.debug("new-trans", "model: Setting new item list");
97 final int cnt = list.size();
98 for (int i = 1; i < cnt - 1; i++) {
99 final TransactionAccount item = list.get(i)
100 .toTransactionAccount();
102 TransactionAccount replacement = new TransactionAccount(item);
103 replacement.isLast = false;
104 list.set(i, replacement);
107 final TransactionAccount last = list.get(cnt - 1)
108 .toTransactionAccount();
110 TransactionAccount replacement = new TransactionAccount(last);
111 replacement.isLast = true;
112 list.set(cnt - 1, replacement);
115 items.setValue(list);
117 private List<Item> copyList() {
118 return copyList(null);
120 private List<Item> copyList(@Nullable List<Item> source) {
121 List<Item> copy = new ArrayList<>();
122 List<Item> oldList = (source == null) ? items.getValue() : source;
125 for (Item item : oldList) {
126 copy.add(Item.from(item));
131 private List<Item> shallowCopyListWithoutItem(int position) {
132 List<Item> copy = new ArrayList<>();
133 List<Item> oldList = items.getValue();
135 if (oldList != null) {
137 for (Item item : oldList) {
146 private List<Item> shallowCopyList() {
147 return new ArrayList<>(items.getValue());
149 LiveData<Boolean> getShowComments() {
152 void observeDataProfile(LifecycleOwner activity) {
153 if (!observingDataProfile)
154 Data.observeProfile(activity, profileObserver);
155 observingDataProfile = true;
157 boolean getSimulateSaveFlag() {
158 Boolean value = simulateSave.getValue();
163 LiveData<Boolean> getSimulateSave() {
166 void toggleSimulateSave() {
167 simulateSave.setValue(!getSimulateSaveFlag());
169 LiveData<Boolean> isSubmittable() {
170 return this.isSubmittable;
173 Logger.debug("new-trans", "Resetting model");
174 List<Item> list = new ArrayList<>();
175 list.add(new TransactionHead(""));
176 list.add(new TransactionAccount(""));
177 list.add(new TransactionAccount(""));
178 noteFocusChanged(0, FocusedElement.Description);
179 isSubmittable.setValue(false);
180 setItemsWithoutSubmittableChecks(list);
182 boolean accountsInInitialState() {
183 final List<Item> list = items.getValue();
188 for (Item item : list) {
189 if (!(item instanceof TransactionAccount))
192 TransactionAccount accRow = (TransactionAccount) item;
193 if (!accRow.isEmpty())
199 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
200 SimpleDate transactionDate = null;
201 final MatchResult matchResult = matchedTemplate.matchResult;
202 final TemplateHeader templateHead = matchedTemplate.templateHead;
204 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
205 templateHead.getDateDay());
206 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
207 templateHead.getDateMonth());
208 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
209 templateHead.getDateYear());
211 if (year > 0 || month > 0 || day > 0) {
212 SimpleDate today = SimpleDate.today();
220 transactionDate = new SimpleDate(year, month, day);
222 Logger.debug("pattern", "setting transaction date to " + transactionDate);
226 List<Item> present = copyList();
228 TransactionHead head = new TransactionHead(present.get(0)
229 .toTransactionHead());
230 if (transactionDate != null)
231 head.setDate(transactionDate);
233 final String transactionDescription = extractStringFromMatches(matchResult,
234 templateHead.getTransactionDescriptionMatchGroup(),
235 templateHead.getTransactionDescription());
236 if (Misc.emptyIsNull(transactionDescription) != null)
237 head.setDescription(transactionDescription);
239 final String transactionComment = extractStringFromMatches(matchResult,
240 templateHead.getTransactionCommentMatchGroup(),
241 templateHead.getTransactionComment());
242 if (Misc.emptyIsNull(transactionComment) != null)
243 head.setComment(transactionComment);
245 List<Item> newItems = new ArrayList<>();
249 for (int i = 1; i < present.size(); i++) {
250 final TransactionAccount row = present.get(i)
251 .toTransactionAccount();
253 newItems.add(new TransactionAccount(row));
258 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
260 final boolean accountsInInitialState = accountsInInitialState();
261 for (TemplateAccount acc : entry.accounts) {
265 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
266 acc.getAccountName());
267 String accountComment =
268 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
269 acc.getAccountComment());
270 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
272 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
276 TransactionAccount accRow = new TransactionAccount(accountName);
277 accRow.setComment(accountComment);
279 accRow.setAmount(amount);
281 newItems.add(accRow);
284 new Handler(Looper.getMainLooper()).post(() -> setItems(newItems));
287 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
293 if (grp > 0 & grp <= m.groupCount())
295 return Integer.parseInt(m.group(grp));
297 catch (NumberFormatException e) {
298 Logger.debug("new-trans", "Error extracting matched number", e);
304 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
310 if (grp > 0 & grp <= m.groupCount())
316 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
322 if (grp > 0 & grp <= m.groupCount())
324 return Float.valueOf(m.group(grp));
326 catch (NumberFormatException e) {
327 Logger.debug("new-trans", "Error extracting matched number", e);
333 void removeItem(int pos) {
334 List<Item> newList = shallowCopyListWithoutItem(pos);
337 void noteFocusChanged(int position, FocusedElement element) {
338 FocusInfo present = focusInfo.getValue();
339 if (present == null || present.position != position || present.element != element)
340 focusInfo.setValue(new FocusInfo(position, element));
342 public LiveData<FocusInfo> getFocusInfo() {
345 void moveItem(int fromIndex, int toIndex) {
346 List<Item> newList = shallowCopyList();
347 Item item = newList.remove(fromIndex);
348 newList.add(toIndex, item);
349 items.setValue(newList); // same count, same submittable state
351 void moveItemLast(List<Item> list, int index) {
355 3 <-- desired position
358 int itemCount = list.size();
360 if (index < itemCount - 1)
361 list.add(list.remove(index));
363 void toggleCurrencyVisible() {
364 final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
366 // remove currency from all items, or reset currency to the default
367 // no need to clone the list, because the removal of the currency won't lead to
368 // visual changes -- the currency fields will be hidden or reset to default anyway
369 // still, there may be changes in the submittable state
370 final List<Item> list = Objects.requireNonNull(this.items.getValue());
371 for (int i = 1; i < list.size(); i++) {
372 ((TransactionAccount) list.get(i)).setCurrency(newValue ? Data.getProfile()
373 .getDefaultCommodity()
376 checkTransactionSubmittable(null);
377 showCurrency.setValue(newValue);
379 void stopObservingBusyFlag(Observer<Boolean> observer) {
380 busyFlag.removeObserver(observer);
382 void incrementBusyCounter() {
383 int newValue = busyCounter.incrementAndGet();
385 busyFlag.postValue(true);
387 void decrementBusyCounter() {
388 int newValue = busyCounter.decrementAndGet();
390 busyFlag.postValue(false);
392 public LiveData<Boolean> getBusyFlag() {
395 public void toggleShowComments() {
396 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
398 public LedgerTransaction constructLedgerTransaction() {
399 List<Item> list = Objects.requireNonNull(items.getValue());
400 TransactionHead head = list.get(0)
401 .toTransactionHead();
402 SimpleDate date = head.getDate();
403 LedgerTransaction tr = head.asLedgerTransaction();
405 tr.setComment(head.getComment());
406 LedgerTransactionAccount emptyAmountAccount = null;
407 float emptyAmountAccountBalance = 0;
408 for (int i = 1; i < list.size(); i++) {
409 TransactionAccount item = list.get(i)
410 .toTransactionAccount();
411 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
414 if (acc.getAccountName()
418 acc.setComment(item.getComment());
420 if (item.isAmountSet()) {
421 acc.setAmount(item.getAmount());
422 emptyAmountAccountBalance += item.getAmount();
425 emptyAmountAccount = acc;
431 if (emptyAmountAccount != null)
432 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
436 void loadTransactionIntoModel(String profileUUID, int transactionId) {
437 List<Item> newList = new ArrayList<>();
438 LedgerTransaction tr;
439 MobileLedgerProfile profile = Data.getProfile(profileUUID);
441 throw new RuntimeException(String.format(
442 "Unable to find profile %s, which is supposed to contain transaction %d",
443 profileUUID, transactionId));
445 tr = profile.loadTransaction(transactionId);
446 TransactionHead head = new TransactionHead(tr.getDescription());
447 head.setComment(tr.getComment());
451 List<LedgerTransactionAccount> accounts = tr.getAccounts();
453 TransactionAccount firstNegative = null;
454 TransactionAccount firstPositive = null;
455 int singleNegativeIndex = -1;
456 int singlePositiveIndex = -1;
457 int negativeCount = 0;
458 for (int i = 0; i < accounts.size(); i++) {
459 LedgerTransactionAccount acc = accounts.get(i);
460 TransactionAccount item =
461 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
464 item.setAccountName(acc.getAccountName());
465 item.setComment(acc.getComment());
466 if (acc.isAmountSet()) {
467 item.setAmount(acc.getAmount());
468 if (acc.getAmount() < 0) {
469 if (firstNegative == null) {
470 firstNegative = item;
471 singleNegativeIndex = i + 1;
474 singleNegativeIndex = -1;
477 if (firstPositive == null) {
478 firstPositive = item;
479 singlePositiveIndex = i + 1;
482 singlePositiveIndex = -1;
488 if (BuildConfig.DEBUG)
489 dumpItemList("Loaded previous transaction", newList);
491 if (singleNegativeIndex != -1) {
492 firstNegative.resetAmount();
493 moveItemLast(newList, singleNegativeIndex);
495 else if (singlePositiveIndex != -1) {
496 firstPositive.resetAmount();
497 moveItemLast(newList, singlePositiveIndex);
502 noteFocusChanged(1, FocusedElement.Amount);
505 * A transaction is submittable if:
507 * 1) has at least two account names
508 * 2) each row with amount has account name
509 * 3) for each commodity:
510 * 3a) amounts must balance to 0, or
511 * 3b) there must be exactly one empty amount (with account)
512 * 4) empty accounts with empty amounts are ignored
514 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
516 * 6) at least two rows need to be present in the ledger
518 * @param list - the item list to check. Can be the displayed list or a list that will be
521 @SuppressLint("DefaultLocale")
522 void checkTransactionSubmittable(@Nullable List<Item> list) {
523 boolean workingWithLiveList = false;
524 boolean liveListCopied = false;
526 list = Objects.requireNonNull(items.getValue());
527 workingWithLiveList = true;
530 if (BuildConfig.DEBUG)
531 dumpItemList("Before submittable checks", list);
534 final BalanceForCurrency balance = new BalanceForCurrency();
535 final String descriptionText = list.get(0)
538 boolean submittable = true;
539 boolean listChanged = false;
540 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
541 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
542 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
543 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
544 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
545 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
546 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
547 final List<Item> emptyRows = new ArrayList<>();
550 if ((descriptionText == null) || descriptionText.trim()
553 Logger.debug("submittable", "Transaction not submittable: missing description");
557 for (int i = 1; i < list.size(); i++) {
558 TransactionAccount item = list.get(i)
559 .toTransactionAccount();
561 String accName = item.getAccountName()
563 String currName = item.getCurrency();
565 itemsForCurrency.add(currName, item);
567 if (accName.isEmpty()) {
568 itemsWithEmptyAccountForCurrency.add(currName, item);
570 if (item.isAmountSet()) {
571 // 2) each amount has account name
572 Logger.debug("submittable", String.format(
573 "Transaction not submittable: row %d has no account name, but" +
574 " has" + " amount %1.2f", i + 1, item.getAmount()));
578 emptyRowsForCurrency.add(currName, item);
583 itemsWithAccountForCurrency.add(currName, item);
586 if (!item.isAmountValid()) {
587 Logger.debug("submittable",
588 String.format("Not submittable: row %d has an invalid amount", i + 1));
591 else if (item.isAmountSet()) {
592 itemsWithAmountForCurrency.add(currName, item);
593 balance.add(currName, item.getAmount());
596 itemsWithEmptyAmountForCurrency.add(currName, item);
598 if (!accName.isEmpty())
599 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
603 // 1) has at least two account names
606 Logger.debug("submittable", "Transaction not submittable: no account names");
607 else if (accounts == 1)
608 Logger.debug("submittable",
609 "Transaction not submittable: only one account name");
611 Logger.debug("submittable",
612 String.format("Transaction not submittable: only %d account names",
617 // 3) for each commodity:
618 // 3a) amount must balance to 0, or
619 // 3b) there must be exactly one empty amount (with account)
620 for (String balCurrency : itemsForCurrency.currencies()) {
621 float currencyBalance = balance.get(balCurrency);
622 if (Misc.isZero(currencyBalance)) {
623 // remove hints from all amount inputs in that currency
624 for (int i = 1; i < list.size(); i++) {
625 TransactionAccount acc = list.get(i)
626 .toTransactionAccount();
627 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
628 if (BuildConfig.DEBUG)
629 Logger.debug("submittable",
630 String.format("Resetting hint of '%s' [%s]",
631 Misc.nullIsEmpty(acc.getAccountName()),
633 // skip if the amount is set, in which case the hint is not
635 if (!acc.isAmountSet() && acc.amountHintIsSet &&
636 !TextUtils.isEmpty(acc.getAmountHint()))
638 if (workingWithLiveList && !liveListCopied) {
639 list = copyList(list);
640 liveListCopied = true;
642 final TransactionAccount newAcc = new TransactionAccount(acc);
643 newAcc.setAmountHint(null);
652 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
653 int balanceReceiversCount = tmpList.size();
654 if (balanceReceiversCount != 1) {
655 if (BuildConfig.DEBUG) {
656 if (balanceReceiversCount == 0)
657 Logger.debug("submittable", String.format(
658 "Transaction not submittable [%s]: non-zero balance " +
659 "with no empty amounts with accounts", balCurrency));
661 Logger.debug("submittable", String.format(
662 "Transaction not submittable [%s]: non-zero balance " +
663 "with multiple empty amounts with accounts", balCurrency));
668 List<Item> emptyAmountList =
669 itemsWithEmptyAmountForCurrency.getList(balCurrency);
671 // suggest off-balance amount to a row and remove hints on other rows
672 Item receiver = null;
673 if (!tmpList.isEmpty())
674 receiver = tmpList.get(0);
675 else if (!emptyAmountList.isEmpty())
676 receiver = emptyAmountList.get(0);
678 for (int i = 0; i < list.size(); i++) {
679 Item item = list.get(i);
680 if (!(item instanceof TransactionAccount))
683 TransactionAccount acc = item.toTransactionAccount();
684 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
687 if (item == receiver) {
688 final String hint = String.format("%1.2f", -currencyBalance);
689 if (!acc.isAmountHintSet() ||
690 !TextUtils.equals(acc.getAmountHint(), hint))
692 Logger.debug("submittable",
693 String.format("Setting amount hint of {%s} to %s [%s]",
694 acc.toString(), hint, balCurrency));
695 if (workingWithLiveList & !liveListCopied) {
696 list = copyList(list);
697 liveListCopied = true;
699 final TransactionAccount newAcc = new TransactionAccount(acc);
700 newAcc.setAmountHint(hint);
706 if (BuildConfig.DEBUG)
707 Logger.debug("submittable",
708 String.format("Resetting hint of '%s' [%s]",
709 Misc.nullIsEmpty(acc.getAccountName()),
711 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
712 if (workingWithLiveList && !liveListCopied) {
713 list = copyList(list);
714 liveListCopied = true;
716 final TransactionAccount newAcc = new TransactionAccount(acc);
717 newAcc.setAmountHint(null);
726 // 5) a row with an empty account name or empty amount is guaranteed to exist for
728 for (String balCurrency : balance.currencies()) {
729 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
730 int currRows = itemsForCurrency.size(balCurrency);
731 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
732 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
733 if ((currEmptyRows == 0) &&
734 ((currRows == currAccounts) || (currRows == currAmounts)))
736 // perhaps there already is an unused empty row for another currency that
738 // boolean foundIt = false;
739 // for (Item item : emptyRows) {
740 // Currency itemCurrency = item.getCurrency();
741 // String itemCurrencyName =
742 // (itemCurrency == null) ? "" : itemCurrency.getName();
743 // if (Misc.isZero(balance.get(itemCurrencyName))) {
744 // item.setCurrency(Currency.loadByName(balCurrency));
745 // item.setAmountHint(
746 // String.format("%1.2f", -balance.get(balCurrency)));
753 if (workingWithLiveList && !liveListCopied) {
754 list = copyList(list);
755 liveListCopied = true;
757 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
758 final float bal = balance.get(balCurrency);
759 if (!Misc.isZero(bal) && currAmounts == currRows)
760 newAcc.setAmountHint(String.format("%4.2f", -bal));
761 Logger.debug("submittable",
762 String.format("Adding new item with %s for currency %s",
763 newAcc.getAmountHint(), balCurrency));
769 // drop extra empty rows, not needed
770 for (String currName : emptyRowsForCurrency.currencies()) {
771 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
772 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
773 if (workingWithLiveList && !liveListCopied) {
774 list = copyList(list);
775 liveListCopied = true;
777 // the list is a copy, so the empty item is no longer present
778 Item itemToRemove = emptyItems.remove(1);
779 removeItemById(list, itemToRemove.id);
783 // unused currency, remove last item (which is also an empty one)
784 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
785 List<Item> currItems = itemsForCurrency.getList(currName);
787 if (currItems.size() == 1) {
788 if (workingWithLiveList && !liveListCopied) {
789 list = copyList(list);
790 liveListCopied = true;
792 // the list is a copy, so the empty item is no longer present
793 removeItemById(list, emptyItems.get(0).id);
799 // 6) at least two rows need to be present in the ledger
800 // (the list also contains header and trailer)
801 while (list.size() < MIN_ITEMS) {
802 if (workingWithLiveList && !liveListCopied) {
803 list = copyList(list);
804 liveListCopied = true;
806 list.add(new TransactionAccount(""));
811 Logger.debug("submittable", submittable ? "YES" : "NO");
812 isSubmittable.setValue(submittable);
814 if (BuildConfig.DEBUG)
815 dumpItemList("After submittable checks", list);
817 catch (NumberFormatException e) {
818 Logger.debug("submittable", "NO (because of NumberFormatException)");
819 isSubmittable.setValue(false);
821 catch (Exception e) {
823 Logger.debug("submittable", "NO (because of an Exception)");
824 isSubmittable.setValue(false);
827 if (listChanged && workingWithLiveList) {
828 setItemsWithoutSubmittableChecks(list);
831 private void removeItemById(@NotNull List<Item> list, int id) {
832 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
833 list.removeIf(item -> item.id == id);
836 for (Item item : list) {
844 @SuppressLint("DefaultLocale")
845 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
846 Logger.debug("submittable", "== Dump of all items " + msg);
847 for (int i = 1; i < list.size(); i++) {
848 TransactionAccount item = list.get(i)
849 .toTransactionAccount();
850 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
853 public void setItemCurrency(int position, String newCurrency) {
854 TransactionAccount item = Objects.requireNonNull(items.getValue())
856 .toTransactionAccount();
857 final String oldCurrency = item.getCurrency();
859 if (Misc.equalStrings(oldCurrency, newCurrency))
862 List<Item> newList = copyList();
863 newList.get(position)
864 .toTransactionAccount()
865 .setCurrency(newCurrency);
869 public boolean accountListIsEmpty() {
870 List<Item> items = Objects.requireNonNull(this.items.getValue());
872 for (Item item : items) {
873 if (!(item instanceof TransactionAccount))
876 if (!((TransactionAccount) item).isEmpty())
883 public static class FocusInfo {
885 FocusedElement element;
886 public FocusInfo(int position, FocusedElement element) {
887 this.position = position;
888 this.element = element;
892 static abstract class Item {
893 private static int idDispenser = 0;
896 synchronized (Item.class) {
900 public static Item from(Item origin) {
901 if (origin instanceof TransactionHead)
902 return new TransactionHead((TransactionHead) origin);
903 if (origin instanceof TransactionAccount)
904 return new TransactionAccount((TransactionAccount) origin);
905 throw new RuntimeException("Don't know how to handle " + origin);
910 public abstract ItemType getType();
911 public TransactionHead toTransactionHead() {
912 if (this instanceof TransactionHead)
913 return (TransactionHead) this;
915 throw new IllegalStateException("Wrong item type " + this);
917 public TransactionAccount toTransactionAccount() {
918 if (this instanceof TransactionAccount)
919 return (TransactionAccount) this;
921 throw new IllegalStateException("Wrong item type " + this);
923 public boolean equalContents(@Nullable Object item) {
927 if (!getClass().equals(item.getClass()))
930 // shortcut - comparing same instance
934 if (this instanceof TransactionHead)
935 return ((TransactionHead) item).equalContents((TransactionHead) this);
936 if (this instanceof TransactionAccount)
937 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
939 throw new RuntimeException("Don't know how to handle " + this);
944 //==========================================================================================
946 public static class TransactionHead extends Item {
947 private SimpleDate date;
948 private String description;
949 private String comment;
950 TransactionHead(String description) {
952 this.description = description;
954 public TransactionHead(TransactionHead origin) {
957 description = origin.description;
958 comment = origin.comment;
960 public SimpleDate getDate() {
963 public void setDate(SimpleDate date) {
966 public void setDate(String text) throws ParseException {
967 if (Misc.emptyIsNull(text) == null) {
972 date = Globals.parseLedgerDate(text);
977 * @return nicely formatted, shortest available date representation
979 String getFormattedDate() {
983 Calendar today = GregorianCalendar.getInstance();
985 if (today.get(Calendar.YEAR) != date.year) {
986 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
989 if (today.get(Calendar.MONTH) + 1 != date.month) {
990 return String.format(Locale.US, "%d/%02d", date.month, date.day);
993 return String.valueOf(date.day);
997 public String toString() {
998 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
999 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1001 if (TextUtils.isEmpty(description))
1002 b.append(" «no description»");
1004 b.append(String.format(" descr'%s'", description));
1007 b.append(String.format("@%s", date.toString()));
1009 if (!TextUtils.isEmpty(comment))
1010 b.append(String.format(" /%s/", comment));
1012 return b.toString();
1014 public String getDescription() {
1017 public void setDescription(String description) {
1018 this.description = description;
1020 public String getComment() {
1023 public void setComment(String comment) {
1024 this.comment = comment;
1027 public ItemType getType() {
1028 return ItemType.generalData;
1030 public LedgerTransaction asLedgerTransaction() {
1031 return new LedgerTransaction(null, date, description, Data.getProfile());
1033 public boolean equalContents(TransactionHead other) {
1037 return Objects.equals(date, other.date) &&
1038 TextUtils.equals(description, other.description) &&
1039 TextUtils.equals(comment, other.comment);
1043 public static class TransactionAccount extends Item {
1044 private String accountName;
1045 private String amountHint;
1046 private String comment;
1047 private String currency;
1048 private float amount;
1049 private boolean amountSet;
1050 private boolean amountValid = true;
1051 private FocusedElement focusedElement = FocusedElement.Account;
1052 private boolean amountHintIsSet = true;
1053 private boolean isLast = false;
1054 private int accountNameCursorPosition;
1055 public TransactionAccount(TransactionAccount origin) {
1057 accountName = origin.accountName;
1058 amount = origin.amount;
1059 amountSet = origin.amountSet;
1060 amountHint = origin.amountHint;
1061 amountHintIsSet = origin.amountHintIsSet;
1062 comment = origin.comment;
1063 currency = origin.currency;
1064 amountValid = origin.amountValid;
1065 focusedElement = origin.focusedElement;
1066 isLast = origin.isLast;
1067 accountNameCursorPosition = origin.accountNameCursorPosition;
1069 public TransactionAccount(LedgerTransactionAccount account) {
1071 currency = account.getCurrency();
1072 amount = account.getAmount();
1074 public TransactionAccount(String accountName) {
1076 this.accountName = accountName;
1078 public TransactionAccount(String accountName, String currency) {
1080 this.accountName = accountName;
1081 this.currency = currency;
1083 public boolean isLast() {
1086 public boolean isAmountSet() {
1089 public String getAccountName() {
1092 public void setAccountName(String accountName) {
1093 this.accountName = accountName;
1095 public float getAmount() {
1097 throw new IllegalStateException("Amount is not set");
1100 public void setAmount(float amount) {
1101 this.amount = amount;
1104 public void resetAmount() {
1108 public ItemType getType() {
1109 return ItemType.transactionRow;
1111 public String getAmountHint() {
1114 public void setAmountHint(String amountHint) {
1115 this.amountHint = amountHint;
1116 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1118 public String getComment() {
1121 public void setComment(String comment) {
1122 this.comment = comment;
1124 public String getCurrency() {
1127 public void setCurrency(String currency) {
1128 this.currency = currency;
1130 public boolean isAmountValid() {
1133 public void setAmountValid(boolean amountValid) {
1134 this.amountValid = amountValid;
1136 public FocusedElement getFocusedElement() {
1137 return focusedElement;
1139 public void setFocusedElement(FocusedElement focusedElement) {
1140 this.focusedElement = focusedElement;
1142 public boolean isAmountHintSet() {
1143 return amountHintIsSet;
1145 public void setAmountHintIsSet(boolean amountHintIsSet) {
1146 this.amountHintIsSet = amountHintIsSet;
1148 public boolean isEmpty() {
1149 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1150 Misc.emptyIsNull(comment) == null;
1152 @SuppressLint("DefaultLocale")
1154 public String toString() {
1155 StringBuilder b = new StringBuilder();
1156 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1157 if (!TextUtils.isEmpty(accountName))
1158 b.append(String.format(" acc'%s'", accountName));
1161 b.append(String.format(" %4.2f", amount));
1162 else if (amountHintIsSet)
1163 b.append(String.format(" (%s)", amountHint));
1165 if (!TextUtils.isEmpty(currency))
1169 if (!TextUtils.isEmpty(comment))
1170 b.append(String.format(" /%s/", comment));
1175 return b.toString();
1177 public boolean equalContents(TransactionAccount other) {
1181 boolean equal = TextUtils.equals(accountName, other.accountName);
1182 equal = equal && TextUtils.equals(comment, other.comment) &&
1183 (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1185 // compare amount hint only if there is no amount
1187 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1188 TextUtils.equals(amountHint, other.amountHint)
1189 : !other.amountHintIsSet);
1190 equal = equal && TextUtils.equals(currency, other.currency) && isLast == other.isLast;
1192 Logger.debug("new-trans",
1193 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1197 public int getAccountNameCursorPosition() {
1198 return accountNameCursorPosition;
1200 public void setAccountNameCursorPosition(int position) {
1201 this.accountNameCursorPosition = position;
1205 private static class BalanceForCurrency {
1206 private final HashMap<String, Float> hashMap = new HashMap<>();
1207 float get(String currencyName) {
1208 Float f = hashMap.get(currencyName);
1211 hashMap.put(currencyName, f);
1215 void add(String currencyName, float amount) {
1216 hashMap.put(currencyName, get(currencyName) + amount);
1218 Set<String> currencies() {
1219 return hashMap.keySet();
1221 boolean containsCurrency(String currencyName) {
1222 return hashMap.containsKey(currencyName);
1226 private static class ItemsForCurrency {
1227 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1229 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1230 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1232 list = new ArrayList<>();
1233 hashMap.put(currencyName, list);
1237 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1238 getList(currencyName).add(item);
1240 int size(@Nullable String currencyName) {
1241 return this.getList(currencyName)
1244 Set<String> currencies() {
1245 return hashMap.keySet();