2 * Copyright © 2020 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;
20 import android.database.Cursor;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.os.AsyncTask;
23 import android.os.Build;
24 import android.text.TextUtils;
26 import androidx.annotation.Nullable;
27 import androidx.lifecycle.LiveData;
28 import androidx.lifecycle.MutableLiveData;
29 import androidx.lifecycle.ViewModel;
31 import net.ktnx.mobileledger.App;
32 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
33 import net.ktnx.mobileledger.async.TransactionAccumulator;
34 import net.ktnx.mobileledger.async.UpdateTransactionsTask;
35 import net.ktnx.mobileledger.model.AccountListItem;
36 import net.ktnx.mobileledger.model.Data;
37 import net.ktnx.mobileledger.model.LedgerAccount;
38 import net.ktnx.mobileledger.model.LedgerTransaction;
39 import net.ktnx.mobileledger.model.MobileLedgerProfile;
40 import net.ktnx.mobileledger.model.TransactionListItem;
41 import net.ktnx.mobileledger.utils.LockHolder;
42 import net.ktnx.mobileledger.utils.Locker;
43 import net.ktnx.mobileledger.utils.Logger;
44 import net.ktnx.mobileledger.utils.MLDB;
45 import net.ktnx.mobileledger.utils.SimpleDate;
47 import java.util.ArrayList;
48 import java.util.Date;
49 import java.util.HashMap;
50 import java.util.Iterator;
51 import java.util.List;
52 import java.util.Locale;
55 import static net.ktnx.mobileledger.utils.Logger.debug;
57 public class MainModel extends ViewModel {
58 public final MutableLiveData<Integer> foundTransactionItemIndex = new MutableLiveData<>(null);
59 private final MutableLiveData<Boolean> updatingFlag = new MutableLiveData<>(false);
60 private final MutableLiveData<String> accountFilter = new MutableLiveData<>();
61 private final MutableLiveData<List<TransactionListItem>> displayedTransactions =
62 new MutableLiveData<>(new ArrayList<>());
63 private final MutableLiveData<List<AccountListItem>> displayedAccounts =
64 new MutableLiveData<>();
65 private final Locker accountsLocker = new Locker();
66 private final MutableLiveData<String> updateError = new MutableLiveData<>();
67 private final Map<String, LedgerAccount> accountMap = new HashMap<>();
68 private MobileLedgerProfile profile;
69 private List<LedgerAccount> allAccounts = new ArrayList<>();
70 private SimpleDate firstTransactionDate;
71 private SimpleDate lastTransactionDate;
72 transient private RetrieveTransactionsTask retrieveTransactionsTask;
73 transient private Thread displayedAccountsUpdater;
74 transient private AccountListLoader loader = null;
75 private TransactionsDisplayedFilter displayedTransactionsUpdater;
76 public static ArrayList<LedgerAccount> mergeAccountListsFromWeb(List<LedgerAccount> oldList,
77 List<LedgerAccount> newList) {
78 LedgerAccount oldAcc, newAcc;
79 ArrayList<LedgerAccount> merged = new ArrayList<>();
81 Iterator<LedgerAccount> oldIterator = oldList.iterator();
82 Iterator<LedgerAccount> newIterator = newList.iterator();
85 if (!oldIterator.hasNext()) {
86 // the rest of the incoming are new
87 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
88 newIterator.forEachRemaining(merged::add);
91 while (newIterator.hasNext())
92 merged.add(newIterator.next());
96 oldAcc = oldIterator.next();
98 if (!newIterator.hasNext()) {
99 // no more incoming accounts. ignore the rest of the old
102 newAcc = newIterator.next();
104 // ignore now missing old items
106 .compareTo(newAcc.getName()) < 0)
109 // add newly found items
111 .compareTo(newAcc.getName()) > 0)
117 // two items with same account names; forward-merge UI-controlled fields
118 // it is important that the result list contains a new LedgerAccount instance
119 // so that the change is propagated to the UI
120 newAcc.setExpanded(oldAcc.isExpanded());
121 newAcc.setAmountsExpanded(oldAcc.amountsExpanded());
127 private void setLastUpdateStamp(long transactionCount) {
128 debug("db", "Updating transaction value stamp");
129 Date now = new Date();
130 profile.setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
131 Data.lastUpdateDate.postValue(now);
133 public void scheduleTransactionListReload() {
134 UpdateTransactionsTask task = new UpdateTransactionsTask();
135 task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, this);
137 public LiveData<Boolean> getUpdatingFlag() {
140 public LiveData<String> getUpdateError() {
143 public void setProfile(MobileLedgerProfile profile) {
144 stopTransactionsRetrieval();
145 this.profile = profile;
147 public LiveData<List<TransactionListItem>> getDisplayedTransactions() {
148 return displayedTransactions;
150 public void setDisplayedTransactions(List<TransactionListItem> list, int transactionCount) {
151 displayedTransactions.postValue(list);
152 Data.lastUpdateTransactionCount.postValue(transactionCount);
154 public SimpleDate getFirstTransactionDate() {
155 return firstTransactionDate;
157 public void setFirstTransactionDate(SimpleDate earliestDate) {
158 this.firstTransactionDate = earliestDate;
160 public MutableLiveData<String> getAccountFilter() {
161 return accountFilter;
163 public SimpleDate getLastTransactionDate() {
164 return lastTransactionDate;
166 public void setLastTransactionDate(SimpleDate latestDate) {
167 this.lastTransactionDate = latestDate;
169 private void applyTransactionFilter(List<LedgerTransaction> list) {
170 final String accFilter = accountFilter.getValue();
171 ArrayList<TransactionListItem> newList = new ArrayList<>();
173 TransactionAccumulator accumulator = new TransactionAccumulator(this);
174 if (TextUtils.isEmpty(accFilter))
175 for (LedgerTransaction tr : list)
176 newList.add(new TransactionListItem(tr));
178 for (LedgerTransaction tr : list)
179 if (tr.hasAccountNamedLike(accFilter))
180 newList.add(new TransactionListItem(tr));
182 displayedTransactions.postValue(newList);
184 public synchronized void scheduleTransactionListRetrieval() {
185 if (retrieveTransactionsTask != null) {
186 Logger.debug("db", "Ignoring request for transaction retrieval - already active");
189 MobileLedgerProfile profile = Data.getProfile();
191 retrieveTransactionsTask = new RetrieveTransactionsTask(this, profile, allAccounts);
192 Logger.debug("db", "Created a background transaction retrieval task");
194 retrieveTransactionsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
196 public synchronized void stopTransactionsRetrieval() {
197 if (retrieveTransactionsTask != null)
198 retrieveTransactionsTask.cancel(true);
200 public void transactionRetrievalDone() {
201 retrieveTransactionsTask = null;
203 public synchronized Locker lockAccountsForWriting() {
204 accountsLocker.lockForWriting();
205 return accountsLocker;
207 public void mergeAccountListFromWeb(List<LedgerAccount> newList) {
209 try (LockHolder l = accountsLocker.lockForWriting()) {
210 allAccounts = mergeAccountListsFromWeb(allAccounts, newList);
211 updateAccountsMap(allAccounts);
214 public LiveData<List<AccountListItem>> getDisplayedAccounts() {
215 return displayedAccounts;
217 synchronized public void scheduleAccountListReload() {
218 Logger.debug("async-acc", "scheduleAccountListReload() enter");
219 if ((loader != null) && loader.isAlive()) {
220 Logger.debug("async-acc", "returning early - loader already active");
224 loader = new AccountListLoader(profile, this);
227 public synchronized void setAndStoreAccountAndTransactionListFromWeb(
228 List<LedgerAccount> accounts, List<LedgerTransaction> transactions) {
229 profile.storeAccountAndTransactionListAsync(accounts, transactions);
231 setLastUpdateStamp(transactions.size());
233 mergeAccountListFromWeb(accounts);
234 updateDisplayedAccounts();
236 updateDisplayedTransactionsFromWeb(transactions);
238 synchronized public void abortAccountListReload() {
244 synchronized public void updateDisplayedAccounts() {
245 if (displayedAccountsUpdater != null) {
246 displayedAccountsUpdater.interrupt();
248 displayedAccountsUpdater = new AccountListDisplayedFilter(this, allAccounts);
249 displayedAccountsUpdater.start();
251 synchronized public void updateDisplayedTransactionsFromWeb(List<LedgerTransaction> list) {
252 if (displayedTransactionsUpdater != null) {
253 displayedTransactionsUpdater.interrupt();
255 displayedTransactionsUpdater = new TransactionsDisplayedFilter(this, list);
256 displayedTransactionsUpdater.start();
258 public List<LedgerAccount> getAllAccounts() {
261 private void updateAccountsMap(List<LedgerAccount> newAccounts) {
263 for (LedgerAccount acc : newAccounts) {
264 accountMap.put(acc.getName(), acc);
268 public LedgerAccount locateAccount(String name) {
269 return accountMap.get(name);
271 public void clearUpdateError() {
272 updateError.postValue(null);
274 public void clearAccounts() { displayedAccounts.postValue(new ArrayList<>()); }
275 public void clearTransactions() {
276 displayedTransactions.setValue(new ArrayList<>());
279 static class AccountListLoader extends Thread {
280 private final MobileLedgerProfile profile;
281 private final MainModel model;
282 AccountListLoader(MobileLedgerProfile profile, MainModel model) {
283 this.profile = profile;
288 Logger.debug("async-acc", "AccountListLoader::run() entered");
289 String profileUUID = profile.getUuid();
290 ArrayList<LedgerAccount> list = new ArrayList<>();
291 HashMap<String, LedgerAccount> map = new HashMap<>();
293 String sql = "SELECT a.name, a.expanded, a.amounts_expanded";
294 sql += " from accounts a WHERE a.profile = ?";
295 sql += " ORDER BY a.name";
297 SQLiteDatabase db = App.getDatabase();
298 Logger.debug("async-acc", "AccountListLoader::run() connected to DB");
299 try (Cursor cursor = db.rawQuery(sql, new String[]{profileUUID})) {
300 Logger.debug("async-acc", "AccountListLoader::run() executed query");
301 while (cursor.moveToNext()) {
305 final String accName = cursor.getString(0);
307 // String.format("Read account '%s' from DB [%s]", accName,
309 String parentName = LedgerAccount.extractParentName(accName);
310 LedgerAccount parent;
311 if (parentName != null) {
312 parent = map.get(parentName);
314 throw new IllegalStateException(
315 String.format("Can't load account '%s': parent '%s' not loaded",
316 accName, parentName));
317 parent.setHasSubAccounts(true);
322 LedgerAccount acc = new LedgerAccount(profile, accName, parent);
323 acc.setExpanded(cursor.getInt(1) == 1);
324 acc.setAmountsExpanded(cursor.getInt(2) == 1);
325 acc.setHasSubAccounts(false);
327 try (Cursor c2 = db.rawQuery(
328 "SELECT value, currency FROM account_values WHERE profile = ?" + " " +
329 "AND account = ?", new String[]{profileUUID, accName}))
331 while (c2.moveToNext()) {
332 acc.addAmount(c2.getFloat(0), c2.getString(1));
337 map.put(accName, acc);
339 Logger.debug("async-acc", "AccountListLoader::run() query execution done");
345 Logger.debug("async-acc", "AccountListLoader::run() posting new list");
346 model.allAccounts = list;
347 model.updateAccountsMap(list);
348 model.updateDisplayedAccounts();
352 static class AccountListDisplayedFilter extends Thread {
353 private final MainModel model;
354 private final List<LedgerAccount> list;
355 AccountListDisplayedFilter(MainModel model, List<LedgerAccount> list) {
361 List<AccountListItem> newDisplayed = new ArrayList<>();
362 Logger.debug("dFilter", "waiting for synchronized block");
363 Logger.debug("dFilter", String.format(Locale.US,
364 "entered synchronized block (about to examine %d accounts)", list.size()));
365 newDisplayed.add(new AccountListItem()); // header
368 for (LedgerAccount a : list) {
373 newDisplayed.add(new AccountListItem(a));
377 if (!isInterrupted()) {
378 model.displayedAccounts.postValue(newDisplayed);
379 Data.lastUpdateAccountCount.postValue(count);
381 Logger.debug("dFilter", "left synchronized block");
385 static class TransactionsDisplayedFilter extends Thread {
386 private final MainModel model;
387 private final List<LedgerTransaction> list;
388 TransactionsDisplayedFilter(MainModel model, List<LedgerTransaction> list) {
394 List<LedgerAccount> newDisplayed = new ArrayList<>();
395 Logger.debug("dFilter", "waiting for synchronized block");
396 Logger.debug("dFilter", String.format(Locale.US,
397 "entered synchronized block (about to examine %d transactions)", list.size()));
398 String accNameFilter = model.getAccountFilter()
401 TransactionAccumulator acc = new TransactionAccumulator(model);
402 for (LedgerTransaction tr : list) {
403 if (isInterrupted()) {
407 if (accNameFilter == null || tr.hasAccountNamedLike(accNameFilter)) {
408 acc.put(tr, tr.getDate());
411 if (!isInterrupted()) {
414 Logger.debug("dFilter", "left synchronized block");