]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
put account expansion bracket after the name, fix rotation animation
[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.getReadableDatabase();
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.getWritableDatabase();
101         db.beginTransaction();
102         try {
103             int orderNo = 0;
104             for (MobileLedgerProfile p : Data.profiles.getList()) {
105                 db.execSQL("update profiles set order_no=? where uuid=?",
106                         new Object[]{orderNo, p.getUuid()});
107                 p.orderNo = orderNo;
108                 orderNo++;
109             }
110             db.setTransactionSuccessful();
111         }
112         finally {
113             db.endTransaction();
114         }
115     }
116     public boolean isPostingPermitted() {
117         return permitPosting;
118     }
119     public void setPostingPermitted(boolean permitPosting) {
120         this.permitPosting = permitPosting;
121     }
122     public String getUuid() {
123         return uuid;
124     }
125     public String getName() {
126         return name;
127     }
128     public void setName(String name) {
129         this.name = name;
130     }
131     public void setName(CharSequence text) {
132         setName(String.valueOf(text));
133     }
134     public String getUrl() {
135         return url;
136     }
137     public void setUrl(String url) {
138         this.url = url;
139     }
140     public void setUrl(CharSequence text) {
141         setUrl(String.valueOf(text));
142     }
143     public boolean isAuthEnabled() {
144         return authEnabled;
145     }
146     public void setAuthEnabled(boolean authEnabled) {
147         this.authEnabled = authEnabled;
148     }
149     public String getAuthUserName() {
150         return authUserName;
151     }
152     public void setAuthUserName(String authUserName) {
153         this.authUserName = authUserName;
154     }
155     public void setAuthUserName(CharSequence text) {
156         setAuthUserName(String.valueOf(text));
157     }
158     public String getAuthPassword() {
159         return authPassword;
160     }
161     public void setAuthPassword(String authPassword) {
162         this.authPassword = authPassword;
163     }
164     public void setAuthPassword(CharSequence text) {
165         setAuthPassword(String.valueOf(text));
166     }
167     public void storeInDB() {
168         SQLiteDatabase db = MLDB.getWritableDatabase();
169         db.beginTransaction();
170         try {
171 //            Log.d("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
172 //                                            "url=%s, permit_posting=%s, authEnabled=%s, " +
173 //                                            "themeId=%d", uuid, name, url,
174 //                    permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
175             db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
176                        "use_authentication, auth_user, " +
177                        "auth_password, theme, order_no) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
178                     new Object[]{uuid, name, permitPosting, url, authEnabled,
179                                  authEnabled ? authUserName : null,
180                                  authEnabled ? authPassword : null, themeId, orderNo
181                     });
182             db.setTransactionSuccessful();
183         }
184         finally {
185             db.endTransaction();
186         }
187     }
188     public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
189         // replace into is a bad idea because it would reset hidden to its default value
190         // we like the default, but for new accounts only
191         db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
192                    "where profile=? and name = ?",
193                 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
194                              acc.getName()
195                 });
196         db.execSQL(
197                 "insert into accounts(profile, name, name_upper, parent_name, level, hidden, expanded, keep) " +
198                 "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
199                 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
200                              acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
201                 });
202 //        Log.d("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
203     }
204     public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
205         db.execSQL("replace into account_values(profile, account, " +
206                    "currency, value, keep) values(?, ?, ?, ?, 1);",
207                 new Object[]{uuid, name, currency, amount});
208     }
209     public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
210         tr.fillDataHash();
211         db.execSQL("DELETE from transactions WHERE profile=? and id=?",
212                 new Object[]{uuid, tr.getId()});
213         db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
214                 new Object[]{uuid, tr.getId()});
215
216         db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
217                    "values(?,?,?,?,?,1)",
218                 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
219                              tr.getDescription(), tr.getDataHash()
220                 });
221
222         for (LedgerTransactionAccount item : tr.getAccounts()) {
223             db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
224                        "account_name, amount, currency) values(?, ?, ?, ?, ?)",
225                     new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
226                                  item.getCurrency()
227                     });
228         }
229         Log.d("profile", String.format("Transaction %d stored", tr.getId()));
230     }
231     public String getOption(String name, String default_value) {
232         SQLiteDatabase db = MLDB.getReadableDatabase();
233         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
234                 new String[]{uuid, name}))
235         {
236             if (cursor.moveToFirst()) {
237                 String result = cursor.getString(0);
238
239                 if (result == null) {
240                     Log.d("profile", "returning default value for " + name);
241                     result = default_value;
242                 }
243                 else Log.d("profile", String.format("option %s=%s", name, result));
244
245                 return result;
246             }
247             else return default_value;
248         }
249         catch (Exception e) {
250             Log.d("db", "returning default value for " + name, e);
251             return default_value;
252         }
253     }
254     public long getLongOption(String name, long default_value) {
255         long longResult;
256         String result = getOption(name, "");
257         if ((result == null) || result.isEmpty()) {
258             Log.d("profile", String.format("Returning default value for option %s", name));
259             longResult = default_value;
260         }
261         else {
262             try {
263                 longResult = Long.parseLong(result);
264                 Log.d("profile", String.format("option %s=%s", name, result));
265             }
266             catch (Exception e) {
267                 Log.d("profile", String.format("Returning default value for option %s", name), e);
268                 longResult = default_value;
269             }
270         }
271
272         return longResult;
273     }
274     public void setOption(String name, String value) {
275         Log.d("profile", String.format("setting option %s=%s", name, value));
276         SQLiteDatabase db = MLDB.getWritableDatabase();
277         db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
278                 new String[]{uuid, name, value});
279     }
280     public void setLongOption(String name, long value) {
281         setOption(name, String.valueOf(value));
282     }
283     public void removeFromDB() {
284         SQLiteDatabase db = MLDB.getWritableDatabase();
285         Log.d("db", String.format("removing progile %s from DB", uuid));
286         db.execSQL("delete from profiles where uuid=?", new Object[]{uuid});
287     }
288     @NonNull
289     public LedgerAccount loadAccount(String name) {
290         SQLiteDatabase db = MLDB.getReadableDatabase();
291         return loadAccount(db, name);
292     }
293     @Nullable
294     public LedgerAccount tryLoadAccount(String acct_name) {
295         SQLiteDatabase db = MLDB.getReadableDatabase();
296         return loadAccount(acct_name);
297     }
298     @NonNull
299     public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
300         LedgerAccount acc = tryLoadAccount(db, accName);
301
302         if (acc == null) throw new RuntimeException("Unable to load account with name "+accName);
303
304         return acc;
305     }
306     @Nullable
307     public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
308         try (Cursor cursor = db.rawQuery(
309                 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
310                 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
311                 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
312         {
313             if (cursor.moveToFirst()) {
314                 LedgerAccount acc = new LedgerAccount(accName);
315                 acc.setHiddenByStar(cursor.getInt(0) == 1);
316                 acc.setExpanded(cursor.getInt(1) == 1);
317                 acc.setHasSubAccounts(cursor.getInt(2) == 1);
318
319                 try (Cursor c2 = db.rawQuery(
320                         "SELECT value, currency FROM account_values WHERE profile = ? " +
321                         "AND account = ?", new String[]{uuid, accName}))
322                 {
323                     while (c2.moveToNext()) {
324                         acc.addAmount(c2.getFloat(0), c2.getString(1));
325                     }
326                 }
327
328                 return acc;
329             }
330             return null;
331         }
332     }
333     public LedgerTransaction loadTransaction(int transactionId) {
334         LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
335         tr.loadData(MLDB.getReadableDatabase());
336
337         return tr;
338     }
339     public int getThemeId() {
340 //        Log.d("profile", String.format("Profile.getThemeId() returning %d", themeId));
341         return this.themeId;
342     }
343     public void setThemeId(int themeId) {
344 //        Log.d("profile", String.format("Profile.setThemeId(%d) called", themeId));
345         this.themeId = themeId;
346     }
347     public void setThemeId(Object o) {
348         setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
349     }
350     public void markTransactionsAsNotPresent(SQLiteDatabase db) {
351         db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
352
353     }
354     public void markAccountsAsNotPresent(SQLiteDatabase db) {
355         db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
356         db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
357
358     }
359     public void deleteNotPresentAccounts(SQLiteDatabase db) {
360         db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
361         db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
362     }
363     public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
364         db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
365                 new Object[]{uuid, transaction.getId()
366                 });
367     }
368     public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
369                                                            LedgerTransaction transaction) {
370         db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
371                 new Object[]{uuid, transaction.getId()
372                 });
373
374     }
375     public void deleteNotPresentTransactions(SQLiteDatabase db) {
376         db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
377     }
378     public void setLastUpdateStamp() {
379         Log.d("db", "Updating transaction value stamp");
380         Date now = new Date();
381         setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
382         Data.lastUpdateDate.set(now);
383     }
384     public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
385         List<LedgerAccount> result = new ArrayList<>();
386         SQLiteDatabase db = MLDB.getReadableDatabase();
387         try (Cursor c = db.rawQuery(
388                 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
389                 new String[]{uuid, acc.getName()}))
390         {
391             while (c.moveToNext()) {
392                 LedgerAccount a = loadAccount(db, c.getString(0));
393                 result.add(a);
394             }
395         }
396
397         return result;
398     }
399     public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
400         List<LedgerAccount> result = new ArrayList<>();
401         ArrayList<LedgerAccount> visibleList = new ArrayList<>();
402         visibleList.add(acc);
403
404         SQLiteDatabase db = MLDB.getReadableDatabase();
405         try (Cursor c = db.rawQuery(
406                 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
407                 new String[]{uuid, acc.getName()}))
408         {
409             while (c.moveToNext()) {
410                 LedgerAccount a = loadAccount(db, c.getString(0));
411                 if (a.isVisible(visibleList)) {
412                     result.add(a);
413                     visibleList.add(a);
414                 }
415             }
416         }
417
418         return result;
419     }
420 }