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