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