]> git.ktnx.net Git - mobile-ledger-staging.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/MainModel.java
convert the last update global header to a list header
[mobile-ledger-staging.git] / app / src / main / java / net / ktnx / mobileledger / ui / MainModel.java
1 /*
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.ui;
19
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;
25
26 import androidx.annotation.Nullable;
27 import androidx.lifecycle.LiveData;
28 import androidx.lifecycle.MutableLiveData;
29 import androidx.lifecycle.ViewModel;
30
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;
46
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;
53 import java.util.Map;
54
55 import static net.ktnx.mobileledger.utils.Logger.debug;
56
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<>();
80
81         Iterator<LedgerAccount> oldIterator = oldList.iterator();
82         Iterator<LedgerAccount> newIterator = newList.iterator();
83
84         while (true) {
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);
89                 }
90                 else {
91                     while (newIterator.hasNext())
92                         merged.add(newIterator.next());
93                 }
94                 break;
95             }
96             oldAcc = oldIterator.next();
97
98             if (!newIterator.hasNext()) {
99                 // no more incoming accounts. ignore the rest of the old
100                 break;
101             }
102             newAcc = newIterator.next();
103
104             // ignore now missing old items
105             if (oldAcc.getName()
106                       .compareTo(newAcc.getName()) < 0)
107                 continue;
108
109             // add newly found items
110             if (oldAcc.getName()
111                       .compareTo(newAcc.getName()) > 0)
112             {
113                 merged.add(newAcc);
114                 continue;
115             }
116
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());
122             merged.add(newAcc);
123         }
124
125         return merged;
126     }
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);
132     }
133     public void scheduleTransactionListReload() {
134         UpdateTransactionsTask task = new UpdateTransactionsTask();
135         task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, this);
136     }
137     public LiveData<Boolean> getUpdatingFlag() {
138         return updatingFlag;
139     }
140     public LiveData<String> getUpdateError() {
141         return updateError;
142     }
143     public void setProfile(MobileLedgerProfile profile) {
144         stopTransactionsRetrieval();
145         this.profile = profile;
146     }
147     public LiveData<List<TransactionListItem>> getDisplayedTransactions() {
148         return displayedTransactions;
149     }
150     public void setDisplayedTransactions(List<TransactionListItem> list) {
151         displayedTransactions.postValue(list);
152     }
153     public SimpleDate getFirstTransactionDate() {
154         return firstTransactionDate;
155     }
156     public void setFirstTransactionDate(SimpleDate earliestDate) {
157         this.firstTransactionDate = earliestDate;
158     }
159     public MutableLiveData<String> getAccountFilter() {
160         return accountFilter;
161     }
162     public SimpleDate getLastTransactionDate() {
163         return lastTransactionDate;
164     }
165     public void setLastTransactionDate(SimpleDate latestDate) {
166         this.lastTransactionDate = latestDate;
167     }
168     private void applyTransactionFilter(List<LedgerTransaction> list) {
169         final String accFilter = accountFilter.getValue();
170         ArrayList<TransactionListItem> newList = new ArrayList<>();
171
172         TransactionAccumulator accumulator = new TransactionAccumulator(this);
173         if (TextUtils.isEmpty(accFilter))
174             for (LedgerTransaction tr : list)
175                 newList.add(new TransactionListItem(tr));
176         else
177             for (LedgerTransaction tr : list)
178                 if (tr.hasAccountNamedLike(accFilter))
179                     newList.add(new TransactionListItem(tr));
180
181         displayedTransactions.postValue(newList);
182     }
183     public synchronized void scheduleTransactionListRetrieval() {
184         if (retrieveTransactionsTask != null) {
185             Logger.debug("db", "Ignoring request for transaction retrieval - already active");
186             return;
187         }
188         MobileLedgerProfile profile = Data.getProfile();
189
190         retrieveTransactionsTask = new RetrieveTransactionsTask(this, profile, allAccounts);
191         Logger.debug("db", "Created a background transaction retrieval task");
192
193         retrieveTransactionsTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
194     }
195     public synchronized void stopTransactionsRetrieval() {
196         if (retrieveTransactionsTask != null)
197             retrieveTransactionsTask.cancel(true);
198     }
199     public void transactionRetrievalDone() {
200         retrieveTransactionsTask = null;
201     }
202     public synchronized Locker lockAccountsForWriting() {
203         accountsLocker.lockForWriting();
204         return accountsLocker;
205     }
206     public void mergeAccountListFromWeb(List<LedgerAccount> newList) {
207
208         try (LockHolder l = accountsLocker.lockForWriting()) {
209             allAccounts = mergeAccountListsFromWeb(allAccounts, newList);
210             updateAccountsMap(allAccounts);
211         }
212     }
213     public LiveData<List<AccountListItem>> getDisplayedAccounts() {
214         return displayedAccounts;
215     }
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");
220             return;
221         }
222
223         loader = new AccountListLoader(profile, this);
224         loader.start();
225     }
226     public synchronized void setAndStoreAccountAndTransactionListFromWeb(
227             List<LedgerAccount> accounts, List<LedgerTransaction> transactions) {
228         profile.storeAccountAndTransactionListAsync(accounts, transactions);
229
230         setLastUpdateStamp();
231
232         mergeAccountListFromWeb(accounts);
233         updateDisplayedAccounts();
234
235         updateDisplayedTransactionsFromWeb(transactions);
236     }
237     synchronized public void abortAccountListReload() {
238         if (loader == null)
239             return;
240         loader.interrupt();
241         loader = null;
242     }
243     synchronized public void updateDisplayedAccounts() {
244         if (displayedAccountsUpdater != null) {
245             displayedAccountsUpdater.interrupt();
246         }
247         displayedAccountsUpdater = new AccountListDisplayedFilter(this, allAccounts);
248         displayedAccountsUpdater.start();
249     }
250     synchronized public void updateDisplayedTransactionsFromWeb(List<LedgerTransaction> list) {
251         if (displayedTransactionsUpdater != null) {
252             displayedTransactionsUpdater.interrupt();
253         }
254         displayedTransactionsUpdater = new TransactionsDisplayedFilter(this, list);
255         displayedTransactionsUpdater.start();
256     }
257     public List<LedgerAccount> getAllAccounts() {
258         return allAccounts;
259     }
260     private void updateAccountsMap(List<LedgerAccount> newAccounts) {
261         accountMap.clear();
262         for (LedgerAccount acc : newAccounts) {
263             accountMap.put(acc.getName(), acc);
264         }
265     }
266     @Nullable
267     public LedgerAccount locateAccount(String name) {
268         return accountMap.get(name);
269     }
270     public void clearUpdateError() {
271         updateError.postValue(null);
272     }
273     public void clearTransactions() {
274         displayedTransactions.setValue(new ArrayList<>());
275     }
276
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;
282             this.model = model;
283         }
284         @Override
285         public void run() {
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<>();
290
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";
294
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()) {
300                     if (isInterrupted())
301                         return;
302
303                     final String accName = cursor.getString(0);
304 //                    debug("accounts",
305 //                            String.format("Read account '%s' from DB [%s]", accName,
306 //                            profileUUID));
307                     String parentName = LedgerAccount.extractParentName(accName);
308                     LedgerAccount parent;
309                     if (parentName != null) {
310                         parent = map.get(parentName);
311                         if (parent == null)
312                             throw new IllegalStateException(
313                                     String.format("Can't load account '%s': parent '%s' not loaded",
314                                             accName, parentName));
315                         parent.setHasSubAccounts(true);
316                     }
317                     else
318                         parent = null;
319
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);
324
325                     try (Cursor c2 = db.rawQuery(
326                             "SELECT value, currency FROM account_values WHERE profile = ?" + " " +
327                             "AND account = ?", new String[]{profileUUID, accName}))
328                     {
329                         while (c2.moveToNext()) {
330                             acc.addAmount(c2.getFloat(0), c2.getString(1));
331                         }
332                     }
333
334                     list.add(acc);
335                     map.put(accName, acc);
336                 }
337                 Logger.debug("async-acc", "AccountListLoader::run() query execution done");
338             }
339
340             if (isInterrupted())
341                 return;
342
343             Logger.debug("async-acc", "AccountListLoader::run() posting new list");
344             model.allAccounts = list;
345             model.updateAccountsMap(list);
346             model.updateDisplayedAccounts();
347         }
348     }
349
350     static class AccountListDisplayedFilter extends Thread {
351         private final MainModel model;
352         private final List<LedgerAccount> list;
353         AccountListDisplayedFilter(MainModel model, List<LedgerAccount> list) {
354             this.model = model;
355             this.list = list;
356         }
357         @Override
358         public void run() {
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) {
365                 if (isInterrupted())
366                     return;
367
368                 if (a.isVisible())
369                     newDisplayed.add(new AccountListItem(a));
370             }
371             if (!isInterrupted()) {
372                 model.displayedAccounts.postValue(newDisplayed);
373             }
374             Logger.debug("dFilter", "left synchronized block");
375         }
376     }
377
378     static class TransactionsDisplayedFilter extends Thread {
379         private final MainModel model;
380         private final List<LedgerTransaction> list;
381         TransactionsDisplayedFilter(MainModel model, List<LedgerTransaction> list) {
382             this.model = model;
383             this.list = list;
384         }
385         @Override
386         public void run() {
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()
392                                         .getValue();
393
394             TransactionAccumulator acc = new TransactionAccumulator(model);
395             for (LedgerTransaction tr : list) {
396                 if (isInterrupted()) {
397                     return;
398                 }
399
400                 if (accNameFilter == null || tr.hasAccountNamedLike(accNameFilter)) {
401                     acc.put(tr, tr.getDate());
402                 }
403             }
404             if (!isInterrupted()) {
405                 acc.done();
406             }
407             Logger.debug("dFilter", "left synchronized block");
408         }
409     }
410 }