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 final Item header = new Item(this, null, "");
47 private final Item trailer = new Item(this);
48 private final ArrayList<Item> items = new ArrayList<>();
49 private final MutableLiveData<Boolean> isSubmittable = new MutableLiveData<>(false);
50 private final MutableLiveData<Integer> focusedItem = new MutableLiveData<>(null);
51 private final MutableLiveData<Integer> accountCount = new MutableLiveData<>(0);
52 public int getAccountCount() {
55 public Date getDate() {
56 return header.date.getValue();
58 public String getDescription() {
59 return header.description.getValue();
61 public LiveData<Boolean> isSubmittable() {
62 return this.isSubmittable;
65 header.date.setValue(null);
66 header.description.setValue(null);
68 items.add(new Item(this, new LedgerTransactionAccount("")));
69 items.add(new Item(this, new LedgerTransactionAccount("")));
70 focusedItem.setValue(0);
72 public void observeFocusedItem(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
73 @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
74 this.focusedItem.observe(owner, observer);
76 public void stopObservingFocusedItem(
77 @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
78 this.focusedItem.removeObserver(observer);
80 public void observeAccountCount(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
82 androidx.lifecycle.Observer<? super Integer> observer) {
83 this.accountCount.observe(owner, observer);
85 public void stopObservingAccountCount(
86 @NonNull androidx.lifecycle.Observer<? super Integer> observer) {
87 this.accountCount.removeObserver(observer);
89 public void setFocusedItem(int position) {
90 focusedItem.setValue(position);
92 public int addAccount(LedgerTransactionAccount acc) {
93 items.add(new Item(this, acc));
94 accountCount.setValue(getAccountCount());
97 boolean accountsInInitialState() {
98 for (Item item : items) {
99 LedgerTransactionAccount acc = item.getAccount();
100 if (acc.isAmountSet()) return false;
101 if (!acc.getAccountName()
103 .isEmpty()) return false;
108 LedgerTransactionAccount getAccount(int index) {
109 return items.get(index)
112 public Item getItem(int index) {
116 else if (index <= items.size()) return items.get(index - 1);
120 // 1) at least two account names
121 // 2) each amount must have account name
122 // 3) amounts must balance to 0, or
123 // 3a) there must be exactly one empty amount
124 // 4) empty accounts with empty amounts are ignored
125 // 5) a row with an empty account name or empty amount is guaranteed to exist
126 public void checkTransactionSubmittable(NewTransactionItemsAdapter adapter) {
128 int accounts_with_values = 0;
130 int amounts_with_accounts = 0;
132 Item empty_amount = null;
133 boolean single_empty_amount = false;
134 boolean single_empty_amount_has_account = false;
135 float running_total = 0f;
136 final String descriptionText = getDescription();
137 final boolean have_description = ((descriptionText != null) && !descriptionText.isEmpty());
140 for (int i = 0; i < this.items.size(); i++) {
141 Item item = this.items.get(i);
143 LedgerTransactionAccount acc = item.getAccount();
144 String acc_name = acc.getAccountName()
146 if (!acc_name.isEmpty()) {
149 if (acc.isAmountSet()) {
150 accounts_with_values++;
155 if (!acc.isAmountSet()) {
156 if (empty_amount == null) {
158 single_empty_amount = true;
159 single_empty_amount_has_account = !acc_name.isEmpty();
161 else if (!acc_name.isEmpty()) single_empty_amount = false;
165 if (!acc_name.isEmpty()) amounts_with_accounts++;
166 running_total += acc.getAmount();
170 if ((empty_rows == 0) &&
171 ((this.items.size() == accounts) || (this.items.size() == amounts)))
176 if (single_empty_amount) {
177 empty_amount.setAmountHint(String.format(Locale.US, "%1.2f",
178 Misc.isZero(running_total) ? 0f : -running_total));
181 debug("submittable", String.format(Locale.US,
182 "%s, accounts=%d, accounts_with_values=%s, " +
183 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
184 "single_empty_with_acc=%s", have_description ? "description" : "NO description",
185 accounts, accounts_with_values, amounts_with_accounts, amounts, running_total,
186 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
188 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
189 (amounts_with_accounts == amounts) &&
190 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
192 debug("submittable", "YES");
193 isSubmittable.setValue(true);
196 debug("submittable", "NO");
197 isSubmittable.setValue(false);
201 catch (NumberFormatException e) {
202 debug("submittable", "NO (because of NumberFormatException)");
203 isSubmittable.setValue(false);
205 catch (Exception e) {
207 debug("submittable", "NO (because of an Exception)");
208 isSubmittable.setValue(false);
211 public void removeItem(int pos) {
213 accountCount.setValue(getAccountCount());
215 public void sendCountNotifications() {
216 accountCount.setValue(getAccountCount());
218 enum ItemType {generalData, transactionRow, bottomFiller}
220 class Item extends Object {
221 private ItemType type;
222 private MutableLiveData<Date> date = new MutableLiveData<>();
223 private MutableLiveData<String> description = new MutableLiveData<>();
224 private LedgerTransactionAccount account;
225 private MutableLiveData<String> amountHint = new MutableLiveData<>();
226 private NewTransactionModel model;
227 private MutableLiveData<Boolean> editable = new MutableLiveData<>(true);
228 public Item(NewTransactionModel model) {
230 type = ItemType.bottomFiller;
231 editable.setValue(false);
233 public Item(NewTransactionModel model, Date date, String description) {
235 this.type = ItemType.generalData;
236 this.date.setValue(date);
237 this.description.setValue(description);
238 this.editable.setValue(true);
240 public Item(NewTransactionModel model, LedgerTransactionAccount account) {
242 this.type = ItemType.transactionRow;
243 this.account = account;
244 this.editable.setValue(true);
246 public NewTransactionModel getModel() {
249 public boolean isEditable() {
250 ensureType(ItemType.transactionRow);
251 return this.editable.getValue();
253 public void setEditable(boolean editable) {
254 ensureType(ItemType.transactionRow);
255 this.editable.setValue(editable);
257 public String getAmountHint() {
258 ensureType(ItemType.transactionRow);
259 return amountHint.getValue();
261 public void setAmountHint(String amountHint) {
262 ensureType(ItemType.transactionRow);
263 this.amountHint.setValue(amountHint);
265 public void observeAmountHint(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
267 androidx.lifecycle.Observer<? super String> observer) {
268 this.amountHint.observe(owner, observer);
270 public void stopObservingAmountHint(
271 @NonNull androidx.lifecycle.Observer<? super String> observer) {
272 this.amountHint.removeObserver(observer);
274 public ItemType getType() {
277 public void ensureType(ItemType wantedType) {
278 if (type != wantedType) {
279 throw new RuntimeException(
280 String.format("Actual type (%d) differs from wanted (%s)", type,
284 public Date getDate() {
285 ensureType(ItemType.generalData);
286 return date.getValue();
288 public void setDate(Date date) {
289 ensureType(ItemType.generalData);
290 this.date.setValue(date);
292 public void setDate(String text) {
293 int year, month, day;
294 final Calendar c = GregorianCalendar.getInstance();
295 Matcher m = reYMD.matcher(text);
297 year = Integer.parseInt(m.group(1));
298 month = Integer.parseInt(m.group(2)) - 1; // month is 0-based
299 day = Integer.parseInt(m.group(3));
302 year = c.get(Calendar.YEAR);
303 m = reMD.matcher(text);
305 month = Integer.parseInt(m.group(1)) - 1;
306 day = Integer.parseInt(m.group(2));
309 month = c.get(Calendar.MONTH);
310 m = reD.matcher(text);
312 day = Integer.parseInt(m.group(1));
315 day = c.get(Calendar.DAY_OF_MONTH);
320 c.set(year, month, day);
322 this.setDate(c.getTime());
324 public void observeDate(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
325 @NonNull androidx.lifecycle.Observer<? super Date> observer) {
326 this.date.observe(owner, observer);
328 public void stopObservingDate(@NonNull androidx.lifecycle.Observer<? super Date> observer) {
329 this.date.removeObserver(observer);
331 public String getDescription() {
332 ensureType(ItemType.generalData);
333 return description.getValue();
335 public void setDescription(String description) {
336 ensureType(ItemType.generalData);
337 this.description.setValue(description);
339 public void observeDescription(@NonNull @NotNull androidx.lifecycle.LifecycleOwner owner,
341 androidx.lifecycle.Observer<? super String> observer) {
342 this.description.observe(owner, observer);
344 public void stopObservingDescription(
345 @NonNull androidx.lifecycle.Observer<? super String> observer) {
346 this.description.removeObserver(observer);
348 public LedgerTransactionAccount getAccount() {
349 ensureType(ItemType.transactionRow);
352 public void setAccountName(String name) {
353 account.setAccountName(name);
358 * @return nicely formatted, shortest available date representation
360 public String getFormattedDate() {
361 if (date == null) return null;
362 Date time = date.getValue();
363 if (time == null) return null;
365 Calendar c = GregorianCalendar.getInstance();
367 Calendar today = GregorianCalendar.getInstance();
369 final int myYear = c.get(Calendar.YEAR);
370 final int myMonth = c.get(Calendar.MONTH);
371 final int myDay = c.get(Calendar.DAY_OF_MONTH);
373 if (today.get(Calendar.YEAR) != myYear) {
374 return String.format(Locale.US, "%d/%02d/%02d", myYear, myMonth, myDay);
377 if (today.get(Calendar.MONTH) != myMonth) {
378 return String.format(Locale.US, "%d/%02d", myMonth, myDay);
381 return String.valueOf(myDay);
383 public void observeEditableFlag(NewTransactionActivity activity,
384 Observer<Boolean> observer) {
385 editable.observe(activity, observer);
387 public void stopObservingEditableFlag(Observer<Boolean> observer) {
388 editable.removeObserver(observer);