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