]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
add profile option for entering dates in the future
[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.setTransactionSuccessful();
318         }
319         finally {
320             db.endTransaction();
321         }
322     }
323     @NonNull
324     public LedgerAccount loadAccount(String name) {
325         SQLiteDatabase db = App.getDatabase();
326         return loadAccount(db, name);
327     }
328     @Nullable
329     public LedgerAccount tryLoadAccount(String acct_name) {
330         SQLiteDatabase db = App.getDatabase();
331         return tryLoadAccount(db, acct_name);
332     }
333     @NonNull
334     public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
335         LedgerAccount acc = tryLoadAccount(db, accName);
336
337         if (acc == null) throw new RuntimeException("Unable to load account with name " + accName);
338
339         return acc;
340     }
341     @Nullable
342     public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
343         try (Cursor cursor = db.rawQuery(
344                 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
345                 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
346                 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
347         {
348             if (cursor.moveToFirst()) {
349                 LedgerAccount acc = new LedgerAccount(accName);
350                 acc.setHiddenByStar(cursor.getInt(0) == 1);
351                 acc.setExpanded(cursor.getInt(1) == 1);
352                 acc.setHasSubAccounts(cursor.getInt(2) == 1);
353
354                 try (Cursor c2 = db.rawQuery(
355                         "SELECT value, currency FROM account_values WHERE profile = ? " +
356                         "AND account = ?", new String[]{uuid, accName}))
357                 {
358                     while (c2.moveToNext()) {
359                         acc.addAmount(c2.getFloat(0), c2.getString(1));
360                     }
361                 }
362
363                 return acc;
364             }
365             return null;
366         }
367     }
368     public LedgerTransaction loadTransaction(int transactionId) {
369         LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
370         tr.loadData(App.getDatabase());
371
372         return tr;
373     }
374     public int getThemeId() {
375 //        debug("profile", String.format("Profile.getThemeId() returning %d", themeId));
376         return this.themeId;
377     }
378     public void setThemeId(Object o) {
379         setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
380     }
381     public void setThemeId(int themeId) {
382 //        debug("profile", String.format("Profile.setThemeId(%d) called", themeId));
383         this.themeId = themeId;
384     }
385     public void markTransactionsAsNotPresent(SQLiteDatabase db) {
386         db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
387
388     }
389     public void markAccountsAsNotPresent(SQLiteDatabase db) {
390         db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
391         db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
392
393     }
394     public void deleteNotPresentAccounts(SQLiteDatabase db) {
395         db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
396         db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
397     }
398     public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
399         db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
400                 new Object[]{uuid, transaction.getId()
401                 });
402     }
403     public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
404                                                            LedgerTransaction transaction) {
405         db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
406                 new Object[]{uuid, transaction.getId()
407                 });
408
409     }
410     public void deleteNotPresentTransactions(SQLiteDatabase db) {
411         db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
412     }
413     public void setLastUpdateStamp() {
414         debug("db", "Updating transaction value stamp");
415         Date now = new Date();
416         setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
417         Data.lastUpdateDate.postValue(now);
418     }
419     public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
420         List<LedgerAccount> result = new ArrayList<>();
421         SQLiteDatabase db = App.getDatabase();
422         try (Cursor c = db.rawQuery(
423                 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
424                 new String[]{uuid, acc.getName()}))
425         {
426             while (c.moveToNext()) {
427                 LedgerAccount a = loadAccount(db, c.getString(0));
428                 result.add(a);
429             }
430         }
431
432         return result;
433     }
434     public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
435         List<LedgerAccount> result = new ArrayList<>();
436         ArrayList<LedgerAccount> visibleList = new ArrayList<>();
437         visibleList.add(acc);
438
439         SQLiteDatabase db = App.getDatabase();
440         try (Cursor c = db.rawQuery(
441                 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
442                 new String[]{uuid, acc.getName()}))
443         {
444             while (c.moveToNext()) {
445                 LedgerAccount a = loadAccount(db, c.getString(0));
446                 if (a.isVisible(visibleList)) {
447                     result.add(a);
448                     visibleList.add(a);
449                 }
450             }
451         }
452
453         return result;
454     }
455     public void wipeAllData() {
456         SQLiteDatabase db = App.getDatabase();
457         db.beginTransaction();
458         try {
459             String[] pUuid = new String[]{uuid};
460             db.execSQL("delete from options where profile=?", pUuid);
461             db.execSQL("delete from accounts where profile=?", pUuid);
462             db.execSQL("delete from account_values where profile=?", pUuid);
463             db.execSQL("delete from transactions where profile=?", pUuid);
464             db.execSQL("delete from transaction_accounts where profile=?", pUuid);
465             db.setTransactionSuccessful();
466             Logger.debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
467         }
468         finally {
469             db.endTransaction();
470         }
471     }
472     public enum FutureDates {
473         None(0), OneMonth(30), TwoMonths(60), ThreeMonths(90), SixMonths(180), OneYear(365),
474         All(-1);
475         private static SparseArray<FutureDates> map = new SparseArray<>();
476
477         static {
478             for (FutureDates item : FutureDates.values()) {
479                 map.put(item.value, item);
480             }
481         }
482
483         private int value;
484         FutureDates(int value) {
485             this.value = value;
486         }
487         public static FutureDates valueOf(int i) {
488             return map.get(i, None);
489         }
490         public int toInt() {
491             return this.value;
492         }
493         public String getText(Resources resources) {
494             switch (value) {
495                 case 30:
496                     return resources.getString(R.string.future_dates_30);
497                 case 60:
498                     return resources.getString(R.string.future_dates_60);
499                 case 90:
500                     return resources.getString(R.string.future_dates_90);
501                 case 180:
502                     return resources.getString(R.string.future_dates_180);
503                 case 365:
504                     return resources.getString(R.string.future_dates_365);
505                 case -1:
506                     return resources.getString(R.string.future_dates_all);
507                 default:
508                     return resources.getString(R.string.future_dates_none);
509             }
510         }
511     }
512 }