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.Profile;
36 import net.ktnx.mobileledger.db.TemplateAccount;
37 import net.ktnx.mobileledger.db.TemplateHeader;
38 import net.ktnx.mobileledger.db.TransactionWithAccounts;
39 import net.ktnx.mobileledger.model.Data;
40 import net.ktnx.mobileledger.model.InertMutableLiveData;
41 import net.ktnx.mobileledger.model.LedgerTransaction;
42 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
43 import net.ktnx.mobileledger.model.MatchedTemplate;
44 import net.ktnx.mobileledger.utils.Globals;
45 import net.ktnx.mobileledger.utils.Logger;
46 import net.ktnx.mobileledger.utils.Misc;
47 import net.ktnx.mobileledger.utils.SimpleDate;
49 import org.jetbrains.annotations.NotNull;
51 import java.text.ParseException;
52 import java.util.ArrayList;
53 import java.util.Calendar;
54 import java.util.GregorianCalendar;
55 import java.util.HashMap;
56 import java.util.List;
57 import java.util.Locale;
58 import java.util.Objects;
60 import java.util.concurrent.atomic.AtomicInteger;
61 import java.util.regex.MatchResult;
63 enum ItemType {generalData, transactionRow}
65 enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
68 public class NewTransactionModel extends ViewModel {
69 private static final int MIN_ITEMS = 3;
70 private final MutableLiveData<Boolean> showCurrency = new MutableLiveData<>(false);
71 private final MutableLiveData<Boolean> isSubmittable = new InertMutableLiveData<>(false);
72 private final MutableLiveData<Boolean> showComments = new MutableLiveData<>(true);
73 private final MutableLiveData<List<Item>> items = new MutableLiveData<>();
74 private final MutableLiveData<Boolean> simulateSave = new InertMutableLiveData<>(false);
75 private final AtomicInteger busyCounter = new AtomicInteger(0);
76 private final MutableLiveData<Boolean> busyFlag = new InertMutableLiveData<>(false);
77 private final Observer<Profile> profileObserver = profile -> {
78 showCurrency.postValue(profile.getShowCommodityByDefault());
79 showComments.postValue(profile.getShowCommentsByDefault());
81 private final MutableLiveData<FocusInfo> focusInfo = new MutableLiveData<>();
82 private boolean observingDataProfile;
83 public NewTransactionModel() {
86 public LiveData<Boolean> getShowCurrency() {
89 public LiveData<List<Item>> getItems() {
92 private void setItems(@NonNull List<Item> newList) {
93 checkTransactionSubmittable(newList);
94 setItemsWithoutSubmittableChecks(newList);
96 private void replaceItems(@NonNull List<Item> newList) {
102 * make old items replaceable in-place. makes the new values visually blend in
104 private void renumberItems() {
105 final List<Item> list = items.getValue();
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<>(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 list.add(new TransactionAccount(""));
195 list.add(new TransactionAccount(""));
196 noteFocusChanged(0, FocusedElement.Description);
198 isSubmittable.setValue(false);
199 setItemsWithoutSubmittableChecks(list);
201 boolean accountsInInitialState() {
202 final List<Item> list = items.getValue();
207 for (Item item : list) {
208 if (!(item instanceof TransactionAccount))
211 TransactionAccount accRow = (TransactionAccount) item;
212 if (!accRow.isEmpty())
218 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
219 SimpleDate transactionDate = null;
220 final MatchResult matchResult = matchedTemplate.matchResult;
221 final TemplateHeader templateHead = matchedTemplate.templateHead;
223 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
224 templateHead.getDateDay());
225 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
226 templateHead.getDateMonth());
227 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
228 templateHead.getDateYear());
230 if (year > 0 || month > 0 || day > 0) {
231 SimpleDate today = SimpleDate.today();
239 transactionDate = new SimpleDate(year, month, day);
241 Logger.debug("pattern", "setting transaction date to " + transactionDate);
245 List<Item> present = copyList();
247 TransactionHead head = new TransactionHead(present.get(0)
248 .toTransactionHead());
249 if (transactionDate != null)
250 head.setDate(transactionDate);
252 final String transactionDescription = extractStringFromMatches(matchResult,
253 templateHead.getTransactionDescriptionMatchGroup(),
254 templateHead.getTransactionDescription());
255 if (Misc.emptyIsNull(transactionDescription) != null)
256 head.setDescription(transactionDescription);
258 final String transactionComment = extractStringFromMatches(matchResult,
259 templateHead.getTransactionCommentMatchGroup(),
260 templateHead.getTransactionComment());
261 if (Misc.emptyIsNull(transactionComment) != null)
262 head.setComment(transactionComment);
264 Item.resetIdDispenser();
265 List<Item> newItems = new ArrayList<>();
269 for (int i = 1; i < present.size(); i++) {
270 final TransactionAccount row = present.get(i)
271 .toTransactionAccount();
273 newItems.add(new TransactionAccount(row));
278 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
280 final boolean accountsInInitialState = accountsInInitialState();
281 for (TemplateAccount acc : entry.accounts) {
285 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
286 acc.getAccountName());
287 String accountComment =
288 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
289 acc.getAccountComment());
290 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
292 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
296 TransactionAccount accRow = new TransactionAccount(accountName);
297 accRow.setComment(accountComment);
299 accRow.setAmount(amount);
301 newItems.add(accRow);
304 new Handler(Looper.getMainLooper()).post(() -> replaceItems(newItems));
307 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
313 if (grp > 0 & grp <= m.groupCount())
315 return Integer.parseInt(m.group(grp));
317 catch (NumberFormatException e) {
318 Logger.debug("new-trans", "Error extracting matched number", e);
324 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
330 if (grp > 0 & grp <= m.groupCount())
336 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
342 if (grp > 0 & grp <= m.groupCount())
344 return Float.valueOf(m.group(grp));
346 catch (NumberFormatException e) {
347 Logger.debug("new-trans", "Error extracting matched number", e);
353 void removeItem(int pos) {
354 Logger.debug("new-trans", String.format(Locale.US, "Removing item at position %d", pos));
355 List<Item> newList = copyListWithoutItem(pos);
356 final FocusInfo fi = focusInfo.getValue();
357 if ((fi != null) && (pos < fi.position))
358 noteFocusChanged(fi.position - 1, fi.element);
361 void noteFocusChanged(int position, FocusedElement element) {
362 FocusInfo present = focusInfo.getValue();
363 if (present == null || present.position != position || present.element != element)
364 focusInfo.setValue(new FocusInfo(position, element));
366 public LiveData<FocusInfo> getFocusInfo() {
369 void moveItem(int fromIndex, int toIndex) {
370 List<Item> newList = shallowCopyList();
371 Item item = newList.remove(fromIndex);
372 newList.add(toIndex, item);
374 FocusInfo fi = focusInfo.getValue();
375 if (fi != null && fi.position == fromIndex)
376 noteFocusChanged(toIndex, fi.element);
378 items.setValue(newList); // same count, same submittable state
380 void moveItemLast(List<Item> list, int index) {
384 3 <-- desired position
387 int itemCount = list.size();
389 if (index < itemCount - 1)
390 list.add(list.remove(index));
392 void toggleCurrencyVisible() {
393 final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
395 // remove currency from all items, or reset currency to the default
396 // no need to clone the list, because the removal of the currency won't lead to
397 // visual changes -- the currency fields will be hidden or reset to default anyway
398 // still, there may be changes in the submittable state
399 final List<Item> list = Objects.requireNonNull(this.items.getValue());
400 for (int i = 1; i < list.size(); i++) {
401 ((TransactionAccount) list.get(i)).setCurrency(newValue ? Data.getProfile()
402 .getDefaultCommodity()
405 checkTransactionSubmittable(null);
406 showCurrency.setValue(newValue);
408 void stopObservingBusyFlag(Observer<Boolean> observer) {
409 busyFlag.removeObserver(observer);
411 void incrementBusyCounter() {
412 int newValue = busyCounter.incrementAndGet();
414 busyFlag.postValue(true);
416 void decrementBusyCounter() {
417 int newValue = busyCounter.decrementAndGet();
419 busyFlag.postValue(false);
421 public LiveData<Boolean> getBusyFlag() {
424 public void toggleShowComments() {
425 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
427 public LedgerTransaction constructLedgerTransaction() {
428 List<Item> list = Objects.requireNonNull(items.getValue());
429 TransactionHead head = list.get(0)
430 .toTransactionHead();
431 SimpleDate date = head.getDate();
432 LedgerTransaction tr = head.asLedgerTransaction();
434 tr.setComment(head.getComment());
435 LedgerTransactionAccount emptyAmountAccount = null;
436 float emptyAmountAccountBalance = 0;
437 for (int i = 1; i < list.size(); i++) {
438 TransactionAccount item = list.get(i)
439 .toTransactionAccount();
440 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
443 if (acc.getAccountName()
447 acc.setComment(item.getComment());
449 if (item.isAmountSet()) {
450 acc.setAmount(item.getAmount());
451 emptyAmountAccountBalance += item.getAmount();
454 emptyAmountAccount = acc;
460 if (emptyAmountAccount != null)
461 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
465 void loadTransactionIntoModel(@NonNull TransactionWithAccounts tr) {
466 List<Item> newList = new ArrayList<>();
467 Item.resetIdDispenser();
469 TransactionHead head = new TransactionHead(tr.transaction.getDescription());
470 head.setComment(tr.transaction.getComment());
474 List<LedgerTransactionAccount> accounts = new ArrayList<>();
475 for (net.ktnx.mobileledger.db.TransactionAccount acc : tr.accounts) {
476 accounts.add(new LedgerTransactionAccount(acc));
479 TransactionAccount firstNegative = null;
480 TransactionAccount firstPositive = null;
481 int singleNegativeIndex = -1;
482 int singlePositiveIndex = -1;
483 int negativeCount = 0;
484 for (int i = 0; i < accounts.size(); i++) {
485 LedgerTransactionAccount acc = accounts.get(i);
486 TransactionAccount item =
487 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
490 item.setAccountName(acc.getAccountName());
491 item.setComment(acc.getComment());
492 if (acc.isAmountSet()) {
493 item.setAmount(acc.getAmount());
494 if (acc.getAmount() < 0) {
495 if (firstNegative == null) {
496 firstNegative = item;
497 singleNegativeIndex = i + 1;
500 singleNegativeIndex = -1;
503 if (firstPositive == null) {
504 firstPositive = item;
505 singlePositiveIndex = i + 1;
508 singlePositiveIndex = -1;
514 if (BuildConfig.DEBUG)
515 dumpItemList("Loaded previous transaction", newList);
517 if (singleNegativeIndex != -1) {
518 firstNegative.resetAmount();
519 moveItemLast(newList, singleNegativeIndex);
521 else if (singlePositiveIndex != -1) {
522 firstPositive.resetAmount();
523 moveItemLast(newList, singlePositiveIndex);
526 new Handler(Looper.getMainLooper()).post(() -> {
528 noteFocusChanged(1, FocusedElement.Amount);
532 * A transaction is submittable if:
534 * 1) has at least two account names
535 * 2) each row with amount has account name
536 * 3) for each commodity:
537 * 3a) amounts must balance to 0, or
538 * 3b) there must be exactly one empty amount (with account)
539 * 4) empty accounts with empty amounts are ignored
541 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
543 * 6) at least two rows need to be present in the ledger
545 * @param list - the item list to check. Can be the displayed list or a list that will be
548 @SuppressLint("DefaultLocale")
549 void checkTransactionSubmittable(@Nullable List<Item> list) {
550 boolean workingWithLiveList = false;
553 workingWithLiveList = true;
556 if (BuildConfig.DEBUG)
557 dumpItemList(String.format("Before submittable checks (%s)",
558 workingWithLiveList ? "LIVE LIST" : "custom list"), list);
561 final BalanceForCurrency balance = new BalanceForCurrency();
562 final String descriptionText = list.get(0)
565 boolean submittable = true;
566 boolean listChanged = false;
567 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
568 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
569 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
570 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
571 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
572 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
573 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
574 final List<Item> emptyRows = new ArrayList<>();
577 if ((descriptionText == null) || descriptionText.trim()
580 Logger.debug("submittable", "Transaction not submittable: missing description");
584 for (int i = 1; i < list.size(); i++) {
585 TransactionAccount item = list.get(i)
586 .toTransactionAccount();
588 String accName = item.getAccountName()
590 String currName = item.getCurrency();
592 itemsForCurrency.add(currName, item);
594 if (accName.isEmpty()) {
595 itemsWithEmptyAccountForCurrency.add(currName, item);
597 if (item.isAmountSet()) {
598 // 2) each amount has account name
599 Logger.debug("submittable", String.format(
600 "Transaction not submittable: row %d has no account name, but" +
601 " has" + " amount %1.2f", i + 1, item.getAmount()));
605 emptyRowsForCurrency.add(currName, item);
610 itemsWithAccountForCurrency.add(currName, item);
613 if (!item.isAmountValid()) {
614 Logger.debug("submittable",
615 String.format("Not submittable: row %d has an invalid amount", i + 1));
618 else if (item.isAmountSet()) {
619 itemsWithAmountForCurrency.add(currName, item);
620 balance.add(currName, item.getAmount());
623 itemsWithEmptyAmountForCurrency.add(currName, item);
625 if (!accName.isEmpty())
626 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
630 // 1) has at least two account names
633 Logger.debug("submittable", "Transaction not submittable: no account names");
634 else if (accounts == 1)
635 Logger.debug("submittable",
636 "Transaction not submittable: only one account name");
638 Logger.debug("submittable",
639 String.format("Transaction not submittable: only %d account names",
644 // 3) for each commodity:
645 // 3a) amount must balance to 0, or
646 // 3b) there must be exactly one empty amount (with account)
647 for (String balCurrency : itemsForCurrency.currencies()) {
648 float currencyBalance = balance.get(balCurrency);
649 if (Misc.isZero(currencyBalance)) {
650 // remove hints from all amount inputs in that currency
651 for (int i = 1; i < list.size(); i++) {
652 TransactionAccount acc = list.get(i)
653 .toTransactionAccount();
654 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
655 if (BuildConfig.DEBUG)
656 Logger.debug("submittable",
657 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
658 i, Misc.nullIsEmpty(acc.getAccountName()),
660 // skip if the amount is set, in which case the hint is not
662 if (!acc.isAmountSet() && acc.amountHintIsSet &&
663 !TextUtils.isEmpty(acc.getAmountHint()))
665 acc.setAmountHint(null);
673 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
674 int balanceReceiversCount = tmpList.size();
675 if (balanceReceiversCount != 1) {
676 if (BuildConfig.DEBUG) {
677 if (balanceReceiversCount == 0)
678 Logger.debug("submittable", String.format(
679 "Transaction not submittable [%s]: non-zero balance " +
680 "with no empty amounts with accounts", balCurrency));
682 Logger.debug("submittable", String.format(
683 "Transaction not submittable [%s]: non-zero balance " +
684 "with multiple empty amounts with accounts", balCurrency));
689 List<Item> emptyAmountList =
690 itemsWithEmptyAmountForCurrency.getList(balCurrency);
692 // suggest off-balance amount to a row and remove hints on other rows
693 Item receiver = null;
694 if (!tmpList.isEmpty())
695 receiver = tmpList.get(0);
696 else if (!emptyAmountList.isEmpty())
697 receiver = emptyAmountList.get(0);
699 for (int i = 0; i < list.size(); i++) {
700 Item item = list.get(i);
701 if (!(item instanceof TransactionAccount))
704 TransactionAccount acc = item.toTransactionAccount();
705 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
708 if (item == receiver) {
709 final String hint = String.format("%1.2f", -currencyBalance);
710 if (!acc.isAmountHintSet() ||
711 !Misc.equalStrings(acc.getAmountHint(), hint))
713 Logger.debug("submittable",
714 String.format("Setting amount hint of {%s} to %s [%s]",
715 acc.toString(), hint, balCurrency));
716 acc.setAmountHint(hint);
721 if (BuildConfig.DEBUG)
722 Logger.debug("submittable",
723 String.format("Resetting hint of '%s' [%s]",
724 Misc.nullIsEmpty(acc.getAccountName()),
726 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
727 acc.setAmountHint(null);
735 // 5) a row with an empty account name or empty amount is guaranteed to exist for
737 for (String balCurrency : balance.currencies()) {
738 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
739 int currRows = itemsForCurrency.size(balCurrency);
740 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
741 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
742 if ((currEmptyRows == 0) &&
743 ((currRows == currAccounts) || (currRows == currAmounts)))
745 // perhaps there already is an unused empty row for another currency that
747 // boolean foundIt = false;
748 // for (Item item : emptyRows) {
749 // Currency itemCurrency = item.getCurrency();
750 // String itemCurrencyName =
751 // (itemCurrency == null) ? "" : itemCurrency.getName();
752 // if (Misc.isZero(balance.get(itemCurrencyName))) {
753 // item.setCurrency(Currency.loadByName(balCurrency));
754 // item.setAmountHint(
755 // String.format("%1.2f", -balance.get(balCurrency)));
762 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
763 final float bal = balance.get(balCurrency);
764 if (!Misc.isZero(bal) && currAmounts == currRows)
765 newAcc.setAmountHint(String.format("%4.2f", -bal));
766 Logger.debug("submittable",
767 String.format("Adding new item with %s for currency %s",
768 newAcc.getAmountHint(), balCurrency));
774 // drop extra empty rows, not needed
775 for (String currName : emptyRowsForCurrency.currencies()) {
776 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
777 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
778 // the list is a copy, so the empty item is no longer present
779 Item itemToRemove = emptyItems.remove(1);
780 removeItemById(list, itemToRemove.id);
784 // unused currency, remove last item (which is also an empty one)
785 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
786 List<Item> currItems = itemsForCurrency.getList(currName);
788 if (currItems.size() == 1) {
789 // the list is a copy, so the empty item is no longer present
790 removeItemById(list, emptyItems.get(0).id);
796 // 6) at least two rows need to be present in the ledger
797 // (the list also contains header and trailer)
798 while (list.size() < MIN_ITEMS) {
799 list.add(new TransactionAccount(""));
803 Logger.debug("submittable", submittable ? "YES" : "NO");
804 isSubmittable.setValue(submittable);
806 if (BuildConfig.DEBUG)
807 dumpItemList("After submittable checks", list);
809 catch (NumberFormatException e) {
810 Logger.debug("submittable", "NO (because of NumberFormatException)");
811 isSubmittable.setValue(false);
813 catch (Exception e) {
815 Logger.debug("submittable", "NO (because of an Exception)");
816 isSubmittable.setValue(false);
819 if (listChanged && workingWithLiveList) {
820 setItemsWithoutSubmittableChecks(list);
823 private void removeItemById(@NotNull List<Item> list, int id) {
824 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
825 list.removeIf(item -> item.id == id);
828 for (Item item : list) {
836 @SuppressLint("DefaultLocale")
837 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
838 Logger.debug("submittable", "== Dump of all items " + msg);
839 for (int i = 1; i < list.size(); i++) {
840 TransactionAccount item = list.get(i)
841 .toTransactionAccount();
842 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
845 public void setItemCurrency(int position, String newCurrency) {
846 TransactionAccount item = Objects.requireNonNull(items.getValue())
848 .toTransactionAccount();
849 final String oldCurrency = item.getCurrency();
851 if (Misc.equalStrings(oldCurrency, newCurrency))
854 List<Item> newList = copyList();
855 newList.get(position)
856 .toTransactionAccount()
857 .setCurrency(newCurrency);
861 public boolean accountListIsEmpty() {
862 List<Item> items = Objects.requireNonNull(this.items.getValue());
864 for (Item item : items) {
865 if (!(item instanceof TransactionAccount))
868 if (!((TransactionAccount) item).isEmpty())
875 public static class FocusInfo {
877 FocusedElement element;
878 public FocusInfo(int position, FocusedElement element) {
879 this.position = position;
880 this.element = element;
884 static abstract class Item {
885 private static int idDispenser = 0;
888 if (this instanceof TransactionHead)
891 synchronized (Item.class) {
895 public Item(int id) {
898 public static Item from(Item origin) {
899 if (origin instanceof TransactionHead)
900 return new TransactionHead((TransactionHead) origin);
901 if (origin instanceof TransactionAccount)
902 return new TransactionAccount((TransactionAccount) origin);
903 throw new RuntimeException("Don't know how to handle " + origin);
905 private static void resetIdDispenser() {
911 public abstract ItemType getType();
912 public TransactionHead toTransactionHead() {
913 if (this instanceof TransactionHead)
914 return (TransactionHead) this;
916 throw new IllegalStateException("Wrong item type " + this);
918 public TransactionAccount toTransactionAccount() {
919 if (this instanceof TransactionAccount)
920 return (TransactionAccount) this;
922 throw new IllegalStateException("Wrong item type " + this);
924 public boolean equalContents(@Nullable Object item) {
928 if (!getClass().equals(item.getClass()))
931 // shortcut - comparing same instance
935 if (this instanceof TransactionHead)
936 return ((TransactionHead) item).equalContents((TransactionHead) this);
937 if (this instanceof TransactionAccount)
938 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
940 throw new RuntimeException("Don't know how to handle " + this);
945 //==========================================================================================
947 public static class TransactionHead extends Item {
948 private SimpleDate date;
949 private String description;
950 private String comment;
951 TransactionHead(String description) {
953 this.description = description;
955 public TransactionHead(TransactionHead origin) {
958 description = origin.description;
959 comment = origin.comment;
961 public SimpleDate getDate() {
964 public void setDate(SimpleDate date) {
967 public void setDate(String text) throws ParseException {
968 if (Misc.emptyIsNull(text) == null) {
973 date = Globals.parseLedgerDate(text);
978 * @return nicely formatted, shortest available date representation
980 String getFormattedDate() {
984 Calendar today = GregorianCalendar.getInstance();
986 if (today.get(Calendar.YEAR) != date.year) {
987 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
990 if (today.get(Calendar.MONTH) + 1 != date.month) {
991 return String.format(Locale.US, "%d/%02d", date.month, date.day);
994 return String.valueOf(date.day);
998 public String toString() {
999 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
1000 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1002 if (TextUtils.isEmpty(description))
1003 b.append(" «no description»");
1005 b.append(String.format(" '%s'", description));
1008 b.append(String.format("@%s", date.toString()));
1010 if (!TextUtils.isEmpty(comment))
1011 b.append(String.format(" /%s/", comment));
1013 return b.toString();
1015 public String getDescription() {
1018 public void setDescription(String description) {
1019 this.description = description;
1021 public String getComment() {
1024 public void setComment(String comment) {
1025 this.comment = comment;
1028 public ItemType getType() {
1029 return ItemType.generalData;
1031 public LedgerTransaction asLedgerTransaction() {
1032 return new LedgerTransaction(0, date, description, Data.getProfile());
1034 public boolean equalContents(TransactionHead other) {
1038 return Objects.equals(date, other.date) &&
1039 Misc.equalStrings(description, other.description) &&
1040 Misc.equalStrings(comment, other.comment);
1044 public static class TransactionAccount extends Item {
1045 private String accountName;
1046 private String amountHint;
1047 private String comment;
1048 private String currency;
1049 private float amount;
1050 private boolean amountSet;
1051 private boolean amountValid = true;
1052 private FocusedElement focusedElement = FocusedElement.Account;
1053 private boolean amountHintIsSet = false;
1054 private boolean isLast = false;
1055 private int accountNameCursorPosition;
1056 public TransactionAccount(TransactionAccount origin) {
1058 accountName = origin.accountName;
1059 amount = origin.amount;
1060 amountSet = origin.amountSet;
1061 amountHint = origin.amountHint;
1062 amountHintIsSet = origin.amountHintIsSet;
1063 comment = origin.comment;
1064 currency = origin.currency;
1065 amountValid = origin.amountValid;
1066 focusedElement = origin.focusedElement;
1067 isLast = origin.isLast;
1068 accountNameCursorPosition = origin.accountNameCursorPosition;
1070 public TransactionAccount(LedgerTransactionAccount account) {
1072 currency = account.getCurrency();
1073 amount = account.getAmount();
1075 public TransactionAccount(String accountName) {
1077 this.accountName = accountName;
1079 public TransactionAccount(String accountName, String currency) {
1081 this.accountName = accountName;
1082 this.currency = currency;
1084 public boolean isLast() {
1087 public boolean isAmountSet() {
1090 public String getAccountName() {
1093 public void setAccountName(String accountName) {
1094 this.accountName = accountName;
1096 public float getAmount() {
1098 throw new IllegalStateException("Amount is not set");
1101 public void setAmount(float amount) {
1102 this.amount = amount;
1105 public void resetAmount() {
1109 public ItemType getType() {
1110 return ItemType.transactionRow;
1112 public String getAmountHint() {
1115 public void setAmountHint(String amountHint) {
1116 this.amountHint = amountHint;
1117 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1119 public String getComment() {
1122 public void setComment(String comment) {
1123 this.comment = comment;
1125 public String getCurrency() {
1128 public void setCurrency(String currency) {
1129 this.currency = currency;
1131 public boolean isAmountValid() {
1134 public void setAmountValid(boolean amountValid) {
1135 this.amountValid = amountValid;
1137 public FocusedElement getFocusedElement() {
1138 return focusedElement;
1140 public void setFocusedElement(FocusedElement focusedElement) {
1141 this.focusedElement = focusedElement;
1143 public boolean isAmountHintSet() {
1144 return amountHintIsSet;
1146 public void setAmountHintIsSet(boolean amountHintIsSet) {
1147 this.amountHintIsSet = amountHintIsSet;
1149 public boolean isEmpty() {
1150 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1151 Misc.emptyIsNull(comment) == null;
1153 @SuppressLint("DefaultLocale")
1155 public String toString() {
1156 StringBuilder b = new StringBuilder();
1157 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1158 if (!TextUtils.isEmpty(accountName))
1159 b.append(String.format(" acc'%s'", accountName));
1162 b.append(String.format(" %4.2f", amount));
1163 else if (amountHintIsSet)
1164 b.append(String.format(" (%s)", amountHint));
1166 if (!TextUtils.isEmpty(currency))
1170 if (!TextUtils.isEmpty(comment))
1171 b.append(String.format(" /%s/", comment));
1176 return b.toString();
1178 public boolean equalContents(TransactionAccount other) {
1182 boolean equal = Misc.equalStrings(accountName, other.accountName);
1183 equal = equal && Misc.equalStrings(comment, other.comment) &&
1184 (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1186 // compare amount hint only if there is no amount
1188 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1189 Misc.equalStrings(amountHint, other.amountHint)
1190 : !other.amountHintIsSet);
1191 equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1193 Logger.debug("new-trans",
1194 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1198 public int getAccountNameCursorPosition() {
1199 return accountNameCursorPosition;
1201 public void setAccountNameCursorPosition(int position) {
1202 this.accountNameCursorPosition = position;
1206 private static class BalanceForCurrency {
1207 private final HashMap<String, Float> hashMap = new HashMap<>();
1208 float get(String currencyName) {
1209 Float f = hashMap.get(currencyName);
1212 hashMap.put(currencyName, f);
1216 void add(String currencyName, float amount) {
1217 hashMap.put(currencyName, get(currencyName) + amount);
1219 Set<String> currencies() {
1220 return hashMap.keySet();
1222 boolean containsCurrency(String currencyName) {
1223 return hashMap.containsKey(currencyName);
1227 private static class ItemsForCurrency {
1228 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1230 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1231 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1233 list = new ArrayList<>();
1234 hashMap.put(currencyName, list);
1238 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1239 getList(currencyName).add(item);
1241 int size(@Nullable String currencyName) {
1242 return this.getList(currencyName)
1245 Set<String> currencies() {
1246 return hashMap.keySet();