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