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