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 replaceItems(@NonNull List<Item> newList) {
101 * make old items replaceable in-place. makes the new values visually blend in
103 private void renumberItems() {
104 final List<Item> list = items.getValue();
110 for (Item item : list)
113 private void setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
114 final int cnt = list.size();
115 for (int i = 1; i < cnt - 1; i++) {
116 final TransactionAccount item = list.get(i)
117 .toTransactionAccount();
119 TransactionAccount replacement = new TransactionAccount(item);
120 replacement.isLast = false;
121 list.set(i, replacement);
124 final TransactionAccount last = list.get(cnt - 1)
125 .toTransactionAccount();
127 TransactionAccount replacement = new TransactionAccount(last);
128 replacement.isLast = true;
129 list.set(cnt - 1, replacement);
132 if (BuildConfig.DEBUG)
133 dumpItemList("Before setValue()", list);
134 items.setValue(list);
136 private List<Item> copyList() {
137 List<Item> copy = new ArrayList<>();
138 List<Item> oldList = items.getValue();
141 for (Item item : oldList) {
142 copy.add(Item.from(item));
147 private List<Item> copyListWithoutItem(int position) {
148 List<Item> copy = new ArrayList<>();
149 List<Item> oldList = items.getValue();
151 if (oldList != null) {
153 for (Item item : oldList) {
156 copy.add(Item.from(item));
162 private List<Item> shallowCopyList() {
163 return new ArrayList<>(items.getValue());
165 LiveData<Boolean> getShowComments() {
168 void observeDataProfile(LifecycleOwner activity) {
169 if (!observingDataProfile)
170 Data.observeProfile(activity, profileObserver);
171 observingDataProfile = true;
173 boolean getSimulateSaveFlag() {
174 Boolean value = simulateSave.getValue();
179 LiveData<Boolean> getSimulateSave() {
182 void toggleSimulateSave() {
183 simulateSave.setValue(!getSimulateSaveFlag());
185 LiveData<Boolean> isSubmittable() {
186 return this.isSubmittable;
189 Logger.debug("new-trans", "Resetting model");
190 List<Item> list = new ArrayList<>();
191 Item.resetIdDispenser();
192 list.add(new TransactionHead(""));
193 list.add(new TransactionAccount(""));
194 list.add(new TransactionAccount(""));
195 noteFocusChanged(0, FocusedElement.Description);
197 isSubmittable.setValue(false);
198 setItemsWithoutSubmittableChecks(list);
200 boolean accountsInInitialState() {
201 final List<Item> list = items.getValue();
206 for (Item item : list) {
207 if (!(item instanceof TransactionAccount))
210 TransactionAccount accRow = (TransactionAccount) item;
211 if (!accRow.isEmpty())
217 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
218 SimpleDate transactionDate = null;
219 final MatchResult matchResult = matchedTemplate.matchResult;
220 final TemplateHeader templateHead = matchedTemplate.templateHead;
222 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
223 templateHead.getDateDay());
224 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
225 templateHead.getDateMonth());
226 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
227 templateHead.getDateYear());
229 if (year > 0 || month > 0 || day > 0) {
230 SimpleDate today = SimpleDate.today();
238 transactionDate = new SimpleDate(year, month, day);
240 Logger.debug("pattern", "setting transaction date to " + transactionDate);
244 List<Item> present = copyList();
246 TransactionHead head = new TransactionHead(present.get(0)
247 .toTransactionHead());
248 if (transactionDate != null)
249 head.setDate(transactionDate);
251 final String transactionDescription = extractStringFromMatches(matchResult,
252 templateHead.getTransactionDescriptionMatchGroup(),
253 templateHead.getTransactionDescription());
254 if (Misc.emptyIsNull(transactionDescription) != null)
255 head.setDescription(transactionDescription);
257 final String transactionComment = extractStringFromMatches(matchResult,
258 templateHead.getTransactionCommentMatchGroup(),
259 templateHead.getTransactionComment());
260 if (Misc.emptyIsNull(transactionComment) != null)
261 head.setComment(transactionComment);
263 Item.resetIdDispenser();
264 List<Item> newItems = new ArrayList<>();
268 for (int i = 1; i < present.size(); i++) {
269 final TransactionAccount row = present.get(i)
270 .toTransactionAccount();
272 newItems.add(new TransactionAccount(row));
277 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
279 final boolean accountsInInitialState = accountsInInitialState();
280 for (TemplateAccount acc : entry.accounts) {
284 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
285 acc.getAccountName());
286 String accountComment =
287 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
288 acc.getAccountComment());
289 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
291 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
295 TransactionAccount accRow = new TransactionAccount(accountName);
296 accRow.setComment(accountComment);
298 accRow.setAmount(amount);
300 newItems.add(accRow);
303 new Handler(Looper.getMainLooper()).post(() -> replaceItems(newItems));
306 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
312 if (grp > 0 & grp <= m.groupCount())
314 return Integer.parseInt(m.group(grp));
316 catch (NumberFormatException e) {
317 Logger.debug("new-trans", "Error extracting matched number", e);
323 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
329 if (grp > 0 & grp <= m.groupCount())
335 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
341 if (grp > 0 & grp <= m.groupCount())
343 return Float.valueOf(m.group(grp));
345 catch (NumberFormatException e) {
346 Logger.debug("new-trans", "Error extracting matched number", e);
352 void removeItem(int pos) {
353 Logger.debug("new-trans", String.format(Locale.US, "Removing item at position %d", pos));
354 List<Item> newList = copyListWithoutItem(pos);
355 final FocusInfo fi = focusInfo.getValue();
356 if ((fi != null) && (pos < fi.position))
357 noteFocusChanged(fi.position - 1, fi.element);
360 void noteFocusChanged(int position, FocusedElement element) {
361 FocusInfo present = focusInfo.getValue();
362 if (present == null || present.position != position || present.element != element)
363 focusInfo.setValue(new FocusInfo(position, element));
365 public LiveData<FocusInfo> getFocusInfo() {
368 void moveItem(int fromIndex, int toIndex) {
369 List<Item> newList = shallowCopyList();
370 Item item = newList.remove(fromIndex);
371 newList.add(toIndex, item);
373 FocusInfo fi = focusInfo.getValue();
374 if (fi != null && fi.position == fromIndex)
375 noteFocusChanged(toIndex, fi.element);
377 items.setValue(newList); // same count, same submittable state
379 void moveItemLast(List<Item> list, int index) {
383 3 <-- desired position
386 int itemCount = list.size();
388 if (index < itemCount - 1)
389 list.add(list.remove(index));
391 void toggleCurrencyVisible() {
392 final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
394 // remove currency from all items, or reset currency to the default
395 // no need to clone the list, because the removal of the currency won't lead to
396 // visual changes -- the currency fields will be hidden or reset to default anyway
397 // still, there may be changes in the submittable state
398 final List<Item> list = Objects.requireNonNull(this.items.getValue());
399 for (int i = 1; i < list.size(); i++) {
400 ((TransactionAccount) list.get(i)).setCurrency(newValue ? Data.getProfile()
401 .getDefaultCommodity()
404 checkTransactionSubmittable(null);
405 showCurrency.setValue(newValue);
407 void stopObservingBusyFlag(Observer<Boolean> observer) {
408 busyFlag.removeObserver(observer);
410 void incrementBusyCounter() {
411 int newValue = busyCounter.incrementAndGet();
413 busyFlag.postValue(true);
415 void decrementBusyCounter() {
416 int newValue = busyCounter.decrementAndGet();
418 busyFlag.postValue(false);
420 public LiveData<Boolean> getBusyFlag() {
423 public void toggleShowComments() {
424 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
426 public LedgerTransaction constructLedgerTransaction() {
427 List<Item> list = Objects.requireNonNull(items.getValue());
428 TransactionHead head = list.get(0)
429 .toTransactionHead();
430 SimpleDate date = head.getDate();
431 LedgerTransaction tr = head.asLedgerTransaction();
433 tr.setComment(head.getComment());
434 LedgerTransactionAccount emptyAmountAccount = null;
435 float emptyAmountAccountBalance = 0;
436 for (int i = 1; i < list.size(); i++) {
437 TransactionAccount item = list.get(i)
438 .toTransactionAccount();
439 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
442 if (acc.getAccountName()
446 acc.setComment(item.getComment());
448 if (item.isAmountSet()) {
449 acc.setAmount(item.getAmount());
450 emptyAmountAccountBalance += item.getAmount();
453 emptyAmountAccount = acc;
459 if (emptyAmountAccount != null)
460 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
464 void loadTransactionIntoModel(long profileId, int transactionId) {
465 List<Item> newList = new ArrayList<>();
466 Item.resetIdDispenser();
467 LedgerTransaction tr;
468 MobileLedgerProfile profile = Data.getProfile(profileId);
470 throw new RuntimeException(String.format(
471 "Unable to find profile %s, which is supposed to contain transaction %d",
472 profileId, transactionId));
474 tr = profile.loadTransaction(transactionId);
475 TransactionHead head = new TransactionHead(tr.getDescription());
476 head.setComment(tr.getComment());
480 List<LedgerTransactionAccount> accounts = tr.getAccounts();
482 TransactionAccount firstNegative = null;
483 TransactionAccount firstPositive = null;
484 int singleNegativeIndex = -1;
485 int singlePositiveIndex = -1;
486 int negativeCount = 0;
487 for (int i = 0; i < accounts.size(); i++) {
488 LedgerTransactionAccount acc = accounts.get(i);
489 TransactionAccount item =
490 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
493 item.setAccountName(acc.getAccountName());
494 item.setComment(acc.getComment());
495 if (acc.isAmountSet()) {
496 item.setAmount(acc.getAmount());
497 if (acc.getAmount() < 0) {
498 if (firstNegative == null) {
499 firstNegative = item;
500 singleNegativeIndex = i + 1;
503 singleNegativeIndex = -1;
506 if (firstPositive == null) {
507 firstPositive = item;
508 singlePositiveIndex = i + 1;
511 singlePositiveIndex = -1;
517 if (BuildConfig.DEBUG)
518 dumpItemList("Loaded previous transaction", newList);
520 if (singleNegativeIndex != -1) {
521 firstNegative.resetAmount();
522 moveItemLast(newList, singleNegativeIndex);
524 else if (singlePositiveIndex != -1) {
525 firstPositive.resetAmount();
526 moveItemLast(newList, singlePositiveIndex);
531 noteFocusChanged(1, FocusedElement.Amount);
534 * A transaction is submittable if:
536 * 1) has at least two account names
537 * 2) each row with amount has account name
538 * 3) for each commodity:
539 * 3a) amounts must balance to 0, or
540 * 3b) there must be exactly one empty amount (with account)
541 * 4) empty accounts with empty amounts are ignored
543 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
545 * 6) at least two rows need to be present in the ledger
547 * @param list - the item list to check. Can be the displayed list or a list that will be
550 @SuppressLint("DefaultLocale")
551 void checkTransactionSubmittable(@Nullable List<Item> list) {
552 boolean workingWithLiveList = false;
555 workingWithLiveList = true;
558 if (BuildConfig.DEBUG)
559 dumpItemList(String.format("Before submittable checks (%s)",
560 workingWithLiveList ? "LIVE LIST" : "custom list"), list);
563 final BalanceForCurrency balance = new BalanceForCurrency();
564 final String descriptionText = list.get(0)
567 boolean submittable = true;
568 boolean listChanged = false;
569 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
570 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
571 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
572 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
573 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
574 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
575 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
576 final List<Item> emptyRows = new ArrayList<>();
579 if ((descriptionText == null) || descriptionText.trim()
582 Logger.debug("submittable", "Transaction not submittable: missing description");
586 for (int i = 1; i < list.size(); i++) {
587 TransactionAccount item = list.get(i)
588 .toTransactionAccount();
590 String accName = item.getAccountName()
592 String currName = item.getCurrency();
594 itemsForCurrency.add(currName, item);
596 if (accName.isEmpty()) {
597 itemsWithEmptyAccountForCurrency.add(currName, item);
599 if (item.isAmountSet()) {
600 // 2) each amount has account name
601 Logger.debug("submittable", String.format(
602 "Transaction not submittable: row %d has no account name, but" +
603 " has" + " amount %1.2f", i + 1, item.getAmount()));
607 emptyRowsForCurrency.add(currName, item);
612 itemsWithAccountForCurrency.add(currName, item);
615 if (!item.isAmountValid()) {
616 Logger.debug("submittable",
617 String.format("Not submittable: row %d has an invalid amount", i + 1));
620 else if (item.isAmountSet()) {
621 itemsWithAmountForCurrency.add(currName, item);
622 balance.add(currName, item.getAmount());
625 itemsWithEmptyAmountForCurrency.add(currName, item);
627 if (!accName.isEmpty())
628 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
632 // 1) has at least two account names
635 Logger.debug("submittable", "Transaction not submittable: no account names");
636 else if (accounts == 1)
637 Logger.debug("submittable",
638 "Transaction not submittable: only one account name");
640 Logger.debug("submittable",
641 String.format("Transaction not submittable: only %d account names",
646 // 3) for each commodity:
647 // 3a) amount must balance to 0, or
648 // 3b) there must be exactly one empty amount (with account)
649 for (String balCurrency : itemsForCurrency.currencies()) {
650 float currencyBalance = balance.get(balCurrency);
651 if (Misc.isZero(currencyBalance)) {
652 // remove hints from all amount inputs in that currency
653 for (int i = 1; i < list.size(); i++) {
654 TransactionAccount acc = list.get(i)
655 .toTransactionAccount();
656 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
657 if (BuildConfig.DEBUG)
658 Logger.debug("submittable",
659 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
660 i, Misc.nullIsEmpty(acc.getAccountName()),
662 // skip if the amount is set, in which case the hint is not
664 if (!acc.isAmountSet() && acc.amountHintIsSet &&
665 !TextUtils.isEmpty(acc.getAmountHint()))
667 acc.setAmountHint(null);
675 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
676 int balanceReceiversCount = tmpList.size();
677 if (balanceReceiversCount != 1) {
678 if (BuildConfig.DEBUG) {
679 if (balanceReceiversCount == 0)
680 Logger.debug("submittable", String.format(
681 "Transaction not submittable [%s]: non-zero balance " +
682 "with no empty amounts with accounts", balCurrency));
684 Logger.debug("submittable", String.format(
685 "Transaction not submittable [%s]: non-zero balance " +
686 "with multiple empty amounts with accounts", balCurrency));
691 List<Item> emptyAmountList =
692 itemsWithEmptyAmountForCurrency.getList(balCurrency);
694 // suggest off-balance amount to a row and remove hints on other rows
695 Item receiver = null;
696 if (!tmpList.isEmpty())
697 receiver = tmpList.get(0);
698 else if (!emptyAmountList.isEmpty())
699 receiver = emptyAmountList.get(0);
701 for (int i = 0; i < list.size(); i++) {
702 Item item = list.get(i);
703 if (!(item instanceof TransactionAccount))
706 TransactionAccount acc = item.toTransactionAccount();
707 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
710 if (item == receiver) {
711 final String hint = String.format("%1.2f", -currencyBalance);
712 if (!acc.isAmountHintSet() ||
713 !Misc.equalStrings(acc.getAmountHint(), hint))
715 Logger.debug("submittable",
716 String.format("Setting amount hint of {%s} to %s [%s]",
717 acc.toString(), hint, balCurrency));
718 acc.setAmountHint(hint);
723 if (BuildConfig.DEBUG)
724 Logger.debug("submittable",
725 String.format("Resetting hint of '%s' [%s]",
726 Misc.nullIsEmpty(acc.getAccountName()),
728 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
729 acc.setAmountHint(null);
737 // 5) a row with an empty account name or empty amount is guaranteed to exist for
739 for (String balCurrency : balance.currencies()) {
740 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
741 int currRows = itemsForCurrency.size(balCurrency);
742 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
743 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
744 if ((currEmptyRows == 0) &&
745 ((currRows == currAccounts) || (currRows == currAmounts)))
747 // perhaps there already is an unused empty row for another currency that
749 // boolean foundIt = false;
750 // for (Item item : emptyRows) {
751 // Currency itemCurrency = item.getCurrency();
752 // String itemCurrencyName =
753 // (itemCurrency == null) ? "" : itemCurrency.getName();
754 // if (Misc.isZero(balance.get(itemCurrencyName))) {
755 // item.setCurrency(Currency.loadByName(balCurrency));
756 // item.setAmountHint(
757 // String.format("%1.2f", -balance.get(balCurrency)));
764 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
765 final float bal = balance.get(balCurrency);
766 if (!Misc.isZero(bal) && currAmounts == currRows)
767 newAcc.setAmountHint(String.format("%4.2f", -bal));
768 Logger.debug("submittable",
769 String.format("Adding new item with %s for currency %s",
770 newAcc.getAmountHint(), balCurrency));
776 // drop extra empty rows, not needed
777 for (String currName : emptyRowsForCurrency.currencies()) {
778 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
779 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
780 // the list is a copy, so the empty item is no longer present
781 Item itemToRemove = emptyItems.remove(1);
782 removeItemById(list, itemToRemove.id);
786 // unused currency, remove last item (which is also an empty one)
787 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
788 List<Item> currItems = itemsForCurrency.getList(currName);
790 if (currItems.size() == 1) {
791 // the list is a copy, so the empty item is no longer present
792 removeItemById(list, emptyItems.get(0).id);
798 // 6) at least two rows need to be present in the ledger
799 // (the list also contains header and trailer)
800 while (list.size() < MIN_ITEMS) {
801 list.add(new TransactionAccount(""));
805 Logger.debug("submittable", submittable ? "YES" : "NO");
806 isSubmittable.setValue(submittable);
808 if (BuildConfig.DEBUG)
809 dumpItemList("After submittable checks", list);
811 catch (NumberFormatException e) {
812 Logger.debug("submittable", "NO (because of NumberFormatException)");
813 isSubmittable.setValue(false);
815 catch (Exception e) {
817 Logger.debug("submittable", "NO (because of an Exception)");
818 isSubmittable.setValue(false);
821 if (listChanged && workingWithLiveList) {
822 setItemsWithoutSubmittableChecks(list);
825 private void removeItemById(@NotNull List<Item> list, int id) {
826 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
827 list.removeIf(item -> item.id == id);
830 for (Item item : list) {
838 @SuppressLint("DefaultLocale")
839 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
840 Logger.debug("submittable", "== Dump of all items " + msg);
841 for (int i = 1; i < list.size(); i++) {
842 TransactionAccount item = list.get(i)
843 .toTransactionAccount();
844 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
847 public void setItemCurrency(int position, String newCurrency) {
848 TransactionAccount item = Objects.requireNonNull(items.getValue())
850 .toTransactionAccount();
851 final String oldCurrency = item.getCurrency();
853 if (Misc.equalStrings(oldCurrency, newCurrency))
856 List<Item> newList = copyList();
857 newList.get(position)
858 .toTransactionAccount()
859 .setCurrency(newCurrency);
863 public boolean accountListIsEmpty() {
864 List<Item> items = Objects.requireNonNull(this.items.getValue());
866 for (Item item : items) {
867 if (!(item instanceof TransactionAccount))
870 if (!((TransactionAccount) item).isEmpty())
877 public static class FocusInfo {
879 FocusedElement element;
880 public FocusInfo(int position, FocusedElement element) {
881 this.position = position;
882 this.element = element;
886 static abstract class Item {
887 private static int idDispenser = 0;
890 if (this instanceof TransactionHead)
893 synchronized (Item.class) {
897 public Item(int id) {
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);
907 private static void resetIdDispenser() {
913 public abstract ItemType getType();
914 public TransactionHead toTransactionHead() {
915 if (this instanceof TransactionHead)
916 return (TransactionHead) this;
918 throw new IllegalStateException("Wrong item type " + this);
920 public TransactionAccount toTransactionAccount() {
921 if (this instanceof TransactionAccount)
922 return (TransactionAccount) this;
924 throw new IllegalStateException("Wrong item type " + this);
926 public boolean equalContents(@Nullable Object item) {
930 if (!getClass().equals(item.getClass()))
933 // shortcut - comparing same instance
937 if (this instanceof TransactionHead)
938 return ((TransactionHead) item).equalContents((TransactionHead) this);
939 if (this instanceof TransactionAccount)
940 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
942 throw new RuntimeException("Don't know how to handle " + this);
947 //==========================================================================================
949 public static class TransactionHead extends Item {
950 private SimpleDate date;
951 private String description;
952 private String comment;
953 TransactionHead(String description) {
955 this.description = description;
957 public TransactionHead(TransactionHead origin) {
960 description = origin.description;
961 comment = origin.comment;
963 public SimpleDate getDate() {
966 public void setDate(SimpleDate date) {
969 public void setDate(String text) throws ParseException {
970 if (Misc.emptyIsNull(text) == null) {
975 date = Globals.parseLedgerDate(text);
980 * @return nicely formatted, shortest available date representation
982 String getFormattedDate() {
986 Calendar today = GregorianCalendar.getInstance();
988 if (today.get(Calendar.YEAR) != date.year) {
989 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
992 if (today.get(Calendar.MONTH) + 1 != date.month) {
993 return String.format(Locale.US, "%d/%02d", date.month, date.day);
996 return String.valueOf(date.day);
1000 public String toString() {
1001 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
1002 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1004 if (TextUtils.isEmpty(description))
1005 b.append(" «no description»");
1007 b.append(String.format(" '%s'", description));
1010 b.append(String.format("@%s", date.toString()));
1012 if (!TextUtils.isEmpty(comment))
1013 b.append(String.format(" /%s/", comment));
1015 return b.toString();
1017 public String getDescription() {
1020 public void setDescription(String description) {
1021 this.description = description;
1023 public String getComment() {
1026 public void setComment(String comment) {
1027 this.comment = comment;
1030 public ItemType getType() {
1031 return ItemType.generalData;
1033 public LedgerTransaction asLedgerTransaction() {
1034 return new LedgerTransaction(0, date, description, Data.getProfile());
1036 public boolean equalContents(TransactionHead other) {
1040 return Objects.equals(date, other.date) &&
1041 Misc.equalStrings(description, other.description) &&
1042 Misc.equalStrings(comment, other.comment);
1046 public static class TransactionAccount extends Item {
1047 private String accountName;
1048 private String amountHint;
1049 private String comment;
1050 private String currency;
1051 private float amount;
1052 private boolean amountSet;
1053 private boolean amountValid = true;
1054 private FocusedElement focusedElement = FocusedElement.Account;
1055 private boolean amountHintIsSet = false;
1056 private boolean isLast = false;
1057 private int accountNameCursorPosition;
1058 public TransactionAccount(TransactionAccount origin) {
1060 accountName = origin.accountName;
1061 amount = origin.amount;
1062 amountSet = origin.amountSet;
1063 amountHint = origin.amountHint;
1064 amountHintIsSet = origin.amountHintIsSet;
1065 comment = origin.comment;
1066 currency = origin.currency;
1067 amountValid = origin.amountValid;
1068 focusedElement = origin.focusedElement;
1069 isLast = origin.isLast;
1070 accountNameCursorPosition = origin.accountNameCursorPosition;
1072 public TransactionAccount(LedgerTransactionAccount account) {
1074 currency = account.getCurrency();
1075 amount = account.getAmount();
1077 public TransactionAccount(String accountName) {
1079 this.accountName = accountName;
1081 public TransactionAccount(String accountName, String currency) {
1083 this.accountName = accountName;
1084 this.currency = currency;
1086 public boolean isLast() {
1089 public boolean isAmountSet() {
1092 public String getAccountName() {
1095 public void setAccountName(String accountName) {
1096 this.accountName = accountName;
1098 public float getAmount() {
1100 throw new IllegalStateException("Amount is not set");
1103 public void setAmount(float amount) {
1104 this.amount = amount;
1107 public void resetAmount() {
1111 public ItemType getType() {
1112 return ItemType.transactionRow;
1114 public String getAmountHint() {
1117 public void setAmountHint(String amountHint) {
1118 this.amountHint = amountHint;
1119 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1121 public String getComment() {
1124 public void setComment(String comment) {
1125 this.comment = comment;
1127 public String getCurrency() {
1130 public void setCurrency(String currency) {
1131 this.currency = currency;
1133 public boolean isAmountValid() {
1136 public void setAmountValid(boolean amountValid) {
1137 this.amountValid = amountValid;
1139 public FocusedElement getFocusedElement() {
1140 return focusedElement;
1142 public void setFocusedElement(FocusedElement focusedElement) {
1143 this.focusedElement = focusedElement;
1145 public boolean isAmountHintSet() {
1146 return amountHintIsSet;
1148 public void setAmountHintIsSet(boolean amountHintIsSet) {
1149 this.amountHintIsSet = amountHintIsSet;
1151 public boolean isEmpty() {
1152 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1153 Misc.emptyIsNull(comment) == null;
1155 @SuppressLint("DefaultLocale")
1157 public String toString() {
1158 StringBuilder b = new StringBuilder();
1159 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1160 if (!TextUtils.isEmpty(accountName))
1161 b.append(String.format(" acc'%s'", accountName));
1164 b.append(String.format(" %4.2f", amount));
1165 else if (amountHintIsSet)
1166 b.append(String.format(" (%s)", amountHint));
1168 if (!TextUtils.isEmpty(currency))
1172 if (!TextUtils.isEmpty(comment))
1173 b.append(String.format(" /%s/", comment));
1178 return b.toString();
1180 public boolean equalContents(TransactionAccount other) {
1184 boolean equal = Misc.equalStrings(accountName, other.accountName);
1185 equal = equal && Misc.equalStrings(comment, other.comment) &&
1186 (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1188 // compare amount hint only if there is no amount
1190 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1191 Misc.equalStrings(amountHint, other.amountHint)
1192 : !other.amountHintIsSet);
1193 equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1195 Logger.debug("new-trans",
1196 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1200 public int getAccountNameCursorPosition() {
1201 return accountNameCursorPosition;
1203 public void setAccountNameCursorPosition(int position) {
1204 this.accountNameCursorPosition = position;
1208 private static class BalanceForCurrency {
1209 private final HashMap<String, Float> hashMap = new HashMap<>();
1210 float get(String currencyName) {
1211 Float f = hashMap.get(currencyName);
1214 hashMap.put(currencyName, f);
1218 void add(String currencyName, float amount) {
1219 hashMap.put(currencyName, get(currencyName) + amount);
1221 Set<String> currencies() {
1222 return hashMap.keySet();
1224 boolean containsCurrency(String currencyName) {
1225 return hashMap.containsKey(currencyName);
1229 private static class ItemsForCurrency {
1230 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1232 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1233 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1235 list = new ArrayList<>();
1236 hashMap.put(currencyName, list);
1240 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1241 getList(currencyName).add(item);
1243 int size(@Nullable String currencyName) {
1244 return this.getList(currencyName)
1247 Set<String> currencies() {
1248 return hashMap.keySet();