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.LockHolder;
26 import net.ktnx.mobileledger.utils.MLDB;
28 import java.util.ArrayList;
29 import java.util.Date;
30 import java.util.List;
31 import java.util.UUID;
33 import androidx.annotation.NonNull;
34 import androidx.annotation.Nullable;
36 import static net.ktnx.mobileledger.utils.Logger.debug;
38 public final class MobileLedgerProfile {
41 private boolean permitPosting;
42 private String preferredAccountsFilter;
44 private boolean authEnabled;
45 private String authUserName;
46 private String authPassword;
48 private int orderNo = -1;
49 public MobileLedgerProfile() {
50 this.uuid = String.valueOf(UUID.randomUUID());
52 public MobileLedgerProfile(String uuid) {
55 public MobileLedgerProfile(MobileLedgerProfile origin) {
58 permitPosting = origin.permitPosting;
59 preferredAccountsFilter = origin.preferredAccountsFilter;
61 authEnabled = origin.authEnabled;
62 authUserName = origin.authUserName;
63 authPassword = origin.authPassword;
64 themeId = origin.themeId;
65 orderNo = origin.orderNo;
67 // loads all profiles into Data.profiles
68 // returns the profile with the given UUID
69 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
70 MobileLedgerProfile result = null;
71 List<MobileLedgerProfile> list = new ArrayList<>();
72 SQLiteDatabase db = MLDB.getDatabase();
73 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
74 "auth_password, permit_posting, theme, order_no, " +
75 "preferred_accounts_filter FROM " +
76 "profiles order by order_no", null))
78 while (cursor.moveToNext()) {
79 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
80 item.setName(cursor.getString(1));
81 item.setUrl(cursor.getString(2));
82 item.setAuthEnabled(cursor.getInt(3) == 1);
83 item.setAuthUserName(cursor.getString(4));
84 item.setAuthPassword(cursor.getString(5));
85 item.setPostingPermitted(cursor.getInt(6) == 1);
86 item.setThemeId(cursor.getInt(7));
87 item.orderNo = cursor.getInt(8);
88 item.setPreferredAccountsFilter(cursor.getString(9));
90 if (item.getUuid().equals(currentProfileUUID)) result = item;
93 Data.profiles.setList(list);
96 public static void storeProfilesOrder() {
97 SQLiteDatabase db = MLDB.getDatabase();
98 db.beginTransaction();
101 try (LockHolder lh = Data.profiles.lockForReading()) {
102 for (int i = 0; i < Data.profiles.size(); i++) {
103 MobileLedgerProfile p = Data.profiles.get(i);
104 db.execSQL("update profiles set order_no=? where uuid=?",
105 new Object[]{orderNo, p.getUuid()});
110 db.setTransactionSuccessful();
116 public String getPreferredAccountsFilter() {
117 return preferredAccountsFilter;
119 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
120 this.preferredAccountsFilter = preferredAccountsFilter;
122 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
123 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
125 public boolean isPostingPermitted() {
126 return permitPosting;
128 public void setPostingPermitted(boolean permitPosting) {
129 this.permitPosting = permitPosting;
131 public String getUuid() {
134 public String getName() {
137 public void setName(CharSequence text) {
138 setName(String.valueOf(text));
140 public void setName(String name) {
143 public String getUrl() {
146 public void setUrl(CharSequence text) {
147 setUrl(String.valueOf(text));
149 public void setUrl(String url) {
152 public boolean isAuthEnabled() {
155 public void setAuthEnabled(boolean authEnabled) {
156 this.authEnabled = authEnabled;
158 public String getAuthUserName() {
161 public void setAuthUserName(CharSequence text) {
162 setAuthUserName(String.valueOf(text));
164 public void setAuthUserName(String authUserName) {
165 this.authUserName = authUserName;
167 public String getAuthPassword() {
170 public void setAuthPassword(CharSequence text) {
171 setAuthPassword(String.valueOf(text));
173 public void setAuthPassword(String authPassword) {
174 this.authPassword = authPassword;
176 public void storeInDB() {
177 SQLiteDatabase db = MLDB.getDatabase();
178 db.beginTransaction();
180 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
181 // "url=%s, permit_posting=%s, authEnabled=%s, " +
182 // "themeId=%d", uuid, name, url,
183 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
184 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
185 "use_authentication, auth_user, " +
186 "auth_password, theme, order_no, preferred_accounts_filter) " +
187 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
188 new Object[]{uuid, name, permitPosting, url, authEnabled,
189 authEnabled ? authUserName : null,
190 authEnabled ? authPassword : null, themeId, orderNo,
191 preferredAccountsFilter
193 db.setTransactionSuccessful();
199 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
200 // replace into is a bad idea because it would reset hidden to its default value
201 // we like the default, but for new accounts only
202 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
203 "where profile=? and name = ?",
204 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
208 "insert into accounts(profile, name, name_upper, parent_name, level, hidden, expanded, keep) " +
209 "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
210 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
211 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
213 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
215 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
216 db.execSQL("replace into account_values(profile, account, " +
217 "currency, value, keep) values(?, ?, ?, ?, 1);",
218 new Object[]{uuid, name, currency, amount});
220 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
222 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
223 new Object[]{uuid, tr.getId()});
224 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
225 new Object[]{uuid, tr.getId()});
227 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
228 "values(?,?,?,?,?,1)",
229 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
230 tr.getDescription(), tr.getDataHash()
233 for (LedgerTransactionAccount item : tr.getAccounts()) {
234 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
235 "account_name, amount, currency) values(?, ?, ?, ?, ?)",
236 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
240 // debug("profile", String.format("Transaction %d stored", tr.getId()));
242 public String getOption(String name, String default_value) {
243 SQLiteDatabase db = MLDB.getDatabase();
244 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
245 new String[]{uuid, name}))
247 if (cursor.moveToFirst()) {
248 String result = cursor.getString(0);
250 if (result == null) {
251 debug("profile", "returning default value for " + name);
252 result = default_value;
254 else debug("profile", String.format("option %s=%s", name, result));
258 else return default_value;
260 catch (Exception e) {
261 debug("db", "returning default value for " + name, e);
262 return default_value;
265 public long getLongOption(String name, long default_value) {
267 String result = getOption(name, "");
268 if ((result == null) || result.isEmpty()) {
269 debug("profile", String.format("Returning default value for option %s", name));
270 longResult = default_value;
274 longResult = Long.parseLong(result);
275 debug("profile", String.format("option %s=%s", name, result));
277 catch (Exception e) {
278 debug("profile", String.format("Returning default value for option %s", name), e);
279 longResult = default_value;
285 public void setOption(String name, String value) {
286 debug("profile", String.format("setting option %s=%s", name, value));
287 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
288 new String[]{uuid, name, value});
290 public void setLongOption(String name, long value) {
291 setOption(name, String.valueOf(value));
293 public void removeFromDB() {
294 SQLiteDatabase db = MLDB.getDatabase();
295 debug("db", String.format("removing profile %s from DB", uuid));
296 db.beginTransaction();
298 Object[] uuid_param = new Object[]{uuid};
299 db.execSQL("delete from profiles where uuid=?", uuid_param);
300 db.execSQL("delete from accounts where profile=?", uuid_param);
301 db.execSQL("delete from account_values where profile=?", uuid_param);
302 db.execSQL("delete from transactions where profile=?", uuid_param);
303 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
304 db.setTransactionSuccessful();
311 public LedgerAccount loadAccount(String name) {
312 SQLiteDatabase db = MLDB.getDatabase();
313 return loadAccount(db, name);
316 public LedgerAccount tryLoadAccount(String acct_name) {
317 SQLiteDatabase db = MLDB.getDatabase();
318 return tryLoadAccount(db, acct_name);
321 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
322 LedgerAccount acc = tryLoadAccount(db, accName);
324 if (acc == null) throw new RuntimeException("Unable to load account with name " + accName);
329 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
330 try (Cursor cursor = db.rawQuery(
331 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
332 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
333 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
335 if (cursor.moveToFirst()) {
336 LedgerAccount acc = new LedgerAccount(accName);
337 acc.setHiddenByStar(cursor.getInt(0) == 1);
338 acc.setExpanded(cursor.getInt(1) == 1);
339 acc.setHasSubAccounts(cursor.getInt(2) == 1);
341 try (Cursor c2 = db.rawQuery(
342 "SELECT value, currency FROM account_values WHERE profile = ? " +
343 "AND account = ?", new String[]{uuid, accName}))
345 while (c2.moveToNext()) {
346 acc.addAmount(c2.getFloat(0), c2.getString(1));
355 public LedgerTransaction loadTransaction(int transactionId) {
356 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
357 tr.loadData(MLDB.getDatabase());
361 public int getThemeId() {
362 // debug("profile", String.format("Profile.getThemeId() returning %d", themeId));
365 public void setThemeId(Object o) {
366 setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
368 public void setThemeId(int themeId) {
369 // debug("profile", String.format("Profile.setThemeId(%d) called", themeId));
370 this.themeId = themeId;
372 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
373 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
376 public void markAccountsAsNotPresent(SQLiteDatabase db) {
377 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
378 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
381 public void deleteNotPresentAccounts(SQLiteDatabase db) {
382 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
383 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
385 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
386 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
387 new Object[]{uuid, transaction.getId()
390 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
391 LedgerTransaction transaction) {
392 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
393 new Object[]{uuid, transaction.getId()
397 public void deleteNotPresentTransactions(SQLiteDatabase db) {
398 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
400 public void setLastUpdateStamp() {
401 debug("db", "Updating transaction value stamp");
402 Date now = new Date();
403 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
404 Data.lastUpdateDate.postValue(now);
406 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
407 List<LedgerAccount> result = new ArrayList<>();
408 SQLiteDatabase db = MLDB.getDatabase();
409 try (Cursor c = db.rawQuery(
410 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
411 new String[]{uuid, acc.getName()}))
413 while (c.moveToNext()) {
414 LedgerAccount a = loadAccount(db, c.getString(0));
421 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
422 List<LedgerAccount> result = new ArrayList<>();
423 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
424 visibleList.add(acc);
426 SQLiteDatabase db = MLDB.getDatabase();
427 try (Cursor c = db.rawQuery(
428 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
429 new String[]{uuid, acc.getName()}))
431 while (c.moveToNext()) {
432 LedgerAccount a = loadAccount(db, c.getString(0));
433 if (a.isVisible(visibleList)) {
442 public void wipeAllData() {
443 SQLiteDatabase db = MLDB.getDatabase();
444 db.beginTransaction();
446 String[] pUuid = new String[]{uuid};
447 db.execSQL("delete from options where profile=?", pUuid);
448 db.execSQL("delete from accounts where profile=?", pUuid);
449 db.execSQL("delete from account_values where profile=?", pUuid);
450 db.execSQL("delete from transactions where profile=?", pUuid);
451 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
452 db.setTransactionSuccessful();