2 * Copyright © 2021 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
9 * MoLe is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License terms for details.
14 * You should have received a copy of the GNU General Public License
15 * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.ui.new_transaction;
20 import android.annotation.SuppressLint;
21 import android.os.Handler;
22 import android.os.Looper;
23 import android.text.TextUtils;
25 import androidx.annotation.NonNull;
26 import androidx.annotation.Nullable;
27 import androidx.lifecycle.LifecycleOwner;
28 import androidx.lifecycle.LiveData;
29 import androidx.lifecycle.MutableLiveData;
30 import androidx.lifecycle.Observer;
31 import androidx.lifecycle.ViewModel;
33 import net.ktnx.mobileledger.BuildConfig;
34 import net.ktnx.mobileledger.db.DB;
35 import net.ktnx.mobileledger.db.TemplateAccount;
36 import net.ktnx.mobileledger.db.TemplateHeader;
37 import net.ktnx.mobileledger.model.Data;
38 import net.ktnx.mobileledger.model.InertMutableLiveData;
39 import net.ktnx.mobileledger.model.LedgerTransaction;
40 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
41 import net.ktnx.mobileledger.model.MatchedTemplate;
42 import net.ktnx.mobileledger.model.MobileLedgerProfile;
43 import net.ktnx.mobileledger.utils.Globals;
44 import net.ktnx.mobileledger.utils.Logger;
45 import net.ktnx.mobileledger.utils.Misc;
46 import net.ktnx.mobileledger.utils.SimpleDate;
48 import org.jetbrains.annotations.NotNull;
50 import java.text.ParseException;
51 import java.util.ArrayList;
52 import java.util.Calendar;
53 import java.util.GregorianCalendar;
54 import java.util.HashMap;
55 import java.util.List;
56 import java.util.Locale;
57 import java.util.Objects;
59 import java.util.concurrent.atomic.AtomicInteger;
60 import java.util.regex.MatchResult;
62 enum ItemType {generalData, transactionRow}
64 enum FocusedElement {Account, Comment, Amount, Description, TransactionComment}
67 public class NewTransactionModel extends ViewModel {
68 private static final int MIN_ITEMS = 3;
69 private final MutableLiveData<Boolean> showCurrency = new MutableLiveData<>(false);
70 private final MutableLiveData<Boolean> isSubmittable = new InertMutableLiveData<>(false);
71 private final MutableLiveData<Boolean> showComments = new MutableLiveData<>(true);
72 private final MutableLiveData<List<Item>> items = new MutableLiveData<>();
73 private final MutableLiveData<Boolean> simulateSave = new InertMutableLiveData<>(false);
74 private final AtomicInteger busyCounter = new AtomicInteger(0);
75 private final MutableLiveData<Boolean> busyFlag = new InertMutableLiveData<>(false);
76 private final Observer<MobileLedgerProfile> profileObserver = profile -> {
77 showCurrency.postValue(profile.getShowCommodityByDefault());
78 showComments.postValue(profile.getShowCommentsByDefault());
80 private final MutableLiveData<FocusInfo> focusInfo = new MutableLiveData<>();
81 private boolean observingDataProfile;
82 public NewTransactionModel() {
85 public LiveData<Boolean> getShowCurrency() {
88 public LiveData<List<Item>> getItems() {
91 private void setItems(@NonNull List<Item> newList) {
92 checkTransactionSubmittable(newList);
93 setItemsWithoutSubmittableChecks(newList);
95 private void setItemsWithoutSubmittableChecks(@NonNull List<Item> list) {
96 Logger.debug("new-trans", "model: Setting new item list");
97 final int cnt = list.size();
98 for (int i = 1; i < cnt - 1; i++) {
99 final TransactionAccount item = list.get(i)
100 .toTransactionAccount();
102 TransactionAccount replacement = new TransactionAccount(item);
103 replacement.isLast = false;
104 list.set(i, replacement);
107 final TransactionAccount last = list.get(cnt - 1)
108 .toTransactionAccount();
110 TransactionAccount replacement = new TransactionAccount(last);
111 replacement.isLast = true;
112 list.set(cnt - 1, replacement);
115 items.setValue(list);
117 private List<Item> copyList() {
118 return copyList(null);
120 private List<Item> copyList(@Nullable List<Item> source) {
121 List<Item> copy = new ArrayList<>();
122 List<Item> oldList = (source == null) ? items.getValue() : source;
125 for (Item item : oldList) {
126 copy.add(Item.from(item));
131 private List<Item> shallowCopyListWithoutItem(int position) {
132 List<Item> copy = new ArrayList<>();
133 List<Item> oldList = items.getValue();
135 if (oldList != null) {
137 for (Item item : oldList) {
146 private List<Item> shallowCopyList() {
147 return new ArrayList<>(items.getValue());
149 LiveData<Boolean> getShowComments() {
152 void observeDataProfile(LifecycleOwner activity) {
153 if (!observingDataProfile)
154 Data.observeProfile(activity, profileObserver);
155 observingDataProfile = true;
157 boolean getSimulateSaveFlag() {
158 Boolean value = simulateSave.getValue();
163 LiveData<Boolean> getSimulateSave() {
166 void toggleSimulateSave() {
167 simulateSave.setValue(!getSimulateSaveFlag());
169 LiveData<Boolean> isSubmittable() {
170 return this.isSubmittable;
173 Logger.debug("new-trans", "Resetting model");
174 List<Item> list = new ArrayList<>();
175 list.add(new TransactionHead(""));
176 list.add(new TransactionAccount(""));
177 list.add(new TransactionAccount(""));
178 setItemsWithoutSubmittableChecks(list);
180 boolean accountsInInitialState() {
181 final List<Item> list = items.getValue();
186 for (Item item : list) {
187 if (!(item instanceof TransactionAccount))
190 TransactionAccount accRow = (TransactionAccount) item;
191 if (!accRow.isEmpty())
197 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
198 SimpleDate transactionDate = null;
199 final MatchResult matchResult = matchedTemplate.matchResult;
200 final TemplateHeader templateHead = matchedTemplate.templateHead;
202 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
203 templateHead.getDateDay());
204 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
205 templateHead.getDateMonth());
206 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
207 templateHead.getDateYear());
209 if (year > 0 || month > 0 || day > 0) {
210 SimpleDate today = SimpleDate.today();
218 transactionDate = new SimpleDate(year, month, day);
220 Logger.debug("pattern", "setting transaction date to " + transactionDate);
224 List<Item> present = copyList();
226 TransactionHead head = new TransactionHead(present.get(0)
227 .toTransactionHead());
228 if (transactionDate != null)
229 head.setDate(transactionDate);
231 final String transactionDescription = extractStringFromMatches(matchResult,
232 templateHead.getTransactionDescriptionMatchGroup(),
233 templateHead.getTransactionDescription());
234 if (Misc.emptyIsNull(transactionDescription) != null)
235 head.setDescription(transactionDescription);
237 final String transactionComment = extractStringFromMatches(matchResult,
238 templateHead.getTransactionCommentMatchGroup(),
239 templateHead.getTransactionComment());
240 if (Misc.emptyIsNull(transactionComment) != null)
241 head.setComment(transactionComment);
243 List<Item> newItems = new ArrayList<>();
247 for (int i = 1; i < present.size(); i++) {
248 final TransactionAccount row = present.get(i)
249 .toTransactionAccount();
251 newItems.add(new TransactionAccount(row));
256 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
258 final boolean accountsInInitialState = accountsInInitialState();
259 for (TemplateAccount acc : entry.accounts) {
263 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
264 acc.getAccountName());
265 String accountComment =
266 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
267 acc.getAccountComment());
268 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
270 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
274 TransactionAccount accRow = new TransactionAccount(accountName);
275 accRow.setComment(accountComment);
277 accRow.setAmount(amount);
279 newItems.add(accRow);
282 new Handler(Looper.getMainLooper()).post(() -> setItems(newItems));
285 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
291 if (grp > 0 & grp <= m.groupCount())
293 return Integer.parseInt(m.group(grp));
295 catch (NumberFormatException e) {
296 Logger.debug("new-trans", "Error extracting matched number", e);
302 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
308 if (grp > 0 & grp <= m.groupCount())
314 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
320 if (grp > 0 & grp <= m.groupCount())
322 return Float.valueOf(m.group(grp));
324 catch (NumberFormatException e) {
325 Logger.debug("new-trans", "Error extracting matched number", e);
331 void removeItem(int pos) {
332 List<Item> newList = shallowCopyListWithoutItem(pos);
335 void noteFocusChanged(int position, FocusedElement element) {
336 FocusInfo present = focusInfo.getValue();
337 if (present == null || present.position != position || present.element != element)
338 focusInfo.setValue(new FocusInfo(position, element));
340 public LiveData<FocusInfo> getFocusInfo() {
343 void moveItem(int fromIndex, int toIndex) {
344 List<Item> newList = shallowCopyList();
345 Item item = newList.remove(fromIndex);
346 newList.add(toIndex, item);
347 items.setValue(newList); // same count, same submittable state
349 void moveItemLast(List<Item> list, int index) {
353 3 <-- desired position
356 int itemCount = list.size();
358 if (index < itemCount - 1)
359 list.add(list.remove(index));
361 void toggleCurrencyVisible() {
362 showCurrency.setValue(!Objects.requireNonNull(showCurrency.getValue()));
364 void stopObservingBusyFlag(Observer<Boolean> observer) {
365 busyFlag.removeObserver(observer);
367 void incrementBusyCounter() {
368 int newValue = busyCounter.incrementAndGet();
370 busyFlag.postValue(true);
372 void decrementBusyCounter() {
373 int newValue = busyCounter.decrementAndGet();
375 busyFlag.postValue(false);
377 public LiveData<Boolean> getBusyFlag() {
380 public void toggleShowComments() {
381 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
383 public LedgerTransaction constructLedgerTransaction() {
384 List<Item> list = Objects.requireNonNull(items.getValue());
385 TransactionHead head = list.get(0)
386 .toTransactionHead();
387 SimpleDate date = head.getDate();
388 LedgerTransaction tr = head.asLedgerTransaction();
390 tr.setComment(head.getComment());
391 LedgerTransactionAccount emptyAmountAccount = null;
392 float emptyAmountAccountBalance = 0;
393 for (int i = 1; i < list.size(); i++) {
394 TransactionAccount item = list.get(i)
395 .toTransactionAccount();
396 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
399 if (acc.getAccountName()
403 acc.setComment(item.getComment());
405 if (item.isAmountSet()) {
406 acc.setAmount(item.getAmount());
407 emptyAmountAccountBalance += item.getAmount();
410 emptyAmountAccount = acc;
416 if (emptyAmountAccount != null)
417 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
421 void loadTransactionIntoModel(String profileUUID, int transactionId) {
422 List<Item> newList = new ArrayList<>();
423 LedgerTransaction tr;
424 MobileLedgerProfile profile = Data.getProfile(profileUUID);
426 throw new RuntimeException(String.format(
427 "Unable to find profile %s, which is supposed to contain transaction %d",
428 profileUUID, transactionId));
430 tr = profile.loadTransaction(transactionId);
431 TransactionHead head = new TransactionHead(tr.getDescription());
432 head.setComment(tr.getComment());
436 List<LedgerTransactionAccount> accounts = tr.getAccounts();
438 TransactionAccount firstNegative = null;
439 TransactionAccount firstPositive = null;
440 int singleNegativeIndex = -1;
441 int singlePositiveIndex = -1;
442 int negativeCount = 0;
443 for (int i = 0; i < accounts.size(); i++) {
444 LedgerTransactionAccount acc = accounts.get(i);
445 TransactionAccount item =
446 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
449 item.setAccountName(acc.getAccountName());
450 item.setComment(acc.getComment());
451 if (acc.isAmountSet()) {
452 item.setAmount(acc.getAmount());
453 if (acc.getAmount() < 0) {
454 if (firstNegative == null) {
455 firstNegative = item;
456 singleNegativeIndex = i + 1;
459 singleNegativeIndex = -1;
462 if (firstPositive == null) {
463 firstPositive = item;
464 singlePositiveIndex = i + 1;
467 singlePositiveIndex = -1;
473 if (BuildConfig.DEBUG)
474 dumpItemList("Loaded previous transaction", newList);
476 if (singleNegativeIndex != -1) {
477 firstNegative.resetAmount();
478 moveItemLast(newList, singleNegativeIndex);
480 else if (singlePositiveIndex != -1) {
481 firstPositive.resetAmount();
482 moveItemLast(newList, singlePositiveIndex);
487 noteFocusChanged(1, FocusedElement.Amount);
490 * A transaction is submittable if:
492 * 1) has at least two account names
493 * 2) each row with amount has account name
494 * 3) for each commodity:
495 * 3a) amounts must balance to 0, or
496 * 3b) there must be exactly one empty amount (with account)
497 * 4) empty accounts with empty amounts are ignored
499 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
501 * 6) at least two rows need to be present in the ledger
503 * @param list - the item list to check. Can be the displayed list or a list that will be
506 @SuppressLint("DefaultLocale")
507 void checkTransactionSubmittable(@Nullable List<Item> list) {
508 boolean workingWithLiveList = false;
509 boolean liveListCopied = false;
511 list = Objects.requireNonNull(items.getValue());
512 workingWithLiveList = true;
515 if (BuildConfig.DEBUG)
516 dumpItemList("Before submittable checks", list);
519 final BalanceForCurrency balance = new BalanceForCurrency();
520 final String descriptionText = list.get(0)
523 boolean submittable = true;
524 boolean listChanged = false;
525 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
526 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
527 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
528 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
529 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
530 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
531 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
532 final List<Item> emptyRows = new ArrayList<>();
535 if ((descriptionText == null) || descriptionText.trim()
538 Logger.debug("submittable", "Transaction not submittable: missing description");
542 for (int i = 1; i < list.size(); i++) {
543 TransactionAccount item = list.get(i)
544 .toTransactionAccount();
546 String accName = item.getAccountName()
548 String currName = item.getCurrency();
550 itemsForCurrency.add(currName, item);
552 if (accName.isEmpty()) {
553 itemsWithEmptyAccountForCurrency.add(currName, item);
555 if (item.isAmountSet()) {
556 // 2) each amount has account name
557 Logger.debug("submittable", String.format(
558 "Transaction not submittable: row %d has no account name, but" +
559 " has" + " amount %1.2f", i + 1, item.getAmount()));
563 emptyRowsForCurrency.add(currName, item);
568 itemsWithAccountForCurrency.add(currName, item);
571 if (!item.isAmountValid()) {
572 Logger.debug("submittable",
573 String.format("Not submittable: row %d has an invalid amount", i + 1));
576 else if (item.isAmountSet()) {
577 itemsWithAmountForCurrency.add(currName, item);
578 balance.add(currName, item.getAmount());
581 itemsWithEmptyAmountForCurrency.add(currName, item);
583 if (!accName.isEmpty())
584 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
588 // 1) has at least two account names
591 Logger.debug("submittable", "Transaction not submittable: no account names");
592 else if (accounts == 1)
593 Logger.debug("submittable",
594 "Transaction not submittable: only one account name");
596 Logger.debug("submittable",
597 String.format("Transaction not submittable: only %d account names",
602 // 3) for each commodity:
603 // 3a) amount must balance to 0, or
604 // 3b) there must be exactly one empty amount (with account)
605 for (String balCurrency : itemsForCurrency.currencies()) {
606 float currencyBalance = balance.get(balCurrency);
607 if (Misc.isZero(currencyBalance)) {
608 // remove hints from all amount inputs in that currency
609 for (int i = 1; i < list.size(); i++) {
610 TransactionAccount acc = list.get(i)
611 .toTransactionAccount();
612 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
613 if (BuildConfig.DEBUG)
614 Logger.debug("submittable",
615 String.format("Resetting hint of '%s' [%s]",
616 Misc.nullIsEmpty(acc.getAccountName()),
618 // skip if the amount is set, in which case the hint is not
620 if (!acc.isAmountSet() && acc.amountHintIsSet &&
621 !TextUtils.isEmpty(acc.getAmountHint()))
623 if (workingWithLiveList && !liveListCopied) {
624 list = copyList(list);
625 liveListCopied = true;
627 final TransactionAccount newAcc = new TransactionAccount(acc);
628 newAcc.setAmountHint(null);
629 if (!liveListCopied) {
630 list = copyList(list);
631 liveListCopied = true;
641 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
642 int balanceReceiversCount = tmpList.size();
643 if (balanceReceiversCount != 1) {
644 if (BuildConfig.DEBUG) {
645 if (balanceReceiversCount == 0)
646 Logger.debug("submittable", String.format(
647 "Transaction not submittable [%s]: non-zero balance " +
648 "with no empty amounts with accounts", balCurrency));
650 Logger.debug("submittable", String.format(
651 "Transaction not submittable [%s]: non-zero balance " +
652 "with multiple empty amounts with accounts", balCurrency));
657 List<Item> emptyAmountList =
658 itemsWithEmptyAmountForCurrency.getList(balCurrency);
660 // suggest off-balance amount to a row and remove hints on other rows
661 Item receiver = null;
662 if (!tmpList.isEmpty())
663 receiver = tmpList.get(0);
664 else if (!emptyAmountList.isEmpty())
665 receiver = emptyAmountList.get(0);
667 for (int i = 0; i < list.size(); i++) {
668 Item item = list.get(i);
669 if (!(item instanceof TransactionAccount))
672 TransactionAccount acc = item.toTransactionAccount();
673 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
676 if (item == receiver) {
677 final String hint = String.format("%1.2f", -currencyBalance);
678 if (!acc.isAmountHintSet() ||
679 !TextUtils.equals(acc.getAmountHint(), hint))
681 Logger.debug("submittable",
682 String.format("Setting amount hint of {%s} to %s [%s]",
683 acc.toString(), hint, balCurrency));
684 if (workingWithLiveList & !liveListCopied) {
685 list = copyList(list);
686 liveListCopied = true;
688 final TransactionAccount newAcc = new TransactionAccount(acc);
689 newAcc.setAmountHint(hint);
695 if (BuildConfig.DEBUG)
696 Logger.debug("submittable",
697 String.format("Resetting hint of '%s' [%s]",
698 Misc.nullIsEmpty(acc.getAccountName()),
700 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
701 if (workingWithLiveList && !liveListCopied) {
702 list = copyList(list);
703 liveListCopied = true;
705 final TransactionAccount newAcc = new TransactionAccount(acc);
706 newAcc.setAmountHint(null);
715 // 5) a row with an empty account name or empty amount is guaranteed to exist for
717 for (String balCurrency : balance.currencies()) {
718 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
719 int currRows = itemsForCurrency.size(balCurrency);
720 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
721 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
722 if ((currEmptyRows == 0) &&
723 ((currRows == currAccounts) || (currRows == currAmounts)))
725 // perhaps there already is an unused empty row for another currency that
727 // boolean foundIt = false;
728 // for (Item item : emptyRows) {
729 // Currency itemCurrency = item.getCurrency();
730 // String itemCurrencyName =
731 // (itemCurrency == null) ? "" : itemCurrency.getName();
732 // if (Misc.isZero(balance.get(itemCurrencyName))) {
733 // item.setCurrency(Currency.loadByName(balCurrency));
734 // item.setAmountHint(
735 // String.format("%1.2f", -balance.get(balCurrency)));
742 if (workingWithLiveList && !liveListCopied) {
743 list = copyList(list);
744 liveListCopied = true;
746 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
747 final float bal = balance.get(balCurrency);
748 if (!Misc.isZero(bal) && currAmounts == currRows)
749 newAcc.setAmountHint(String.format("%4.2f", -bal));
750 Logger.debug("submittable",
751 String.format("Adding new item with %s for currency %s",
752 newAcc.getAmountHint(), balCurrency));
758 // drop extra empty rows, not needed
759 for (String currName : emptyRowsForCurrency.currencies()) {
760 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
761 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
762 if (workingWithLiveList && !liveListCopied) {
763 list = copyList(list);
764 liveListCopied = true;
766 // the list is a copy, so the empty item is no longer present
767 Item itemToRemove = emptyItems.remove(1);
768 removeItemById(list, itemToRemove.id);
772 // unused currency, remove last item (which is also an empty one)
773 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
774 List<Item> currItems = itemsForCurrency.getList(currName);
776 if (currItems.size() == 1) {
777 if (workingWithLiveList && !liveListCopied) {
778 list = copyList(list);
779 liveListCopied = true;
781 // the list is a copy, so the empty item is no longer present
782 removeItemById(list, emptyItems.get(0).id);
788 // 6) at least two rows need to be present in the ledger
789 // (the list also contains header and trailer)
790 while (list.size() < MIN_ITEMS) {
791 if (workingWithLiveList && !liveListCopied) {
792 list = copyList(list);
793 liveListCopied = true;
795 list.add(new TransactionAccount(""));
800 Logger.debug("submittable", submittable ? "YES" : "NO");
801 isSubmittable.setValue(submittable);
803 if (BuildConfig.DEBUG)
804 dumpItemList("After submittable checks", list);
806 catch (NumberFormatException e) {
807 Logger.debug("submittable", "NO (because of NumberFormatException)");
808 isSubmittable.setValue(false);
810 catch (Exception e) {
812 Logger.debug("submittable", "NO (because of an Exception)");
813 isSubmittable.setValue(false);
816 if (listChanged && workingWithLiveList) {
817 setItemsWithoutSubmittableChecks(list);
820 private void removeItemById(@NotNull List<Item> list, int id) {
821 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
822 list.removeIf(item -> item.id == id);
825 for (Item item : list) {
833 @SuppressLint("DefaultLocale")
834 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
835 Logger.debug("submittable", "== Dump of all items " + msg);
836 for (int i = 1; i < list.size(); i++) {
837 TransactionAccount item = list.get(i)
838 .toTransactionAccount();
839 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
842 public void setItemCurrency(int position, String newCurrency) {
843 TransactionAccount item = Objects.requireNonNull(items.getValue())
845 .toTransactionAccount();
846 final String oldCurrency = item.getCurrency();
848 if (Misc.equalStrings(oldCurrency, newCurrency))
851 List<Item> newList = copyList();
852 newList.get(position)
853 .toTransactionAccount()
854 .setCurrency(newCurrency);
858 public boolean accountListIsEmpty() {
859 List<Item> items = Objects.requireNonNull(this.items.getValue());
861 for (Item item : items) {
862 if (!(item instanceof TransactionAccount))
865 if (!((TransactionAccount) item).isEmpty())
872 public static class FocusInfo {
874 FocusedElement element;
875 public FocusInfo(int position, FocusedElement element) {
876 this.position = position;
877 this.element = element;
881 static abstract class Item {
882 private static int idDispenser = 0;
885 synchronized (Item.class) {
889 public static Item from(Item origin) {
890 if (origin instanceof TransactionHead)
891 return new TransactionHead((TransactionHead) origin);
892 if (origin instanceof TransactionAccount)
893 return new TransactionAccount((TransactionAccount) origin);
894 throw new RuntimeException("Don't know how to handle " + origin);
899 public abstract ItemType getType();
900 public TransactionHead toTransactionHead() {
901 if (this instanceof TransactionHead)
902 return (TransactionHead) this;
904 throw new IllegalStateException("Wrong item type " + this);
906 public TransactionAccount toTransactionAccount() {
907 if (this instanceof TransactionAccount)
908 return (TransactionAccount) this;
910 throw new IllegalStateException("Wrong item type " + this);
912 public boolean equalContents(@Nullable Object item) {
916 if (!getClass().equals(item.getClass()))
919 // shortcut - comparing same instance
923 if (this instanceof TransactionHead)
924 return ((TransactionHead) item).equalContents((TransactionHead) this);
925 if (this instanceof TransactionAccount)
926 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
928 throw new RuntimeException("Don't know how to handle " + this);
933 //==========================================================================================
935 public static class TransactionHead extends Item {
936 private SimpleDate date;
937 private String description;
938 private String comment;
939 TransactionHead(String description) {
941 this.description = description;
943 public TransactionHead(TransactionHead origin) {
946 description = origin.description;
947 comment = origin.comment;
949 public SimpleDate getDate() {
952 public void setDate(SimpleDate date) {
955 public void setDate(String text) throws ParseException {
956 if (Misc.emptyIsNull(text) == null) {
961 date = Globals.parseLedgerDate(text);
966 * @return nicely formatted, shortest available date representation
968 String getFormattedDate() {
972 Calendar today = GregorianCalendar.getInstance();
974 if (today.get(Calendar.YEAR) != date.year) {
975 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
978 if (today.get(Calendar.MONTH) + 1 != date.month) {
979 return String.format(Locale.US, "%d/%02d", date.month, date.day);
982 return String.valueOf(date.day);
986 public String toString() {
987 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
988 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
990 if (TextUtils.isEmpty(description))
991 b.append(" «no description»");
993 b.append(String.format(" descr'%s'", description));
996 b.append(String.format("@%s", date.toString()));
998 if (!TextUtils.isEmpty(comment))
999 b.append(String.format(" /%s/", comment));
1001 return b.toString();
1003 public String getDescription() {
1006 public void setDescription(String description) {
1007 this.description = description;
1009 public String getComment() {
1012 public void setComment(String comment) {
1013 this.comment = comment;
1016 public ItemType getType() {
1017 return ItemType.generalData;
1019 public LedgerTransaction asLedgerTransaction() {
1020 return new LedgerTransaction(null, date, description, Data.getProfile());
1022 public boolean equalContents(TransactionHead other) {
1026 return Objects.equals(date, other.date) &&
1027 TextUtils.equals(description, other.description) &&
1028 TextUtils.equals(comment, other.comment);
1032 public static class TransactionAccount extends Item {
1033 private String accountName;
1034 private String amountHint;
1035 private String comment;
1036 private String currency;
1037 private float amount;
1038 private boolean amountSet;
1039 private boolean amountValid = true;
1040 private FocusedElement focusedElement = FocusedElement.Account;
1041 private boolean amountHintIsSet = true;
1042 private boolean isLast = false;
1043 private int accountNameCursorPosition;
1044 public TransactionAccount(TransactionAccount origin) {
1046 accountName = origin.accountName;
1047 amount = origin.amount;
1048 amountSet = origin.amountSet;
1049 amountHint = origin.amountHint;
1050 amountHintIsSet = origin.amountHintIsSet;
1051 comment = origin.comment;
1052 currency = origin.currency;
1053 amountValid = origin.amountValid;
1054 focusedElement = origin.focusedElement;
1055 isLast = origin.isLast;
1056 accountNameCursorPosition = origin.accountNameCursorPosition;
1058 public TransactionAccount(LedgerTransactionAccount account) {
1060 currency = account.getCurrency();
1061 amount = account.getAmount();
1063 public TransactionAccount(String accountName) {
1065 this.accountName = accountName;
1067 public TransactionAccount(String accountName, String currency) {
1069 this.accountName = accountName;
1070 this.currency = currency;
1072 public boolean isLast() {
1075 public boolean isAmountSet() {
1078 public String getAccountName() {
1081 public void setAccountName(String accountName) {
1082 this.accountName = accountName;
1084 public float getAmount() {
1086 throw new IllegalStateException("Amount is not set");
1089 public void setAmount(float amount) {
1090 this.amount = amount;
1093 public void resetAmount() {
1097 public ItemType getType() {
1098 return ItemType.transactionRow;
1100 public String getAmountHint() {
1103 public void setAmountHint(String amountHint) {
1104 this.amountHint = amountHint;
1105 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1107 public String getComment() {
1110 public void setComment(String comment) {
1111 this.comment = comment;
1113 public String getCurrency() {
1116 public void setCurrency(String currency) {
1117 this.currency = currency;
1119 public boolean isAmountValid() {
1122 public void setAmountValid(boolean amountValid) {
1123 this.amountValid = amountValid;
1125 public FocusedElement getFocusedElement() {
1126 return focusedElement;
1128 public void setFocusedElement(FocusedElement focusedElement) {
1129 this.focusedElement = focusedElement;
1131 public boolean isAmountHintSet() {
1132 return amountHintIsSet;
1134 public void setAmountHintIsSet(boolean amountHintIsSet) {
1135 this.amountHintIsSet = amountHintIsSet;
1137 public boolean isEmpty() {
1138 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1139 Misc.emptyIsNull(comment) == null;
1141 @SuppressLint("DefaultLocale")
1143 public String toString() {
1144 StringBuilder b = new StringBuilder();
1145 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1146 if (!TextUtils.isEmpty(accountName))
1147 b.append(String.format(" acc'%s'", accountName));
1150 b.append(String.format(" %4.2f", amount));
1151 else if (amountHintIsSet)
1152 b.append(String.format(" (%s)", amountHint));
1154 if (!TextUtils.isEmpty(currency))
1158 if (!TextUtils.isEmpty(comment))
1159 b.append(String.format(" /%s/", comment));
1161 return b.toString();
1163 public boolean equalContents(TransactionAccount other) {
1167 boolean equal = TextUtils.equals(accountName, other.accountName);
1168 equal = equal && TextUtils.equals(comment, other.comment) &&
1169 (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1171 // compare amount hint only if there is no amount
1173 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1174 TextUtils.equals(amountHint, other.amountHint)
1175 : !other.amountHintIsSet);
1176 equal = equal && TextUtils.equals(currency, other.currency) && isLast == other.isLast;
1178 Logger.debug("new-trans",
1179 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
1183 public int getAccountNameCursorPosition() {
1184 return accountNameCursorPosition;
1186 public void setAccountNameCursorPosition(int position) {
1187 this.accountNameCursorPosition = position;
1191 private static class BalanceForCurrency {
1192 private final HashMap<String, Float> hashMap = new HashMap<>();
1193 float get(String currencyName) {
1194 Float f = hashMap.get(currencyName);
1197 hashMap.put(currencyName, f);
1201 void add(String currencyName, float amount) {
1202 hashMap.put(currencyName, get(currencyName) + amount);
1204 Set<String> currencies() {
1205 return hashMap.keySet();
1207 boolean containsCurrency(String currencyName) {
1208 return hashMap.containsKey(currencyName);
1212 private static class ItemsForCurrency {
1213 private final HashMap<String, List<Item>> hashMap = new HashMap<>();
1215 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
1216 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
1218 list = new ArrayList<>();
1219 hashMap.put(currencyName, list);
1223 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
1224 getList(currencyName).add(item);
1226 int size(@Nullable String currencyName) {
1227 return this.getList(currencyName)
1230 Set<String> currencies() {
1231 return hashMap.keySet();