2 * Copyright © 2019 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.activity;
20 import androidx.annotation.NonNull;
21 import androidx.lifecycle.LiveData;
22 import androidx.lifecycle.MutableLiveData;
23 import androidx.lifecycle.Observer;
24 import androidx.lifecycle.ViewModel;
26 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
27 import net.ktnx.mobileledger.utils.Misc;
29 import org.jetbrains.annotations.NotNull;
31 import java.util.ArrayList;
32 import java.util.Calendar;
33 import java.util.Date;
34 import java.util.GregorianCalendar;
35 import java.util.Locale;
36 import java.util.regex.Matcher;
37 import java.util.regex.Pattern;
39 import static net.ktnx.mobileledger.utils.Logger.debug;
40 import static net.ktnx.mobileledger.utils.Misc.isZero;
42 public class NewTransactionModel extends ViewModel {
43 static final Pattern reYMD = Pattern.compile("^\\s*(\\d+)\\d*/\\s*(\\d+)\\s*/\\s*(\\d+)\\s*$");
44 static final Pattern reMD = Pattern.compile("^\\s*(\\d+)\\s*/\\s*(\\d+)\\s*$");
45 static final Pattern reD = Pattern.compile("\\s*(\\d+)\\s*$");
46 private static final String ZERO_AMOUNT_HINT = "0.00";
47 private final Item header = new Item(this, null, "");
48 private final Item trailer = new Item(this);
49 private final ArrayList<Item> items = new ArrayList<>();
50 private final MutableLiveData<Boolean> isSubmittable = new MutableLiveData<>(false);
51 private final MutableLiveData<Integer> focusedItem = new MutableLiveData<>(null);
52 private final MutableLiveData<Integer> accountCount = new MutableLiveData<>(0);
53 public int getAccountCount() {
56 public Date getDate() {
57 return header.date.getValue();
59 public String getDescription() {
60 return header.description.getValue();
62 public LiveData<Boolean> isSubmittable() {
63 return this.isSubmittable;
66 header.date.setValue(null);
67 header.description.setValue(null);
69 items.add(new Item(this, new LedgerTransactionAccount("")));
70 items.add(new Item(this, new LedgerTransactionAccount("")));
71 focusedItem.setValue(0);
73 public void observeFocusedItem(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
74 @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
75 this.focusedItem.observe(owner, observer);
77 public void stopObservingFocusedItem(
78 @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
79 this.focusedItem.removeObserver(observer);
81 public void observeAccountCount(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
83 androidx.lifecycle.Observer<? super Integer> observer) {
84 this.accountCount.observe(owner, observer);
86 public void stopObservingAccountCount(
87 @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
88 this.accountCount.removeObserver(observer);
90 public void setFocusedItem(int position) {
91 focusedItem.setValue(position);
93 public int addAccount(LedgerTransactionAccount acc) {
94 items.add(new Item(this, acc));
95 accountCount.setValue(getAccountCount());
98 boolean accountsInInitialState() {
99 for (Item item : items) {
100 LedgerTransactionAccount acc = item.getAccount();
101 if (acc.isAmountSet())
103 if (!acc.getAccountName()
111 LedgerTransactionAccount getAccount(int index) {
112 return items.get(index)
115 public Item getItem(int index) {
120 if (index <= items.size())
121 return items.get(index - 1);
126 // 1) at least two account names
127 // 2) each amount must have account name
128 // 3) amounts must balance to 0, or
129 // 3a) there must be exactly one empty amount
130 // 4) empty accounts with empty amounts are ignored
131 // 5) a row with an empty account name or empty amount is guaranteed to exist
132 public void checkTransactionSubmittable(NewTransactionItemsAdapter adapter) {
134 int accounts_with_values = 0;
136 int amounts_with_accounts = 0;
138 Item empty_amount = null;
139 boolean single_empty_amount = false;
140 boolean single_empty_amount_has_account = false;
141 float running_total = 0f;
142 final String descriptionText = getDescription();
143 final boolean have_description = ((descriptionText != null) && !descriptionText.isEmpty());
146 for (int i = 0; i < this.items.size(); i++) {
147 Item item = this.items.get(i);
149 LedgerTransactionAccount acc = item.getAccount();
150 String acc_name = acc.getAccountName()
152 if (acc_name.isEmpty()) {
158 if (acc.isAmountSet()) {
159 accounts_with_values++;
163 if (acc.isAmountSet()) {
165 if (!acc_name.isEmpty())
166 amounts_with_accounts++;
167 running_total += acc.getAmount();
170 if (empty_amount == null) {
172 single_empty_amount = true;
173 single_empty_amount_has_account = !acc_name.isEmpty();
175 else if (!acc_name.isEmpty())
176 single_empty_amount = false;
180 if ((empty_rows == 0) &&
181 ((this.items.size() == accounts) || (this.items.size() == amounts)))
186 for (NewTransactionModel.Item item : items) {
188 final LedgerTransactionAccount acc = item.getAccount();
189 if (acc.isAmountSet())
192 if (single_empty_amount) {
193 if (item.equals(empty_amount)) {
194 empty_amount.setAmountHint(String.format(Locale.US, "%1.2f",
195 Misc.isZero(running_total) ? 0f : -running_total));
200 // no single empty account and this account's amount is not set
201 // => hint should be '0.00'
202 String hint = item.getAmountHint();
203 if ((hint == null) || !hint.equals(ZERO_AMOUNT_HINT)) {
204 item.setAmountHint(ZERO_AMOUNT_HINT);
210 debug("submittable", String.format(Locale.US,
211 "%s, accounts=%d, accounts_with_values=%s, " +
212 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
213 "single_empty_with_acc=%s", have_description ? "description" : "NO description",
214 accounts, accounts_with_values, amounts_with_accounts, amounts, running_total,
215 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
217 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
218 (amounts_with_accounts == amounts) &&
219 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
221 debug("submittable", "YES");
222 isSubmittable.setValue(true);
225 debug("submittable", "NO");
226 isSubmittable.setValue(false);
230 catch (NumberFormatException e) {
231 debug("submittable", "NO (because of NumberFormatException)");
232 isSubmittable.setValue(false);
234 catch (Exception e) {
236 debug("submittable", "NO (because of an Exception)");
237 isSubmittable.setValue(false);
240 public void removeItem(int pos) {
242 accountCount.setValue(getAccountCount());
244 public void sendCountNotifications() {
245 accountCount.setValue(getAccountCount());
247 enum ItemType {generalData, transactionRow, bottomFiller}
249 class Item extends Object {
250 private ItemType type;
251 private MutableLiveData<Date> date = new MutableLiveData<>();
252 private MutableLiveData<String> description = new MutableLiveData<>();
253 private LedgerTransactionAccount account;
254 private MutableLiveData<String> amountHint = new MutableLiveData<>();
255 private NewTransactionModel model;
256 private MutableLiveData<Boolean> editable = new MutableLiveData<>(true);
257 public Item(NewTransactionModel model) {
259 type = ItemType.bottomFiller;
260 editable.setValue(false);
262 public Item(NewTransactionModel model, Date date, String description) {
264 this.type = ItemType.generalData;
265 this.date.setValue(date);
266 this.description.setValue(description);
267 this.editable.setValue(true);
269 public Item(NewTransactionModel model, LedgerTransactionAccount account) {
271 this.type = ItemType.transactionRow;
272 this.account = account;
273 this.editable.setValue(true);
275 public NewTransactionModel getModel() {
278 public boolean isEditable() {
279 ensureType(ItemType.transactionRow);
280 return this.editable.getValue();
282 public void setEditable(boolean editable) {
283 ensureType(ItemType.transactionRow);
284 this.editable.setValue(editable);
286 public String getAmountHint() {
287 ensureType(ItemType.transactionRow);
288 return amountHint.getValue();
290 public void setAmountHint(String amountHint) {
291 ensureType(ItemType.transactionRow);
292 this.amountHint.setValue(amountHint);
294 public void observeAmountHint(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
296 androidx.lifecycle.Observer<? super String> observer) {
297 this.amountHint.observe(owner, observer);
299 public void stopObservingAmountHint(
300 @NonNull androidx.lifecycle.Observer<? super String> observer) {
301 this.amountHint.removeObserver(observer);
303 public ItemType getType() {
306 public void ensureType(ItemType wantedType) {
307 if (type != wantedType) {
308 throw new RuntimeException(
309 String.format("Actual type (%s) differs from wanted (%s)", type,
313 public Date getDate() {
314 ensureType(ItemType.generalData);
315 return date.getValue();
317 public void setDate(Date date) {
318 ensureType(ItemType.generalData);
319 this.date.setValue(date);
321 public void setDate(String text) {
322 int year, month, day;
323 final Calendar c = GregorianCalendar.getInstance();
324 Matcher m = reYMD.matcher(text);
326 year = Integer.parseInt(m.group(1));
327 month = Integer.parseInt(m.group(2)) - 1; // month is 0-based
328 day = Integer.parseInt(m.group(3));
331 year = c.get(Calendar.YEAR);
332 m = reMD.matcher(text);
334 month = Integer.parseInt(m.group(1)) - 1;
335 day = Integer.parseInt(m.group(2));
338 month = c.get(Calendar.MONTH);
339 m = reD.matcher(text);
341 day = Integer.parseInt(m.group(1));
344 day = c.get(Calendar.DAY_OF_MONTH);
349 c.set(year, month, day);
351 this.setDate(c.getTime());
353 public void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
354 @NonNull androidx.lifecycle.Observer<? super Date> observer) {
355 this.date.observe(owner, observer);
357 public void stopObservingDate(@NonNull androidx.lifecycle.Observer<? super Date> observer) {
358 this.date.removeObserver(observer);
360 public String getDescription() {
361 ensureType(ItemType.generalData);
362 return description.getValue();
364 public void setDescription(String description) {
365 ensureType(ItemType.generalData);
366 this.description.setValue(description);
368 public void observeDescription(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
370 androidx.lifecycle.Observer<? super String> observer) {
371 this.description.observe(owner, observer);
373 public void stopObservingDescription(
374 @NonNull androidx.lifecycle.Observer<? super String> observer) {
375 this.description.removeObserver(observer);
377 public LedgerTransactionAccount getAccount() {
378 ensureType(ItemType.transactionRow);
381 public void setAccountName(String name) {
382 account.setAccountName(name);
387 * @return nicely formatted, shortest available date representation
389 public String getFormattedDate() {
392 Date time = date.getValue();
396 Calendar c = GregorianCalendar.getInstance();
398 Calendar today = GregorianCalendar.getInstance();
400 final int myYear = c.get(Calendar.YEAR);
401 final int myMonth = c.get(Calendar.MONTH);
402 final int myDay = c.get(Calendar.DAY_OF_MONTH);
404 if (today.get(Calendar.YEAR) != myYear) {
405 return String.format(Locale.US, "%d/%02d/%02d", myYear, myMonth, myDay);
408 if (today.get(Calendar.MONTH) != myMonth) {
409 return String.format(Locale.US, "%d/%02d", myMonth, myDay);
412 return String.valueOf(myDay);
414 public void observeEditableFlag(NewTransactionActivity activity,
415 Observer<Boolean> observer) {
416 editable.observe(activity, observer);
418 public void stopObservingEditableFlag(Observer<Boolean> observer) {
419 editable.removeObserver(observer);