]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
no direct interface to ObservableList's value
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / MobileLedgerProfile.java
1 /*
2  * Copyright © 2019 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * MoLe is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.model;
19
20 import android.database.Cursor;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.util.Log;
23
24 import net.ktnx.mobileledger.utils.Globals;
25 import net.ktnx.mobileledger.utils.MLDB;
26
27 import java.util.ArrayList;
28 import java.util.Date;
29 import java.util.List;
30 import java.util.UUID;
31
32 import androidx.annotation.NonNull;
33 import androidx.annotation.Nullable;
34
35 public final class MobileLedgerProfile {
36     private String uuid;
37     private String name;
38     private boolean permitPosting;
39     private String url;
40     private boolean authEnabled;
41     private String authUserName;
42     private String authPassword;
43     private int themeId;
44     private int orderNo = -1;
45     public MobileLedgerProfile(String uuid, String name, boolean permitPosting, String url,
46                                boolean authEnabled, String authUserName, String authPassword) {
47         this(uuid, name, permitPosting, url, authEnabled, authUserName, authPassword, -1);
48
49     }
50     public MobileLedgerProfile(String uuid, String name, boolean permitPosting, String url,
51                                boolean authEnabled, String authUserName, String authPassword,
52                                int themeId) {
53         this.uuid = uuid;
54         this.name = name;
55         this.permitPosting = permitPosting;
56         this.url = url;
57         this.authEnabled = authEnabled;
58         this.authUserName = authUserName;
59         this.authPassword = authPassword;
60         this.themeId = themeId;
61         this.orderNo = -1;
62     }
63     public MobileLedgerProfile(CharSequence name, boolean permitPosting, CharSequence url,
64                                boolean authEnabled, CharSequence authUserName,
65                                CharSequence authPassword, int themeId) {
66         this.uuid = String.valueOf(UUID.randomUUID());
67         this.name = String.valueOf(name);
68         this.permitPosting = permitPosting;
69         this.url = String.valueOf(url);
70         this.authEnabled = authEnabled;
71         this.authUserName = String.valueOf(authUserName);
72         this.authPassword = String.valueOf(authPassword);
73         this.themeId = themeId;
74         this.orderNo = -1;
75     }
76     // loads all profiles into Data.profiles
77     // returns the profile with the given UUID
78     public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
79         MobileLedgerProfile result = null;
80         List<MobileLedgerProfile> list = new ArrayList<>();
81         SQLiteDatabase db = MLDB.getDatabase();
82         try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
83                                          "auth_password, permit_posting, theme, order_no FROM " +
84                                          "profiles order by order_no", null))
85         {
86             while (cursor.moveToNext()) {
87                 MobileLedgerProfile item =
88                         new MobileLedgerProfile(cursor.getString(0), cursor.getString(1),
89                                 cursor.getInt(6) == 1, cursor.getString(2), cursor.getInt(3) == 1,
90                                 cursor.getString(4), cursor.getString(5), cursor.getInt(7));
91                 item.orderNo = cursor.getInt(8);
92                 list.add(item);
93                 if (item.getUuid().equals(currentProfileUUID)) result = item;
94             }
95         }
96         Data.profiles.setList(list);
97         return result;
98     }
99     public static void storeProfilesOrder() {
100         SQLiteDatabase db = MLDB.getDatabase();
101         db.beginTransaction();
102         try {
103             int orderNo = 0;
104                 for (int i = 0; i < Data.profiles.size(); i++) {
105                     MobileLedgerProfile p = Data.profiles.get(i);
106                     db.execSQL("update profiles set order_no=? where uuid=?",
107                             new Object[]{orderNo, p.getUuid()});
108                     p.orderNo = orderNo;
109                     orderNo++;
110             }
111             db.setTransactionSuccessful();
112         }
113         finally {
114             db.endTransaction();
115         }
116     }
117     public boolean isPostingPermitted() {
118         return permitPosting;
119     }
120     public void setPostingPermitted(boolean permitPosting) {
121         this.permitPosting = permitPosting;
122     }
123     public String getUuid() {
124         return uuid;
125     }
126     public String getName() {
127         return name;
128     }
129     public void setName(String name) {
130         this.name = name;
131     }
132     public void setName(CharSequence text) {
133         setName(String.valueOf(text));
134     }
135     public String getUrl() {
136         return url;
137     }
138     public void setUrl(String url) {
139         this.url = url;
140     }
141     public void setUrl(CharSequence text) {
142         setUrl(String.valueOf(text));
143     }
144     public boolean isAuthEnabled() {
145         return authEnabled;
146     }
147     public void setAuthEnabled(boolean authEnabled) {
148         this.authEnabled = authEnabled;
149     }
150     public String getAuthUserName() {
151         return authUserName;
152     }
153     public void setAuthUserName(String authUserName) {
154         this.authUserName = authUserName;
155     }
156     public void setAuthUserName(CharSequence text) {
157         setAuthUserName(String.valueOf(text));
158     }
159     public String getAuthPassword() {
160         return authPassword;
161     }
162     public void setAuthPassword(String authPassword) {
163         this.authPassword = authPassword;
164     }
165     public void setAuthPassword(CharSequence text) {
166         setAuthPassword(String.valueOf(text));
167     }
168     public void storeInDB() {
169         SQLiteDatabase db = MLDB.getDatabase();
170         db.beginTransaction();
171         try {
172 //            Log.d("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
173 //                                            "url=%s, permit_posting=%s, authEnabled=%s, " +
174 //                                            "themeId=%d", uuid, name, url,
175 //                    permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
176             db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
177                        "use_authentication, auth_user, " +
178                        "auth_password, theme, order_no) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
179                     new Object[]{uuid, name, permitPosting, url, authEnabled,
180                                  authEnabled ? authUserName : null,
181                                  authEnabled ? authPassword : null, themeId, orderNo
182                     });
183             db.setTransactionSuccessful();
184         }
185         finally {
186             db.endTransaction();
187         }
188     }
189     public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
190         // replace into is a bad idea because it would reset hidden to its default value
191         // we like the default, but for new accounts only
192         db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
193                    "where profile=? and name = ?",
194                 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
195                              acc.getName()
196                 });
197         db.execSQL(
198                 "insert into accounts(profile, name, name_upper, parent_name, level, hidden, expanded, keep) " +
199                 "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
200                 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
201                              acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
202                 });
203 //        Log.d("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
204     }
205     public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
206         db.execSQL("replace into account_values(profile, account, " +
207                    "currency, value, keep) values(?, ?, ?, ?, 1);",
208                 new Object[]{uuid, name, currency, amount});
209     }
210     public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
211         tr.fillDataHash();
212         db.execSQL("DELETE from transactions WHERE profile=? and id=?",
213                 new Object[]{uuid, tr.getId()});
214         db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
215                 new Object[]{uuid, tr.getId()});
216
217         db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
218                    "values(?,?,?,?,?,1)",
219                 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
220                              tr.getDescription(), tr.getDataHash()
221                 });
222
223         for (LedgerTransactionAccount item : tr.getAccounts()) {
224             db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
225                        "account_name, amount, currency) values(?, ?, ?, ?, ?)",
226                     new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
227                                  item.getCurrency()
228                     });
229         }
230         Log.d("profile", String.format("Transaction %d stored", tr.getId()));
231     }
232     public String getOption(String name, String default_value) {
233         SQLiteDatabase db = MLDB.getDatabase();
234         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
235                 new String[]{uuid, name}))
236         {
237             if (cursor.moveToFirst()) {
238                 String result = cursor.getString(0);
239
240                 if (result == null) {
241                     Log.d("profile", "returning default value for " + name);
242                     result = default_value;
243                 }
244                 else Log.d("profile", String.format("option %s=%s", name, result));
245
246                 return result;
247             }
248             else return default_value;
249         }
250         catch (Exception e) {
251             Log.d("db", "returning default value for " + name, e);
252             return default_value;
253         }
254     }
255     public long getLongOption(String name, long default_value) {
256         long longResult;
257         String result = getOption(name, "");
258         if ((result == null) || result.isEmpty()) {
259             Log.d("profile", String.format("Returning default value for option %s", name));
260             longResult = default_value;
261         }
262         else {
263             try {
264                 longResult = Long.parseLong(result);
265                 Log.d("profile", String.format("option %s=%s", name, result));
266             }
267             catch (Exception e) {
268                 Log.d("profile", String.format("Returning default value for option %s", name), e);
269                 longResult = default_value;
270             }
271         }
272
273         return longResult;
274     }
275     public void setOption(String name, String value) {
276         Log.d("profile", String.format("setting option %s=%s", name, value));
277         SQLiteDatabase db = MLDB.getDatabase();
278         db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
279                 new String[]{uuid, name, value});
280     }
281     public void setLongOption(String name, long value) {
282         setOption(name, String.valueOf(value));
283     }
284     public void removeFromDB() {
285         SQLiteDatabase db = MLDB.getDatabase();
286         Log.d("db", String.format("removing profile %s from DB", uuid));
287         db.beginTransaction();
288         try {
289             db.execSQL("delete from profiles where uuid=?", new Object[]{uuid});
290             db.execSQL("delete from accounts where profile=?", new Object[]{uuid});
291             db.execSQL("delete from account_values where profile=?", new Object[]{uuid});
292             db.execSQL("delete from transactions where profile=?", new Object[]{uuid});
293             db.execSQL("delete from transaction_accounts where profile=?", new Object[]{uuid});
294             db.setTransactionSuccessful();
295         }
296         finally {
297             db.endTransaction();
298         }
299     }
300     @NonNull
301     public LedgerAccount loadAccount(String name) {
302         SQLiteDatabase db = MLDB.getDatabase();
303         return loadAccount(db, name);
304     }
305     @Nullable
306     public LedgerAccount tryLoadAccount(String acct_name) {
307         SQLiteDatabase db = MLDB.getDatabase();
308         return tryLoadAccount(db, acct_name);
309     }
310     @NonNull
311     public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
312         LedgerAccount acc = tryLoadAccount(db, accName);
313
314         if (acc == null) throw new RuntimeException("Unable to load account with name " + accName);
315
316         return acc;
317     }
318     @Nullable
319     public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
320         try (Cursor cursor = db.rawQuery(
321                 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
322                 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
323                 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
324         {
325             if (cursor.moveToFirst()) {
326                 LedgerAccount acc = new LedgerAccount(accName);
327                 acc.setHiddenByStar(cursor.getInt(0) == 1);
328                 acc.setExpanded(cursor.getInt(1) == 1);
329                 acc.setHasSubAccounts(cursor.getInt(2) == 1);
330
331                 try (Cursor c2 = db.rawQuery(
332                         "SELECT value, currency FROM account_values WHERE profile = ? " +
333                         "AND account = ?", new String[]{uuid, accName}))
334                 {
335                     while (c2.moveToNext()) {
336                         acc.addAmount(c2.getFloat(0), c2.getString(1));
337                     }
338                 }
339
340                 return acc;
341             }
342             return null;
343         }
344     }
345     public LedgerTransaction loadTransaction(int transactionId) {
346         LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
347         tr.loadData(MLDB.getDatabase());
348
349         return tr;
350     }
351     public int getThemeId() {
352 //        Log.d("profile", String.format("Profile.getThemeId() returning %d", themeId));
353         return this.themeId;
354     }
355     public void setThemeId(int themeId) {
356 //        Log.d("profile", String.format("Profile.setThemeId(%d) called", themeId));
357         this.themeId = themeId;
358     }
359     public void setThemeId(Object o) {
360         setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
361     }
362     public void markTransactionsAsNotPresent(SQLiteDatabase db) {
363         db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
364
365     }
366     public void markAccountsAsNotPresent(SQLiteDatabase db) {
367         db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
368         db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
369
370     }
371     public void deleteNotPresentAccounts(SQLiteDatabase db) {
372         db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
373         db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
374     }
375     public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
376         db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
377                 new Object[]{uuid, transaction.getId()
378                 });
379     }
380     public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
381                                                            LedgerTransaction transaction) {
382         db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
383                 new Object[]{uuid, transaction.getId()
384                 });
385
386     }
387     public void deleteNotPresentTransactions(SQLiteDatabase db) {
388         db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
389     }
390     public void setLastUpdateStamp() {
391         Log.d("db", "Updating transaction value stamp");
392         Date now = new Date();
393         setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
394         Data.lastUpdateDate.set(now);
395     }
396     public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
397         List<LedgerAccount> result = new ArrayList<>();
398         SQLiteDatabase db = MLDB.getDatabase();
399         try (Cursor c = db.rawQuery(
400                 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
401                 new String[]{uuid, acc.getName()}))
402         {
403             while (c.moveToNext()) {
404                 LedgerAccount a = loadAccount(db, c.getString(0));
405                 result.add(a);
406             }
407         }
408
409         return result;
410     }
411     public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
412         List<LedgerAccount> result = new ArrayList<>();
413         ArrayList<LedgerAccount> visibleList = new ArrayList<>();
414         visibleList.add(acc);
415
416         SQLiteDatabase db = MLDB.getDatabase();
417         try (Cursor c = db.rawQuery(
418                 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
419                 new String[]{uuid, acc.getName()}))
420         {
421             while (c.moveToNext()) {
422                 LedgerAccount a = loadAccount(db, c.getString(0));
423                 if (a.isVisible(visibleList)) {
424                     result.add(a);
425                     visibleList.add(a);
426                 }
427             }
428         }
429
430         return result;
431     }
432 }