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 List<Item> list = new ArrayList<>();
174 list.add(new TransactionHead(""));
175 list.add(new TransactionAccount(""));
176 list.add(new TransactionAccount(""));
177 setItemsWithoutSubmittableChecks(list);
179 boolean accountsInInitialState() {
180 final List<Item> list = items.getValue();
185 for (Item item : list) {
186 if (!(item instanceof TransactionAccount))
189 TransactionAccount accRow = (TransactionAccount) item;
190 if (!accRow.isEmpty())
196 void applyTemplate(MatchedTemplate matchedTemplate, String text) {
197 SimpleDate transactionDate = null;
198 final MatchResult matchResult = matchedTemplate.matchResult;
199 final TemplateHeader templateHead = matchedTemplate.templateHead;
201 int day = extractIntFromMatches(matchResult, templateHead.getDateDayMatchGroup(),
202 templateHead.getDateDay());
203 int month = extractIntFromMatches(matchResult, templateHead.getDateMonthMatchGroup(),
204 templateHead.getDateMonth());
205 int year = extractIntFromMatches(matchResult, templateHead.getDateYearMatchGroup(),
206 templateHead.getDateYear());
208 if (year > 0 || month > 0 || day > 0) {
209 SimpleDate today = SimpleDate.today();
217 transactionDate = new SimpleDate(year, month, day);
219 Logger.debug("pattern", "setting transaction date to " + transactionDate);
223 List<Item> present = copyList();
225 TransactionHead head = new TransactionHead(present.get(0)
226 .toTransactionHead());
227 if (transactionDate != null)
228 head.setDate(transactionDate);
230 final String transactionDescription = extractStringFromMatches(matchResult,
231 templateHead.getTransactionDescriptionMatchGroup(),
232 templateHead.getTransactionDescription());
233 if (Misc.emptyIsNull(transactionDescription) != null)
234 head.setDescription(transactionDescription);
236 final String transactionComment = extractStringFromMatches(matchResult,
237 templateHead.getTransactionCommentMatchGroup(),
238 templateHead.getTransactionComment());
239 if (Misc.emptyIsNull(transactionComment) != null)
240 head.setComment(transactionComment);
242 List<Item> newItems = new ArrayList<>();
246 for (int i = 1; i < present.size(); i++) {
247 final TransactionAccount row = present.get(i)
248 .toTransactionAccount();
250 newItems.add(new TransactionAccount(row));
255 .getTemplateWithAccountsAsync(templateHead.getId(), entry -> {
257 final boolean accountsInInitialState = accountsInInitialState();
258 for (TemplateAccount acc : entry.accounts) {
262 extractStringFromMatches(matchResult, acc.getAccountNameMatchGroup(),
263 acc.getAccountName());
264 String accountComment =
265 extractStringFromMatches(matchResult, acc.getAccountCommentMatchGroup(),
266 acc.getAccountComment());
267 Float amount = extractFloatFromMatches(matchResult, acc.getAmountMatchGroup(),
269 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
273 TransactionAccount accRow = new TransactionAccount(accountName);
274 accRow.setComment(accountComment);
276 accRow.setAmount(amount);
278 newItems.add(accRow);
281 new Handler(Looper.getMainLooper()).post(() -> setItems(newItems));
284 private int extractIntFromMatches(MatchResult m, Integer group, Integer literal) {
290 if (grp > 0 & grp <= m.groupCount())
292 return Integer.parseInt(m.group(grp));
294 catch (NumberFormatException e) {
295 Logger.debug("new-trans", "Error extracting matched number", e);
301 private String extractStringFromMatches(MatchResult m, Integer group, String literal) {
307 if (grp > 0 & grp <= m.groupCount())
313 private Float extractFloatFromMatches(MatchResult m, Integer group, Float literal) {
319 if (grp > 0 & grp <= m.groupCount())
321 return Float.valueOf(m.group(grp));
323 catch (NumberFormatException e) {
324 Logger.debug("new-trans", "Error extracting matched number", e);
330 void removeItem(int pos) {
331 List<Item> newList = shallowCopyListWithoutItem(pos);
334 void noteFocusChanged(int position, FocusedElement element) {
335 FocusInfo present = focusInfo.getValue();
336 if (present == null || present.position != position || present.element != element)
337 focusInfo.setValue(new FocusInfo(position, element));
339 public LiveData<FocusInfo> getFocusInfo() {
342 void moveItem(int fromIndex, int toIndex) {
343 List<Item> newList = shallowCopyList();
344 Item item = newList.remove(fromIndex);
345 newList.add(toIndex, item);
346 items.setValue(newList); // same count, same submittable state
348 void moveItemLast(List<Item> list, int index) {
352 3 <-- desired position
355 int itemCount = list.size();
357 if (index < itemCount - 1)
358 list.add(list.remove(index));
360 void toggleCurrencyVisible() {
361 showCurrency.setValue(!Objects.requireNonNull(showCurrency.getValue()));
363 void stopObservingBusyFlag(Observer<Boolean> observer) {
364 busyFlag.removeObserver(observer);
366 void incrementBusyCounter() {
367 int newValue = busyCounter.incrementAndGet();
369 busyFlag.postValue(true);
371 void decrementBusyCounter() {
372 int newValue = busyCounter.decrementAndGet();
374 busyFlag.postValue(false);
376 public LiveData<Boolean> getBusyFlag() {
379 public void toggleShowComments() {
380 showComments.setValue(!Objects.requireNonNull(showComments.getValue()));
382 public LedgerTransaction constructLedgerTransaction() {
383 List<Item> list = Objects.requireNonNull(items.getValue());
384 TransactionHead head = list.get(0)
385 .toTransactionHead();
386 SimpleDate date = head.getDate();
387 LedgerTransaction tr = head.asLedgerTransaction();
389 tr.setComment(head.getComment());
390 LedgerTransactionAccount emptyAmountAccount = null;
391 float emptyAmountAccountBalance = 0;
392 for (int i = 1; i < list.size(); i++) {
393 TransactionAccount item = list.get(i)
394 .toTransactionAccount();
395 LedgerTransactionAccount acc = new LedgerTransactionAccount(item.getAccountName()
398 if (acc.getAccountName()
402 acc.setComment(item.getComment());
404 if (item.isAmountSet()) {
405 acc.setAmount(item.getAmount());
406 emptyAmountAccountBalance += item.getAmount();
409 emptyAmountAccount = acc;
415 if (emptyAmountAccount != null)
416 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
420 void loadTransactionIntoModel(String profileUUID, int transactionId) {
421 List<Item> newList = new ArrayList<>();
422 LedgerTransaction tr;
423 MobileLedgerProfile profile = Data.getProfile(profileUUID);
425 throw new RuntimeException(String.format(
426 "Unable to find profile %s, which is supposed to contain transaction %d",
427 profileUUID, transactionId));
429 tr = profile.loadTransaction(transactionId);
430 TransactionHead head = new TransactionHead(tr.getDescription());
431 head.setComment(tr.getComment());
435 List<LedgerTransactionAccount> accounts = tr.getAccounts();
437 TransactionAccount firstNegative = null;
438 TransactionAccount firstPositive = null;
439 int singleNegativeIndex = -1;
440 int singlePositiveIndex = -1;
441 int negativeCount = 0;
442 for (int i = 0; i < accounts.size(); i++) {
443 LedgerTransactionAccount acc = accounts.get(i);
444 TransactionAccount item =
445 new TransactionAccount(acc.getAccountName(), acc.getCurrency());
448 item.setAccountName(acc.getAccountName());
449 item.setComment(acc.getComment());
450 if (acc.isAmountSet()) {
451 item.setAmount(acc.getAmount());
452 if (acc.getAmount() < 0) {
453 if (firstNegative == null) {
454 firstNegative = item;
455 singleNegativeIndex = i + 1;
458 singleNegativeIndex = -1;
461 if (firstPositive == null) {
462 firstPositive = item;
463 singlePositiveIndex = i + 1;
466 singlePositiveIndex = -1;
472 if (BuildConfig.DEBUG)
473 dumpItemList("Loaded previous transaction", newList);
475 if (singleNegativeIndex != -1) {
476 firstNegative.resetAmount();
477 moveItemLast(newList, singleNegativeIndex);
479 else if (singlePositiveIndex != -1) {
480 firstPositive.resetAmount();
481 moveItemLast(newList, singlePositiveIndex);
486 noteFocusChanged(1, FocusedElement.Amount);
489 * A transaction is submittable if:
491 * 1) has at least two account names
492 * 2) each row with amount has account name
493 * 3) for each commodity:
494 * 3a) amounts must balance to 0, or
495 * 3b) there must be exactly one empty amount (with account)
496 * 4) empty accounts with empty amounts are ignored
498 * 5) a row with an empty account name or empty amount is guaranteed to exist for each
500 * 6) at least two rows need to be present in the ledger
502 * @param list - the item list to check. Can be the displayed list or a list that will be
505 @SuppressLint("DefaultLocale")
506 void checkTransactionSubmittable(@Nullable List<Item> list) {
507 boolean workingWithLiveList = false;
508 boolean liveListCopied = false;
510 list = Objects.requireNonNull(items.getValue());
511 workingWithLiveList = true;
514 if (BuildConfig.DEBUG)
515 dumpItemList("Before submittable checks", list);
518 final BalanceForCurrency balance = new BalanceForCurrency();
519 final String descriptionText = list.get(0)
522 boolean submittable = true;
523 boolean listChanged = false;
524 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
525 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
526 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
527 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
528 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
529 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
530 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
531 final List<Item> emptyRows = new ArrayList<>();
534 if ((descriptionText == null) || descriptionText.trim()
537 Logger.debug("submittable", "Transaction not submittable: missing description");
541 for (int i = 1; i < list.size(); i++) {
542 TransactionAccount item = list.get(i)
543 .toTransactionAccount();
545 String accName = item.getAccountName()
547 String currName = item.getCurrency();
549 itemsForCurrency.add(currName, item);
551 if (accName.isEmpty()) {
552 itemsWithEmptyAccountForCurrency.add(currName, item);
554 if (item.isAmountSet()) {
555 // 2) each amount has account name
556 Logger.debug("submittable", String.format(
557 "Transaction not submittable: row %d has no account name, but" +
558 " has" + " amount %1.2f", i + 1, item.getAmount()));
562 emptyRowsForCurrency.add(currName, item);
567 itemsWithAccountForCurrency.add(currName, item);
570 if (!item.isAmountValid()) {
571 Logger.debug("submittable",
572 String.format("Not submittable: row %d has an invalid amount", i + 1));
575 else if (item.isAmountSet()) {
576 itemsWithAmountForCurrency.add(currName, item);
577 balance.add(currName, item.getAmount());
580 itemsWithEmptyAmountForCurrency.add(currName, item);
582 if (!accName.isEmpty())
583 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
587 // 1) has at least two account names
590 Logger.debug("submittable", "Transaction not submittable: no account names");
591 else if (accounts == 1)
592 Logger.debug("submittable",
593 "Transaction not submittable: only one account name");
595 Logger.debug("submittable",
596 String.format("Transaction not submittable: only %d account names",
601 // 3) for each commodity:
602 // 3a) amount must balance to 0, or
603 // 3b) there must be exactly one empty amount (with account)
604 for (String balCurrency : itemsForCurrency.currencies()) {
605 float currencyBalance = balance.get(balCurrency);
606 if (Misc.isZero(currencyBalance)) {
607 // remove hints from all amount inputs in that currency
608 for (int i = 1; i < list.size(); i++) {
609 TransactionAccount acc = list.get(i)
610 .toTransactionAccount();
611 if (Misc.equalStrings(acc.getCurrency(), balCurrency)) {
612 if (BuildConfig.DEBUG)
613 Logger.debug("submittable",
614 String.format("Resetting hint of '%s' [%s]",
615 Misc.nullIsEmpty(acc.getAccountName()),
617 // skip if the amount is set, in which case the hint is not
619 if (!acc.isAmountSet() && acc.amountHintIsSet &&
620 !TextUtils.isEmpty(acc.getAmountHint()))
622 if (workingWithLiveList && !liveListCopied) {
623 list = copyList(list);
624 liveListCopied = true;
626 final TransactionAccount newAcc = new TransactionAccount(acc);
627 newAcc.setAmountHint(null);
628 if (!liveListCopied) {
629 list = copyList(list);
630 liveListCopied = true;
640 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
641 int balanceReceiversCount = tmpList.size();
642 if (balanceReceiversCount != 1) {
643 if (BuildConfig.DEBUG) {
644 if (balanceReceiversCount == 0)
645 Logger.debug("submittable", String.format(
646 "Transaction not submittable [%s]: non-zero balance " +
647 "with no empty amounts with accounts", balCurrency));
649 Logger.debug("submittable", String.format(
650 "Transaction not submittable [%s]: non-zero balance " +
651 "with multiple empty amounts with accounts", balCurrency));
656 List<Item> emptyAmountList =
657 itemsWithEmptyAmountForCurrency.getList(balCurrency);
659 // suggest off-balance amount to a row and remove hints on other rows
660 Item receiver = null;
661 if (!tmpList.isEmpty())
662 receiver = tmpList.get(0);
663 else if (!emptyAmountList.isEmpty())
664 receiver = emptyAmountList.get(0);
666 for (int i = 0; i < list.size(); i++) {
667 Item item = list.get(i);
668 if (!(item instanceof TransactionAccount))
671 TransactionAccount acc = item.toTransactionAccount();
672 if (!Misc.equalStrings(acc.getCurrency(), balCurrency))
675 if (item == receiver) {
676 final String hint = String.format("%1.2f", -currencyBalance);
677 if (!acc.isAmountHintSet() ||
678 !TextUtils.equals(acc.getAmountHint(), hint))
680 Logger.debug("submittable",
681 String.format("Setting amount hint of {%s} to %s [%s]",
682 acc.toString(), hint, balCurrency));
683 if (workingWithLiveList & !liveListCopied) {
684 list = copyList(list);
685 liveListCopied = true;
687 final TransactionAccount newAcc = new TransactionAccount(acc);
688 newAcc.setAmountHint(hint);
694 if (BuildConfig.DEBUG)
695 Logger.debug("submittable",
696 String.format("Resetting hint of '%s' [%s]",
697 Misc.nullIsEmpty(acc.getAccountName()),
699 if (acc.amountHintIsSet && !TextUtils.isEmpty(acc.getAmountHint())) {
700 if (workingWithLiveList && !liveListCopied) {
701 list = copyList(list);
702 liveListCopied = true;
704 final TransactionAccount newAcc = new TransactionAccount(acc);
705 newAcc.setAmountHint(null);
714 // 5) a row with an empty account name or empty amount is guaranteed to exist for
716 for (String balCurrency : balance.currencies()) {
717 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
718 int currRows = itemsForCurrency.size(balCurrency);
719 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
720 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
721 if ((currEmptyRows == 0) &&
722 ((currRows == currAccounts) || (currRows == currAmounts)))
724 // perhaps there already is an unused empty row for another currency that
726 // boolean foundIt = false;
727 // for (Item item : emptyRows) {
728 // Currency itemCurrency = item.getCurrency();
729 // String itemCurrencyName =
730 // (itemCurrency == null) ? "" : itemCurrency.getName();
731 // if (Misc.isZero(balance.get(itemCurrencyName))) {
732 // item.setCurrency(Currency.loadByName(balCurrency));
733 // item.setAmountHint(
734 // String.format("%1.2f", -balance.get(balCurrency)));
741 if (workingWithLiveList && !liveListCopied) {
742 list = copyList(list);
743 liveListCopied = true;
745 final TransactionAccount newAcc = new TransactionAccount("", balCurrency);
746 final float bal = balance.get(balCurrency);
747 if (!Misc.isZero(bal) && currAmounts == currRows)
748 newAcc.setAmountHint(String.format("%4.2f", -bal));
749 Logger.debug("submittable",
750 String.format("Adding new item with %s for currency %s",
751 newAcc.getAmountHint(), balCurrency));
757 // drop extra empty rows, not needed
758 for (String currName : emptyRowsForCurrency.currencies()) {
759 List<Item> emptyItems = emptyRowsForCurrency.getList(currName);
760 while ((list.size() > MIN_ITEMS) && (emptyItems.size() > 1)) {
761 if (workingWithLiveList && !liveListCopied) {
762 list = copyList(list);
763 liveListCopied = true;
765 // the list is a copy, so the empty item is no longer present
766 Item itemToRemove = emptyItems.remove(1);
767 removeItemById(list, itemToRemove.id);
771 // unused currency, remove last item (which is also an empty one)
772 if ((list.size() > MIN_ITEMS) && (emptyItems.size() == 1)) {
773 List<Item> currItems = itemsForCurrency.getList(currName);
775 if (currItems.size() == 1) {
776 if (workingWithLiveList && !liveListCopied) {
777 list = copyList(list);
778 liveListCopied = true;
780 // the list is a copy, so the empty item is no longer present
781 removeItemById(list, emptyItems.get(0).id);
787 // 6) at least two rows need to be present in the ledger
788 // (the list also contains header and trailer)
789 while (list.size() < MIN_ITEMS) {
790 if (workingWithLiveList && !liveListCopied) {
791 list = copyList(list);
792 liveListCopied = true;
794 list.add(new TransactionAccount(""));
799 Logger.debug("submittable", submittable ? "YES" : "NO");
800 isSubmittable.setValue(submittable);
802 if (BuildConfig.DEBUG)
803 dumpItemList("After submittable checks", list);
805 catch (NumberFormatException e) {
806 Logger.debug("submittable", "NO (because of NumberFormatException)");
807 isSubmittable.setValue(false);
809 catch (Exception e) {
811 Logger.debug("submittable", "NO (because of an Exception)");
812 isSubmittable.setValue(false);
815 if (listChanged && workingWithLiveList) {
816 setItemsWithoutSubmittableChecks(list);
819 private void removeItemById(@NotNull List<Item> list, int id) {
820 if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
821 list.removeIf(item -> item.id == id);
824 for (Item item : list) {
832 @SuppressLint("DefaultLocale")
833 private void dumpItemList(@NotNull String msg, @NotNull List<Item> list) {
834 Logger.debug("submittable", "== Dump of all items " + msg);
835 for (int i = 1; i < list.size(); i++) {
836 TransactionAccount item = list.get(i)
837 .toTransactionAccount();
838 Logger.debug("submittable", String.format("%d:%s", i, item.toString()));
841 public void setItemCurrency(int position, String newCurrency) {
842 TransactionAccount item = Objects.requireNonNull(items.getValue())
844 .toTransactionAccount();
845 final String oldCurrency = item.getCurrency();
847 if (Misc.equalStrings(oldCurrency, newCurrency))
850 List<Item> newList = copyList();
851 newList.get(position)
852 .toTransactionAccount()
853 .setCurrency(newCurrency);
857 public boolean accountListIsEmpty() {
858 List<Item> items = Objects.requireNonNull(this.items.getValue());
860 for (Item item : items) {
861 if (!(item instanceof TransactionAccount))
864 if (!((TransactionAccount) item).isEmpty())
871 public static class FocusInfo {
873 FocusedElement element;
874 public FocusInfo(int position, FocusedElement element) {
875 this.position = position;
876 this.element = element;
880 static abstract class Item {
881 private static int idDispenser = 0;
884 synchronized (Item.class) {
888 public static Item from(Item origin) {
889 if (origin instanceof TransactionHead)
890 return new TransactionHead((TransactionHead) origin);
891 if (origin instanceof TransactionAccount)
892 return new TransactionAccount((TransactionAccount) origin);
893 throw new RuntimeException("Don't know how to handle " + origin);
898 public abstract ItemType getType();
899 public TransactionHead toTransactionHead() {
900 if (this instanceof TransactionHead)
901 return (TransactionHead) this;
903 throw new IllegalStateException("Wrong item type " + this);
905 public TransactionAccount toTransactionAccount() {
906 if (this instanceof TransactionAccount)
907 return (TransactionAccount) this;
909 throw new IllegalStateException("Wrong item type " + this);
911 public boolean equalContents(@Nullable Object item) {
915 if (!getClass().equals(item.getClass()))
918 // shortcut - comparing same instance
922 if (this instanceof TransactionHead)
923 return ((TransactionHead) item).equalContents((TransactionHead) this);
924 if (this instanceof TransactionAccount)
925 return ((TransactionAccount) item).equalContents((TransactionAccount) this);
927 throw new RuntimeException("Don't know how to handle " + this);
932 //==========================================================================================
934 public static class TransactionHead extends Item {
935 private SimpleDate date;
936 private String description;
937 private String comment;
938 TransactionHead(String description) {
940 this.description = description;
942 public TransactionHead(TransactionHead origin) {
945 description = origin.description;
946 comment = origin.comment;
948 public SimpleDate getDate() {
951 public void setDate(SimpleDate date) {
954 public void setDate(String text) throws ParseException {
955 if (Misc.emptyIsNull(text) == null) {
960 date = Globals.parseLedgerDate(text);
965 * @return nicely formatted, shortest available date representation
967 String getFormattedDate() {
971 Calendar today = GregorianCalendar.getInstance();
973 if (today.get(Calendar.YEAR) != date.year) {
974 return String.format(Locale.US, "%d/%02d/%02d", date.year, date.month, date.day);
977 if (today.get(Calendar.MONTH) + 1 != date.month) {
978 return String.format(Locale.US, "%d/%02d", date.month, date.day);
981 return String.valueOf(date.day);
985 public String toString() {
986 @SuppressLint("DefaultLocale") StringBuilder b = new StringBuilder(
987 String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
989 if (TextUtils.isEmpty(description))
990 b.append(" «no description»");
992 b.append(String.format(" descr'%s'", description));
995 b.append(String.format("@%s", date.toString()));
997 if (!TextUtils.isEmpty(comment))
998 b.append(String.format(" /%s/", comment));
1000 return b.toString();
1002 public String getDescription() {
1005 public void setDescription(String description) {
1006 this.description = description;
1008 public String getComment() {
1011 public void setComment(String comment) {
1012 this.comment = comment;
1015 public ItemType getType() {
1016 return ItemType.generalData;
1018 public LedgerTransaction asLedgerTransaction() {
1019 return new LedgerTransaction(null, date, description, Data.getProfile());
1021 public boolean equalContents(TransactionHead other) {
1025 return Objects.equals(date, other.date) &&
1026 TextUtils.equals(description, other.description) &&
1027 TextUtils.equals(comment, other.comment);
1031 public static class TransactionAccount extends Item {
1032 private String accountName;
1033 private String amountHint;
1034 private String comment;
1035 private String currency;
1036 private float amount;
1037 private boolean amountSet;
1038 private boolean amountValid = true;
1039 private FocusedElement focusedElement = FocusedElement.Account;
1040 private boolean amountHintIsSet = true;
1041 private boolean isLast = false;
1042 public TransactionAccount(TransactionAccount origin) {
1044 accountName = origin.accountName;
1045 amount = origin.amount;
1046 amountSet = origin.amountSet;
1047 amountHint = origin.amountHint;
1048 amountHintIsSet = origin.amountHintIsSet;
1049 comment = origin.comment;
1050 currency = origin.currency;
1051 amountValid = origin.amountValid;
1052 focusedElement = origin.focusedElement;
1053 isLast = origin.isLast;
1055 public TransactionAccount(LedgerTransactionAccount account) {
1057 currency = account.getCurrency();
1058 amount = account.getAmount();
1060 public TransactionAccount(String accountName) {
1062 this.accountName = accountName;
1064 public TransactionAccount(String accountName, String currency) {
1066 this.accountName = accountName;
1067 this.currency = currency;
1069 public boolean isLast() {
1072 public boolean isAmountSet() {
1075 public String getAccountName() {
1078 public void setAccountName(String accountName) {
1079 this.accountName = accountName;
1081 public float getAmount() {
1083 throw new IllegalStateException("Amount is not set");
1086 public void setAmount(float amount) {
1087 this.amount = amount;
1090 public void resetAmount() {
1094 public ItemType getType() {
1095 return ItemType.transactionRow;
1097 public String getAmountHint() {
1100 public void setAmountHint(String amountHint) {
1101 this.amountHint = amountHint;
1102 amountHintIsSet = !TextUtils.isEmpty(amountHint);
1104 public String getComment() {
1107 public void setComment(String comment) {
1108 this.comment = comment;
1110 public String getCurrency() {
1113 public void setCurrency(String currency) {
1114 this.currency = currency;
1116 public boolean isAmountValid() {
1119 public void setAmountValid(boolean amountValid) {
1120 this.amountValid = amountValid;
1122 public FocusedElement getFocusedElement() {
1123 return focusedElement;
1125 public void setFocusedElement(FocusedElement focusedElement) {
1126 this.focusedElement = focusedElement;
1128 public boolean isAmountHintSet() {
1129 return amountHintIsSet;
1131 public void setAmountHintIsSet(boolean amountHintIsSet) {
1132 this.amountHintIsSet = amountHintIsSet;
1134 public boolean isEmpty() {
1135 return !amountSet && Misc.emptyIsNull(accountName) == null &&
1136 Misc.emptyIsNull(comment) == null;
1138 @SuppressLint("DefaultLocale")
1140 public String toString() {
1141 StringBuilder b = new StringBuilder();
1142 b.append(String.format("id:%d/%s", id, Integer.toHexString(hashCode())));
1143 if (!TextUtils.isEmpty(accountName))
1144 b.append(String.format(" acc'%s'", accountName));
1147 b.append(String.format(" %4.2f", amount));
1148 else if (amountHintIsSet)
1149 b.append(String.format(" (%s)", amountHint));
1151 if (!TextUtils.isEmpty(currency))
1155 if (!TextUtils.isEmpty(comment))
1156 b.append(String.format(" /%s/", comment));
1158 return b.toString();
1160 public boolean equalContents(TransactionAccount other) {
1164 boolean equal = TextUtils.equals(accountName, other.accountName);
1165 equal = equal && TextUtils.equals(comment, other.comment) &&
1166 (amountSet ? other.amountSet && amount == other.amount : !other.amountSet);
1168 // compare amount hint only if there is no amount
1170 equal = equal && (amountHintIsSet ? other.amountHintIsSet &&
1171 TextUtils.equals(amountHint, other.amountHint)
1172 : !other.amountHintIsSet);
1173 equal = equal && TextUtils.equals(currency, other.currency) && isLast == other.isLast;
1175 Logger.debug("new-trans",
1176 String.format("Comparing {%s} and {%s}: %s", this.toString(), other.toString(),
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();