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