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