]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
more debug (disabled)
[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 public final class MobileLedgerProfile {
33     private String uuid;
34     private String name;
35     private boolean permitPosting;
36     private String url;
37     private boolean authEnabled;
38     private String authUserName;
39     private String authPassword;
40     private int themeId;
41     private int orderNo = -1;
42     public MobileLedgerProfile(String uuid, String name, boolean permitPosting, String url,
43                                boolean authEnabled, String authUserName, String authPassword) {
44         this(uuid, name, permitPosting, url, authEnabled, authUserName, authPassword, -1);
45
46     }
47     public MobileLedgerProfile(String uuid, String name, boolean permitPosting, String url,
48                                boolean authEnabled, String authUserName, String authPassword,
49                                int themeId) {
50         this.uuid = uuid;
51         this.name = name;
52         this.permitPosting = permitPosting;
53         this.url = url;
54         this.authEnabled = authEnabled;
55         this.authUserName = authUserName;
56         this.authPassword = authPassword;
57         this.themeId = themeId;
58         this.orderNo = -1;
59     }
60     public MobileLedgerProfile(CharSequence name, boolean permitPosting, CharSequence url,
61                                boolean authEnabled, CharSequence authUserName,
62                                CharSequence authPassword, int themeId) {
63         this.uuid = String.valueOf(UUID.randomUUID());
64         this.name = String.valueOf(name);
65         this.permitPosting = permitPosting;
66         this.url = String.valueOf(url);
67         this.authEnabled = authEnabled;
68         this.authUserName = String.valueOf(authUserName);
69         this.authPassword = String.valueOf(authPassword);
70         this.themeId = themeId;
71         this.orderNo = -1;
72     }
73     // loads all profiles into Data.profiles
74     // returns the profile with the given UUID
75     public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
76         MobileLedgerProfile result = null;
77         List<MobileLedgerProfile> list = new ArrayList<>();
78         SQLiteDatabase db = MLDB.getReadableDatabase();
79         try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
80                                          "auth_password, permit_posting, theme, order_no FROM " +
81                                          "profiles order by order_no", null))
82         {
83             while (cursor.moveToNext()) {
84                 MobileLedgerProfile item =
85                         new MobileLedgerProfile(cursor.getString(0), cursor.getString(1),
86                                 cursor.getInt(6) == 1, cursor.getString(2), cursor.getInt(3) == 1,
87                                 cursor.getString(4), cursor.getString(5), cursor.getInt(7));
88                 item.orderNo = cursor.getInt(8);
89                 list.add(item);
90                 if (item.getUuid().equals(currentProfileUUID)) result = item;
91             }
92         }
93         Data.profiles.setList(list);
94         return result;
95     }
96     public static void storeProfilesOrder() {
97         SQLiteDatabase db = MLDB.getWritableDatabase();
98         db.beginTransaction();
99         try {
100             int orderNo = 0;
101             for (MobileLedgerProfile p : Data.profiles.getList()) {
102                 db.execSQL("update profiles set order_no=? where uuid=?",
103                         new Object[]{orderNo, p.getUuid()});
104                 p.orderNo = orderNo;
105                 orderNo++;
106             }
107             db.setTransactionSuccessful();
108         }
109         finally {
110             db.endTransaction();
111         }
112     }
113     public boolean isPostingPermitted() {
114         return permitPosting;
115     }
116     public void setPostingPermitted(boolean permitPosting) {
117         this.permitPosting = permitPosting;
118     }
119     public String getUuid() {
120         return uuid;
121     }
122     public String getName() {
123         return name;
124     }
125     public void setName(String name) {
126         this.name = name;
127     }
128     public void setName(CharSequence text) {
129         setName(String.valueOf(text));
130     }
131     public String getUrl() {
132         return url;
133     }
134     public void setUrl(String url) {
135         this.url = url;
136     }
137     public void setUrl(CharSequence text) {
138         setUrl(String.valueOf(text));
139     }
140     public boolean isAuthEnabled() {
141         return authEnabled;
142     }
143     public void setAuthEnabled(boolean authEnabled) {
144         this.authEnabled = authEnabled;
145     }
146     public String getAuthUserName() {
147         return authUserName;
148     }
149     public void setAuthUserName(String authUserName) {
150         this.authUserName = authUserName;
151     }
152     public void setAuthUserName(CharSequence text) {
153         setAuthUserName(String.valueOf(text));
154     }
155     public String getAuthPassword() {
156         return authPassword;
157     }
158     public void setAuthPassword(String authPassword) {
159         this.authPassword = authPassword;
160     }
161     public void setAuthPassword(CharSequence text) {
162         setAuthPassword(String.valueOf(text));
163     }
164     public void storeInDB() {
165         SQLiteDatabase db = MLDB.getWritableDatabase();
166         db.beginTransaction();
167         try {
168 //            Log.d("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
169 //                                            "url=%s, permit_posting=%s, authEnabled=%s, " +
170 //                                            "themeId=%d", uuid, name, url,
171 //                    permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
172             db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
173                        "use_authentication, auth_user, " +
174                        "auth_password, theme, order_no) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
175                     new Object[]{uuid, name, permitPosting, url, authEnabled,
176                                  authEnabled ? authUserName : null,
177                                  authEnabled ? authPassword : null, themeId, orderNo
178                     });
179             db.setTransactionSuccessful();
180         }
181         finally {
182             db.endTransaction();
183         }
184     }
185     public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
186         // replace into is a bad idea because it would reset hidden to its default value
187         // we like the default, but for new accounts only
188         db.execSQL("update accounts set level = ?, keep = 1 where profile=? and name = ?",
189                 new Object[]{acc.getLevel(), uuid, acc.getName()});
190         db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, keep) " +
191                    "select ?,?,?,?,?,1 where (select changes() = 0)",
192                 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
193                              acc.getLevel()
194                 });
195 //        Log.d("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
196     }
197     public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
198         db.execSQL("replace into account_values(profile, account, " +
199                    "currency, value, keep) values(?, ?, ?, ?, 1);",
200                 new Object[]{uuid, name, currency, amount});
201     }
202     public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
203         tr.fillDataHash();
204         db.execSQL("DELETE from transactions WHERE profile=? and id=?",
205                 new Object[]{uuid, tr.getId()});
206         db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
207                 new Object[]{uuid, tr.getId()});
208
209         db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
210                    "values(?,?,?,?,?,1)",
211                 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
212                              tr.getDescription(), tr.getDataHash()
213                 });
214
215         for (LedgerTransactionAccount item : tr.getAccounts()) {
216             db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
217                        "account_name, amount, currency) values(?, ?, ?, ?, ?)",
218                     new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
219                                  item.getCurrency()
220                     });
221         }
222         Log.d("profile", String.format("Transaction %d stored", tr.getId()));
223     }
224     public String getOption(String name, String default_value) {
225         SQLiteDatabase db = MLDB.getReadableDatabase();
226         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
227                 new String[]{uuid, name}))
228         {
229             if (cursor.moveToFirst()) {
230                 String result = cursor.getString(0);
231
232                 if (result == null) {
233                     Log.d("profile", "returning default value for " + name);
234                     result = default_value;
235                 }
236                 else Log.d("profile", String.format("option %s=%s", name, result));
237
238                 return result;
239             }
240             else return default_value;
241         }
242         catch (Exception e) {
243             Log.d("db", "returning default value for " + name, e);
244             return default_value;
245         }
246     }
247     public long getLongOption(String name, long default_value) {
248         long longResult;
249         String result = getOption(name, "");
250         if ((result == null) || result.isEmpty()) {
251             Log.d("profile", String.format("Returning default value for option %s", name));
252             longResult = default_value;
253         }
254         else {
255             try {
256                 longResult = Long.parseLong(result);
257                 Log.d("profile", String.format("option %s=%s", name, result));
258             }
259             catch (Exception e) {
260                 Log.d("profile", String.format("Returning default value for option %s", name), e);
261                 longResult = default_value;
262             }
263         }
264
265         return longResult;
266     }
267     public void setOption(String name, String value) {
268         Log.d("profile", String.format("setting option %s=%s", name, value));
269         SQLiteDatabase db = MLDB.getWritableDatabase();
270         db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
271                 new String[]{uuid, name, value});
272     }
273     public void setLongOption(String name, long value) {
274         setOption(name, String.valueOf(value));
275     }
276     public void removeFromDB() {
277         SQLiteDatabase db = MLDB.getWritableDatabase();
278         Log.d("db", String.format("removing progile %s from DB", uuid));
279         db.execSQL("delete from profiles where uuid=?", new Object[]{uuid});
280     }
281     public LedgerAccount loadAccount(String name) {
282         SQLiteDatabase db = MLDB.getReadableDatabase();
283         try (Cursor cursor = db.rawQuery("SELECT hidden from accounts where profile=? and name=?",
284                 new String[]{uuid, name}))
285         {
286             if (cursor.moveToFirst()) {
287                 LedgerAccount acc = new LedgerAccount(name);
288                 acc.setHidden(cursor.getInt(0) == 1);
289
290                 return acc;
291             }
292         }
293
294         return null;
295     }
296     public LedgerTransaction loadTransaction(int transactionId) {
297         LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
298         tr.loadData(MLDB.getReadableDatabase());
299
300         return tr;
301     }
302     public int getThemeId() {
303 //        Log.d("profile", String.format("Profile.getThemeId() returning %d", themeId));
304         return this.themeId;
305     }
306     public void setThemeId(int themeId) {
307 //        Log.d("profile", String.format("Profile.setThemeId(%d) called", themeId));
308         this.themeId = themeId;
309     }
310     public void setThemeId(Object o) {
311         setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
312     }
313     public void markTransactionsAsNotPresent(SQLiteDatabase db) {
314         db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
315
316     }
317     public void markAccountsAsNotPresent(SQLiteDatabase db) {
318         db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
319         db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
320
321     }
322     public void deleteNotPresentAccounts(SQLiteDatabase db) {
323         db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
324         db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
325     }
326     public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
327         db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
328                 new Object[]{uuid, transaction.getId()
329                 });
330     }
331     public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
332                                                            LedgerTransaction transaction) {
333         db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
334                 new Object[]{uuid, transaction.getId()
335                 });
336
337     }
338     public void deleteNotPresentTransactions(SQLiteDatabase db) {
339         db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
340     }
341     public void setLastUpdateStamp() {
342         Log.d("db", "Updating transaction value stamp");
343         Date now = new Date();
344         setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
345         Data.lastUpdateDate.set(now);
346     }
347 }