X-Git-Url: https://git.ktnx.net/?p=mobile-ledger.git;a=blobdiff_plain;f=app%2Fsrc%2Fmain%2Fjava%2Fnet%2Fktnx%2Fmobileledger%2Fui%2Factivity%2FNewTransactionModel.java;h=3350664eac43c41a32d9032f8c3edbfee6696988;hp=34d3a8493a3a9e782de7d315b1f25d9e6656d7bb;hb=217da55a224e2ae899d0b50604e2e54f882ec04f;hpb=73db4eac40acaf517513c6ccc0c3e44472c7dbdf diff --git a/app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionModel.java b/app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionModel.java index 34d3a849..3350664e 100644 --- a/app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionModel.java +++ b/app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionModel.java @@ -1,5 +1,5 @@ /* - * Copyright © 2019 Damyan Ivanov. + * Copyright © 2020 Damyan Ivanov. * This file is part of MoLe. * MoLe is free software: you can distribute it and/or modify it * under the term of the GNU General Public License as published by @@ -17,77 +17,58 @@ package net.ktnx.mobileledger.ui.activity; -import android.annotation.SuppressLint; - import androidx.annotation.NonNull; -import androidx.annotation.Nullable; import androidx.lifecycle.LifecycleOwner; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModel; -import net.ktnx.mobileledger.BuildConfig; import net.ktnx.mobileledger.model.Currency; import net.ktnx.mobileledger.model.Data; import net.ktnx.mobileledger.model.LedgerTransactionAccount; import net.ktnx.mobileledger.model.MobileLedgerProfile; -import net.ktnx.mobileledger.utils.Logger; -import net.ktnx.mobileledger.utils.Misc; +import net.ktnx.mobileledger.utils.Globals; +import net.ktnx.mobileledger.utils.SimpleDate; import org.jetbrains.annotations.NotNull; +import java.text.ParseException; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; -import java.util.Date; import java.util.GregorianCalendar; -import java.util.HashMap; -import java.util.List; import java.util.Locale; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import static net.ktnx.mobileledger.utils.Logger.debug; +import java.util.concurrent.atomic.AtomicInteger; public class NewTransactionModel extends ViewModel { - private static final Pattern reYMD = - Pattern.compile("^\\s*(\\d+)\\d*/\\s*(\\d+)\\s*/\\s*(\\d+)\\s*$"); - private static final Pattern reMD = Pattern.compile("^\\s*(\\d+)\\s*/\\s*(\\d+)\\s*$"); - private static final Pattern reD = Pattern.compile("\\s*(\\d+)\\s*$"); final MutableLiveData showCurrency = new MutableLiveData<>(false); + final ArrayList items = new ArrayList<>(); + final MutableLiveData isSubmittable = new MutableLiveData<>(false); + final MutableLiveData showComments = new MutableLiveData<>(true); private final Item header = new Item(this, null, ""); private final Item trailer = new Item(this); - private final ArrayList items = new ArrayList<>(); - private final MutableLiveData isSubmittable = new MutableLiveData<>(false); private final MutableLiveData focusedItem = new MutableLiveData<>(0); private final MutableLiveData accountCount = new MutableLiveData<>(0); private final MutableLiveData simulateSave = new MutableLiveData<>(false); - /* - Slots contain lists of items, all using the same currency, including the possible - item with no account/amount that is used to help balancing the transaction - - There is one slot per currency - */ - private final HashMap> slots = new HashMap<>(); - private int checkHoldCounter = 0; + private final AtomicInteger busyCounter = new AtomicInteger(0); + private final MutableLiveData busyFlag = new MutableLiveData<>(false); private boolean observingDataProfile; - private Observer profileObserver = - profile -> showCurrency.postValue(profile.getShowCommodityByDefault()); - public void observeDataProfile(LifecycleOwner activity) { + private Observer profileObserver = profile -> { + showCurrency.postValue(profile.getShowCommodityByDefault()); + showComments.postValue(profile.getShowCommentsByDefault()); + }; + void observeShowComments(LifecycleOwner owner, Observer observer) { + showComments.observe(owner, observer); + } + void observeBusyFlag(@NonNull LifecycleOwner owner, Observer observer) { + busyFlag.observe(owner, observer); + } + void observeDataProfile(LifecycleOwner activity) { if (!observingDataProfile) Data.profile.observe(activity, profileObserver); observingDataProfile = true; } - void holdSubmittableChecks() { - checkHoldCounter++; - } - void releaseSubmittableChecks() { - if (checkHoldCounter == 0) - throw new RuntimeException("Asymmetrical call to releaseSubmittableChecks"); - checkHoldCounter--; - } boolean getSimulateSave() { return simulateSave.getValue(); } @@ -104,18 +85,22 @@ public class NewTransactionModel extends ViewModel { int getAccountCount() { return items.size(); } - public Date getDate() { + public SimpleDate getDate() { return header.date.getValue(); } public String getDescription() { return header.description.getValue(); } + public String getComment() { + return header.comment.getValue(); + } LiveData isSubmittable() { return this.isSubmittable; } void reset() { header.date.setValue(null); header.description.setValue(null); + header.comment.setValue(null); items.clear(); items.add(new Item(this, new LedgerTransactionAccount(""))); items.add(new Item(this, new LedgerTransactionAccount(""))); @@ -171,248 +156,7 @@ public class NewTransactionModel extends ViewModel { return trailer; } - /* - A transaction is submittable if: - 0) has description - 1) has at least two account names - 2) each row with amount has account name - 3) for each commodity: - 3a) amounts must balance to 0, or - 3b) there must be exactly one empty amount (with account) - 4) empty accounts with empty amounts are ignored - Side effects: - 5) a row with an empty account name or empty amount is guaranteed to exist for each commodity - 6) at least two rows need to be present in the ledger - - */ - @SuppressLint("DefaultLocale") - void checkTransactionSubmittable(NewTransactionItemsAdapter adapter) { - if (checkHoldCounter > 0) - return; - - int accounts = 0; - final BalanceForCurrency balance = new BalanceForCurrency(); - final String descriptionText = getDescription(); - boolean submittable = true; - final ItemsForCurrency itemsForCurrency = new ItemsForCurrency(); - final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency(); - final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency(); - final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency(); - final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency(); - final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency(); - final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency(); - final List emptyRows = new ArrayList<>(); - - try { - if ((descriptionText == null) || descriptionText.trim() - .isEmpty()) - { - Logger.debug("submittable", "Transaction not submittable: missing description"); - submittable = false; - } - - for (int i = 0; i < this.items.size(); i++) { - Item item = this.items.get(i); - - LedgerTransactionAccount acc = item.getAccount(); - String acc_name = acc.getAccountName() - .trim(); - String currName = acc.getCurrency(); - - itemsForCurrency.add(currName, item); - - if (acc_name.isEmpty()) { - itemsWithEmptyAccountForCurrency.add(currName, item); - - if (acc.isAmountSet()) { - // 2) each amount has account name - Logger.debug("submittable", String.format( - "Transaction not submittable: row %d has no account name, but" + - " has" + " amount %1.2f", i + 1, acc.getAmount())); - submittable = false; - } - else { - emptyRowsForCurrency.add(currName, item); - } - } - else { - accounts++; - itemsWithAccountForCurrency.add(currName, item); - } - - if (acc.isAmountSet()) { - itemsWithAmountForCurrency.add(currName, item); - balance.add(currName, acc.getAmount()); - } - else { - itemsWithEmptyAmountForCurrency.add(currName, item); - - if (!acc_name.isEmpty()) - itemsWithAccountAndEmptyAmountForCurrency.add(currName, item); - } - } - - // 1) has at least two account names - if (accounts < 2) { - if (accounts == 0) - Logger.debug("submittable", - "Transaction not submittable: no account " + "names"); - else if (accounts == 1) - Logger.debug("submittable", - "Transaction not submittable: only one account name"); - else - Logger.debug("submittable", - String.format("Transaction not submittable: only %d account names", - accounts)); - submittable = false; - } - - // 3) for each commodity: - // 3a) amount must balance to 0, or - // 3b) there must be exactly one empty amount (with account) - for (String balCurrency : itemsForCurrency.currencies()) { - float currencyBalance = balance.get(balCurrency); - if (Misc.isZero(currencyBalance)) { - // remove hints from all amount inputs in that currency - for (Item item : items) { - if (Currency.equal(item.getCurrency(), balCurrency)) - item.setAmountHint(null); - } - } - else { - List list = - itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency); - int balanceReceiversCount = list.size(); - if (balanceReceiversCount != 1) { - if (BuildConfig.DEBUG) { - if (balanceReceiversCount == 0) - Logger.debug("submittable", String.format( - "Transaction not submittable [%s]: non-zero balance " + - "with no empty amounts with accounts", balCurrency)); - else - Logger.debug("submittable", String.format( - "Transaction not submittable [%s]: non-zero balance " + - "with multiple empty amounts with accounts", balCurrency)); - } - submittable = false; - } - - List emptyAmountList = - itemsWithEmptyAmountForCurrency.getList(balCurrency); - - // suggest off-balance amount to a row and remove hints on other rows - Item receiver = null; - if (!list.isEmpty()) - receiver = list.get(0); - else if (!emptyAmountList.isEmpty()) - receiver = emptyAmountList.get(0); - - for (Item item : items) { - if (!Currency.equal(item.getCurrency(), balCurrency)) - continue; - - if (item.equals(receiver)) { - if (BuildConfig.DEBUG) - Logger.debug("submittable", - String.format("Setting amount hint to %1.2f [%s]", - -currencyBalance, balCurrency)); - item.setAmountHint(String.format("%1.2f", -currencyBalance)); - } - else { - if (BuildConfig.DEBUG) - Logger.debug("submittable", - String.format("Resetting hint of '%s' [%s]", - (item.getAccount() == null) ? "" : item.getAccount() - .getAccountName(), - balCurrency)); - item.setAmountHint(null); - } - } - } - } - - // 5) a row with an empty account name or empty amount is guaranteed to exist for - // each commodity - for (String balCurrency : balance.currencies()) { - int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency); - int currRows = itemsForCurrency.size(balCurrency); - int currAccounts = itemsWithAccountForCurrency.size(balCurrency); - int currAmounts = itemsWithAmountForCurrency.size(balCurrency); - if ((currEmptyRows == 0) && - ((currRows == currAccounts) || (currRows == currAmounts))) - { - // perhaps there already is an unused empty row for another currency that - // is not used? -// boolean foundIt = false; -// for (Item item : emptyRows) { -// Currency itemCurrency = item.getCurrency(); -// String itemCurrencyName = -// (itemCurrency == null) ? "" : itemCurrency.getName(); -// if (Misc.isZero(balance.get(itemCurrencyName))) { -// item.setCurrency(Currency.loadByName(balCurrency)); -// item.setAmountHint( -// String.format("%1.2f", -balance.get(balCurrency))); -// foundIt = true; -// break; -// } -// } -// -// if (!foundIt) - adapter.addRow(balCurrency); - } - } - - // drop extra empty rows, not needed - for (String currName : emptyRowsForCurrency.currencies()) { - List emptyItems = emptyRowsForCurrency.getList(currName); - while ((this.items.size() > 2) && (emptyItems.size() > 1)) { - Item item = emptyItems.get(1); - emptyItems.remove(1); - removeRow(item, adapter); - } - - // unused currency, remove last item (which is also an empty one) - if ((items.size() > 2) && (emptyItems.size() == 1)) { - List currItems = itemsForCurrency.getList(currName); - - if (currItems.size() == 1) { - Item item = emptyItems.get(0); - removeRow(item, adapter); - } - } - } - - // 6) at least two rows need to be present in the ledger - while (this.items.size() < 2) - adapter.addRow(); - - - debug("submittable", submittable ? "YES" : "NO"); - isSubmittable.setValue(submittable); - - if (BuildConfig.DEBUG) { - debug("submittable", "== Dump of all items"); - for (int i = 0; i < items.size(); i++) { - Item item = items.get(i); - LedgerTransactionAccount acc = item.getAccount(); - debug("submittable", String.format("Item %2d: [%4.2f(%s) %s] %s ; %s", i, - acc.isAmountSet() ? acc.getAmount() : 0, - item.isAmountHintSet() ? item.getAmountHint() : "ø", acc.getCurrency(), - acc.getAccountName(), acc.getComment())); - } - } - } - catch (NumberFormatException e) { - debug("submittable", "NO (because of NumberFormatException)"); - isSubmittable.setValue(false); - } - catch (Exception e) { - e.printStackTrace(); - debug("submittable", "NO (because of an Exception)"); - isSubmittable.setValue(false); - } - } - private void removeRow(Item item, NewTransactionItemsAdapter adapter) { + void removeRow(Item item, NewTransactionItemsAdapter adapter) { int pos = items.indexOf(item); items.remove(pos); if (adapter != null) { @@ -439,10 +183,6 @@ public class NewTransactionModel extends ViewModel { void swapItems(int one, int two) { Collections.swap(items, one - 1, two - 1); } - void toggleComment(int position) { - final MutableLiveData commentVisible = getItem(position).commentVisible; - commentVisible.postValue(!commentVisible.getValue()); - } void moveItemLast(int index) { /* 0 1 <-- index @@ -459,78 +199,36 @@ public class NewTransactionModel extends ViewModel { void toggleCurrencyVisible() { showCurrency.setValue(!showCurrency.getValue()); } - public void setItemCurrency(Item item, Currency newCurrency, - NewTransactionItemsAdapter adapter) { - Currency oldCurrency = item.getCurrency(); - if (!Currency.equal(newCurrency, oldCurrency)) { - holdSubmittableChecks(); - try { - item.setCurrency(newCurrency); -// for (Item i : items) { -// if (Currency.equal(i.getCurrency(), oldCurrency)) -// i.setCurrency(newCurrency); -// } - } - finally { - releaseSubmittableChecks(); - } - - checkTransactionSubmittable(adapter); - } + void stopObservingBusyFlag(Observer observer) { + busyFlag.removeObserver(observer); + } + void incrementBusyCounter() { + int newValue = busyCounter.incrementAndGet(); + if (newValue == 1) + busyFlag.postValue(true); + } + void decrementBusyCounter() { + int newValue = busyCounter.decrementAndGet(); + if (newValue == 0) + busyFlag.postValue(false); + } + public boolean getBusyFlag() { + return busyFlag.getValue(); + } + public void toggleShowComments() { + showComments.setValue(!showComments.getValue()); } enum ItemType {generalData, transactionRow, bottomFiller} - enum FocusedElement {Account, Comment, Amount} + enum FocusedElement {Account, Comment, Amount, Description, TransactionComment} - private class ItemsForCurrency { - private HashMap> hashMap = new HashMap<>(); - @NonNull - List getList(@Nullable String currencyName) { - List list = hashMap.get(currencyName); - if (list == null) { - list = new ArrayList<>(); - hashMap.put(currencyName, list); - } - return list; - } - void add(@Nullable String currencyName, @NonNull Item item) { - getList(currencyName).add(item); - } - int size(@Nullable String currencyName) { - return this.getList(currencyName) - .size(); - } - Set currencies() { - return hashMap.keySet(); - } - } //========================================================================================== - private class BalanceForCurrency { - private HashMap hashMap = new HashMap<>(); - float get(String currencyName) { - Float f = hashMap.get(currencyName); - if (f == null) { - f = 0f; - hashMap.put(currencyName, f); - } - return f; - } - void add(String currencyName, float amount) { - hashMap.put(currencyName, get(currencyName) + amount); - } - Set currencies() { - return hashMap.keySet(); - } - boolean containsCurrency(String currencyName) { - return hashMap.containsKey(currencyName); - } - } - class Item { + static class Item { private ItemType type; - private MutableLiveData date = new MutableLiveData<>(); + private MutableLiveData date = new MutableLiveData<>(); private MutableLiveData description = new MutableLiveData<>(); private LedgerTransactionAccount account; private MutableLiveData amountHint = new MutableLiveData<>(null); @@ -538,15 +236,15 @@ public class NewTransactionModel extends ViewModel { private MutableLiveData editable = new MutableLiveData<>(true); private FocusedElement focusedElement = FocusedElement.Account; private MutableLiveData comment = new MutableLiveData<>(null); - private MutableLiveData commentVisible = new MutableLiveData<>(false); private MutableLiveData currency = new MutableLiveData<>(null); + private MutableLiveData amountValid = new MutableLiveData<>(true); private boolean amountHintIsSet = false; Item(NewTransactionModel model) { this.model = model; type = ItemType.bottomFiller; editable.setValue(false); } - Item(NewTransactionModel model, Date date, String description) { + Item(NewTransactionModel model, SimpleDate date, String description) { this.model = model; this.type = ItemType.generalData; this.date.setValue(date); @@ -623,58 +321,30 @@ public class NewTransactionModel extends ViewModel { wantedType)); } } - public Date getDate() { + public SimpleDate getDate() { ensureType(ItemType.generalData); return date.getValue(); } - public void setDate(Date date) { + public void setDate(SimpleDate date) { ensureType(ItemType.generalData); this.date.setValue(date); } - public void setDate(String text) { + public void setDate(String text) throws ParseException { if ((text == null) || text.trim() .isEmpty()) { - setDate((Date) null); + setDate((SimpleDate) null); return; } - int year, month, day; - final Calendar c = GregorianCalendar.getInstance(); - Matcher m = reYMD.matcher(text); - if (m.matches()) { - year = Integer.parseInt(m.group(1)); - month = Integer.parseInt(m.group(2)) - 1; // month is 0-based - day = Integer.parseInt(m.group(3)); - } - else { - year = c.get(Calendar.YEAR); - m = reMD.matcher(text); - if (m.matches()) { - month = Integer.parseInt(m.group(1)) - 1; - day = Integer.parseInt(m.group(2)); - } - else { - month = c.get(Calendar.MONTH); - m = reD.matcher(text); - if (m.matches()) { - day = Integer.parseInt(m.group(1)); - } - else { - day = c.get(Calendar.DAY_OF_MONTH); - } - } - } - - c.set(year, month, day); - - this.setDate(c.getTime()); + SimpleDate date = Globals.parseLedgerDate(text); + this.setDate(date); } void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner, - @NonNull androidx.lifecycle.Observer observer) { + @NonNull androidx.lifecycle.Observer observer) { this.date.observe(owner, observer); } - void stopObservingDate(@NonNull androidx.lifecycle.Observer observer) { + void stopObservingDate(@NonNull androidx.lifecycle.Observer observer) { this.date.removeObserver(observer); } public String getDescription() { @@ -693,6 +363,22 @@ public class NewTransactionModel extends ViewModel { @NonNull androidx.lifecycle.Observer observer) { this.description.removeObserver(observer); } + public String getTransactionComment() { + ensureType(ItemType.generalData); + return comment.getValue(); + } + public void setTransactionComment(String transactionComment) { + ensureType(ItemType.generalData); + this.comment.setValue(transactionComment); + } + void observeTransactionComment(@NonNull @NotNull LifecycleOwner owner, + @NonNull Observer observer) { + ensureType(ItemType.generalData); + this.comment.observe(owner, observer); + } + void stopObservingTransactionComment(@NonNull Observer observer) { + this.comment.removeObserver(observer); + } public LedgerTransactionAccount getAccount() { ensureType(ItemType.transactionRow); return account; @@ -708,27 +394,21 @@ public class NewTransactionModel extends ViewModel { String getFormattedDate() { if (date == null) return null; - Date time = date.getValue(); - if (time == null) + SimpleDate d = date.getValue(); + if (d == null) return null; - Calendar c = GregorianCalendar.getInstance(); - c.setTime(time); Calendar today = GregorianCalendar.getInstance(); - final int myYear = c.get(Calendar.YEAR); - final int myMonth = c.get(Calendar.MONTH); - final int myDay = c.get(Calendar.DAY_OF_MONTH); - - if (today.get(Calendar.YEAR) != myYear) { - return String.format(Locale.US, "%d/%02d/%02d", myYear, myMonth + 1, myDay); + if (today.get(Calendar.YEAR) != d.year) { + return String.format(Locale.US, "%d/%02d/%02d", d.year, d.month, d.day); } - if (today.get(Calendar.MONTH) != myMonth) { - return String.format(Locale.US, "%d/%02d", myMonth + 1, myDay); + if (today.get(Calendar.MONTH) != d.month - 1) { + return String.format(Locale.US, "%d/%02d", d.month, d.day); } - return String.valueOf(myDay); + return String.valueOf(d.day); } void observeEditableFlag(NewTransactionActivity activity, Observer observer) { editable.observe(activity, observer); @@ -736,12 +416,6 @@ public class NewTransactionModel extends ViewModel { void stopObservingEditableFlag(Observer observer) { editable.removeObserver(observer); } - void observeCommentVisible(NewTransactionActivity activity, Observer observer) { - commentVisible.observe(activity, observer); - } - void stopObservingCommentVisible(Observer observer) { - commentVisible.removeObserver(observer); - } void observeComment(NewTransactionActivity activity, Observer observer) { comment.observe(activity, observer); } @@ -778,5 +452,17 @@ public class NewTransactionModel extends ViewModel { boolean isAmountHintSet() { return amountHintIsSet; } + void validateAmount() { + amountValid.setValue(true); + } + void invalidateAmount() { + amountValid.setValue(false); + } + void observeAmountValidity(NewTransactionActivity activity, Observer observer) { + amountValid.observe(activity, observer); + } + void stopObservingAmountValidity(Observer observer) { + amountValid.removeObserver(observer); + } } }