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