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() {
84 public LiveData<Boolean> getShowCurrency() {
87 public LiveData<List<Item>> getItems() {
90 private void setItems(@NonNull List<Item> newList) {
91 checkTransactionSubmittable(newList);
92 setItemsWithoutSubmittableChecks(newList);
94 private void replaceItems(@NonNull List<Item> newList) {
100 * make old items replaceable in-place. makes the new values visually blend in
102 private void renumberItems() {
103 renumberItems(items.getValue());
105 private void renumberItems(List<Item> list) {
111 for (Item item : list)
114 private void setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
115 final int cnt = list.size();
116 for (int i = 1; i < cnt - 1; i++) {
117 final TransactionAccount item = list.get(i)
118 .toTransactionAccount();
120 TransactionAccount replacement = new TransactionAccount(item);
121 replacement.isLast = false;
122 list.set(i, replacement);
125 final TransactionAccount last = list.get(cnt - 1)
126 .toTransactionAccount();
128 TransactionAccount replacement = new TransactionAccount(last);
129 replacement.isLast = true;
130 list.set(cnt - 1, replacement);
133 if (BuildConfig.DEBUG)
134 dumpItemList("Before setValue()", list);
135 items.setValue(list);
137 private List<Item> copyList() {
138 List<Item> copy = new ArrayList<>();
139 List<Item> oldList = items.getValue();
142 for (Item item : oldList) {
143 copy.add(Item.from(item));
148 private List<Item> copyListWithoutItem(int position) {
149 List<Item> copy = new ArrayList<>();
150 List<Item> oldList = items.getValue();
152 if (oldList != null) {
154 for (Item item : oldList) {
157 copy.add(Item.from(item));
163 private List<Item> shallowCopyList() {
164 return new ArrayList<>(Objects.requireNonNull(items.getValue()));
166 LiveData<Boolean> getShowComments() {
169 void observeDataProfile(LifecycleOwner activity) {
170 if (!observingDataProfile)
171 Data.observeProfile(activity, profileObserver);
172 observingDataProfile = true;
174 boolean getSimulateSaveFlag() {
175 Boolean value = simulateSave.getValue();
180 LiveData<Boolean> getSimulateSave() {
183 void toggleSimulateSave() {
184 simulateSave.setValue(!getSimulateSaveFlag());
186 LiveData<Boolean> isSubmittable() {
187 return this.isSubmittable;
190 Logger.debug("new-trans", "Resetting model");
191 List<Item> list = new ArrayList<>();
192 Item.resetIdDispenser();
193 list.add(new TransactionHead(""));
194 final String defaultCurrency = Objects.requireNonNull(Data.getProfile())
195 .getDefaultCommodity();
196 list.add(new TransactionAccount("", defaultCurrency));
197 list.add(new TransactionAccount("", defaultCurrency));
198 noteFocusChanged(0, FocusedElement.Description);
200 isSubmittable.setValue(false);
201 setItemsWithoutSubmittableChecks(list);
203 boolean accountsInInitialState() {
204 final List<Item> list = items.getValue();
209 for (Item item : list) {
210 if (!(item instanceof TransactionAccount))
213 TransactionAccount accRow = (TransactionAccount) item;
214 if (!accRow.isEmpty())
220 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
221 SimpleDate transactionDate = null;
222 final MatchResult matchResult = matchedTemplate.matchResult;
223 final TemplateHeader templateHead = matchedTemplate.templateHead;
225 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
226 templateHead.getDateDay());
227 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
228 templateHead.getDateMonth());
229 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
230 templateHead.getDateYear());
232 if (year > 0 || month > 0 || day > 0) {
233 SimpleDate today = SimpleDate.today();
241 transactionDate = new SimpleDate(year, month, day);
243 Logger.debug("pattern", "setting transaction date to " + transactionDate);
247 List<Item> present = copyList();
249 TransactionHead head = new TransactionHead(present.get(0)
250 .toTransactionHead());
251 if (transactionDate != null)
252 head.setDate(transactionDate);
254 final String transactionDescription = extractStringFromMatches(matchResult,
255 templateHead.getTransactionDescriptionMatchGroup(),
256 templateHead.getTransactionDescription());
257 if (Misc.emptyIsNull(transactionDescription) != null)
258 head.setDescription(transactionDescription);
260 final String transactionComment = extractStringFromMatches(matchResult,
261 templateHead.getTransactionCommentMatchGroup(),
262 templateHead.getTransactionComment());
263 if (Misc.emptyIsNull(transactionComment) != null)
264 head.setComment(transactionComment);
266 List<Item> newItems = new ArrayList<>();
270 for (int i = 1; i < present.size(); i++) {
271 final TransactionAccount row = present.get(i)
272 .toTransactionAccount();
274 newItems.add(new TransactionAccount(row));
279 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
281 final boolean accountsInInitialState = accountsInInitialState();
282 for (TemplateAccount acc : entry.accounts) {
286 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
287 acc.getAccountName());
288 String accountComment =
289 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
290 acc.getAccountComment());
291 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
293 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
296 TransactionAccount accRow = new TransactionAccount(accountName);
297 accRow.setComment(accountComment);
299 accRow.setAmount(amount);
301 extractCurrencyFromMatches(matchResult, acc.getCurrencyMatchGroup(),
302 acc.getCurrencyObject()));
304 newItems.add(accRow);
307 renumberItems(newItems);
308 Misc.onMainThread(() -> replaceItems(newItems));
312 private String extractCurrencyFromMatches(MatchResult m, Integer group, Currency literal) {
313 return Misc.nullIsEmpty(
314 extractStringFromMatches(m, group, (literal == null) ? "" : literal.getName()));
316 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
322 if (grp > 0 && grp <= m.groupCount())
324 return Integer.parseInt(m.group(grp));
326 catch (NumberFormatException e) {
327 Logger.debug("new-trans", "Error extracting matched number", e);
334 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
340 if (grp > 0 && grp <= m.groupCount())
346 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
352 if (grp > 0 && grp <= m.groupCount())
354 return Float.valueOf(m.group(grp));
356 catch (NumberFormatException e) {
357 Logger.debug("new-trans", "Error extracting matched number", e);
363 void removeItem(int pos) {
364 Logger.debug("new-trans", String.format(Locale.US, "Removing item at position %d", pos));
365 List<Item> newList = copyListWithoutItem(pos);
366 final FocusInfo fi = focusInfo.getValue();
367 if ((fi != null) && (pos < fi.position))
368 noteFocusChanged(fi.position - 1, fi.element);
371 void noteFocusChanged(int position, FocusedElement element) {
372 FocusInfo present = focusInfo.getValue();
373 if (present == null || present.position != position || present.element != element)
374 focusInfo.setValue(new FocusInfo(position, element));
376 public LiveData<FocusInfo> getFocusInfo() {
379 void moveItem(int fromIndex, int toIndex) {
380 List<Item> newList = shallowCopyList();
381 Item item = newList.remove(fromIndex);
382 newList.add(toIndex, item);
384 FocusInfo fi = focusInfo.getValue();
385 if (fi != null && fi.position == fromIndex)
386 noteFocusChanged(toIndex, fi.element);
388 items.setValue(newList); // same count, same submittable state
390 void moveItemLast(List<Item> list, int index) {
394 3 <-- desired position
397 int itemCount = list.size();
399 if (index < itemCount - 1)
400 list.add(list.remove(index));
402 void toggleCurrencyVisible() {
403 final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
405 // remove currency from all items, or reset currency to the default
406 // no need to clone the list, because the removal of the currency won't lead to
407 // visual changes -- the currency fields will be hidden or reset to default anyway
408 // still, there may be changes in the submittable state
409 final List<Item> list = Objects.requireNonNull(this.items.getValue());
410 final Profile profile = Objects.requireNonNull(Data.getProfile());
411 for (int i = 1; i < list.size(); i++) {
412 ((TransactionAccount) list.get(i)).setCurrency(
413 newValue ? profile.getDefaultCommodity() : "");
415 checkTransactionSubmittable(null);
416 showCurrency.setValue(newValue);
418 void stopObservingBusyFlag(Observer<Boolean> observer) {
419 busyFlag.removeObserver(observer);
421 void incrementBusyCounter() {
422 int newValue = busyCounter.incrementAndGet();
424 busyFlag.postValue(true);
426 void decrementBusyCounter() {
427 int newValue = busyCounter.decrementAndGet();
429 busyFlag.postValue(false);
431 public LiveData<Boolean> getBusyFlag() {
434 public void toggleShowComments() {
435 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
437 public LedgerTransaction constructLedgerTransaction() {
438 List<Item> list = Objects.requireNonNull(items.getValue());
439 TransactionHead head = list.get(0)
440 .toTransactionHead();
441 LedgerTransaction tr = head.asLedgerTransaction();
443 tr.setComment(head.getComment());
444 LedgerTransactionAccount emptyAmountAccount = null;
445 float emptyAmountAccountBalance = 0;
446 for (int i = 1; i < list.size(); i++) {
447 TransactionAccount item = list.get(i)
448 .toTransactionAccount();
449 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
452 if (acc.getAccountName()
456 acc.setComment(item.getComment());
458 if (item.isAmountSet()) {
459 acc.setAmount(item.getAmount());
460 emptyAmountAccountBalance += item.getAmount();
463 emptyAmountAccount = acc;
469 if (emptyAmountAccount != null)
470 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
474 void loadTransactionIntoModel(@NonNull TransactionWithAccounts tr) {
475 List<Item> newList = new ArrayList<>();
476 Item.resetIdDispenser();
478 Item currentHead = Objects.requireNonNull(items.getValue())
480 TransactionHead head = new TransactionHead(tr.transaction.getDescription());
481 head.setComment(tr.transaction.getComment());
482 if (currentHead instanceof TransactionHead)
483 head.setDate(((TransactionHead) currentHead).date);
487 List<LedgerTransactionAccount> accounts = new ArrayList<>();
488 for (net.ktnx.mobileledger.db.TransactionAccount acc : tr.accounts) {
489 accounts.add(new LedgerTransactionAccount(acc));
492 TransactionAccount firstNegative = null;
493 TransactionAccount firstPositive = null;
494 int singleNegativeIndex = -1;
495 int singlePositiveIndex = -1;
496 int negativeCount = 0;
497 for (int i = 0; i < accounts.size(); i++) {
498 LedgerTransactionAccount acc = accounts.get(i);
499 TransactionAccount item = new TransactionAccount(acc.getAccountName(),
500 Misc.nullIsEmpty(acc.getCurrency()));
503 item.setAccountName(acc.getAccountName());
504 item.setComment(acc.getComment());
505 if (acc.isAmountSet()) {
506 item.setAmount(acc.getAmount());
507 if (acc.getAmount() < 0) {
508 if (firstNegative == null) {
509 firstNegative = item;
510 singleNegativeIndex = i + 1;
513 singleNegativeIndex = -1;
516 if (firstPositive == null) {
517 firstPositive = item;
518 singlePositiveIndex = i + 1;
521 singlePositiveIndex = -1;
527 if (BuildConfig.DEBUG)
528 dumpItemList("Loaded previous transaction", newList);
530 if (singleNegativeIndex != -1) {
531 firstNegative.resetAmount();
532 moveItemLast(newList, singleNegativeIndex);
534 else if (singlePositiveIndex != -1) {
535 firstPositive.resetAmount();
536 moveItemLast(newList, singlePositiveIndex);
539 Misc.onMainThread(() -> {
541 noteFocusChanged(1, FocusedElement.Amount);
545 * A transaction is submittable if:
547 * 1) has at least two account names
548 * 2) each row with amount has account name
549 * 3) for each commodity:
550 * 3a) amounts must balance to 0, or
551 * 3b) there must be exactly one empty amount (with account)
552 * 4) empty accounts with empty amounts are ignored
554 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
556 * 6) at least two rows need to be present in the ledger
558 * @param list - the item list to check. Can be the displayed list or a list that will be
561 @SuppressLint("DefaultLocale")
562 void checkTransactionSubmittable(@Nullable List<Item> list) {
563 boolean workingWithLiveList = false;
566 workingWithLiveList = true;
569 if (BuildConfig.DEBUG)
570 dumpItemList(String.format("Before submittable checks (%s)",
571 workingWithLiveList ? "LIVE LIST" : "custom list"), list);
574 final BalanceForCurrency balance = new BalanceForCurrency();
575 final String descriptionText = list.get(0)
578 boolean submittable = true;
579 boolean listChanged = false;
580 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
581 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
582 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
583 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
584 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
585 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
586 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
587 final List<Item> emptyRows = new ArrayList<>();
590 if ((descriptionText == null) || descriptionText.trim()
593 Logger.debug("submittable", "Transaction not submittable: missing description");
597 boolean hasInvalidAmount = false;
599 for (int i = 1; i < list.size(); i++) {
600 TransactionAccount item = list.get(i)
601 .toTransactionAccount();
603 String accName = item.getAccountName()
605 String currName = item.getCurrency();
607 itemsForCurrency.add(currName, item);
609 if (accName.isEmpty()) {
610 itemsWithEmptyAccountForCurrency.add(currName, item);
612 if (item.isAmountSet()) {
613 // 2) each amount has account name
614 Logger.debug("submittable", String.format(
615 "Transaction not submittable: row %d has no account name, but" +
616 " has" + " amount %1.2f", i + 1, item.getAmount()));
620 emptyRowsForCurrency.add(currName, item);
625 itemsWithAccountForCurrency.add(currName, item);
628 if (item.isAmountSet() && item.isAmountValid()) {
629 itemsWithAmountForCurrency.add(currName, item);
630 balance.add(currName, item.getAmount());
633 if (!item.isAmountValid()) {
634 Logger.debug("submittable",
635 String.format("Not submittable: row %d has an invalid amount", i));
637 hasInvalidAmount = true;
640 itemsWithEmptyAmountForCurrency.add(currName, item);
642 if (!accName.isEmpty())
643 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
647 // 1) has at least two account names
650 Logger.debug("submittable", "Transaction not submittable: no account names");
651 else if (accounts == 1)
652 Logger.debug("submittable",
653 "Transaction not submittable: only one account name");
655 Logger.debug("submittable",
656 String.format("Transaction not submittable: only %d account names",
661 // 3) for each commodity:
662 // 3a) amount must balance to 0, or
663 // 3b) there must be exactly one empty amount (with account)
664 for (String balCurrency : itemsForCurrency.currencies()) {
665 float currencyBalance = balance.get(balCurrency);
666 if (Misc.isZero(currencyBalance)) {
667 // remove hints from all amount inputs in that currency
668 for (int i = 1; i < list.size(); i++) {
669 TransactionAccount acc = list.get(i)
670 .toTransactionAccount();
671 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
672 if (BuildConfig.DEBUG)
673 Logger.debug("submittable",
674 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
675 i, Misc.nullIsEmpty(acc.getAccountName()),
677 // skip if the amount is set, in which case the hint is not
679 if (!acc.isAmountSet() && acc.amountHintIsSet &&
680 !TextUtils.isEmpty(acc.getAmountHint()))
682 acc.setAmountHint(null);
690 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
691 int balanceReceiversCount = tmpList.size();
692 if (balanceReceiversCount != 1) {
693 if (BuildConfig.DEBUG) {
694 if (balanceReceiversCount == 0)
695 Logger.debug("submittable", String.format(
696 "Transaction not submittable [curr:%s]: non-zero balance " +
697 "with no empty amounts with accounts", balCurrency));
699 Logger.debug("submittable", String.format(
700 "Transaction not submittable [curr:%s]: non-zero balance " +
701 "with multiple empty amounts with accounts", balCurrency));
706 List<Item> emptyAmountList =
707 itemsWithEmptyAmountForCurrency.getList(balCurrency);
709 // suggest off-balance amount to a row and remove hints on other rows
710 Item receiver = null;
711 if (!tmpList.isEmpty())
712 receiver = tmpList.get(0);
713 else if (!emptyAmountList.isEmpty())
714 receiver = emptyAmountList.get(0);
716 for (int i = 0; i < list.size(); i++) {
717 Item item = list.get(i);
718 if (!(item instanceof TransactionAccount))
721 TransactionAccount acc = item.toTransactionAccount();
722 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
725 if (item == receiver) {
726 final String hint = Data.formatNumber(-currencyBalance);
727 if (!acc.isAmountHintSet() ||
728 !Misc.equalStrings(acc.getAmountHint(), hint))
730 Logger.debug("submittable",
731 String.format("Setting amount hint of {%s} to %s [%s]",
732 acc.toString(), hint, balCurrency));
733 acc.setAmountHint(hint);
738 if (BuildConfig.DEBUG)
739 Logger.debug("submittable",
740 String.format("Resetting hint of '%s' [%s]",
741 Misc.nullIsEmpty(acc.getAccountName()),
743 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
744 acc.setAmountHint(null);
752 // 5) a row with an empty account name or empty amount is guaranteed to exist for
754 if (!hasInvalidAmount) {
755 for (String balCurrency : balance.currencies()) {
756 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
757 int currRows = itemsForCurrency.size(balCurrency);
758 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
759 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
760 if ((currEmptyRows == 0) &&
761 ((currRows == currAccounts) || (currRows == currAmounts)))
763 // perhaps there already is an unused empty row for another currency that
765 // boolean foundIt = false;
766 // for (Item item : emptyRows) {
767 // Currency itemCurrency = item.getCurrency();
768 // String itemCurrencyName =
769 // (itemCurrency == null) ? "" : itemCurrency.getName();
770 // if (Misc.isZero(balance.get(itemCurrencyName))) {
771 // item.setCurrency(Currency.loadByName(balCurrency));
772 // item.setAmountHint(
773 // Data.formatNumber(-balance.get(balCurrency)));
780 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
781 final float bal = balance.get(balCurrency);
782 if (!Misc.isZero(bal) && currAmounts == currRows)
783 newAcc.setAmountHint(Data.formatNumber(-bal));
784 Logger.debug("submittable",
785 String.format("Adding new item with %s for currency %s",
786 newAcc.getAmountHint(), balCurrency));
793 // drop extra empty rows, not needed
794 for (String currName : emptyRowsForCurrency.currencies()) {
795 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
796 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
797 // the list is a copy, so the empty item is no longer present
798 Item itemToRemove = emptyItems.remove(1);
799 removeItemById(list, itemToRemove.id);
803 // unused currency, remove last item (which is also an empty one)
804 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
805 List<Item> currItems = itemsForCurrency.getList(currName);
807 if (currItems.size() == 1) {
808 // the list is a copy, so the empty item is no longer present
809 removeItemById(list, emptyItems.get(0).id);
815 // 6) at least two rows need to be present in the ledger
816 // (the list also contains header and trailer)
817 while (list.size() < MIN_ITEMS) {
818 list.add(new TransactionAccount(""));
822 Logger.debug("submittable", submittable ? "YES" : "NO");
823 isSubmittable.setValue(submittable);
825 if (BuildConfig.DEBUG)
826 dumpItemList("After submittable checks", list);
828 catch (NumberFormatException e) {
829 Logger.debug("submittable", "NO (because of NumberFormatException)");
830 isSubmittable.setValue(false);
832 catch (Exception e) {
834 Logger.debug("submittable", "NO (because of an Exception)");
835 isSubmittable.setValue(false);
838 if (listChanged && workingWithLiveList) {
839 setItemsWithoutSubmittableChecks(list);
842 private void removeItemById(@NotNull List<Item> list, int id) {
843 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
844 list.removeIf(item -> item.id == id);
847 for (Item item : list) {
855 @SuppressLint("DefaultLocale")
856 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
857 Logger.debug("submittable", "== Dump of all items " + msg);
858 for (int i = 1; i < list.size(); i++) {
859 TransactionAccount item = list.get(i)
860 .toTransactionAccount();
861 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
864 public void setItemCurrency(int position, String newCurrency) {
865 TransactionAccount item = Objects.requireNonNull(items.getValue())
867 .toTransactionAccount();
868 final String oldCurrency = item.getCurrency();
870 if (Misc.equalStrings(oldCurrency, newCurrency))
873 List<Item> newList = copyList();
874 newList.get(position)
875 .toTransactionAccount()
876 .setCurrency(newCurrency);
880 public boolean accountListIsEmpty() {
881 List<Item> items = Objects.requireNonNull(this.items.getValue());
883 for (Item item : items) {
884 if (!(item instanceof TransactionAccount))
887 if (!((TransactionAccount) item).isEmpty())
894 public static class FocusInfo {
896 FocusedElement element;
897 public FocusInfo(int position, FocusedElement element) {
898 this.position = position;
899 this.element = element;
903 static abstract class Item {
904 private static int idDispenser = 0;
907 if (this instanceof TransactionHead)
910 synchronized (Item.class) {
914 public Item(int id) {
917 public static Item from(Item origin) {
918 if (origin instanceof TransactionHead)
919 return new TransactionHead((TransactionHead) origin);
920 if (origin instanceof TransactionAccount)
921 return new TransactionAccount((TransactionAccount) origin);
922 throw new RuntimeException("Don't know how to handle " + origin);
924 private static void resetIdDispenser() {
930 public abstract ItemType getType();
931 public TransactionHead toTransactionHead() {
932 if (this instanceof TransactionHead)
933 return (TransactionHead) this;
935 throw new IllegalStateException("Wrong item type " + this);
937 public TransactionAccount toTransactionAccount() {
938 if (this instanceof TransactionAccount)
939 return (TransactionAccount) this;
941 throw new IllegalStateException("Wrong item type " + this);
943 public boolean equalContents(@Nullable Object item) {
947 if (!getClass().equals(item.getClass()))
950 // shortcut - comparing same instance
954 if (this instanceof TransactionHead)
955 return ((TransactionHead) item).equalContents((TransactionHead) this);
956 if (this instanceof TransactionAccount)
957 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
959 throw new RuntimeException("Don't know how to handle " + this);
964 //==========================================================================================
966 public static class TransactionHead extends Item {
967 private SimpleDate date;
968 private String description;
969 private String comment;
970 TransactionHead(String description) {
972 this.description = description;
974 public TransactionHead(TransactionHead origin) {
977 description = origin.description;
978 comment = origin.comment;
980 public SimpleDate getDate() {
983 public void setDate(SimpleDate date) {
986 public void setDate(String text) throws ParseException {
987 if (Misc.emptyIsNull(text) == null) {
992 date = Globals.parseLedgerDate(text);
997 * @return nicely formatted, shortest available date representation
999 String getFormattedDate() {
1003 Calendar today = GregorianCalendar.getInstance();
1005 if (today.get(Calendar.YEAR) != date.year) {
1006 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
1009 if (today.get(Calendar.MONTH) + 1 != date.month) {
1010 return String.format(Locale.US, "%d/%02d", date.month, date.day);
1013 return String.valueOf(date.day);
1017 public String toString() {
1018 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
1019 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1021 if (TextUtils.isEmpty(description))
1022 b.append(" «no description»");
1024 b.append(String.format(" '%s'", description));
1027 b.append(String.format("@%s", date.toString()));
1029 if (!TextUtils.isEmpty(comment))
1030 b.append(String.format(" /%s/", comment));
1032 return b.toString();
1034 public String getDescription() {
1037 public void setDescription(String description) {
1038 this.description = description;
1040 public String getComment() {
1043 public void setComment(String comment) {
1044 this.comment = comment;
1047 public ItemType getType() {
1048 return ItemType.generalData;
1050 public LedgerTransaction asLedgerTransaction() {
1051 return new LedgerTransaction(0, (date == null) ? SimpleDate.today() : date, description,
1052 Objects.requireNonNull(Data.getProfile()));
1054 public boolean equalContents(TransactionHead other) {
1058 return Objects.equals(date, other.date) &&
1059 Misc.equalStrings(description, other.description) &&
1060 Misc.equalStrings(comment, other.comment);
1064 public static class TransactionAccount extends Item {
1065 private String accountName;
1066 private String amountHint;
1067 private String comment;
1069 private String currency = "";
1070 private float amount;
1071 private boolean amountSet;
1072 private boolean amountValid = true;
1074 private String amountText = "";
1075 private FocusedElement focusedElement = FocusedElement.Account;
1076 private boolean amountHintIsSet = false;
1077 private boolean isLast = false;
1078 private int accountNameCursorPosition;
1079 public TransactionAccount(TransactionAccount origin) {
1081 accountName = origin.accountName;
1082 amount = origin.amount;
1083 amountSet = origin.amountSet;
1084 amountHint = origin.amountHint;
1085 amountHintIsSet = origin.amountHintIsSet;
1086 amountText = origin.amountText;
1087 comment = origin.comment;
1088 currency = origin.currency;
1089 amountValid = origin.amountValid;
1090 focusedElement = origin.focusedElement;
1091 isLast = origin.isLast;
1092 accountNameCursorPosition = origin.accountNameCursorPosition;
1094 public TransactionAccount(String accountName) {
1096 this.accountName = accountName;
1098 public TransactionAccount(String accountName, @NotNull String currency) {
1100 this.accountName = accountName;
1101 this.currency = currency;
1103 public @NotNull String getAmountText() {
1106 public void setAmountText(@NotNull String amountText) {
1107 this.amountText = amountText;
1109 public boolean setAndCheckAmountText(@NotNull String amountText) {
1110 String amtText = amountText.trim();
1111 this.amountText = amtText;
1113 boolean significantChange = false;
1115 if (amtText.isEmpty()) {
1117 significantChange = true;
1123 amtText = amtText.replace(Data.getDecimalSeparator(), Data.decimalDot);
1124 final float parsedAmount = Float.parseFloat(amtText);
1125 if (!amountSet || !amountValid || !Misc.equalFloats(parsedAmount, amount))
1126 significantChange = true;
1127 amount = parsedAmount;
1131 catch (NumberFormatException e) {
1132 Logger.debug("new-trans", String.format(
1133 "assuming amount is not set due to number format exception. " +
1134 "input was '%s'", amtText));
1135 if (amountValid) // it was valid and now it's not
1136 significantChange = true;
1137 amountValid = false;
1141 return significantChange;
1143 public boolean isLast() {
1146 public boolean isAmountSet() {
1149 public String getAccountName() {
1152 public void setAccountName(String accountName) {
1153 this.accountName = accountName;
1155 public float getAmount() {
1157 throw new IllegalStateException("Amount is not set");
1160 public void setAmount(float amount) {
1161 this.amount = amount;
1164 amountText = Data.formatNumber(amount);
1166 public void resetAmount() {
1172 public ItemType getType() {
1173 return ItemType.transactionRow;
1175 public String getAmountHint() {
1178 public void setAmountHint(String amountHint) {
1179 this.amountHint = amountHint;
1180 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1182 public String getComment() {
1185 public void setComment(String comment) {
1186 this.comment = comment;
1189 public String getCurrency() {
1192 public void setCurrency(@org.jetbrains.annotations.Nullable String currency) {
1193 this.currency = Misc.nullIsEmpty(currency);
1195 public boolean isAmountValid() {
1198 public void setAmountValid(boolean amountValid) {
1199 this.amountValid = amountValid;
1201 public FocusedElement getFocusedElement() {
1202 return focusedElement;
1204 public void setFocusedElement(FocusedElement focusedElement) {
1205 this.focusedElement = focusedElement;
1207 public boolean isAmountHintSet() {
1208 return amountHintIsSet;
1210 public void setAmountHintIsSet(boolean amountHintIsSet) {
1211 this.amountHintIsSet = amountHintIsSet;
1213 public boolean isEmpty() {
1214 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1215 Misc.emptyIsNull(comment) == null;
1217 @SuppressLint("DefaultLocale")
1220 public String toString() {
1221 StringBuilder b = new StringBuilder();
1222 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1223 if (!TextUtils.isEmpty(accountName))
1224 b.append(String.format(" acc'%s'", accountName));
1227 b.append(amountText)
1229 .append(amountValid ? "valid" : "invalid")
1231 .append(String.format(Locale.ROOT, " {raw %4.2f}", amount));
1232 else if (amountHintIsSet)
1233 b.append(String.format(" (hint %s)", amountHint));
1235 if (!TextUtils.isEmpty(currency))
1239 if (!TextUtils.isEmpty(comment))
1240 b.append(String.format(" /%s/", comment));
1245 return b.toString();
1247 public boolean equalContents(TransactionAccount other) {
1251 boolean equal = Misc.equalStrings(accountName, other.accountName);
1252 equal = equal && Misc.equalStrings(comment, other.comment) &&
1253 (amountSet ? other.amountSet && amountValid == other.amountValid &&
1254 Misc.equalStrings(amountText, other.amountText)
1255 : !other.amountSet);
1257 // compare amount hint only if there is no amount
1259 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1260 Misc.equalStrings(amountHint, other.amountHint)
1261 : !other.amountHintIsSet);
1262 equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1264 Logger.debug("new-trans",
1265 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1269 public int getAccountNameCursorPosition() {
1270 return accountNameCursorPosition;
1272 public void setAccountNameCursorPosition(int position) {
1273 this.accountNameCursorPosition = position;
1277 private static class BalanceForCurrency {
1278 private final HashMap<String, Float> hashMap = new HashMap<>();
1279 float get(String currencyName) {
1280 Float f = hashMap.get(currencyName);
1283 hashMap.put(currencyName, f);
1287 void add(String currencyName, float amount) {
1288 hashMap.put(currencyName, get(currencyName) + amount);
1290 Set<String> currencies() {
1291 return hashMap.keySet();
1293 boolean containsCurrency(String currencyName) {
1294 return hashMap.containsKey(currencyName);
1298 private static class ItemsForCurrency {
1299 private final HashMap<@NotNull String, List<Item>> hashMap = new HashMap<>();
1301 List<NewTransactionModel.Item> getList(@NotNull String currencyName) {
1302 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1304 list = new ArrayList<>();
1305 hashMap.put(currencyName, list);
1309 void add(@NotNull String currencyName, @NonNull NewTransactionModel.Item item) {
1310 getList(Objects.requireNonNull(currencyName)).add(item);
1312 int size(@NotNull String currencyName) {
1313 return this.getList(Objects.requireNonNull(currencyName))
1316 Set<String> currencies() {
1317 return hashMap.keySet();