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