]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
migrate to surrogate IDs for all database objects
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / MobileLedgerProfile.java
1 /*
2  * Copyright © 2021 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.Context;
21 import android.content.Intent;
22 import android.content.res.Resources;
23 import android.database.Cursor;
24 import android.database.sqlite.SQLiteDatabase;
25 import android.os.Bundle;
26 import android.text.TextUtils;
27 import android.util.SparseArray;
28
29 import androidx.annotation.Nullable;
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.json.API;
35 import net.ktnx.mobileledger.ui.profiles.ProfileDetailActivity;
36 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
37 import net.ktnx.mobileledger.utils.Logger;
38 import net.ktnx.mobileledger.utils.Misc;
39 import net.ktnx.mobileledger.utils.SimpleDate;
40
41 import org.jetbrains.annotations.Contract;
42
43 import java.util.ArrayList;
44 import java.util.HashMap;
45 import java.util.List;
46 import java.util.Locale;
47 import java.util.Map;
48 import java.util.Objects;
49
50 import static net.ktnx.mobileledger.utils.Logger.debug;
51
52 public final class MobileLedgerProfile {
53     // N.B. when adding new fields, update the copy-constructor below
54     private final long id;
55     private String name;
56     private boolean permitPosting;
57     private boolean showCommentsByDefault;
58     private boolean showCommodityByDefault;
59     private String defaultCommodity;
60     private String preferredAccountsFilter;
61     private String url;
62     private boolean authEnabled;
63     private String authUserName;
64     private String authPassword;
65     private int themeHue;
66     private int orderNo = -1;
67     private API apiVersion = API.auto;
68     private FutureDates futureDates = FutureDates.None;
69     private boolean accountsLoaded;
70     private boolean transactionsLoaded;
71     private HledgerVersion detectedVersion;
72     // N.B. when adding new fields, update the copy-constructor below
73     transient private AccountAndTransactionListSaver accountAndTransactionListSaver;
74     public MobileLedgerProfile(long id) {
75         this.id = id;
76     }
77     public MobileLedgerProfile(MobileLedgerProfile origin) {
78         id = origin.id;
79         name = origin.name;
80         permitPosting = origin.permitPosting;
81         showCommentsByDefault = origin.showCommentsByDefault;
82         showCommodityByDefault = origin.showCommodityByDefault;
83         preferredAccountsFilter = origin.preferredAccountsFilter;
84         url = origin.url;
85         authEnabled = origin.authEnabled;
86         authUserName = origin.authUserName;
87         authPassword = origin.authPassword;
88         themeHue = origin.themeHue;
89         orderNo = origin.orderNo;
90         futureDates = origin.futureDates;
91         apiVersion = origin.apiVersion;
92         defaultCommodity = origin.defaultCommodity;
93         accountsLoaded = origin.accountsLoaded;
94         transactionsLoaded = origin.transactionsLoaded;
95         if (origin.detectedVersion != null)
96             detectedVersion = new HledgerVersion(origin.detectedVersion);
97     }
98     // loads all profiles into Data.profiles
99     // returns the profile with the given UUID
100     public static MobileLedgerProfile loadAllFromDB(long currentProfileId) {
101         MobileLedgerProfile result = null;
102         ArrayList<MobileLedgerProfile> list = new ArrayList<>();
103         SQLiteDatabase db = App.getDatabase();
104         try (Cursor cursor = db.rawQuery("SELECT id, name, url, use_authentication, auth_user, " +
105                                          "auth_password, permit_posting, theme, order_no, " +
106                                          "preferred_accounts_filter, future_dates, api_version, " +
107                                          "show_commodity_by_default, default_commodity, " +
108                                          "show_comments_by_default, detected_version_pre_1_19, " +
109                                          "detected_version_major, detected_version_minor FROM " +
110                                          "profiles order by order_no", null))
111         {
112             while (cursor.moveToNext()) {
113                 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getLong(0));
114                 item.setName(cursor.getString(1));
115                 item.setUrl(cursor.getString(2));
116                 item.setAuthEnabled(cursor.getInt(3) == 1);
117                 item.setAuthUserName(cursor.getString(4));
118                 item.setAuthPassword(cursor.getString(5));
119                 item.setPostingPermitted(cursor.getInt(6) == 1);
120                 item.setThemeId(cursor.getInt(7));
121                 item.orderNo = cursor.getInt(8);
122                 item.setPreferredAccountsFilter(cursor.getString(9));
123                 item.setFutureDates(cursor.getInt(10));
124                 item.setApiVersion(cursor.getInt(11));
125                 item.setShowCommodityByDefault(cursor.getInt(12) == 1);
126                 item.setDefaultCommodity(cursor.getString(13));
127                 item.setShowCommentsByDefault(cursor.getInt(14) == 1);
128                 {
129                     boolean pre_1_20 = cursor.getInt(15) == 1;
130                     int major = cursor.getInt(16);
131                     int minor = cursor.getInt(17);
132
133                     if (!pre_1_20 && major == 0 && minor == 0) {
134                         item.detectedVersion = null;
135                     }
136                     else if (pre_1_20) {
137                         item.detectedVersion = new HledgerVersion(true);
138                     }
139                     else {
140                         item.detectedVersion = new HledgerVersion(major, minor);
141                     }
142                 }
143                 list.add(item);
144                 if (item.getId() == currentProfileId)
145                     result = item;
146             }
147         }
148         Data.profiles.postValue(list);
149         return result;
150     }
151     public static void storeProfilesOrder() {
152         SQLiteDatabase db = App.getDatabase();
153         db.beginTransactionNonExclusive();
154         try {
155             int orderNo = 0;
156             for (MobileLedgerProfile p : Objects.requireNonNull(Data.profiles.getValue())) {
157                 db.execSQL("update profiles set order_no=? where uuid=?",
158                         new Object[]{orderNo, p.getId()});
159                 p.orderNo = orderNo;
160                 orderNo++;
161             }
162             db.setTransactionSuccessful();
163         }
164         finally {
165             db.endTransaction();
166         }
167     }
168     static public void startEditProfileActivity(Context context, MobileLedgerProfile profile) {
169         Intent intent = new Intent(context, ProfileDetailActivity.class);
170         Bundle args = new Bundle();
171         if (profile != null) {
172             int index = Data.getProfileIndex(profile);
173             if (index != -1)
174                 intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
175         }
176         intent.putExtras(args);
177         context.startActivity(intent, args);
178     }
179     public HledgerVersion getDetectedVersion() {
180         return detectedVersion;
181     }
182     public void setDetectedVersion(HledgerVersion detectedVersion) {
183         this.detectedVersion = detectedVersion;
184     }
185     @Contract(value = "null -> false", pure = true)
186     @Override
187     public boolean equals(@Nullable Object obj) {
188         if (obj == null)
189             return false;
190         if (obj == this)
191             return true;
192         if (obj.getClass() != this.getClass())
193             return false;
194
195         MobileLedgerProfile p = (MobileLedgerProfile) obj;
196         if (id != p.id)
197             return false;
198         if (!name.equals(p.name))
199             return false;
200         if (permitPosting != p.permitPosting)
201             return false;
202         if (showCommentsByDefault != p.showCommentsByDefault)
203             return false;
204         if (showCommodityByDefault != p.showCommodityByDefault)
205             return false;
206         if (!Objects.equals(defaultCommodity, p.defaultCommodity))
207             return false;
208         if (!Objects.equals(preferredAccountsFilter, p.preferredAccountsFilter))
209             return false;
210         if (!Objects.equals(url, p.url))
211             return false;
212         if (authEnabled != p.authEnabled)
213             return false;
214         if (!Objects.equals(authUserName, p.authUserName))
215             return false;
216         if (!Objects.equals(authPassword, p.authPassword))
217             return false;
218         if (themeHue != p.themeHue)
219             return false;
220         if (apiVersion != p.apiVersion)
221             return false;
222         if (!Objects.equals(detectedVersion, p.detectedVersion))
223             return false;
224         return futureDates == p.futureDates;
225     }
226     public boolean getShowCommentsByDefault() {
227         return showCommentsByDefault;
228     }
229     public void setShowCommentsByDefault(boolean newValue) {
230         this.showCommentsByDefault = newValue;
231     }
232     public boolean getShowCommodityByDefault() {
233         return showCommodityByDefault;
234     }
235     public void setShowCommodityByDefault(boolean showCommodityByDefault) {
236         this.showCommodityByDefault = showCommodityByDefault;
237     }
238     public String getDefaultCommodity() {
239         return defaultCommodity;
240     }
241     public void setDefaultCommodity(String defaultCommodity) {
242         this.defaultCommodity = defaultCommodity;
243     }
244     public void setDefaultCommodity(CharSequence defaultCommodity) {
245         if (defaultCommodity == null)
246             this.defaultCommodity = null;
247         else
248             this.defaultCommodity = String.valueOf(defaultCommodity);
249     }
250     public API getApiVersion() {
251         return apiVersion;
252     }
253     public void setApiVersion(API apiVersion) {
254         this.apiVersion = apiVersion;
255     }
256     public void setApiVersion(int apiVersion) {
257         this.apiVersion = API.valueOf(apiVersion);
258     }
259     public FutureDates getFutureDates() {
260         return futureDates;
261     }
262     public void setFutureDates(int anInt) {
263         futureDates = FutureDates.valueOf(anInt);
264     }
265     public void setFutureDates(FutureDates futureDates) {
266         this.futureDates = futureDates;
267     }
268     public String getPreferredAccountsFilter() {
269         return preferredAccountsFilter;
270     }
271     public void setPreferredAccountsFilter(String preferredAccountsFilter) {
272         this.preferredAccountsFilter = preferredAccountsFilter;
273     }
274     public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
275         setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
276     }
277     public boolean isPostingPermitted() {
278         return permitPosting;
279     }
280     public void setPostingPermitted(boolean permitPosting) {
281         this.permitPosting = permitPosting;
282     }
283     public long getId() {
284         return id;
285     }
286     public String getName() {
287         return name;
288     }
289     public void setName(CharSequence text) {
290         setName(String.valueOf(text));
291     }
292     public void setName(String name) {
293         this.name = name;
294     }
295     public String getUrl() {
296         return url;
297     }
298     public void setUrl(CharSequence text) {
299         setUrl(String.valueOf(text));
300     }
301     public void setUrl(String url) {
302         this.url = url;
303     }
304     public boolean isAuthEnabled() {
305         return authEnabled;
306     }
307     public void setAuthEnabled(boolean authEnabled) {
308         this.authEnabled = authEnabled;
309     }
310     public String getAuthUserName() {
311         return authUserName;
312     }
313     public void setAuthUserName(CharSequence text) {
314         setAuthUserName(String.valueOf(text));
315     }
316     public void setAuthUserName(String authUserName) {
317         this.authUserName = authUserName;
318     }
319     public String getAuthPassword() {
320         return authPassword;
321     }
322     public void setAuthPassword(CharSequence text) {
323         setAuthPassword(String.valueOf(text));
324     }
325     public void setAuthPassword(String authPassword) {
326         this.authPassword = authPassword;
327     }
328     public void storeInDB() {
329         SQLiteDatabase db = App.getDatabase();
330         db.beginTransactionNonExclusive();
331         try {
332 //            debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
333 //                                            "url=%s, permit_posting=%s, authEnabled=%s, " +
334 //                                            "themeHue=%d", uuid, name, url,
335 //                    permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeHue));
336             db.execSQL("REPLACE INTO profiles(id, name, permit_posting, url, " +
337                        "use_authentication, auth_user, auth_password, theme, order_no, " +
338                        "preferred_accounts_filter, future_dates, api_version, " +
339                        "show_commodity_by_default, default_commodity, show_comments_by_default," +
340                        "detected_version_pre_1_19, detected_version_major, " +
341                        "detected_version_minor) " +
342                        "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
343                     new Object[]{id, name, permitPosting, url, authEnabled,
344                                  authEnabled ? authUserName : null,
345                                  authEnabled ? authPassword : null, themeHue, orderNo,
346                                  preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt(),
347                                  showCommodityByDefault, defaultCommodity, showCommentsByDefault,
348                                  (detectedVersion != null) && detectedVersion.isPre_1_20_1(),
349                                  (detectedVersion == null) ? 0 : detectedVersion.getMajor(),
350                                  (detectedVersion == null) ? 0 : detectedVersion.getMinor()
351                     });
352             db.setTransactionSuccessful();
353         }
354         finally {
355             db.endTransaction();
356         }
357     }
358     public void storeAccount(SQLiteDatabase db, int generation, LedgerAccount acc,
359                              boolean storeUiFields) {
360         // replace into is a bad idea because it would reset hidden to its default value
361         // we like the default, but for new accounts only
362         String sql = "update accounts set generation = ?";
363         List<Object> params = new ArrayList<>();
364         params.add(generation);
365         if (storeUiFields) {
366             sql += ", expanded=?";
367             params.add(acc.isExpanded() ? 1 : 0);
368         }
369         sql += " where profile=? and name=?";
370         params.add(id);
371         params.add(acc.getName());
372         db.execSQL(sql, params.toArray());
373
374         db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, " +
375                    "expanded, generation) select ?,?,?,?,?,0,? where (select changes() = 0)",
376                 new Object[]{id, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
377                              acc.getLevel(), generation
378                 });
379 //        debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
380     }
381     public void storeAccountValue(SQLiteDatabase db, int generation, String name, String currency,
382                                   Float amount) {
383         if (!TextUtils.isEmpty(currency)) {
384             boolean exists;
385             try (Cursor c = db.rawQuery("select 1 from currencies where name=?",
386                     new String[]{currency}))
387             {
388                 exists = c.moveToFirst();
389             }
390             if (!exists) {
391                 db.execSQL(
392                         "insert into currencies(id, name, position, has_gap) values((select max" +
393                         "(id) from currencies)+1, ?, ?, ?)", new Object[]{currency,
394                                                                           Objects.requireNonNull(
395                                                                                   Data.currencySymbolPosition.getValue()).toString(),
396                                                                           Data.currencyGap.getValue()
397                         });
398             }
399         }
400
401         db.execSQL("replace into account_values(profile, account, " +
402                    "currency, value, generation) values(?, ?, ?, ?, ?);",
403                 new Object[]{id, name, Misc.emptyIsNull(currency), amount, generation});
404     }
405     public void storeTransaction(SQLiteDatabase db, int generation, LedgerTransaction tr) {
406         tr.fillDataHash();
407 //        Logger.debug("storeTransaction", String.format(Locale.US, "ID %d", tr.getId()));
408         SimpleDate d = tr.getDate();
409         db.execSQL("UPDATE transactions SET year=?, month=?, day=?, description=?, comment=?, " +
410                    "data_hash=?, generation=? WHERE profile=? AND id=?",
411                 new Object[]{d.year, d.month, d.day, tr.getDescription(), tr.getComment(),
412                              tr.getDataHash(), generation, id, tr.getId()
413                 });
414         db.execSQL("INSERT INTO transactions(profile, id, year, month, day, description, " +
415                    "comment, data_hash, generation) " +
416                    "select ?,?,?,?,?,?,?,?,? WHERE (select changes() = 0)",
417                 new Object[]{id, tr.getId(), tr.getDate().year, tr.getDate().month,
418                              tr.getDate().day, tr.getDescription(), tr.getComment(),
419                              tr.getDataHash(), generation
420                 });
421
422         int accountOrderNo = 1;
423         for (LedgerTransactionAccount item : tr.getAccounts()) {
424             db.execSQL("UPDATE transaction_accounts SET account_name=?, amount=?, currency=?, " +
425                        "comment=?, generation=? " +
426                        "WHERE profile=? AND transaction_id=? AND order_no=?",
427                     new Object[]{item.getAccountName(), item.getAmount(),
428                                  Misc.nullIsEmpty(item.getCurrency()), item.getComment(),
429                                  generation, id, tr.getId(), accountOrderNo
430                     });
431             db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
432                        "order_no, account_name, amount, currency, comment, generation) " +
433                        "select ?, ?, ?, ?, ?, ?, ?, ? WHERE (select changes() = 0)",
434                     new Object[]{id, tr.getId(), accountOrderNo, item.getAccountName(),
435                                  item.getAmount(), Misc.nullIsEmpty(item.getCurrency()),
436                                  item.getComment(), generation
437                     });
438
439             accountOrderNo++;
440         }
441 //        debug("profile", String.format("Transaction %d stored", tr.getId()));
442     }
443     public String getOption(String name, String default_value) {
444         SQLiteDatabase db = App.getDatabase();
445         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
446                 new String[]{String.valueOf(id), name}))
447         {
448             if (cursor.moveToFirst()) {
449                 String result = cursor.getString(0);
450
451                 if (result == null) {
452                     debug("profile", "returning default value for " + name);
453                     result = default_value;
454                 }
455                 else
456                     debug("profile", String.format("option %s=%s", name, result));
457
458                 return result;
459             }
460             else
461                 return default_value;
462         }
463         catch (Exception e) {
464             debug("db", "returning default value for " + name, e);
465             return default_value;
466         }
467     }
468     public long getLongOption(String name, long default_value) {
469         long longResult;
470         String result = getOption(name, "");
471         if ((result == null) || result.isEmpty()) {
472             debug("profile", String.format("Returning default value for option %s", name));
473             longResult = default_value;
474         }
475         else {
476             try {
477                 longResult = Long.parseLong(result);
478                 debug("profile", String.format("option %s=%s", name, result));
479             }
480             catch (Exception e) {
481                 debug("profile", String.format("Returning default value for option %s", name), e);
482                 longResult = default_value;
483             }
484         }
485
486         return longResult;
487     }
488     public void setOption(String name, String value) {
489         debug("profile", String.format("setting option %s=%s", name, value));
490         DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
491                 new String[]{String.valueOf(id), name, value});
492     }
493     public void setLongOption(String name, long value) {
494         setOption(name, String.valueOf(value));
495     }
496     public void removeFromDB() {
497         SQLiteDatabase db = App.getDatabase();
498         debug("db", String.format(Locale.ROOT, "removing profile %d from DB", id));
499         db.beginTransactionNonExclusive();
500         try {
501             Object[] id_param = new Object[]{id};
502             db.execSQL("delete from transaction_accounts where profile=?", id_param);
503             db.execSQL("delete from transactions where profile=?", id_param);
504             db.execSQL("delete from account_values where profile=?", id_param);
505             db.execSQL("delete from accounts where profile=?", id_param);
506             db.execSQL("delete from options where profile=?", id_param);
507             db.execSQL("delete from profiles where uuid=?", id_param);
508             db.setTransactionSuccessful();
509         }
510         finally {
511             db.endTransaction();
512         }
513     }
514     public LedgerTransaction loadTransaction(int transactionId) {
515         LedgerTransaction tr = new LedgerTransaction(transactionId, this.id);
516         tr.loadData(App.getDatabase());
517
518         return tr;
519     }
520     public int getThemeHue() {
521 //        debug("profile", String.format("Profile.getThemeHue() returning %d", themeHue));
522         return this.themeHue;
523     }
524     public void setThemeHue(Object o) {
525         setThemeId(Integer.parseInt(String.valueOf(o)));
526     }
527     public void setThemeId(int themeHue) {
528 //        debug("profile", String.format("Profile.setThemeHue(%d) called", themeHue));
529         this.themeHue = themeHue;
530     }
531     public int getNextTransactionsGeneration(SQLiteDatabase db) {
532         int generation = 1;
533         try (Cursor c = db.rawQuery("SELECT generation FROM transactions WHERE profile=? LIMIT 1",
534                 new String[]{String.valueOf(id)}))
535         {
536             if (c.moveToFirst()) {
537                 generation = c.getInt(0) + 1;
538             }
539         }
540         return generation;
541     }
542     private int getNextAccountsGeneration(SQLiteDatabase db) {
543         int generation = 1;
544         try (Cursor c = db.rawQuery("SELECT generation FROM accounts WHERE profile=? LIMIT 1",
545                 new String[]{String.valueOf(id)}))
546         {
547             if (c.moveToFirst()) {
548                 generation = c.getInt(0) + 1;
549             }
550         }
551         return generation;
552     }
553     private void deleteNotPresentAccounts(SQLiteDatabase db, int generation) {
554         Logger.debug("db/benchmark", "Deleting obsolete accounts");
555         db.execSQL("DELETE FROM account_values WHERE profile=? AND generation <> ?",
556                 new Object[]{id, generation});
557         db.execSQL("DELETE FROM accounts WHERE profile=? AND generation <> ?",
558                 new Object[]{id, generation});
559         Logger.debug("db/benchmark", "Done deleting obsolete accounts");
560     }
561     private void deleteNotPresentTransactions(SQLiteDatabase db, int generation) {
562         Logger.debug("db/benchmark", "Deleting obsolete transactions");
563         db.execSQL("DELETE FROM transaction_accounts WHERE profile=? AND generation <> ?",
564                 new Object[]{id, generation});
565         db.execSQL("DELETE FROM transactions WHERE profile=? AND generation <> ?",
566                 new Object[]{id, generation});
567         Logger.debug("db/benchmark", "Done deleting obsolete transactions");
568     }
569     public void wipeAllData() {
570         SQLiteDatabase db = App.getDatabase();
571         db.beginTransaction();
572         try {
573             String[] pUuid = new String[]{String.valueOf(id)};
574             db.execSQL("delete from options where profile=?", pUuid);
575             db.execSQL("delete from accounts where profile=?", pUuid);
576             db.execSQL("delete from account_values where profile=?", pUuid);
577             db.execSQL("delete from transactions where profile=?", pUuid);
578             db.execSQL("delete from transaction_accounts where profile=?", pUuid);
579             db.setTransactionSuccessful();
580             debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
581         }
582         finally {
583             db.endTransaction();
584         }
585     }
586     public List<Currency> getCurrencies() {
587         SQLiteDatabase db = App.getDatabase();
588
589         ArrayList<Currency> result = new ArrayList<>();
590
591         try (Cursor c = db.rawQuery("SELECT c.id, c.name, c.position, c.has_gap FROM currencies c",
592                 new String[]{}))
593         {
594             while (c.moveToNext()) {
595                 Currency currency = new Currency(c.getInt(0), c.getString(1),
596                         Currency.Position.valueOf(c.getString(2)), c.getInt(3) == 1);
597                 result.add(currency);
598             }
599         }
600
601         return result;
602     }
603     Currency loadCurrencyByName(String name) {
604         SQLiteDatabase db = App.getDatabase();
605         Currency result = tryLoadCurrencyByName(db, name);
606         if (result == null)
607             throw new RuntimeException(String.format("Unable to load currency '%s'", name));
608         return result;
609     }
610     private Currency tryLoadCurrencyByName(SQLiteDatabase db, String name) {
611         try (Cursor cursor = db.rawQuery(
612                 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.name=?",
613                 new String[]{name}))
614         {
615             if (cursor.moveToFirst()) {
616                 return new Currency(cursor.getInt(0), cursor.getString(1),
617                         Currency.Position.valueOf(cursor.getString(2)), cursor.getInt(3) == 1);
618             }
619             return null;
620         }
621     }
622     public void storeAccountAndTransactionListAsync(List<LedgerAccount> accounts,
623                                                     List<LedgerTransaction> transactions) {
624         if (accountAndTransactionListSaver != null)
625             accountAndTransactionListSaver.interrupt();
626
627         accountAndTransactionListSaver =
628                 new AccountAndTransactionListSaver(this, accounts, transactions);
629         accountAndTransactionListSaver.start();
630     }
631     private Currency tryLoadCurrencyById(SQLiteDatabase db, int id) {
632         try (Cursor cursor = db.rawQuery(
633                 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.id=?",
634                 new String[]{String.valueOf(id)}))
635         {
636             if (cursor.moveToFirst()) {
637                 return new Currency(cursor.getInt(0), cursor.getString(1),
638                         Currency.Position.valueOf(cursor.getString(2)), cursor.getInt(3) == 1);
639             }
640             return null;
641         }
642     }
643     public Currency loadCurrencyById(int id) {
644         SQLiteDatabase db = App.getDatabase();
645         Currency result = tryLoadCurrencyById(db, id);
646         if (result == null)
647             throw new RuntimeException(String.format("Unable to load currency with id '%d'", id));
648         return result;
649     }
650
651     public enum FutureDates {
652         None(0), OneWeek(7), TwoWeeks(14), OneMonth(30), TwoMonths(60), ThreeMonths(90),
653         SixMonths(180), OneYear(365), All(-1);
654         private static final SparseArray<FutureDates> map = new SparseArray<>();
655
656         static {
657             for (FutureDates item : FutureDates.values()) {
658                 map.put(item.value, item);
659             }
660         }
661
662         private final int value;
663         FutureDates(int value) {
664             this.value = value;
665         }
666         public static FutureDates valueOf(int i) {
667             return map.get(i, None);
668         }
669         public int toInt() {
670             return this.value;
671         }
672         public String getText(Resources resources) {
673             switch (value) {
674                 case 7:
675                     return resources.getString(R.string.future_dates_7);
676                 case 14:
677                     return resources.getString(R.string.future_dates_14);
678                 case 30:
679                     return resources.getString(R.string.future_dates_30);
680                 case 60:
681                     return resources.getString(R.string.future_dates_60);
682                 case 90:
683                     return resources.getString(R.string.future_dates_90);
684                 case 180:
685                     return resources.getString(R.string.future_dates_180);
686                 case 365:
687                     return resources.getString(R.string.future_dates_365);
688                 case -1:
689                     return resources.getString(R.string.future_dates_all);
690                 default:
691                     return resources.getString(R.string.future_dates_none);
692             }
693         }
694     }
695
696     private static class AccountAndTransactionListSaver extends Thread {
697         private final MobileLedgerProfile profile;
698         private final List<LedgerAccount> accounts;
699         private final List<LedgerTransaction> transactions;
700         AccountAndTransactionListSaver(MobileLedgerProfile profile, List<LedgerAccount> accounts,
701                                        List<LedgerTransaction> transactions) {
702             this.accounts = accounts;
703             this.transactions = transactions;
704             this.profile = profile;
705         }
706         public int getNextDescriptionsGeneration(SQLiteDatabase db) {
707             int generation = 1;
708             try (Cursor c = db.rawQuery("SELECT generation FROM description_history LIMIT 1",
709                     null))
710             {
711                 if (c.moveToFirst()) {
712                     generation = c.getInt(0) + 1;
713                 }
714             }
715             return generation;
716         }
717         void deleteNotPresentDescriptions(SQLiteDatabase db, int generation) {
718             Logger.debug("db/benchmark", "Deleting obsolete descriptions");
719             db.execSQL("DELETE FROM description_history WHERE generation <> ?",
720                     new Object[]{generation});
721             db.execSQL("DELETE FROM description_history WHERE generation <> ?",
722                     new Object[]{generation});
723             Logger.debug("db/benchmark", "Done deleting obsolete descriptions");
724         }
725         @Override
726         public void run() {
727             SQLiteDatabase db = App.getDatabase();
728             db.beginTransactionNonExclusive();
729             try {
730                 int accountsGeneration = profile.getNextAccountsGeneration(db);
731                 if (isInterrupted())
732                     return;
733
734                 int transactionsGeneration = profile.getNextTransactionsGeneration(db);
735                 if (isInterrupted())
736                     return;
737
738                 for (LedgerAccount acc : accounts) {
739                     profile.storeAccount(db, accountsGeneration, acc, false);
740                     if (isInterrupted())
741                         return;
742                     for (LedgerAmount amt : acc.getAmounts()) {
743                         profile.storeAccountValue(db, accountsGeneration, acc.getName(),
744                                 amt.getCurrency(), amt.getAmount());
745                         if (isInterrupted())
746                             return;
747                     }
748                 }
749
750                 for (LedgerTransaction tr : transactions) {
751                     profile.storeTransaction(db, transactionsGeneration, tr);
752                     if (isInterrupted())
753                         return;
754                 }
755
756                 profile.deleteNotPresentTransactions(db, transactionsGeneration);
757                 if (isInterrupted()) {
758                     return;
759                 }
760                 profile.deleteNotPresentAccounts(db, accountsGeneration);
761                 if (isInterrupted())
762                     return;
763
764                 Map<String, Boolean> unique = new HashMap<>();
765
766                 debug("descriptions", "Starting refresh");
767                 int descriptionsGeneration = getNextDescriptionsGeneration(db);
768                 try (Cursor c = db.rawQuery("SELECT distinct description from transactions",
769                         null))
770                 {
771                     while (c.moveToNext()) {
772                         String description = c.getString(0);
773                         String descriptionUpper = description.toUpperCase();
774                         if (unique.containsKey(descriptionUpper))
775                             continue;
776
777                         storeDescription(db, descriptionsGeneration, description, descriptionUpper);
778
779                         unique.put(descriptionUpper, true);
780                     }
781                 }
782                 deleteNotPresentDescriptions(db, descriptionsGeneration);
783
784                 db.setTransactionSuccessful();
785             }
786             finally {
787                 db.endTransaction();
788             }
789         }
790         private void storeDescription(SQLiteDatabase db, int generation, String description,
791                                       String descriptionUpper) {
792             db.execSQL("UPDATE description_history SET description=?, generation=? WHERE " +
793                        "description_upper=?", new Object[]{description, generation, descriptionUpper
794             });
795             db.execSQL(
796                     "INSERT INTO description_history(description, description_upper, generation) " +
797                     "select ?,?,? WHERE (select changes() = 0)",
798                     new Object[]{description, descriptionUpper, generation
799                     });
800         }
801     }
802 }