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