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