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