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