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