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