2 * Copyright © 2021 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
9 * MoLe is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License terms for details.
14 * You should have received a copy of the GNU General Public License
15 * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.ui.new_transaction;
20 import android.annotation.SuppressLint;
21 import android.os.Handler;
22 import android.os.Looper;
23 import android.text.TextUtils;
25 import androidx.annotation.NonNull;
26 import androidx.annotation.Nullable;
27 import androidx.lifecycle.LifecycleOwner;
28 import androidx.lifecycle.LiveData;
29 import androidx.lifecycle.MutableLiveData;
30 import androidx.lifecycle.Observer;
31 import androidx.lifecycle.ViewModel;
33 import net.ktnx.mobileledger.BuildConfig;
34 import net.ktnx.mobileledger.db.DB;
35 import net.ktnx.mobileledger.db.TemplateAccount;
36 import net.ktnx.mobileledger.db.TemplateHeader;
37 import net.ktnx.mobileledger.model.Data;
38 import net.ktnx.mobileledger.model.InertMutableLiveData;
39 import net.ktnx.mobileledger.model.LedgerTransaction;
40 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
41 import net.ktnx.mobileledger.model.MatchedTemplate;
42 import net.ktnx.mobileledger.model.MobileLedgerProfile;
43 import net.ktnx.mobileledger.utils.Globals;
44 import net.ktnx.mobileledger.utils.Logger;
45 import net.ktnx.mobileledger.utils.Misc;
46 import net.ktnx.mobileledger.utils.SimpleDate;
48 import org.jetbrains.annotations.NotNull;
50 import java.text.ParseException;
51 import java.util.ArrayList;
52 import java.util.Calendar;
53 import java.util.GregorianCalendar;
54 import java.util.HashMap;
55 import java.util.List;
56 import java.util.Locale;
57 import java.util.Objects;
59 import java.util.concurrent.atomic.AtomicInteger;
60 import java.util.regex.MatchResult;
62 enum ItemType {generalData, transactionRow}
64 enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
67 public class NewTransactionModel extends ViewModel {
68 private static final int MIN_ITEMS = 3;
69 private final MutableLiveData<Boolean> showCurrency = new MutableLiveData<>(false);
70 private final MutableLiveData<Boolean> isSubmittable = new InertMutableLiveData<>(false);
71 private final MutableLiveData<Boolean> showComments = new MutableLiveData<>(true);
72 private final MutableLiveData<List<Item>> items = new MutableLiveData<>();
73 private final MutableLiveData<Boolean> simulateSave = new InertMutableLiveData<>(false);
74 private final AtomicInteger busyCounter = new AtomicInteger(0);
75 private final MutableLiveData<Boolean> busyFlag = new InertMutableLiveData<>(false);
76 private final Observer<MobileLedgerProfile> profileObserver = profile -> {
77 showCurrency.postValue(profile.getShowCommodityByDefault());
78 showComments.postValue(profile.getShowCommentsByDefault());
80 private final MutableLiveData<FocusInfo> focusInfo = new MutableLiveData<>();
81 private boolean observingDataProfile;
82 public NewTransactionModel() {
85 public LiveData<Boolean> getShowCurrency() {
88 public LiveData<List<Item>> getItems() {
91 private void setItems(@NonNull List<Item> newList) {
92 checkTransactionSubmittable(newList);
93 setItemsWithoutSubmittableChecks(newList);
95 private void setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
96 final int cnt = list.size();
97 for (int i = 1; i < cnt - 1; i++) {
98 final TransactionAccount item = list.get(i)
99 .toTransactionAccount();
101 TransactionAccount replacement = new TransactionAccount(item);
102 replacement.isLast = false;
103 list.set(i, replacement);
106 final TransactionAccount last = list.get(cnt - 1)
107 .toTransactionAccount();
109 TransactionAccount replacement = new TransactionAccount(last);
110 replacement.isLast = true;
111 list.set(cnt - 1, replacement);
114 if (BuildConfig.DEBUG)
115 dumpItemList("Before setValue()", list);
116 items.setValue(list);
118 private List<Item> copyList() {
119 List<Item> copy = new ArrayList<>();
120 List<Item> oldList = items.getValue();
123 for (Item item : oldList) {
124 copy.add(Item.from(item));
129 private List<Item> copyListWithoutItem(int position) {
130 List<Item> copy = new ArrayList<>();
131 List<Item> oldList = items.getValue();
133 if (oldList != null) {
135 for (Item item : oldList) {
138 copy.add(Item.from(item));
144 private List<Item> shallowCopyList() {
145 return new ArrayList<>(items.getValue());
147 LiveData<Boolean> getShowComments() {
150 void observeDataProfile(LifecycleOwner activity) {
151 if (!observingDataProfile)
152 Data.observeProfile(activity, profileObserver);
153 observingDataProfile = true;
155 boolean getSimulateSaveFlag() {
156 Boolean value = simulateSave.getValue();
161 LiveData<Boolean> getSimulateSave() {
164 void toggleSimulateSave() {
165 simulateSave.setValue(!getSimulateSaveFlag());
167 LiveData<Boolean> isSubmittable() {
168 return this.isSubmittable;
171 Logger.debug("new-trans", "Resetting model");
172 List<Item> list = new ArrayList<>();
173 Item.resetIdDispenser();
174 list.add(new TransactionHead(""));
175 list.add(new TransactionAccount(""));
176 list.add(new TransactionAccount(""));
177 noteFocusChanged(0, FocusedElement.Description);
178 isSubmittable.setValue(false);
179 setItemsWithoutSubmittableChecks(list);
181 boolean accountsInInitialState() {
182 final List<Item> list = items.getValue();
187 for (Item item : list) {
188 if (!(item instanceof TransactionAccount))
191 TransactionAccount accRow = (TransactionAccount) item;
192 if (!accRow.isEmpty())
198 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
199 SimpleDate transactionDate = null;
200 final MatchResult matchResult = matchedTemplate.matchResult;
201 final TemplateHeader templateHead = matchedTemplate.templateHead;
203 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
204 templateHead.getDateDay());
205 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
206 templateHead.getDateMonth());
207 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
208 templateHead.getDateYear());
210 if (year > 0 || month > 0 || day > 0) {
211 SimpleDate today = SimpleDate.today();
219 transactionDate = new SimpleDate(year, month, day);
221 Logger.debug("pattern", "setting transaction date to " + transactionDate);
225 List<Item> present = copyList();
227 TransactionHead head = new TransactionHead(present.get(0)
228 .toTransactionHead());
229 if (transactionDate != null)
230 head.setDate(transactionDate);
232 final String transactionDescription = extractStringFromMatches(matchResult,
233 templateHead.getTransactionDescriptionMatchGroup(),
234 templateHead.getTransactionDescription());
235 if (Misc.emptyIsNull(transactionDescription) != null)
236 head.setDescription(transactionDescription);
238 final String transactionComment = extractStringFromMatches(matchResult,
239 templateHead.getTransactionCommentMatchGroup(),
240 templateHead.getTransactionComment());
241 if (Misc.emptyIsNull(transactionComment) != null)
242 head.setComment(transactionComment);
244 List<Item> newItems = new ArrayList<>();
248 for (int i = 1; i < present.size(); i++) {
249 final TransactionAccount row = present.get(i)
250 .toTransactionAccount();
252 newItems.add(new TransactionAccount(row));
257 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
259 final boolean accountsInInitialState = accountsInInitialState();
260 for (TemplateAccount acc : entry.accounts) {
264 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
265 acc.getAccountName());
266 String accountComment =
267 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
268 acc.getAccountComment());
269 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
271 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
275 TransactionAccount accRow = new TransactionAccount(accountName);
276 accRow.setComment(accountComment);
278 accRow.setAmount(amount);
280 newItems.add(accRow);
283 new Handler(Looper.getMainLooper()).post(() -> setItems(newItems));
286 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
292 if (grp > 0 & grp <= m.groupCount())
294 return Integer.parseInt(m.group(grp));
296 catch (NumberFormatException e) {
297 Logger.debug("new-trans", "Error extracting matched number", e);
303 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
309 if (grp > 0 & grp <= m.groupCount())
315 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
321 if (grp > 0 & grp <= m.groupCount())
323 return Float.valueOf(m.group(grp));
325 catch (NumberFormatException e) {
326 Logger.debug("new-trans", "Error extracting matched number", e);
332 void removeItem(int pos) {
333 Logger.debug("new-trans", String.format(Locale.US, "Removing item at position %d", pos));
334 List<Item> newList = copyListWithoutItem(pos);
335 final FocusInfo fi = focusInfo.getValue();
336 if ((fi != null) && (pos < fi.position))
337 noteFocusChanged(fi.position - 1, fi.element);
340 void noteFocusChanged(int position, FocusedElement element) {
341 FocusInfo present = focusInfo.getValue();
342 if (present == null || present.position != position || present.element != element)
343 focusInfo.setValue(new FocusInfo(position, element));
345 public LiveData<FocusInfo> getFocusInfo() {
348 void moveItem(int fromIndex, int toIndex) {
349 List<Item> newList = shallowCopyList();
350 Item item = newList.remove(fromIndex);
351 newList.add(toIndex, item);
353 FocusInfo fi = focusInfo.getValue();
354 if (fi != null && fi.position == fromIndex)
355 noteFocusChanged(toIndex, fi.element);
357 items.setValue(newList); // same count, same submittable state
359 void moveItemLast(List<Item> list, int index) {
363 3 <-- desired position
366 int itemCount = list.size();
368 if (index < itemCount - 1)
369 list.add(list.remove(index));
371 void toggleCurrencyVisible() {
372 final boolean newValue = !Objects.requireNonNull(showCurrency.getValue());
374 // remove currency from all items, or reset currency to the default
375 // no need to clone the list, because the removal of the currency won't lead to
376 // visual changes -- the currency fields will be hidden or reset to default anyway
377 // still, there may be changes in the submittable state
378 final List<Item> list = Objects.requireNonNull(this.items.getValue());
379 for (int i = 1; i < list.size(); i++) {
380 ((TransactionAccount) list.get(i)).setCurrency(newValue ? Data.getProfile()
381 .getDefaultCommodity()
384 checkTransactionSubmittable(null);
385 showCurrency.setValue(newValue);
387 void stopObservingBusyFlag(Observer<Boolean> observer) {
388 busyFlag.removeObserver(observer);
390 void incrementBusyCounter() {
391 int newValue = busyCounter.incrementAndGet();
393 busyFlag.postValue(true);
395 void decrementBusyCounter() {
396 int newValue = busyCounter.decrementAndGet();
398 busyFlag.postValue(false);
400 public LiveData<Boolean> getBusyFlag() {
403 public void toggleShowComments() {
404 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
406 public LedgerTransaction constructLedgerTransaction() {
407 List<Item> list = Objects.requireNonNull(items.getValue());
408 TransactionHead head = list.get(0)
409 .toTransactionHead();
410 SimpleDate date = head.getDate();
411 LedgerTransaction tr = head.asLedgerTransaction();
413 tr.setComment(head.getComment());
414 LedgerTransactionAccount emptyAmountAccount = null;
415 float emptyAmountAccountBalance = 0;
416 for (int i = 1; i < list.size(); i++) {
417 TransactionAccount item = list.get(i)
418 .toTransactionAccount();
419 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
422 if (acc.getAccountName()
426 acc.setComment(item.getComment());
428 if (item.isAmountSet()) {
429 acc.setAmount(item.getAmount());
430 emptyAmountAccountBalance += item.getAmount();
433 emptyAmountAccount = acc;
439 if (emptyAmountAccount != null)
440 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
444 void loadTransactionIntoModel(String profileUUID, int transactionId) {
445 List<Item> newList = new ArrayList<>();
446 Item.resetIdDispenser();
447 LedgerTransaction tr;
448 MobileLedgerProfile profile = Data.getProfile(profileUUID);
450 throw new RuntimeException(String.format(
451 "Unable to find profile %s, which is supposed to contain transaction %d",
452 profileUUID, transactionId));
454 tr = profile.loadTransaction(transactionId);
455 TransactionHead head = new TransactionHead(tr.getDescription());
456 head.setComment(tr.getComment());
460 List<LedgerTransactionAccount> accounts = tr.getAccounts();
462 TransactionAccount firstNegative = null;
463 TransactionAccount firstPositive = null;
464 int singleNegativeIndex = -1;
465 int singlePositiveIndex = -1;
466 int negativeCount = 0;
467 for (int i = 0; i < accounts.size(); i++) {
468 LedgerTransactionAccount acc = accounts.get(i);
469 TransactionAccount item =
470 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
473 item.setAccountName(acc.getAccountName());
474 item.setComment(acc.getComment());
475 if (acc.isAmountSet()) {
476 item.setAmount(acc.getAmount());
477 if (acc.getAmount() < 0) {
478 if (firstNegative == null) {
479 firstNegative = item;
480 singleNegativeIndex = i + 1;
483 singleNegativeIndex = -1;
486 if (firstPositive == null) {
487 firstPositive = item;
488 singlePositiveIndex = i + 1;
491 singlePositiveIndex = -1;
497 if (BuildConfig.DEBUG)
498 dumpItemList("Loaded previous transaction", newList);
500 if (singleNegativeIndex != -1) {
501 firstNegative.resetAmount();
502 moveItemLast(newList, singleNegativeIndex);
504 else if (singlePositiveIndex != -1) {
505 firstPositive.resetAmount();
506 moveItemLast(newList, singlePositiveIndex);
511 noteFocusChanged(1, FocusedElement.Amount);
514 * A transaction is submittable if:
516 * 1) has at least two account names
517 * 2) each row with amount has account name
518 * 3) for each commodity:
519 * 3a) amounts must balance to 0, or
520 * 3b) there must be exactly one empty amount (with account)
521 * 4) empty accounts with empty amounts are ignored
523 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
525 * 6) at least two rows need to be present in the ledger
527 * @param list - the item list to check. Can be the displayed list or a list that will be
530 @SuppressLint("DefaultLocale")
531 void checkTransactionSubmittable(@Nullable List<Item> list) {
532 boolean workingWithLiveList = false;
535 workingWithLiveList = true;
538 if (BuildConfig.DEBUG)
539 dumpItemList(String.format("Before submittable checks (%s)",
540 workingWithLiveList ? "LIVE LIST" : "custom list"), list);
543 final BalanceForCurrency balance = new BalanceForCurrency();
544 final String descriptionText = list.get(0)
547 boolean submittable = true;
548 boolean listChanged = false;
549 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
550 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
551 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
552 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
553 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
554 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
555 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
556 final List<Item> emptyRows = new ArrayList<>();
559 if ((descriptionText == null) || descriptionText.trim()
562 Logger.debug("submittable", "Transaction not submittable: missing description");
566 for (int i = 1; i < list.size(); i++) {
567 TransactionAccount item = list.get(i)
568 .toTransactionAccount();
570 String accName = item.getAccountName()
572 String currName = item.getCurrency();
574 itemsForCurrency.add(currName, item);
576 if (accName.isEmpty()) {
577 itemsWithEmptyAccountForCurrency.add(currName, item);
579 if (item.isAmountSet()) {
580 // 2) each amount has account name
581 Logger.debug("submittable", String.format(
582 "Transaction not submittable: row %d has no account name, but" +
583 " has" + " amount %1.2f", i + 1, item.getAmount()));
587 emptyRowsForCurrency.add(currName, item);
592 itemsWithAccountForCurrency.add(currName, item);
595 if (!item.isAmountValid()) {
596 Logger.debug("submittable",
597 String.format("Not submittable: row %d has an invalid amount", i + 1));
600 else if (item.isAmountSet()) {
601 itemsWithAmountForCurrency.add(currName, item);
602 balance.add(currName, item.getAmount());
605 itemsWithEmptyAmountForCurrency.add(currName, item);
607 if (!accName.isEmpty())
608 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
612 // 1) has at least two account names
615 Logger.debug("submittable", "Transaction not submittable: no account names");
616 else if (accounts == 1)
617 Logger.debug("submittable",
618 "Transaction not submittable: only one account name");
620 Logger.debug("submittable",
621 String.format("Transaction not submittable: only %d account names",
626 // 3) for each commodity:
627 // 3a) amount must balance to 0, or
628 // 3b) there must be exactly one empty amount (with account)
629 for (String balCurrency : itemsForCurrency.currencies()) {
630 float currencyBalance = balance.get(balCurrency);
631 if (Misc.isZero(currencyBalance)) {
632 // remove hints from all amount inputs in that currency
633 for (int i = 1; i < list.size(); i++) {
634 TransactionAccount acc = list.get(i)
635 .toTransactionAccount();
636 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
637 if (BuildConfig.DEBUG)
638 Logger.debug("submittable",
639 String.format(Locale.US, "Resetting hint of %d:'%s' [%s]",
640 i, Misc.nullIsEmpty(acc.getAccountName()),
642 // skip if the amount is set, in which case the hint is not
644 if (!acc.isAmountSet() && acc.amountHintIsSet &&
645 !TextUtils.isEmpty(acc.getAmountHint()))
647 acc.setAmountHint(null);
655 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
656 int balanceReceiversCount = tmpList.size();
657 if (balanceReceiversCount != 1) {
658 if (BuildConfig.DEBUG) {
659 if (balanceReceiversCount == 0)
660 Logger.debug("submittable", String.format(
661 "Transaction not submittable [%s]: non-zero balance " +
662 "with no empty amounts with accounts", balCurrency));
664 Logger.debug("submittable", String.format(
665 "Transaction not submittable [%s]: non-zero balance " +
666 "with multiple empty amounts with accounts", balCurrency));
671 List<Item> emptyAmountList =
672 itemsWithEmptyAmountForCurrency.getList(balCurrency);
674 // suggest off-balance amount to a row and remove hints on other rows
675 Item receiver = null;
676 if (!tmpList.isEmpty())
677 receiver = tmpList.get(0);
678 else if (!emptyAmountList.isEmpty())
679 receiver = emptyAmountList.get(0);
681 for (int i = 0; i < list.size(); i++) {
682 Item item = list.get(i);
683 if (!(item instanceof TransactionAccount))
686 TransactionAccount acc = item.toTransactionAccount();
687 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
690 if (item == receiver) {
691 final String hint = String.format("%1.2f", -currencyBalance);
692 if (!acc.isAmountHintSet() ||
693 !Misc.equalStrings(acc.getAmountHint(), hint))
695 Logger.debug("submittable",
696 String.format("Setting amount hint of {%s} to %s [%s]",
697 acc.toString(), hint, balCurrency));
698 acc.setAmountHint(hint);
703 if (BuildConfig.DEBUG)
704 Logger.debug("submittable",
705 String.format("Resetting hint of '%s' [%s]",
706 Misc.nullIsEmpty(acc.getAccountName()),
708 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
709 acc.setAmountHint(null);
717 // 5) a row with an empty account name or empty amount is guaranteed to exist for
719 for (String balCurrency : balance.currencies()) {
720 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
721 int currRows = itemsForCurrency.size(balCurrency);
722 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
723 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
724 if ((currEmptyRows == 0) &&
725 ((currRows == currAccounts) || (currRows == currAmounts)))
727 // perhaps there already is an unused empty row for another currency that
729 // boolean foundIt = false;
730 // for (Item item : emptyRows) {
731 // Currency itemCurrency = item.getCurrency();
732 // String itemCurrencyName =
733 // (itemCurrency == null) ? "" : itemCurrency.getName();
734 // if (Misc.isZero(balance.get(itemCurrencyName))) {
735 // item.setCurrency(Currency.loadByName(balCurrency));
736 // item.setAmountHint(
737 // String.format("%1.2f", -balance.get(balCurrency)));
744 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
745 final float bal = balance.get(balCurrency);
746 if (!Misc.isZero(bal) && currAmounts == currRows)
747 newAcc.setAmountHint(String.format("%4.2f", -bal));
748 Logger.debug("submittable",
749 String.format("Adding new item with %s for currency %s",
750 newAcc.getAmountHint(), balCurrency));
756 // drop extra empty rows, not needed
757 for (String currName : emptyRowsForCurrency.currencies()) {
758 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
759 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
760 // the list is a copy, so the empty item is no longer present
761 Item itemToRemove = emptyItems.remove(1);
762 removeItemById(list, itemToRemove.id);
766 // unused currency, remove last item (which is also an empty one)
767 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
768 List<Item> currItems = itemsForCurrency.getList(currName);
770 if (currItems.size() == 1) {
771 // the list is a copy, so the empty item is no longer present
772 removeItemById(list, emptyItems.get(0).id);
778 // 6) at least two rows need to be present in the ledger
779 // (the list also contains header and trailer)
780 while (list.size() < MIN_ITEMS) {
781 list.add(new TransactionAccount(""));
785 Logger.debug("submittable", submittable ? "YES" : "NO");
786 isSubmittable.setValue(submittable);
788 if (BuildConfig.DEBUG)
789 dumpItemList("After submittable checks", list);
791 catch (NumberFormatException e) {
792 Logger.debug("submittable", "NO (because of NumberFormatException)");
793 isSubmittable.setValue(false);
795 catch (Exception e) {
797 Logger.debug("submittable", "NO (because of an Exception)");
798 isSubmittable.setValue(false);
801 if (listChanged && workingWithLiveList) {
802 setItemsWithoutSubmittableChecks(list);
805 private void removeItemById(@NotNull List<Item> list, int id) {
806 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
807 list.removeIf(item -> item.id == id);
810 for (Item item : list) {
818 @SuppressLint("DefaultLocale")
819 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
820 Logger.debug("submittable", "== Dump of all items " + msg);
821 for (int i = 1; i < list.size(); i++) {
822 TransactionAccount item = list.get(i)
823 .toTransactionAccount();
824 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
827 public void setItemCurrency(int position, String newCurrency) {
828 TransactionAccount item = Objects.requireNonNull(items.getValue())
830 .toTransactionAccount();
831 final String oldCurrency = item.getCurrency();
833 if (Misc.equalStrings(oldCurrency, newCurrency))
836 List<Item> newList = copyList();
837 newList.get(position)
838 .toTransactionAccount()
839 .setCurrency(newCurrency);
843 public boolean accountListIsEmpty() {
844 List<Item> items = Objects.requireNonNull(this.items.getValue());
846 for (Item item : items) {
847 if (!(item instanceof TransactionAccount))
850 if (!((TransactionAccount) item).isEmpty())
857 public static class FocusInfo {
859 FocusedElement element;
860 public FocusInfo(int position, FocusedElement element) {
861 this.position = position;
862 this.element = element;
866 static abstract class Item {
867 private static int idDispenser = 0;
870 synchronized (Item.class) {
874 public static Item from(Item origin) {
875 if (origin instanceof TransactionHead)
876 return new TransactionHead((TransactionHead) origin);
877 if (origin instanceof TransactionAccount)
878 return new TransactionAccount((TransactionAccount) origin);
879 throw new RuntimeException("Don't know how to handle " + origin);
881 private static void resetIdDispenser() {
887 public abstract ItemType getType();
888 public TransactionHead toTransactionHead() {
889 if (this instanceof TransactionHead)
890 return (TransactionHead) this;
892 throw new IllegalStateException("Wrong item type " + this);
894 public TransactionAccount toTransactionAccount() {
895 if (this instanceof TransactionAccount)
896 return (TransactionAccount) this;
898 throw new IllegalStateException("Wrong item type " + this);
900 public boolean equalContents(@Nullable Object item) {
904 if (!getClass().equals(item.getClass()))
907 // shortcut - comparing same instance
911 if (this instanceof TransactionHead)
912 return ((TransactionHead) item).equalContents((TransactionHead) this);
913 if (this instanceof TransactionAccount)
914 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
916 throw new RuntimeException("Don't know how to handle " + this);
921 //==========================================================================================
923 public static class TransactionHead extends Item {
924 private SimpleDate date;
925 private String description;
926 private String comment;
927 TransactionHead(String description) {
929 this.description = description;
931 public TransactionHead(TransactionHead origin) {
934 description = origin.description;
935 comment = origin.comment;
937 public SimpleDate getDate() {
940 public void setDate(SimpleDate date) {
943 public void setDate(String text) throws ParseException {
944 if (Misc.emptyIsNull(text) == null) {
949 date = Globals.parseLedgerDate(text);
954 * @return nicely formatted, shortest available date representation
956 String getFormattedDate() {
960 Calendar today = GregorianCalendar.getInstance();
962 if (today.get(Calendar.YEAR) != date.year) {
963 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
966 if (today.get(Calendar.MONTH) + 1 != date.month) {
967 return String.format(Locale.US, "%d/%02d", date.month, date.day);
970 return String.valueOf(date.day);
974 public String toString() {
975 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
976 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
978 if (TextUtils.isEmpty(description))
979 b.append(" «no description»");
981 b.append(String.format(" '%s'", description));
984 b.append(String.format("@%s", date.toString()));
986 if (!TextUtils.isEmpty(comment))
987 b.append(String.format(" /%s/", comment));
991 public String getDescription() {
994 public void setDescription(String description) {
995 this.description = description;
997 public String getComment() {
1000 public void setComment(String comment) {
1001 this.comment = comment;
1004 public ItemType getType() {
1005 return ItemType.generalData;
1007 public LedgerTransaction asLedgerTransaction() {
1008 return new LedgerTransaction(null, date, description, Data.getProfile());
1010 public boolean equalContents(TransactionHead other) {
1014 return Objects.equals(date, other.date) &&
1015 Misc.equalStrings(description, other.description) &&
1016 Misc.equalStrings(comment, other.comment);
1020 public static class TransactionAccount extends Item {
1021 private String accountName;
1022 private String amountHint;
1023 private String comment;
1024 private String currency;
1025 private float amount;
1026 private boolean amountSet;
1027 private boolean amountValid = true;
1028 private FocusedElement focusedElement = FocusedElement.Account;
1029 private boolean amountHintIsSet = false;
1030 private boolean isLast = false;
1031 private int accountNameCursorPosition;
1032 public TransactionAccount(TransactionAccount origin) {
1034 accountName = origin.accountName;
1035 amount = origin.amount;
1036 amountSet = origin.amountSet;
1037 amountHint = origin.amountHint;
1038 amountHintIsSet = origin.amountHintIsSet;
1039 comment = origin.comment;
1040 currency = origin.currency;
1041 amountValid = origin.amountValid;
1042 focusedElement = origin.focusedElement;
1043 isLast = origin.isLast;
1044 accountNameCursorPosition = origin.accountNameCursorPosition;
1046 public TransactionAccount(LedgerTransactionAccount account) {
1048 currency = account.getCurrency();
1049 amount = account.getAmount();
1051 public TransactionAccount(String accountName) {
1053 this.accountName = accountName;
1055 public TransactionAccount(String accountName, String currency) {
1057 this.accountName = accountName;
1058 this.currency = currency;
1060 public boolean isLast() {
1063 public boolean isAmountSet() {
1066 public String getAccountName() {
1069 public void setAccountName(String accountName) {
1070 this.accountName = accountName;
1072 public float getAmount() {
1074 throw new IllegalStateException("Amount is not set");
1077 public void setAmount(float amount) {
1078 this.amount = amount;
1081 public void resetAmount() {
1085 public ItemType getType() {
1086 return ItemType.transactionRow;
1088 public String getAmountHint() {
1091 public void setAmountHint(String amountHint) {
1092 this.amountHint = amountHint;
1093 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1095 public String getComment() {
1098 public void setComment(String comment) {
1099 this.comment = comment;
1101 public String getCurrency() {
1104 public void setCurrency(String currency) {
1105 this.currency = currency;
1107 public boolean isAmountValid() {
1110 public void setAmountValid(boolean amountValid) {
1111 this.amountValid = amountValid;
1113 public FocusedElement getFocusedElement() {
1114 return focusedElement;
1116 public void setFocusedElement(FocusedElement focusedElement) {
1117 this.focusedElement = focusedElement;
1119 public boolean isAmountHintSet() {
1120 return amountHintIsSet;
1122 public void setAmountHintIsSet(boolean amountHintIsSet) {
1123 this.amountHintIsSet = amountHintIsSet;
1125 public boolean isEmpty() {
1126 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1127 Misc.emptyIsNull(comment) == null;
1129 @SuppressLint("DefaultLocale")
1131 public String toString() {
1132 StringBuilder b = new StringBuilder();
1133 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1134 if (!TextUtils.isEmpty(accountName))
1135 b.append(String.format(" acc'%s'", accountName));
1138 b.append(String.format(" %4.2f", amount));
1139 else if (amountHintIsSet)
1140 b.append(String.format(" (%s)", amountHint));
1142 if (!TextUtils.isEmpty(currency))
1146 if (!TextUtils.isEmpty(comment))
1147 b.append(String.format(" /%s/", comment));
1152 return b.toString();
1154 public boolean equalContents(TransactionAccount other) {
1158 boolean equal = Misc.equalStrings(accountName, other.accountName);
1159 equal = equal && Misc.equalStrings(comment, other.comment) &&
1160 (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1162 // compare amount hint only if there is no amount
1164 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1165 Misc.equalStrings(amountHint, other.amountHint)
1166 : !other.amountHintIsSet);
1167 equal = equal && Misc.equalStrings(currency, other.currency) && isLast == other.isLast;
1169 Logger.debug("new-trans",
1170 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1174 public int getAccountNameCursorPosition() {
1175 return accountNameCursorPosition;
1177 public void setAccountNameCursorPosition(int position) {
1178 this.accountNameCursorPosition = position;
1182 private static class BalanceForCurrency {
1183 private final HashMap<String, Float> hashMap = new HashMap<>();
1184 float get(String currencyName) {
1185 Float f = hashMap.get(currencyName);
1188 hashMap.put(currencyName, f);
1192 void add(String currencyName, float amount) {
1193 hashMap.put(currencyName, get(currencyName) + amount);
1195 Set<String> currencies() {
1196 return hashMap.keySet();
1198 boolean containsCurrency(String currencyName) {
1199 return hashMap.containsKey(currencyName);
1203 private static class ItemsForCurrency {
1204 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1206 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1207 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1209 list = new ArrayList<>();
1210 hashMap.put(currencyName, list);
1214 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1215 getList(currencyName).add(item);
1217 int size(@Nullable String currencyName) {
1218 return this.getList(currencyName)
1221 Set<String> currencies() {
1222 return hashMap.keySet();