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