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.
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.
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/>.
18 package net.ktnx.mobileledger.model;
20 import android.database.Cursor;
21 import android.database.sqlite.SQLiteDatabase;
23 import net.ktnx.mobileledger.async.DbOpQueue;
24 import net.ktnx.mobileledger.utils.Globals;
25 import net.ktnx.mobileledger.utils.MLDB;
27 import java.util.ArrayList;
28 import java.util.Date;
29 import java.util.List;
30 import java.util.UUID;
32 import androidx.annotation.NonNull;
33 import androidx.annotation.Nullable;
35 import static net.ktnx.mobileledger.utils.Logger.debug;
37 public final class MobileLedgerProfile {
40 private boolean permitPosting;
41 private String preferredAccountsFilter;
43 private boolean authEnabled;
44 private String authUserName;
45 private String authPassword;
47 private int orderNo = -1;
48 public MobileLedgerProfile() {
49 this.uuid = String.valueOf(UUID.randomUUID());
51 public MobileLedgerProfile(String uuid) {
54 public MobileLedgerProfile(MobileLedgerProfile origin) {
57 permitPosting = origin.permitPosting;
58 preferredAccountsFilter = origin.preferredAccountsFilter;
60 authEnabled = origin.authEnabled;
61 authUserName = origin.authUserName;
62 authPassword = origin.authPassword;
63 themeId = origin.themeId;
64 orderNo = origin.orderNo;
66 // loads all profiles into Data.profiles
67 // returns the profile with the given UUID
68 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
69 MobileLedgerProfile result = null;
70 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
71 SQLiteDatabase db = MLDB.getDatabase();
72 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
73 "auth_password, permit_posting, theme, order_no, " +
74 "preferred_accounts_filter FROM " +
75 "profiles order by order_no", null))
77 while (cursor.moveToNext()) {
78 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
79 item.setName(cursor.getString(1));
80 item.setUrl(cursor.getString(2));
81 item.setAuthEnabled(cursor.getInt(3) == 1);
82 item.setAuthUserName(cursor.getString(4));
83 item.setAuthPassword(cursor.getString(5));
84 item.setPostingPermitted(cursor.getInt(6) == 1);
85 item.setThemeId(cursor.getInt(7));
86 item.orderNo = cursor.getInt(8);
87 item.setPreferredAccountsFilter(cursor.getString(9));
89 if (item.getUuid().equals(currentProfileUUID)) result = item;
92 Data.profiles.setValue(list);
95 public static void storeProfilesOrder() {
96 SQLiteDatabase db = MLDB.getDatabase();
97 db.beginTransaction();
100 for (MobileLedgerProfile p : Data.profiles.getValue()) {
101 db.execSQL("update profiles set order_no=? where uuid=?",
102 new Object[]{orderNo, p.getUuid()});
106 db.setTransactionSuccessful();
112 public String getPreferredAccountsFilter() {
113 return preferredAccountsFilter;
115 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
116 this.preferredAccountsFilter = preferredAccountsFilter;
118 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
119 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
121 public boolean isPostingPermitted() {
122 return permitPosting;
124 public void setPostingPermitted(boolean permitPosting) {
125 this.permitPosting = permitPosting;
127 public String getUuid() {
130 public String getName() {
133 public void setName(CharSequence text) {
134 setName(String.valueOf(text));
136 public void setName(String name) {
139 public String getUrl() {
142 public void setUrl(CharSequence text) {
143 setUrl(String.valueOf(text));
145 public void setUrl(String url) {
148 public boolean isAuthEnabled() {
151 public void setAuthEnabled(boolean authEnabled) {
152 this.authEnabled = authEnabled;
154 public String getAuthUserName() {
157 public void setAuthUserName(CharSequence text) {
158 setAuthUserName(String.valueOf(text));
160 public void setAuthUserName(String authUserName) {
161 this.authUserName = authUserName;
163 public String getAuthPassword() {
166 public void setAuthPassword(CharSequence text) {
167 setAuthPassword(String.valueOf(text));
169 public void setAuthPassword(String authPassword) {
170 this.authPassword = authPassword;
172 public void storeInDB() {
173 SQLiteDatabase db = MLDB.getDatabase();
174 db.beginTransaction();
176 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
177 // "url=%s, permit_posting=%s, authEnabled=%s, " +
178 // "themeId=%d", uuid, name, url,
179 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
180 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
181 "use_authentication, auth_user, " +
182 "auth_password, theme, order_no, preferred_accounts_filter) " +
183 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
184 new Object[]{uuid, name, permitPosting, url, authEnabled,
185 authEnabled ? authUserName : null,
186 authEnabled ? authPassword : null, themeId, orderNo,
187 preferredAccountsFilter
189 db.setTransactionSuccessful();
195 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
196 // replace into is a bad idea because it would reset hidden to its default value
197 // we like the default, but for new accounts only
198 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
199 "where profile=? and name = ?",
200 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
204 "insert into accounts(profile, name, name_upper, parent_name, level, hidden, expanded, keep) " +
205 "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
206 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
207 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
209 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
211 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
212 db.execSQL("replace into account_values(profile, account, " +
213 "currency, value, keep) values(?, ?, ?, ?, 1);",
214 new Object[]{uuid, name, currency, amount});
216 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
218 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
219 new Object[]{uuid, tr.getId()});
220 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
221 new Object[]{uuid, tr.getId()});
223 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
224 "values(?,?,?,?,?,1)",
225 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
226 tr.getDescription(), tr.getDataHash()
229 for (LedgerTransactionAccount item : tr.getAccounts()) {
230 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
231 "account_name, amount, currency) values(?, ?, ?, ?, ?)",
232 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
236 // debug("profile", String.format("Transaction %d stored", tr.getId()));
238 public String getOption(String name, String default_value) {
239 SQLiteDatabase db = MLDB.getDatabase();
240 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
241 new String[]{uuid, name}))
243 if (cursor.moveToFirst()) {
244 String result = cursor.getString(0);
246 if (result == null) {
247 debug("profile", "returning default value for " + name);
248 result = default_value;
250 else debug("profile", String.format("option %s=%s", name, result));
254 else return default_value;
256 catch (Exception e) {
257 debug("db", "returning default value for " + name, e);
258 return default_value;
261 public long getLongOption(String name, long default_value) {
263 String result = getOption(name, "");
264 if ((result == null) || result.isEmpty()) {
265 debug("profile", String.format("Returning default value for option %s", name));
266 longResult = default_value;
270 longResult = Long.parseLong(result);
271 debug("profile", String.format("option %s=%s", name, result));
273 catch (Exception e) {
274 debug("profile", String.format("Returning default value for option %s", name), e);
275 longResult = default_value;
281 public void setOption(String name, String value) {
282 debug("profile", String.format("setting option %s=%s", name, value));
283 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
284 new String[]{uuid, name, value});
286 public void setLongOption(String name, long value) {
287 setOption(name, String.valueOf(value));
289 public void removeFromDB() {
290 SQLiteDatabase db = MLDB.getDatabase();
291 debug("db", String.format("removing profile %s from DB", uuid));
292 db.beginTransaction();
294 Object[] uuid_param = new Object[]{uuid};
295 db.execSQL("delete from profiles where uuid=?", uuid_param);
296 db.execSQL("delete from accounts where profile=?", uuid_param);
297 db.execSQL("delete from account_values where profile=?", uuid_param);
298 db.execSQL("delete from transactions where profile=?", uuid_param);
299 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
300 db.setTransactionSuccessful();
307 public LedgerAccount loadAccount(String name) {
308 SQLiteDatabase db = MLDB.getDatabase();
309 return loadAccount(db, name);
312 public LedgerAccount tryLoadAccount(String acct_name) {
313 SQLiteDatabase db = MLDB.getDatabase();
314 return tryLoadAccount(db, acct_name);
317 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
318 LedgerAccount acc = tryLoadAccount(db, accName);
320 if (acc == null) throw new RuntimeException("Unable to load account with name " + accName);
325 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
326 try (Cursor cursor = db.rawQuery(
327 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
328 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
329 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
331 if (cursor.moveToFirst()) {
332 LedgerAccount acc = new LedgerAccount(accName);
333 acc.setHiddenByStar(cursor.getInt(0) == 1);
334 acc.setExpanded(cursor.getInt(1) == 1);
335 acc.setHasSubAccounts(cursor.getInt(2) == 1);
337 try (Cursor c2 = db.rawQuery(
338 "SELECT value, currency FROM account_values WHERE profile = ? " +
339 "AND account = ?", new String[]{uuid, accName}))
341 while (c2.moveToNext()) {
342 acc.addAmount(c2.getFloat(0), c2.getString(1));
351 public LedgerTransaction loadTransaction(int transactionId) {
352 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
353 tr.loadData(MLDB.getDatabase());
357 public int getThemeId() {
358 // debug("profile", String.format("Profile.getThemeId() returning %d", themeId));
361 public void setThemeId(Object o) {
362 setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
364 public void setThemeId(int themeId) {
365 // debug("profile", String.format("Profile.setThemeId(%d) called", themeId));
366 this.themeId = themeId;
368 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
369 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
372 public void markAccountsAsNotPresent(SQLiteDatabase db) {
373 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
374 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
377 public void deleteNotPresentAccounts(SQLiteDatabase db) {
378 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
379 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
381 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
382 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
383 new Object[]{uuid, transaction.getId()
386 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
387 LedgerTransaction transaction) {
388 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
389 new Object[]{uuid, transaction.getId()
393 public void deleteNotPresentTransactions(SQLiteDatabase db) {
394 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
396 public void setLastUpdateStamp() {
397 debug("db", "Updating transaction value stamp");
398 Date now = new Date();
399 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
400 Data.lastUpdateDate.postValue(now);
402 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
403 List<LedgerAccount> result = new ArrayList<>();
404 SQLiteDatabase db = MLDB.getDatabase();
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()}))
409 while (c.moveToNext()) {
410 LedgerAccount a = loadAccount(db, c.getString(0));
417 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
418 List<LedgerAccount> result = new ArrayList<>();
419 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
420 visibleList.add(acc);
422 SQLiteDatabase db = MLDB.getDatabase();
423 try (Cursor c = db.rawQuery(
424 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
425 new String[]{uuid, acc.getName()}))
427 while (c.moveToNext()) {
428 LedgerAccount a = loadAccount(db, c.getString(0));
429 if (a.isVisible(visibleList)) {
438 public void wipeAllData() {
439 SQLiteDatabase db = MLDB.getDatabase();
440 db.beginTransaction();
442 String[] pUuid = new String[]{uuid};
443 db.execSQL("delete from options where profile=?", pUuid);
444 db.execSQL("delete from accounts where profile=?", pUuid);
445 db.execSQL("delete from account_values where profile=?", pUuid);
446 db.execSQL("delete from transactions where profile=?", pUuid);
447 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
448 db.setTransactionSuccessful();