]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
add profile setting for default currency (db part)
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / MobileLedgerProfile.java
1 /*
2  * Copyright © 2019 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.NonNull;
26 import androidx.annotation.Nullable;
27
28 import net.ktnx.mobileledger.App;
29 import net.ktnx.mobileledger.R;
30 import net.ktnx.mobileledger.async.DbOpQueue;
31 import net.ktnx.mobileledger.async.SendTransactionTask;
32 import net.ktnx.mobileledger.utils.Globals;
33 import net.ktnx.mobileledger.utils.Logger;
34 import net.ktnx.mobileledger.utils.MLDB;
35 import net.ktnx.mobileledger.utils.Misc;
36
37 import java.util.ArrayList;
38 import java.util.Date;
39 import java.util.List;
40 import java.util.Locale;
41 import java.util.UUID;
42
43 import static net.ktnx.mobileledger.utils.Logger.debug;
44
45 public final class MobileLedgerProfile {
46     private String uuid;
47     private String name;
48     private boolean permitPosting;
49     private boolean showCommodityByDefault;
50     private String defaultCommodity;
51     private String preferredAccountsFilter;
52     private String url;
53     private boolean authEnabled;
54     private String authUserName;
55     private String authPassword;
56     private int themeHue;
57     private int orderNo = -1;
58     private FutureDates futureDates = FutureDates.None;
59     private SendTransactionTask.API apiVersion = SendTransactionTask.API.auto;
60     public MobileLedgerProfile() {
61         this.uuid = String.valueOf(UUID.randomUUID());
62     }
63     public MobileLedgerProfile(String uuid) {
64         this.uuid = uuid;
65     }
66     public MobileLedgerProfile(MobileLedgerProfile origin) {
67         uuid = origin.uuid;
68         name = origin.name;
69         permitPosting = origin.permitPosting;
70         showCommodityByDefault = origin.showCommodityByDefault;
71         preferredAccountsFilter = origin.preferredAccountsFilter;
72         url = origin.url;
73         authEnabled = origin.authEnabled;
74         authUserName = origin.authUserName;
75         authPassword = origin.authPassword;
76         themeHue = origin.themeHue;
77         orderNo = origin.orderNo;
78         futureDates = origin.futureDates;
79         apiVersion = origin.apiVersion;
80         defaultCommodity = origin.defaultCommodity;
81     }
82     // loads all profiles into Data.profiles
83     // returns the profile with the given UUID
84     public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
85         MobileLedgerProfile result = null;
86         ArrayList<MobileLedgerProfile> list = new ArrayList<>();
87         SQLiteDatabase db = App.getDatabase();
88         try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
89                                          "auth_password, permit_posting, theme, order_no, " +
90                                          "preferred_accounts_filter, future_dates, api_version, " +
91                                          "show_commodity_by_default, default_commodity FROM " +
92                                          "profiles order by order_no", null))
93         {
94             while (cursor.moveToNext()) {
95                 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
96                 item.setName(cursor.getString(1));
97                 item.setUrl(cursor.getString(2));
98                 item.setAuthEnabled(cursor.getInt(3) == 1);
99                 item.setAuthUserName(cursor.getString(4));
100                 item.setAuthPassword(cursor.getString(5));
101                 item.setPostingPermitted(cursor.getInt(6) == 1);
102                 item.setThemeId(cursor.getInt(7));
103                 item.orderNo = cursor.getInt(8);
104                 item.setPreferredAccountsFilter(cursor.getString(9));
105                 item.setFutureDates(cursor.getInt(10));
106                 item.setApiVersion(cursor.getInt(11));
107                 item.setShowCommodityByDefault(cursor.getInt(12) == 1);
108                 item.setDefaultCommodity(cursor.getString(13));
109                 list.add(item);
110                 if (item.getUuid()
111                         .equals(currentProfileUUID))
112                     result = item;
113             }
114         }
115         Data.profiles.setValue(list);
116         return result;
117     }
118     public static void storeProfilesOrder() {
119         SQLiteDatabase db = App.getDatabase();
120         db.beginTransactionNonExclusive();
121         try {
122             int orderNo = 0;
123             for (MobileLedgerProfile p : Data.profiles.getValue()) {
124                 db.execSQL("update profiles set order_no=? where uuid=?",
125                         new Object[]{orderNo, p.getUuid()});
126                 p.orderNo = orderNo;
127                 orderNo++;
128             }
129             db.setTransactionSuccessful();
130         }
131         finally {
132             db.endTransaction();
133         }
134     }
135     public boolean getShowCommodityByDefault() {
136         return showCommodityByDefault;
137     }
138     public void setShowCommodityByDefault(boolean showCommodityByDefault) {
139         this.showCommodityByDefault = showCommodityByDefault;
140     }
141     public String getDefaultCommodity() {
142         return defaultCommodity;
143     }
144     public void setDefaultCommodity(String defaultCommodity) {
145         this.defaultCommodity = defaultCommodity;
146     }
147     public void setDefaultCommodity(CharSequence defaultCommodity) {
148         if (defaultCommodity == null)
149             this.defaultCommodity = null;
150         else
151             this.defaultCommodity = String.valueOf(defaultCommodity);
152     }
153     public SendTransactionTask.API getApiVersion() {
154         return apiVersion;
155     }
156     public void setApiVersion(SendTransactionTask.API apiVersion) {
157         this.apiVersion = apiVersion;
158     }
159     public void setApiVersion(int apiVersion) {
160         this.apiVersion = SendTransactionTask.API.valueOf(apiVersion);
161     }
162     public FutureDates getFutureDates() {
163         return futureDates;
164     }
165     public void setFutureDates(int anInt) {
166         futureDates = FutureDates.valueOf(anInt);
167     }
168     public void setFutureDates(FutureDates futureDates) {
169         this.futureDates = futureDates;
170     }
171     public String getPreferredAccountsFilter() {
172         return preferredAccountsFilter;
173     }
174     public void setPreferredAccountsFilter(String preferredAccountsFilter) {
175         this.preferredAccountsFilter = preferredAccountsFilter;
176     }
177     public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
178         setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
179     }
180     public boolean isPostingPermitted() {
181         return permitPosting;
182     }
183     public void setPostingPermitted(boolean permitPosting) {
184         this.permitPosting = permitPosting;
185     }
186     public String getUuid() {
187         return uuid;
188     }
189     public String getName() {
190         return name;
191     }
192     public void setName(CharSequence text) {
193         setName(String.valueOf(text));
194     }
195     public void setName(String name) {
196         this.name = name;
197     }
198     public String getUrl() {
199         return url;
200     }
201     public void setUrl(CharSequence text) {
202         setUrl(String.valueOf(text));
203     }
204     public void setUrl(String url) {
205         this.url = url;
206     }
207     public boolean isAuthEnabled() {
208         return authEnabled;
209     }
210     public void setAuthEnabled(boolean authEnabled) {
211         this.authEnabled = authEnabled;
212     }
213     public String getAuthUserName() {
214         return authUserName;
215     }
216     public void setAuthUserName(CharSequence text) {
217         setAuthUserName(String.valueOf(text));
218     }
219     public void setAuthUserName(String authUserName) {
220         this.authUserName = authUserName;
221     }
222     public String getAuthPassword() {
223         return authPassword;
224     }
225     public void setAuthPassword(CharSequence text) {
226         setAuthPassword(String.valueOf(text));
227     }
228     public void setAuthPassword(String authPassword) {
229         this.authPassword = authPassword;
230     }
231     public void storeInDB() {
232         SQLiteDatabase db = App.getDatabase();
233         db.beginTransactionNonExclusive();
234         try {
235 //            debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
236 //                                            "url=%s, permit_posting=%s, authEnabled=%s, " +
237 //                                            "themeHue=%d", uuid, name, url,
238 //                    permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeHue));
239             db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
240                        "use_authentication, auth_user, auth_password, theme, order_no, " +
241                        "preferred_accounts_filter, future_dates, api_version, " +
242                        "show_commodity_by_default, default_commodity) " +
243                        "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
244                     new Object[]{uuid, name, permitPosting, url, authEnabled,
245                                  authEnabled ? authUserName : null,
246                                  authEnabled ? authPassword : null, themeHue, orderNo,
247                                  preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt(),
248                                  showCommodityByDefault, defaultCommodity
249                     });
250             db.setTransactionSuccessful();
251         }
252         finally {
253             db.endTransaction();
254         }
255     }
256     public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
257         // replace into is a bad idea because it would reset hidden to its default value
258         // we like the default, but for new accounts only
259         db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
260                    "where profile=? and name = ?",
261                 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
262                              acc.getName()
263                 });
264         db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, hidden, " +
265                    "expanded, keep) " + "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
266                 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
267                              acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
268                 });
269 //        debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
270     }
271     public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
272         db.execSQL("replace into account_values(profile, account, " +
273                    "currency, value, keep) values(?, ?, ?, ?, 1);",
274                 new Object[]{uuid, name, Misc.emptyIsNull(currency), amount});
275     }
276     public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
277         tr.fillDataHash();
278         db.execSQL("DELETE from transactions WHERE profile=? and id=?",
279                 new Object[]{uuid, tr.getId()});
280         db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
281                 new Object[]{uuid, tr.getId()});
282
283         db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
284                    "values(?,?,?,?,?,1)",
285                 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
286                              tr.getDescription(), tr.getDataHash()
287                 });
288
289         for (LedgerTransactionAccount item : tr.getAccounts()) {
290             db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
291                        "account_name, amount, currency, comment) values(?, ?, ?, ?, ?, ?)",
292                     new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
293                                  Misc.nullIsEmpty(item.getCurrency()), item.getComment()
294                     });
295         }
296 //        debug("profile", String.format("Transaction %d stored", tr.getId()));
297     }
298     public String getOption(String name, String default_value) {
299         SQLiteDatabase db = App.getDatabase();
300         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
301                 new String[]{uuid, name}))
302         {
303             if (cursor.moveToFirst()) {
304                 String result = cursor.getString(0);
305
306                 if (result == null) {
307                     debug("profile", "returning default value for " + name);
308                     result = default_value;
309                 }
310                 else
311                     debug("profile", String.format("option %s=%s", name, result));
312
313                 return result;
314             }
315             else
316                 return default_value;
317         }
318         catch (Exception e) {
319             debug("db", "returning default value for " + name, e);
320             return default_value;
321         }
322     }
323     public long getLongOption(String name, long default_value) {
324         long longResult;
325         String result = getOption(name, "");
326         if ((result == null) || result.isEmpty()) {
327             debug("profile", String.format("Returning default value for option %s", name));
328             longResult = default_value;
329         }
330         else {
331             try {
332                 longResult = Long.parseLong(result);
333                 debug("profile", String.format("option %s=%s", name, result));
334             }
335             catch (Exception e) {
336                 debug("profile", String.format("Returning default value for option %s", name), e);
337                 longResult = default_value;
338             }
339         }
340
341         return longResult;
342     }
343     public void setOption(String name, String value) {
344         debug("profile", String.format("setting option %s=%s", name, value));
345         DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
346                 new String[]{uuid, name, value});
347     }
348     public void setLongOption(String name, long value) {
349         setOption(name, String.valueOf(value));
350     }
351     public void removeFromDB() {
352         SQLiteDatabase db = App.getDatabase();
353         debug("db", String.format("removing profile %s from DB", uuid));
354         db.beginTransactionNonExclusive();
355         try {
356             Object[] uuid_param = new Object[]{uuid};
357             db.execSQL("delete from profiles where uuid=?", uuid_param);
358             db.execSQL("delete from accounts where profile=?", uuid_param);
359             db.execSQL("delete from account_values where profile=?", uuid_param);
360             db.execSQL("delete from transactions where profile=?", uuid_param);
361             db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
362             db.execSQL("delete from options where profile=?", uuid_param);
363             db.setTransactionSuccessful();
364         }
365         finally {
366             db.endTransaction();
367         }
368     }
369     @NonNull
370     public LedgerAccount loadAccount(String name) {
371         SQLiteDatabase db = App.getDatabase();
372         return loadAccount(db, name);
373     }
374     @Nullable
375     public LedgerAccount tryLoadAccount(String acct_name) {
376         SQLiteDatabase db = App.getDatabase();
377         return tryLoadAccount(db, acct_name);
378     }
379     @NonNull
380     public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
381         LedgerAccount acc = tryLoadAccount(db, accName);
382
383         if (acc == null)
384             throw new RuntimeException("Unable to load account with name " + accName);
385
386         return acc;
387     }
388     @Nullable
389     public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
390         try (Cursor cursor = db.rawQuery(
391                 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
392                 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
393                 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
394         {
395             if (cursor.moveToFirst()) {
396                 LedgerAccount acc = new LedgerAccount(accName);
397                 acc.setHiddenByStar(cursor.getInt(0) == 1);
398                 acc.setExpanded(cursor.getInt(1) == 1);
399                 acc.setHasSubAccounts(cursor.getInt(2) == 1);
400
401                 try (Cursor c2 = db.rawQuery(
402                         "SELECT value, currency FROM account_values WHERE profile = ? " +
403                         "AND account = ?", new String[]{uuid, accName}))
404                 {
405                     while (c2.moveToNext()) {
406                         acc.addAmount(c2.getFloat(0), c2.getString(1));
407                     }
408                 }
409
410                 return acc;
411             }
412             return null;
413         }
414     }
415     public LedgerTransaction loadTransaction(int transactionId) {
416         LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
417         tr.loadData(App.getDatabase());
418
419         return tr;
420     }
421     public int getThemeHue() {
422 //        debug("profile", String.format("Profile.getThemeHue() returning %d", themeHue));
423         return this.themeHue;
424     }
425     public void setThemeHue(Object o) {
426         setThemeId(Integer.valueOf(String.valueOf(o)));
427     }
428     public void setThemeId(int themeHue) {
429 //        debug("profile", String.format("Profile.setThemeHue(%d) called", themeHue));
430         this.themeHue = themeHue;
431     }
432     public void markTransactionsAsNotPresent(SQLiteDatabase db) {
433         db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
434
435     }
436     public void markAccountsAsNotPresent(SQLiteDatabase db) {
437         db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
438         db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
439
440     }
441     public void deleteNotPresentAccounts(SQLiteDatabase db) {
442         db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
443         db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
444     }
445     public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
446         db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
447                 new Object[]{uuid, transaction.getId()
448                 });
449     }
450     public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
451                                                            LedgerTransaction transaction) {
452         db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
453                 new Object[]{uuid, transaction.getId()
454                 });
455
456     }
457     public void deleteNotPresentTransactions(SQLiteDatabase db) {
458         db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
459     }
460     public void setLastUpdateStamp() {
461         debug("db", "Updating transaction value stamp");
462         Date now = new Date();
463         setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
464         Data.lastUpdateDate.postValue(now);
465     }
466     public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
467         List<LedgerAccount> result = new ArrayList<>();
468         SQLiteDatabase db = App.getDatabase();
469         try (Cursor c = db.rawQuery(
470                 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
471                 new String[]{uuid, acc.getName()}))
472         {
473             while (c.moveToNext()) {
474                 LedgerAccount a = loadAccount(db, c.getString(0));
475                 result.add(a);
476             }
477         }
478
479         return result;
480     }
481     public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
482         List<LedgerAccount> result = new ArrayList<>();
483         ArrayList<LedgerAccount> visibleList = new ArrayList<>();
484         visibleList.add(acc);
485
486         SQLiteDatabase db = App.getDatabase();
487         try (Cursor c = db.rawQuery(
488                 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
489                 new String[]{uuid, acc.getName()}))
490         {
491             while (c.moveToNext()) {
492                 LedgerAccount a = loadAccount(db, c.getString(0));
493                 if (a.isVisible(visibleList)) {
494                     result.add(a);
495                     visibleList.add(a);
496                 }
497             }
498         }
499
500         return result;
501     }
502     public void wipeAllData() {
503         SQLiteDatabase db = App.getDatabase();
504         db.beginTransaction();
505         try {
506             String[] pUuid = new String[]{uuid};
507             db.execSQL("delete from options where profile=?", pUuid);
508             db.execSQL("delete from accounts where profile=?", pUuid);
509             db.execSQL("delete from account_values where profile=?", pUuid);
510             db.execSQL("delete from transactions where profile=?", pUuid);
511             db.execSQL("delete from transaction_accounts where profile=?", pUuid);
512             db.setTransactionSuccessful();
513             Logger.debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
514         }
515         finally {
516             db.endTransaction();
517         }
518     }
519     public List<Currency> getCurrencies() {
520         SQLiteDatabase db = App.getDatabase();
521
522         ArrayList<Currency> result = new ArrayList<>();
523
524         try (Cursor c = db.rawQuery("SELECT c.id, c.name, c.position, c.has_gap FROM currencies c",
525                 new String[]{}))
526         {
527             while (c.moveToNext()) {
528                 Currency currency = new Currency(c.getInt(0), c.getString(1),
529                         Currency.Position.valueOf(c.getInt(2)), c.getInt(3) == 1);
530                 result.add(currency);
531             }
532         }
533
534         return result;
535     }
536     Currency loadCurrencyByName(String name) {
537         SQLiteDatabase db = App.getDatabase();
538         Currency result = tryLoadCurrencyByName(db, name);
539         if (result == null)
540             throw new RuntimeException(String.format("Unable to load currency '%s'", name));
541         return result;
542     }
543     private Currency tryLoadCurrencyByName(SQLiteDatabase db, String name) {
544         try (Cursor cursor = db.rawQuery(
545                 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.name=?",
546                 new String[]{name}))
547         {
548             if (cursor.moveToFirst()) {
549                 return new Currency(cursor.getInt(0), cursor.getString(1),
550                         Currency.Position.valueOf(cursor.getInt(2)), cursor.getInt(3) == 1);
551             }
552             return null;
553         }
554     }
555     public enum FutureDates {
556         None(0), OneWeek(7), TwoWeeks(14), OneMonth(30), TwoMonths(60), ThreeMonths(90),
557         SixMonths(180), OneYear(365), All(-1);
558         private static SparseArray<FutureDates> map = new SparseArray<>();
559
560         static {
561             for (FutureDates item : FutureDates.values()) {
562                 map.put(item.value, item);
563             }
564         }
565
566         private int value;
567         FutureDates(int value) {
568             this.value = value;
569         }
570         public static FutureDates valueOf(int i) {
571             return map.get(i, None);
572         }
573         public int toInt() {
574             return this.value;
575         }
576         public String getText(Resources resources) {
577             switch (value) {
578                 case 7:
579                     return resources.getString(R.string.future_dates_7);
580                 case 14:
581                     return resources.getString(R.string.future_dates_14);
582                 case 30:
583                     return resources.getString(R.string.future_dates_30);
584                 case 60:
585                     return resources.getString(R.string.future_dates_60);
586                 case 90:
587                     return resources.getString(R.string.future_dates_90);
588                 case 180:
589                     return resources.getString(R.string.future_dates_180);
590                 case 365:
591                     return resources.getString(R.string.future_dates_365);
592                 case -1:
593                     return resources.getString(R.string.future_dates_all);
594                 default:
595                     return resources.getString(R.string.future_dates_none);
596             }
597         }
598     }
599 }