]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
d9fd260a4533e173aa2ac187a985f941a46d344a
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / MobileLedgerProfile.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.model;
19
20 import android.content.res.Resources;
21 import android.database.Cursor;
22 import android.database.sqlite.SQLiteDatabase;
23 import android.os.Build;
24 import android.text.TextUtils;
25 import android.util.SparseArray;
26
27 import androidx.annotation.Nullable;
28 import androidx.lifecycle.LiveData;
29 import androidx.lifecycle.MutableLiveData;
30
31 import net.ktnx.mobileledger.App;
32 import net.ktnx.mobileledger.R;
33 import net.ktnx.mobileledger.async.DbOpQueue;
34 import net.ktnx.mobileledger.async.SendTransactionTask;
35 import net.ktnx.mobileledger.utils.LockHolder;
36 import net.ktnx.mobileledger.utils.Locker;
37 import net.ktnx.mobileledger.utils.Logger;
38 import net.ktnx.mobileledger.utils.MLDB;
39 import net.ktnx.mobileledger.utils.Misc;
40 import net.ktnx.mobileledger.utils.SimpleDate;
41
42 import org.jetbrains.annotations.Contract;
43
44 import java.util.ArrayList;
45 import java.util.Calendar;
46 import java.util.Date;
47 import java.util.HashMap;
48 import java.util.Iterator;
49 import java.util.List;
50 import java.util.Locale;
51 import java.util.Map;
52 import java.util.Objects;
53
54 import static net.ktnx.mobileledger.utils.Logger.debug;
55
56 public final class MobileLedgerProfile {
57     private final MutableLiveData<List<LedgerAccount>> displayedAccounts;
58     private final MutableLiveData<List<LedgerTransaction>> allTransactions;
59     private final MutableLiveData<List<LedgerTransaction>> displayedTransactions;
60     // N.B. when adding new fields, update the copy-constructor below
61     private final String uuid;
62     private final Locker accountsLocker = new Locker();
63     private List<LedgerAccount> allAccounts;
64     private String name;
65     private boolean permitPosting;
66     private boolean showCommentsByDefault;
67     private boolean showCommodityByDefault;
68     private String defaultCommodity;
69     private String preferredAccountsFilter;
70     private String url;
71     private boolean authEnabled;
72     private String authUserName;
73     private String authPassword;
74     private int themeHue;
75     private int orderNo = -1;
76     private SendTransactionTask.API apiVersion = SendTransactionTask.API.auto;
77     private Calendar firstTransactionDate;
78     private Calendar lastTransactionDate;
79     private FutureDates futureDates = FutureDates.None;
80     private boolean accountsLoaded;
81     private boolean transactionsLoaded;
82     // N.B. when adding new fields, update the copy-constructor below
83     transient private AccountListLoader loader = null;
84     transient private Thread displayedAccountsUpdater;
85     transient private AccountListSaver accountListSaver;
86     transient private TransactionListSaver transactionListSaver;
87     transient private AccountAndTransactionListSaver accountAndTransactionListSaver;
88     private Map<String, LedgerAccount> accountMap = new HashMap<>();
89     public MobileLedgerProfile(String uuid) {
90         this.uuid = uuid;
91         allAccounts = new ArrayList<>();
92         displayedAccounts = new MutableLiveData<>();
93         allTransactions = new MutableLiveData<>(new ArrayList<>());
94         displayedTransactions = new MutableLiveData<>(new ArrayList<>());
95     }
96     public MobileLedgerProfile(MobileLedgerProfile origin) {
97         uuid = origin.uuid;
98         name = origin.name;
99         permitPosting = origin.permitPosting;
100         showCommentsByDefault = origin.showCommentsByDefault;
101         showCommodityByDefault = origin.showCommodityByDefault;
102         preferredAccountsFilter = origin.preferredAccountsFilter;
103         url = origin.url;
104         authEnabled = origin.authEnabled;
105         authUserName = origin.authUserName;
106         authPassword = origin.authPassword;
107         themeHue = origin.themeHue;
108         orderNo = origin.orderNo;
109         futureDates = origin.futureDates;
110         apiVersion = origin.apiVersion;
111         defaultCommodity = origin.defaultCommodity;
112         firstTransactionDate = origin.firstTransactionDate;
113         lastTransactionDate = origin.lastTransactionDate;
114         displayedAccounts = origin.displayedAccounts;
115         allAccounts = origin.allAccounts;
116         accountMap = origin.accountMap;
117         displayedTransactions = origin.displayedTransactions;
118         allTransactions = origin.allTransactions;
119         accountsLoaded = origin.accountsLoaded;
120         transactionsLoaded = origin.transactionsLoaded;
121     }
122     // loads all profiles into Data.profiles
123     // returns the profile with the given UUID
124     public static MobileLedgerProfile loadAllFromDB(@Nullable String currentProfileUUID) {
125         MobileLedgerProfile result = null;
126         ArrayList<MobileLedgerProfile> list = new ArrayList<>();
127         SQLiteDatabase db = App.getDatabase();
128         try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
129                                          "auth_password, permit_posting, theme, order_no, " +
130                                          "preferred_accounts_filter, future_dates, api_version, " +
131                                          "show_commodity_by_default, default_commodity, " +
132                                          "show_comments_by_default FROM " +
133                                          "profiles order by order_no", null))
134         {
135             while (cursor.moveToNext()) {
136                 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
137                 item.setName(cursor.getString(1));
138                 item.setUrl(cursor.getString(2));
139                 item.setAuthEnabled(cursor.getInt(3) == 1);
140                 item.setAuthUserName(cursor.getString(4));
141                 item.setAuthPassword(cursor.getString(5));
142                 item.setPostingPermitted(cursor.getInt(6) == 1);
143                 item.setThemeId(cursor.getInt(7));
144                 item.orderNo = cursor.getInt(8);
145                 item.setPreferredAccountsFilter(cursor.getString(9));
146                 item.setFutureDates(cursor.getInt(10));
147                 item.setApiVersion(cursor.getInt(11));
148                 item.setShowCommodityByDefault(cursor.getInt(12) == 1);
149                 item.setDefaultCommodity(cursor.getString(13));
150                 item.setShowCommentsByDefault(cursor.getInt(14) == 1);
151                 list.add(item);
152                 if (item.getUuid()
153                         .equals(currentProfileUUID))
154                     result = item;
155             }
156         }
157         Data.profiles.setValue(list);
158         return result;
159     }
160     public static void storeProfilesOrder() {
161         SQLiteDatabase db = App.getDatabase();
162         db.beginTransactionNonExclusive();
163         try {
164             int orderNo = 0;
165             for (MobileLedgerProfile p : Objects.requireNonNull(Data.profiles.getValue())) {
166                 db.execSQL("update profiles set order_no=? where uuid=?",
167                         new Object[]{orderNo, p.getUuid()});
168                 p.orderNo = orderNo;
169                 orderNo++;
170             }
171             db.setTransactionSuccessful();
172         }
173         finally {
174             db.endTransaction();
175         }
176     }
177     public static ArrayList<LedgerAccount> mergeAccountListsFromWeb(List<LedgerAccount> oldList,
178                                                                     List<LedgerAccount> newList) {
179         LedgerAccount oldAcc, newAcc;
180         ArrayList<LedgerAccount> merged = new ArrayList<>();
181
182         Iterator<LedgerAccount> oldIterator = oldList.iterator();
183         Iterator<LedgerAccount> newIterator = newList.iterator();
184
185         while (true) {
186             if (!oldIterator.hasNext()) {
187                 // the rest of the incoming are new
188                 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
189                     newIterator.forEachRemaining(merged::add);
190                 }
191                 else {
192                     while (newIterator.hasNext())
193                         merged.add(newIterator.next());
194                 }
195                 break;
196             }
197             oldAcc = oldIterator.next();
198
199             if (!newIterator.hasNext()) {
200                 // no more incoming accounts. ignore the rest of the old
201                 break;
202             }
203             newAcc = newIterator.next();
204
205             // ignore now missing old items
206             if (oldAcc.getName()
207                       .compareTo(newAcc.getName()) < 0)
208                 continue;
209
210             // add newly found items
211             if (oldAcc.getName()
212                       .compareTo(newAcc.getName()) > 0)
213             {
214                 merged.add(newAcc);
215                 continue;
216             }
217
218             // two items with same account names; forward-merge UI-controlled fields
219             // it is important that the result list contains a new LedgerAccount instance
220             // so that the change is propagated to the UI
221             newAcc.setExpanded(oldAcc.isExpanded());
222             newAcc.setAmountsExpanded(oldAcc.amountsExpanded());
223             merged.add(newAcc);
224         }
225
226         return merged;
227     }
228     public void mergeAccountListFromWeb(List<LedgerAccount> newList) {
229
230         try (LockHolder l = accountsLocker.lockForWriting()) {
231             allAccounts = mergeAccountListsFromWeb(allAccounts, newList);
232             updateAccountsMap(allAccounts);
233         }
234     }
235     public LiveData<List<LedgerAccount>> getDisplayedAccounts() {
236         return displayedAccounts;
237     }
238     @Contract(value = "null -> false", pure = true)
239     @Override
240     public boolean equals(@Nullable Object obj) {
241         if (obj == null)
242             return false;
243         if (obj == this)
244             return true;
245         if (obj.getClass() != this.getClass())
246             return false;
247
248         MobileLedgerProfile p = (MobileLedgerProfile) obj;
249         if (!uuid.equals(p.uuid))
250             return false;
251         if (!name.equals(p.name))
252             return false;
253         if (permitPosting != p.permitPosting)
254             return false;
255         if (showCommentsByDefault != p.showCommentsByDefault)
256             return false;
257         if (showCommodityByDefault != p.showCommodityByDefault)
258             return false;
259         if (!Objects.equals(defaultCommodity, p.defaultCommodity))
260             return false;
261         if (!Objects.equals(preferredAccountsFilter, p.preferredAccountsFilter))
262             return false;
263         if (!Objects.equals(url, p.url))
264             return false;
265         if (authEnabled != p.authEnabled)
266             return false;
267         if (!Objects.equals(authUserName, p.authUserName))
268             return false;
269         if (!Objects.equals(authPassword, p.authPassword))
270             return false;
271         if (themeHue != p.themeHue)
272             return false;
273         if (apiVersion != p.apiVersion)
274             return false;
275         if (!Objects.equals(firstTransactionDate, p.firstTransactionDate))
276             return false;
277         if (!Objects.equals(lastTransactionDate, p.lastTransactionDate))
278             return false;
279         return futureDates == p.futureDates;
280     }
281     synchronized public void scheduleAccountListReload() {
282         Logger.debug("async-acc", "scheduleAccountListReload() enter");
283         if ((loader != null) && loader.isAlive()) {
284             Logger.debug("async-acc", "returning early - loader already active");
285             return;
286         }
287
288         Logger.debug("async-acc", "Starting AccountListLoader");
289         loader = new AccountListLoader(this);
290         loader.start();
291     }
292     synchronized public void abortAccountListReload() {
293         if (loader == null)
294             return;
295         loader.interrupt();
296         loader = null;
297     }
298     public boolean getShowCommentsByDefault() {
299         return showCommentsByDefault;
300     }
301     public void setShowCommentsByDefault(boolean newValue) {
302         this.showCommentsByDefault = newValue;
303     }
304     public boolean getShowCommodityByDefault() {
305         return showCommodityByDefault;
306     }
307     public void setShowCommodityByDefault(boolean showCommodityByDefault) {
308         this.showCommodityByDefault = showCommodityByDefault;
309     }
310     public String getDefaultCommodity() {
311         return defaultCommodity;
312     }
313     public void setDefaultCommodity(String defaultCommodity) {
314         this.defaultCommodity = defaultCommodity;
315     }
316     public void setDefaultCommodity(CharSequence defaultCommodity) {
317         if (defaultCommodity == null)
318             this.defaultCommodity = null;
319         else
320             this.defaultCommodity = String.valueOf(defaultCommodity);
321     }
322     public SendTransactionTask.API getApiVersion() {
323         return apiVersion;
324     }
325     public void setApiVersion(SendTransactionTask.API apiVersion) {
326         this.apiVersion = apiVersion;
327     }
328     public void setApiVersion(int apiVersion) {
329         this.apiVersion = SendTransactionTask.API.valueOf(apiVersion);
330     }
331     public FutureDates getFutureDates() {
332         return futureDates;
333     }
334     public void setFutureDates(int anInt) {
335         futureDates = FutureDates.valueOf(anInt);
336     }
337     public void setFutureDates(FutureDates futureDates) {
338         this.futureDates = futureDates;
339     }
340     public String getPreferredAccountsFilter() {
341         return preferredAccountsFilter;
342     }
343     public void setPreferredAccountsFilter(String preferredAccountsFilter) {
344         this.preferredAccountsFilter = preferredAccountsFilter;
345     }
346     public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
347         setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
348     }
349     public boolean isPostingPermitted() {
350         return permitPosting;
351     }
352     public void setPostingPermitted(boolean permitPosting) {
353         this.permitPosting = permitPosting;
354     }
355     public String getUuid() {
356         return uuid;
357     }
358     public String getName() {
359         return name;
360     }
361     public void setName(CharSequence text) {
362         setName(String.valueOf(text));
363     }
364     public void setName(String name) {
365         this.name = name;
366     }
367     public String getUrl() {
368         return url;
369     }
370     public void setUrl(CharSequence text) {
371         setUrl(String.valueOf(text));
372     }
373     public void setUrl(String url) {
374         this.url = url;
375     }
376     public boolean isAuthEnabled() {
377         return authEnabled;
378     }
379     public void setAuthEnabled(boolean authEnabled) {
380         this.authEnabled = authEnabled;
381     }
382     public String getAuthUserName() {
383         return authUserName;
384     }
385     public void setAuthUserName(CharSequence text) {
386         setAuthUserName(String.valueOf(text));
387     }
388     public void setAuthUserName(String authUserName) {
389         this.authUserName = authUserName;
390     }
391     public String getAuthPassword() {
392         return authPassword;
393     }
394     public void setAuthPassword(CharSequence text) {
395         setAuthPassword(String.valueOf(text));
396     }
397     public void setAuthPassword(String authPassword) {
398         this.authPassword = authPassword;
399     }
400     public void storeInDB() {
401         SQLiteDatabase db = App.getDatabase();
402         db.beginTransactionNonExclusive();
403         try {
404 //            debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
405 //                                            "url=%s, permit_posting=%s, authEnabled=%s, " +
406 //                                            "themeHue=%d", uuid, name, url,
407 //                    permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeHue));
408             db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
409                        "use_authentication, auth_user, auth_password, theme, order_no, " +
410                        "preferred_accounts_filter, future_dates, api_version, " +
411                        "show_commodity_by_default, default_commodity, show_comments_by_default) " +
412                        "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
413                     new Object[]{uuid, name, permitPosting, url, authEnabled,
414                                  authEnabled ? authUserName : null,
415                                  authEnabled ? authPassword : null, themeHue, orderNo,
416                                  preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt(),
417                                  showCommodityByDefault, defaultCommodity, showCommentsByDefault
418                     });
419             db.setTransactionSuccessful();
420         }
421         finally {
422             db.endTransaction();
423         }
424     }
425     public void storeAccount(SQLiteDatabase db, int generation, LedgerAccount acc,
426                              boolean storeUiFields) {
427         // replace into is a bad idea because it would reset hidden to its default value
428         // we like the default, but for new accounts only
429         String sql = "update accounts set generation = ?";
430         List<Object> params = new ArrayList<>();
431         params.add(generation);
432         if (storeUiFields) {
433             sql += ", expanded=?";
434             params.add(acc.isExpanded() ? 1 : 0);
435         }
436         sql += " where profile=? and name=?";
437         params.add(uuid);
438         params.add(acc.getName());
439         db.execSQL(sql, params.toArray());
440
441         db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, " +
442                    "expanded, generation) select ?,?,?,?,?,0,? where (select changes() = 0)",
443                 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
444                              acc.getLevel(), generation
445                 });
446 //        debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
447     }
448     public void storeAccountValue(SQLiteDatabase db, int generation, String name, String currency,
449                                   Float amount) {
450         db.execSQL("replace into account_values(profile, account, " +
451                    "currency, value, generation) values(?, ?, ?, ?, ?);",
452                 new Object[]{uuid, name, Misc.emptyIsNull(currency), amount, generation});
453     }
454     public void storeTransaction(SQLiteDatabase db, int generation, LedgerTransaction tr) {
455         tr.fillDataHash();
456         SimpleDate d = tr.getDate();
457         db.execSQL("UPDATE transactions SET year=?, month=?, day=?, description=?, comment=?, " +
458                    "data_hash=?, generation=? WHERE profile=? AND id=?",
459                 new Object[]{d.year, d.month, d.day, tr.getDescription(), tr.getComment(),
460                              tr.getDataHash(), generation, uuid, tr.getId()
461                 });
462         db.execSQL("INSERT INTO transactions(profile, id, year, month, day, description, " +
463                    "comment, data_hash, generation) " +
464                    "select ?,?,?,?,?,?,?,?,? WHERE (select changes() = 0)",
465                 new Object[]{uuid, tr.getId(), tr.getDate().year, tr.getDate().month,
466                              tr.getDate().day, tr.getDescription(), tr.getComment(),
467                              tr.getDataHash(), generation
468                 });
469
470         int accountOrderNo = 1;
471         for (LedgerTransactionAccount item : tr.getAccounts()) {
472             db.execSQL("UPDATE transaction_accounts SET account_name=?, amount=?, currency=?, " +
473                        "comment=?, generation=? " +
474                        "WHERE profile=? AND transaction_id=? AND order_no=?",
475                     new Object[]{item.getAccountName(), item.getAmount(),
476                                  Misc.nullIsEmpty(item.getCurrency()), item.getComment(),
477                                  generation, uuid, tr.getId(), accountOrderNo
478                     });
479             db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
480                        "order_no, account_name, amount, currency, comment, generation) " +
481                        "select ?, ?, ?, ?, ?, ?, ?, ? WHERE (select changes() = 0)",
482                     new Object[]{uuid, tr.getId(), accountOrderNo, item.getAccountName(),
483                                  item.getAmount(), Misc.nullIsEmpty(item.getCurrency()),
484                                  item.getComment(), generation
485                     });
486
487             accountOrderNo++;
488         }
489 //        debug("profile", String.format("Transaction %d stored", tr.getId()));
490     }
491     public String getOption(String name, String default_value) {
492         SQLiteDatabase db = App.getDatabase();
493         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
494                 new String[]{uuid, name}))
495         {
496             if (cursor.moveToFirst()) {
497                 String result = cursor.getString(0);
498
499                 if (result == null) {
500                     debug("profile", "returning default value for " + name);
501                     result = default_value;
502                 }
503                 else
504                     debug("profile", String.format("option %s=%s", name, result));
505
506                 return result;
507             }
508             else
509                 return default_value;
510         }
511         catch (Exception e) {
512             debug("db", "returning default value for " + name, e);
513             return default_value;
514         }
515     }
516     public long getLongOption(String name, long default_value) {
517         long longResult;
518         String result = getOption(name, "");
519         if ((result == null) || result.isEmpty()) {
520             debug("profile", String.format("Returning default value for option %s", name));
521             longResult = default_value;
522         }
523         else {
524             try {
525                 longResult = Long.parseLong(result);
526                 debug("profile", String.format("option %s=%s", name, result));
527             }
528             catch (Exception e) {
529                 debug("profile", String.format("Returning default value for option %s", name), e);
530                 longResult = default_value;
531             }
532         }
533
534         return longResult;
535     }
536     public void setOption(String name, String value) {
537         debug("profile", String.format("setting option %s=%s", name, value));
538         DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
539                 new String[]{uuid, name, value});
540     }
541     public void setLongOption(String name, long value) {
542         setOption(name, String.valueOf(value));
543     }
544     public void removeFromDB() {
545         SQLiteDatabase db = App.getDatabase();
546         debug("db", String.format("removing profile %s from DB", uuid));
547         db.beginTransactionNonExclusive();
548         try {
549             Object[] uuid_param = new Object[]{uuid};
550             db.execSQL("delete from profiles where uuid=?", uuid_param);
551             db.execSQL("delete from accounts where profile=?", uuid_param);
552             db.execSQL("delete from account_values where profile=?", uuid_param);
553             db.execSQL("delete from transactions where profile=?", uuid_param);
554             db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
555             db.execSQL("delete from options where profile=?", uuid_param);
556             db.setTransactionSuccessful();
557         }
558         finally {
559             db.endTransaction();
560         }
561     }
562     public LedgerTransaction loadTransaction(int transactionId) {
563         LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
564         tr.loadData(App.getDatabase());
565
566         return tr;
567     }
568     public int getThemeHue() {
569 //        debug("profile", String.format("Profile.getThemeHue() returning %d", themeHue));
570         return this.themeHue;
571     }
572     public void setThemeHue(Object o) {
573         setThemeId(Integer.parseInt(String.valueOf(o)));
574     }
575     public void setThemeId(int themeHue) {
576 //        debug("profile", String.format("Profile.setThemeHue(%d) called", themeHue));
577         this.themeHue = themeHue;
578     }
579     public int getNextTransactionsGeneration(SQLiteDatabase db) {
580         int generation = 1;
581         try (Cursor c = db.rawQuery("SELECT generation FROM transactions WHERE profile=? LIMIT 1",
582                 new String[]{uuid}))
583         {
584             if (c.moveToFirst()) {
585                 generation = c.getInt(0) + 1;
586             }
587         }
588         return generation;
589     }
590     private int getNextAccountsGeneration(SQLiteDatabase db) {
591         int generation = 1;
592         try (Cursor c = db.rawQuery("SELECT generation FROM accounts WHERE profile=? LIMIT 1",
593                 new String[]{uuid}))
594         {
595             if (c.moveToFirst()) {
596                 generation = c.getInt(0) + 1;
597             }
598         }
599         return generation;
600     }
601     private void deleteNotPresentAccounts(SQLiteDatabase db, int generation) {
602         Logger.debug("db/benchmark", "Deleting obsolete accounts");
603         db.execSQL("DELETE FROM account_values WHERE profile=? AND generation <> ?",
604                 new Object[]{uuid, generation});
605         db.execSQL("DELETE FROM accounts WHERE profile=? AND generation <> ?",
606                 new Object[]{uuid, generation});
607         Logger.debug("db/benchmark", "Done deleting obsolete accounts");
608     }
609     private void deleteNotPresentTransactions(SQLiteDatabase db, int generation) {
610         Logger.debug("db/benchmark", "Deleting obsolete transactions");
611         db.execSQL("DELETE FROM transaction_accounts WHERE profile=? AND generation <> ?",
612                 new Object[]{uuid, generation});
613         db.execSQL("DELETE FROM transactions WHERE profile=? AND generation <> ?",
614                 new Object[]{uuid, generation});
615         Logger.debug("db/benchmark", "Done deleting obsolete transactions");
616     }
617     private void setLastUpdateStamp() {
618         debug("db", "Updating transaction value stamp");
619         Date now = new Date();
620         setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
621         Data.lastUpdateDate.postValue(now);
622     }
623     public void wipeAllData() {
624         SQLiteDatabase db = App.getDatabase();
625         db.beginTransaction();
626         try {
627             String[] pUuid = new String[]{uuid};
628             db.execSQL("delete from options where profile=?", pUuid);
629             db.execSQL("delete from accounts where profile=?", pUuid);
630             db.execSQL("delete from account_values where profile=?", pUuid);
631             db.execSQL("delete from transactions where profile=?", pUuid);
632             db.execSQL("delete from transaction_accounts where profile=?", pUuid);
633             db.setTransactionSuccessful();
634             debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
635         }
636         finally {
637             db.endTransaction();
638         }
639     }
640     public List<Currency> getCurrencies() {
641         SQLiteDatabase db = App.getDatabase();
642
643         ArrayList<Currency> result = new ArrayList<>();
644
645         try (Cursor c = db.rawQuery("SELECT c.id, c.name, c.position, c.has_gap FROM currencies c",
646                 new String[]{}))
647         {
648             while (c.moveToNext()) {
649                 Currency currency = new Currency(c.getInt(0), c.getString(1),
650                         Currency.Position.valueOf(c.getInt(2)), c.getInt(3) == 1);
651                 result.add(currency);
652             }
653         }
654
655         return result;
656     }
657     Currency loadCurrencyByName(String name) {
658         SQLiteDatabase db = App.getDatabase();
659         Currency result = tryLoadCurrencyByName(db, name);
660         if (result == null)
661             throw new RuntimeException(String.format("Unable to load currency '%s'", name));
662         return result;
663     }
664     private Currency tryLoadCurrencyByName(SQLiteDatabase db, String name) {
665         try (Cursor cursor = db.rawQuery(
666                 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.name=?",
667                 new String[]{name}))
668         {
669             if (cursor.moveToFirst()) {
670                 return new Currency(cursor.getInt(0), cursor.getString(1),
671                         Currency.Position.valueOf(cursor.getInt(2)), cursor.getInt(3) == 1);
672             }
673             return null;
674         }
675     }
676     public Calendar getFirstTransactionDate() {
677         return firstTransactionDate;
678     }
679     public Calendar getLastTransactionDate() {
680         return lastTransactionDate;
681     }
682     private void applyTransactionFilter(List<LedgerTransaction> list) {
683         final String accFilter = Data.accountFilter.getValue();
684         if (TextUtils.isEmpty(accFilter)) {
685             displayedTransactions.postValue(list);
686         }
687         else {
688             ArrayList<LedgerTransaction> newList = new ArrayList<>();
689             for (LedgerTransaction tr : list) {
690                 if (tr.hasAccountNamedLike(accFilter))
691                     newList.add(tr);
692             }
693             displayedTransactions.postValue(newList);
694         }
695     }
696     synchronized public void storeAccountListAsync(List<LedgerAccount> list,
697                                                    boolean storeUiFields) {
698         if (accountListSaver != null)
699             accountListSaver.interrupt();
700         accountListSaver = new AccountListSaver(this, list, storeUiFields);
701         accountListSaver.start();
702     }
703     public void setAndStoreAccountListFromWeb(ArrayList<LedgerAccount> list) {
704         SQLiteDatabase db = App.getDatabase();
705         db.beginTransactionNonExclusive();
706         try {
707             Logger.debug("db/benchmark",
708                     String.format(Locale.US, "Storing %d accounts", list.size()));
709             int gen = getNextAccountsGeneration(db);
710             Logger.debug("db/benckmark",
711                     String.format(Locale.US, "Got next generation of %d", gen));
712             for (LedgerAccount acc : list) {
713                 storeAccount(db, gen, acc, false);
714                 for (LedgerAmount amt : acc.getAmounts()) {
715                     storeAccountValue(db, gen, acc.getName(), amt.getCurrency(), amt.getAmount());
716                 }
717             }
718             Logger.debug("db/benchmark", "Done storing accounts");
719             deleteNotPresentAccounts(db, gen);
720             setLastUpdateStamp();
721             db.setTransactionSuccessful();
722         }
723         finally {
724             db.endTransaction();
725         }
726
727         mergeAccountListFromWeb(list);
728         updateDisplayedAccounts();
729     }
730     public synchronized Locker lockAccountsForWriting() {
731         accountsLocker.lockForWriting();
732         return accountsLocker;
733     }
734     public void setAndStoreTransactionList(ArrayList<LedgerTransaction> list) {
735         storeTransactionListAsync(this, list);
736
737         allTransactions.postValue(list);
738     }
739     private void storeTransactionListAsync(MobileLedgerProfile mobileLedgerProfile,
740                                            List<LedgerTransaction> list) {
741         if (transactionListSaver != null)
742             transactionListSaver.interrupt();
743
744         transactionListSaver = new TransactionListSaver(this, list);
745         transactionListSaver.start();
746     }
747     public void setAndStoreAccountAndTransactionListFromWeb(List<LedgerAccount> accounts,
748                                                             List<LedgerTransaction> transactions) {
749         storeAccountAndTransactionListAsync(accounts, transactions, false);
750
751         mergeAccountListFromWeb(accounts);
752         updateDisplayedAccounts();
753
754         allTransactions.postValue(transactions);
755     }
756     private void storeAccountAndTransactionListAsync(List<LedgerAccount> accounts,
757                                                      List<LedgerTransaction> transactions,
758                                                      boolean storeAccUiFields) {
759         if (accountAndTransactionListSaver != null)
760             accountAndTransactionListSaver.interrupt();
761
762         accountAndTransactionListSaver =
763                 new AccountAndTransactionListSaver(this, accounts, transactions, storeAccUiFields);
764         accountAndTransactionListSaver.start();
765     }
766     synchronized public void updateDisplayedAccounts() {
767         if (displayedAccountsUpdater != null) {
768             displayedAccountsUpdater.interrupt();
769         }
770         displayedAccountsUpdater = new AccountListDisplayedFilter(this, allAccounts);
771         displayedAccountsUpdater.start();
772     }
773     public List<LedgerAccount> getAllAccounts() {
774         return allAccounts;
775     }
776     private void updateAccountsMap(List<LedgerAccount> newAccounts) {
777         accountMap.clear();
778         for (LedgerAccount acc : newAccounts) {
779             accountMap.put(acc.getName(), acc);
780         }
781     }
782     @Nullable
783     public LedgerAccount locateAccount(String name) {
784         return accountMap.get(name);
785     }
786
787     public enum FutureDates {
788         None(0), OneWeek(7), TwoWeeks(14), OneMonth(30), TwoMonths(60), ThreeMonths(90),
789         SixMonths(180), OneYear(365), All(-1);
790         private static SparseArray<FutureDates> map = new SparseArray<>();
791
792         static {
793             for (FutureDates item : FutureDates.values()) {
794                 map.put(item.value, item);
795             }
796         }
797
798         private int value;
799         FutureDates(int value) {
800             this.value = value;
801         }
802         public static FutureDates valueOf(int i) {
803             return map.get(i, None);
804         }
805         public int toInt() {
806             return this.value;
807         }
808         public String getText(Resources resources) {
809             switch (value) {
810                 case 7:
811                     return resources.getString(R.string.future_dates_7);
812                 case 14:
813                     return resources.getString(R.string.future_dates_14);
814                 case 30:
815                     return resources.getString(R.string.future_dates_30);
816                 case 60:
817                     return resources.getString(R.string.future_dates_60);
818                 case 90:
819                     return resources.getString(R.string.future_dates_90);
820                 case 180:
821                     return resources.getString(R.string.future_dates_180);
822                 case 365:
823                     return resources.getString(R.string.future_dates_365);
824                 case -1:
825                     return resources.getString(R.string.future_dates_all);
826                 default:
827                     return resources.getString(R.string.future_dates_none);
828             }
829         }
830     }
831
832     static class AccountListLoader extends Thread {
833         MobileLedgerProfile profile;
834         AccountListLoader(MobileLedgerProfile profile) {
835             this.profile = profile;
836         }
837         @Override
838         public void run() {
839             Logger.debug("async-acc", "AccountListLoader::run() entered");
840             String profileUUID = profile.getUuid();
841             ArrayList<LedgerAccount> list = new ArrayList<>();
842             HashMap<String, LedgerAccount> map = new HashMap<>();
843
844             String sql = "SELECT a.name, a.expanded, a.amounts_expanded";
845             sql += " from accounts a WHERE a.profile = ?";
846             sql += " ORDER BY a.name";
847
848             SQLiteDatabase db = App.getDatabase();
849             Logger.debug("async-acc", "AccountListLoader::run() connected to DB");
850             try (Cursor cursor = db.rawQuery(sql, new String[]{profileUUID})) {
851                 Logger.debug("async-acc", "AccountListLoader::run() executed query");
852                 while (cursor.moveToNext()) {
853                     if (isInterrupted())
854                         return;
855
856                     final String accName = cursor.getString(0);
857 //                    debug("accounts",
858 //                            String.format("Read account '%s' from DB [%s]", accName,
859 //                            profileUUID));
860                     String parentName = LedgerAccount.extractParentName(accName);
861                     LedgerAccount parent;
862                     if (parentName != null) {
863                         parent = map.get(parentName);
864                         if (parent == null)
865                             throw new IllegalStateException(
866                                     String.format("Can't load account '%s': parent '%s' not loaded",
867                                             accName, parentName));
868                         parent.setHasSubAccounts(true);
869                     }
870                     else
871                         parent = null;
872
873                     LedgerAccount acc = new LedgerAccount(profile, accName, parent);
874                     acc.setExpanded(cursor.getInt(1) == 1);
875                     acc.setAmountsExpanded(cursor.getInt(2) == 1);
876                     acc.setHasSubAccounts(false);
877
878                     try (Cursor c2 = db.rawQuery(
879                             "SELECT value, currency FROM account_values WHERE profile = ?" + " " +
880                             "AND account = ?", new String[]{profileUUID, accName}))
881                     {
882                         while (c2.moveToNext()) {
883                             acc.addAmount(c2.getFloat(0), c2.getString(1));
884                         }
885                     }
886
887                     list.add(acc);
888                     map.put(accName, acc);
889                 }
890                 Logger.debug("async-acc", "AccountListLoader::run() query execution done");
891             }
892
893             if (isInterrupted())
894                 return;
895
896             Logger.debug("async-acc", "AccountListLoader::run() posting new list");
897             profile.allAccounts = list;
898             profile.updateAccountsMap(list);
899             profile.updateDisplayedAccounts();
900         }
901     }
902
903     static class AccountListDisplayedFilter extends Thread {
904         private final MobileLedgerProfile profile;
905         private final List<LedgerAccount> list;
906         AccountListDisplayedFilter(MobileLedgerProfile profile, List<LedgerAccount> list) {
907             this.profile = profile;
908             this.list = list;
909         }
910         @Override
911         public void run() {
912             List<LedgerAccount> newDisplayed = new ArrayList<>();
913             Logger.debug("dFilter", "waiting for synchronized block");
914             Logger.debug("dFilter", String.format(Locale.US,
915                     "entered synchronized block (about to examine %d accounts)", list.size()));
916             for (LedgerAccount a : list) {
917                 if (isInterrupted()) {
918                     return;
919                 }
920
921                 if (a.isVisible()) {
922                     newDisplayed.add(a);
923                 }
924             }
925             if (!isInterrupted()) {
926                 profile.displayedAccounts.postValue(newDisplayed);
927             }
928             Logger.debug("dFilter", "left synchronized block");
929         }
930     }
931
932     private static class AccountListSaver extends Thread {
933         private final MobileLedgerProfile profile;
934         private final List<LedgerAccount> list;
935         private final boolean storeUiFields;
936         AccountListSaver(MobileLedgerProfile profile, List<LedgerAccount> list,
937                          boolean storeUiFields) {
938             this.list = list;
939             this.profile = profile;
940             this.storeUiFields = storeUiFields;
941         }
942         @Override
943         public void run() {
944             SQLiteDatabase db = App.getDatabase();
945             db.beginTransactionNonExclusive();
946             try {
947                 int generation = profile.getNextAccountsGeneration(db);
948                 if (isInterrupted())
949                     return;
950                 for (LedgerAccount acc : list) {
951                     profile.storeAccount(db, generation, acc, storeUiFields);
952                     if (isInterrupted())
953                         return;
954                 }
955                 profile.deleteNotPresentAccounts(db, generation);
956                 if (isInterrupted())
957                     return;
958                 profile.setLastUpdateStamp();
959                 db.setTransactionSuccessful();
960             }
961             finally {
962                 db.endTransaction();
963             }
964         }
965     }
966
967     private static class TransactionListSaver extends Thread {
968         private final MobileLedgerProfile profile;
969         private final List<LedgerTransaction> list;
970         TransactionListSaver(MobileLedgerProfile profile, List<LedgerTransaction> list) {
971             this.list = list;
972             this.profile = profile;
973         }
974         @Override
975         public void run() {
976             SQLiteDatabase db = App.getDatabase();
977             db.beginTransactionNonExclusive();
978             try {
979                 Logger.debug("db/benchmark",
980                         String.format(Locale.US, "Storing %d transactions", list.size()));
981                 int generation = profile.getNextTransactionsGeneration(db);
982                 Logger.debug("db/benchmark",
983                         String.format(Locale.US, "Got next generation of %d", generation));
984                 if (isInterrupted())
985                     return;
986                 for (LedgerTransaction tr : list) {
987                     profile.storeTransaction(db, generation, tr);
988                     if (isInterrupted())
989                         return;
990                 }
991                 Logger.debug("db/benchmark", "Done storing transactions");
992                 profile.deleteNotPresentTransactions(db, generation);
993                 if (isInterrupted())
994                     return;
995                 profile.setLastUpdateStamp();
996                 db.setTransactionSuccessful();
997             }
998             finally {
999                 db.endTransaction();
1000             }
1001         }
1002     }
1003
1004     private static class AccountAndTransactionListSaver extends Thread {
1005         private final MobileLedgerProfile profile;
1006         private final List<LedgerAccount> accounts;
1007         private final List<LedgerTransaction> transactions;
1008         private final boolean storeAccUiFields;
1009         AccountAndTransactionListSaver(MobileLedgerProfile profile, List<LedgerAccount> accounts,
1010                                        List<LedgerTransaction> transactions,
1011                                        boolean storeAccUiFields) {
1012             this.accounts = accounts;
1013             this.transactions = transactions;
1014             this.profile = profile;
1015             this.storeAccUiFields = storeAccUiFields;
1016         }
1017         @Override
1018         public void run() {
1019             SQLiteDatabase db = App.getDatabase();
1020             db.beginTransactionNonExclusive();
1021             try {
1022                 int accountsGeneration = profile.getNextAccountsGeneration(db);
1023                 if (isInterrupted())
1024                     return;
1025
1026                 int transactionsGeneration = profile.getNextTransactionsGeneration(db);
1027                 if (isInterrupted()) {
1028                     return;
1029                 }
1030
1031                 for (LedgerAccount acc : accounts) {
1032                     profile.storeAccount(db, accountsGeneration, acc, storeAccUiFields);
1033                     if (isInterrupted())
1034                         return;
1035                 }
1036
1037                 for (LedgerTransaction tr : transactions) {
1038                     profile.storeTransaction(db, transactionsGeneration, tr);
1039                     if (isInterrupted()) {
1040                         return;
1041                     }
1042                 }
1043
1044                 profile.deleteNotPresentAccounts(db, accountsGeneration);
1045                 if (isInterrupted()) {
1046                     return;
1047                 }
1048                 profile.deleteNotPresentTransactions(db, transactionsGeneration);
1049                 if (isInterrupted())
1050                     return;
1051
1052                 profile.setLastUpdateStamp();
1053
1054                 db.setTransactionSuccessful();
1055             }
1056             finally {
1057                 db.endTransaction();
1058             }
1059         }
1060     }
1061 }