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() {
128 debug("db", "Updating transaction value stamp");
129 Date now = new Date();
130 profile.setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
131 Data.lastUpdateLiveData.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) {
151 displayedTransactions.postValue(list);
153 public SimpleDate getFirstTransactionDate() {
154 return firstTransactionDate;
156 public void setFirstTransactionDate(SimpleDate earliestDate) {
157 this.firstTransactionDate = earliestDate;
159 public MutableLiveData<String> getAccountFilter() {
160 return accountFilter;
162 public SimpleDate getLastTransactionDate() {
163 return lastTransactionDate;
165 public void setLastTransactionDate(SimpleDate latestDate) {
166 this.lastTransactionDate = latestDate;
168 private void applyTransactionFilter(List<LedgerTransaction> list) {
169 final String accFilter = accountFilter.getValue();
170 ArrayList<TransactionListItem> newList = new ArrayList<>();
172 TransactionAccumulator accumulator = new TransactionAccumulator(this);
173 if (TextUtils.isEmpty(accFilter))
174 for (LedgerTransaction tr : list)
175 newList.add(new TransactionListItem(tr));
177 for (LedgerTransaction tr : list)
178 if (tr.hasAccountNamedLike(accFilter))
179 newList.add(new TransactionListItem(tr));
181 displayedTransactions.postValue(newList);
183 public synchronized void scheduleTransactionListRetrieval() {
184 if (retrieveTransactionsTask != null) {
185 Logger.debug("db", "Ignoring request for transaction retrieval - already active");
188 MobileLedgerProfile profile = Data.getProfile();
190 retrieveTransactionsTask = new RetrieveTransactionsTask(this, profile, allAccounts);
191 Logger.debug("db", "Created a background transaction retrieval task");
193 retrieveTransactionsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
195 public synchronized void stopTransactionsRetrieval() {
196 if (retrieveTransactionsTask != null)
197 retrieveTransactionsTask.cancel(true);
199 public void transactionRetrievalDone() {
200 retrieveTransactionsTask = null;
202 public synchronized Locker lockAccountsForWriting() {
203 accountsLocker.lockForWriting();
204 return accountsLocker;
206 public void mergeAccountListFromWeb(List<LedgerAccount> newList) {
208 try (LockHolder l = accountsLocker.lockForWriting()) {
209 allAccounts = mergeAccountListsFromWeb(allAccounts, newList);
210 updateAccountsMap(allAccounts);
213 public LiveData<List<AccountListItem>> getDisplayedAccounts() {
214 return displayedAccounts;
216 synchronized public void scheduleAccountListReload() {
217 Logger.debug("async-acc", "scheduleAccountListReload() enter");
218 if ((loader != null) && loader.isAlive()) {
219 Logger.debug("async-acc", "returning early - loader already active");
223 loader = new AccountListLoader(profile, this);
226 public synchronized void setAndStoreAccountAndTransactionListFromWeb(
227 List<LedgerAccount> accounts, List<LedgerTransaction> transactions) {
228 profile.storeAccountAndTransactionListAsync(accounts, transactions);
230 setLastUpdateStamp();
232 mergeAccountListFromWeb(accounts);
233 updateDisplayedAccounts();
235 updateDisplayedTransactionsFromWeb(transactions);
237 synchronized public void abortAccountListReload() {
243 synchronized public void updateDisplayedAccounts() {
244 if (displayedAccountsUpdater != null) {
245 displayedAccountsUpdater.interrupt();
247 displayedAccountsUpdater = new AccountListDisplayedFilter(this, allAccounts);
248 displayedAccountsUpdater.start();
250 synchronized public void updateDisplayedTransactionsFromWeb(List<LedgerTransaction> list) {
251 if (displayedTransactionsUpdater != null) {
252 displayedTransactionsUpdater.interrupt();
254 displayedTransactionsUpdater = new TransactionsDisplayedFilter(this, list);
255 displayedTransactionsUpdater.start();
257 public List<LedgerAccount> getAllAccounts() {
260 private void updateAccountsMap(List<LedgerAccount> newAccounts) {
262 for (LedgerAccount acc : newAccounts) {
263 accountMap.put(acc.getName(), acc);
267 public LedgerAccount locateAccount(String name) {
268 return accountMap.get(name);
270 public void clearUpdateError() {
271 updateError.postValue(null);
273 public void clearTransactions() {
274 displayedTransactions.setValue(new ArrayList<>());
277 static class AccountListLoader extends Thread {
278 private final MobileLedgerProfile profile;
279 private final MainModel model;
280 AccountListLoader(MobileLedgerProfile profile, MainModel model) {
281 this.profile = profile;
286 Logger.debug("async-acc", "AccountListLoader::run() entered");
287 String profileUUID = profile.getUuid();
288 ArrayList<LedgerAccount> list = new ArrayList<>();
289 HashMap<String, LedgerAccount> map = new HashMap<>();
291 String sql = "SELECT a.name, a.expanded, a.amounts_expanded";
292 sql += " from accounts a WHERE a.profile = ?";
293 sql += " ORDER BY a.name";
295 SQLiteDatabase db = App.getDatabase();
296 Logger.debug("async-acc", "AccountListLoader::run() connected to DB");
297 try (Cursor cursor = db.rawQuery(sql, new String[]{profileUUID})) {
298 Logger.debug("async-acc", "AccountListLoader::run() executed query");
299 while (cursor.moveToNext()) {
303 final String accName = cursor.getString(0);
305 // String.format("Read account '%s' from DB [%s]", accName,
307 String parentName = LedgerAccount.extractParentName(accName);
308 LedgerAccount parent;
309 if (parentName != null) {
310 parent = map.get(parentName);
312 throw new IllegalStateException(
313 String.format("Can't load account '%s': parent '%s' not loaded",
314 accName, parentName));
315 parent.setHasSubAccounts(true);
320 LedgerAccount acc = new LedgerAccount(profile, accName, parent);
321 acc.setExpanded(cursor.getInt(1) == 1);
322 acc.setAmountsExpanded(cursor.getInt(2) == 1);
323 acc.setHasSubAccounts(false);
325 try (Cursor c2 = db.rawQuery(
326 "SELECT value, currency FROM account_values WHERE profile = ?" + " " +
327 "AND account = ?", new String[]{profileUUID, accName}))
329 while (c2.moveToNext()) {
330 acc.addAmount(c2.getFloat(0), c2.getString(1));
335 map.put(accName, acc);
337 Logger.debug("async-acc", "AccountListLoader::run() query execution done");
343 Logger.debug("async-acc", "AccountListLoader::run() posting new list");
344 model.allAccounts = list;
345 model.updateAccountsMap(list);
346 model.updateDisplayedAccounts();
350 static class AccountListDisplayedFilter extends Thread {
351 private final MainModel model;
352 private final List<LedgerAccount> list;
353 AccountListDisplayedFilter(MainModel model, List<LedgerAccount> list) {
359 List<AccountListItem> newDisplayed = new ArrayList<>();
360 Logger.debug("dFilter", "waiting for synchronized block");
361 Logger.debug("dFilter", String.format(Locale.US,
362 "entered synchronized block (about to examine %d accounts)", list.size()));
363 newDisplayed.add(new AccountListItem()); // header
364 for (LedgerAccount a : list) {
369 newDisplayed.add(new AccountListItem(a));
371 if (!isInterrupted()) {
372 model.displayedAccounts.postValue(newDisplayed);
374 Logger.debug("dFilter", "left synchronized block");
378 static class TransactionsDisplayedFilter extends Thread {
379 private final MainModel model;
380 private final List<LedgerTransaction> list;
381 TransactionsDisplayedFilter(MainModel model, List<LedgerTransaction> list) {
387 List<LedgerAccount> newDisplayed = new ArrayList<>();
388 Logger.debug("dFilter", "waiting for synchronized block");
389 Logger.debug("dFilter", String.format(Locale.US,
390 "entered synchronized block (about to examine %d transactions)", list.size()));
391 String accNameFilter = model.getAccountFilter()
394 TransactionAccumulator acc = new TransactionAccumulator(model);
395 for (LedgerTransaction tr : list) {
396 if (isInterrupted()) {
400 if (accNameFilter == null || tr.hasAccountNamedLike(accNameFilter)) {
401 acc.put(tr, tr.getDate());
404 if (!isInterrupted()) {
407 Logger.debug("dFilter", "left synchronized block");