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