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