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