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.Logger;
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.Locale;
32 import java.util.UUID;
34 import androidx.annotation.NonNull;
35 import androidx.annotation.Nullable;
37 import static net.ktnx.mobileledger.utils.Logger.debug;
39 public final class MobileLedgerProfile {
42 private boolean permitPosting;
43 private String preferredAccountsFilter;
45 private boolean authEnabled;
46 private String authUserName;
47 private String authPassword;
49 private int orderNo = -1;
50 public MobileLedgerProfile() {
51 this.uuid = String.valueOf(UUID.randomUUID());
53 public MobileLedgerProfile(String uuid) {
56 public MobileLedgerProfile(MobileLedgerProfile origin) {
59 permitPosting = origin.permitPosting;
60 preferredAccountsFilter = origin.preferredAccountsFilter;
62 authEnabled = origin.authEnabled;
63 authUserName = origin.authUserName;
64 authPassword = origin.authPassword;
65 themeId = origin.themeId;
66 orderNo = origin.orderNo;
68 // loads all profiles into Data.profiles
69 // returns the profile with the given UUID
70 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
71 MobileLedgerProfile result = null;
72 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
73 SQLiteDatabase db = MLDB.getDatabase();
74 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
75 "auth_password, permit_posting, theme, order_no, " +
76 "preferred_accounts_filter FROM " +
77 "profiles order by order_no", null))
79 while (cursor.moveToNext()) {
80 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
81 item.setName(cursor.getString(1));
82 item.setUrl(cursor.getString(2));
83 item.setAuthEnabled(cursor.getInt(3) == 1);
84 item.setAuthUserName(cursor.getString(4));
85 item.setAuthPassword(cursor.getString(5));
86 item.setPostingPermitted(cursor.getInt(6) == 1);
87 item.setThemeId(cursor.getInt(7));
88 item.orderNo = cursor.getInt(8);
89 item.setPreferredAccountsFilter(cursor.getString(9));
91 if (item.getUuid().equals(currentProfileUUID)) result = item;
94 Data.profiles.setValue(list);
97 public static void storeProfilesOrder() {
98 SQLiteDatabase db = MLDB.getDatabase();
99 db.beginTransaction();
102 for (MobileLedgerProfile p : Data.profiles.getValue()) {
103 db.execSQL("update profiles set order_no=? where uuid=?",
104 new Object[]{orderNo, p.getUuid()});
108 db.setTransactionSuccessful();
114 public String getPreferredAccountsFilter() {
115 return preferredAccountsFilter;
117 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
118 this.preferredAccountsFilter = preferredAccountsFilter;
120 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
121 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
123 public boolean isPostingPermitted() {
124 return permitPosting;
126 public void setPostingPermitted(boolean permitPosting) {
127 this.permitPosting = permitPosting;
129 public String getUuid() {
132 public String getName() {
135 public void setName(CharSequence text) {
136 setName(String.valueOf(text));
138 public void setName(String name) {
141 public String getUrl() {
144 public void setUrl(CharSequence text) {
145 setUrl(String.valueOf(text));
147 public void setUrl(String url) {
150 public boolean isAuthEnabled() {
153 public void setAuthEnabled(boolean authEnabled) {
154 this.authEnabled = authEnabled;
156 public String getAuthUserName() {
159 public void setAuthUserName(CharSequence text) {
160 setAuthUserName(String.valueOf(text));
162 public void setAuthUserName(String authUserName) {
163 this.authUserName = authUserName;
165 public String getAuthPassword() {
168 public void setAuthPassword(CharSequence text) {
169 setAuthPassword(String.valueOf(text));
171 public void setAuthPassword(String authPassword) {
172 this.authPassword = authPassword;
174 public void storeInDB() {
175 SQLiteDatabase db = MLDB.getDatabase();
176 db.beginTransaction();
178 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
179 // "url=%s, permit_posting=%s, authEnabled=%s, " +
180 // "themeId=%d", uuid, name, url,
181 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
182 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
183 "use_authentication, auth_user, " +
184 "auth_password, theme, order_no, preferred_accounts_filter) " +
185 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
186 new Object[]{uuid, name, permitPosting, url, authEnabled,
187 authEnabled ? authUserName : null,
188 authEnabled ? authPassword : null, themeId, orderNo,
189 preferredAccountsFilter
191 db.setTransactionSuccessful();
197 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
198 // replace into is a bad idea because it would reset hidden to its default value
199 // we like the default, but for new accounts only
200 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
201 "where profile=? and name = ?",
202 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
206 "insert into accounts(profile, name, name_upper, parent_name, level, hidden, expanded, keep) " +
207 "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
208 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
209 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
211 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
213 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
214 db.execSQL("replace into account_values(profile, account, " +
215 "currency, value, keep) values(?, ?, ?, ?, 1);",
216 new Object[]{uuid, name, currency, amount});
218 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
220 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
221 new Object[]{uuid, tr.getId()});
222 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
223 new Object[]{uuid, tr.getId()});
225 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
226 "values(?,?,?,?,?,1)",
227 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
228 tr.getDescription(), tr.getDataHash()
231 for (LedgerTransactionAccount item : tr.getAccounts()) {
232 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
233 "account_name, amount, currency) values(?, ?, ?, ?, ?)",
234 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
238 // debug("profile", String.format("Transaction %d stored", tr.getId()));
240 public String getOption(String name, String default_value) {
241 SQLiteDatabase db = MLDB.getDatabase();
242 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
243 new String[]{uuid, name}))
245 if (cursor.moveToFirst()) {
246 String result = cursor.getString(0);
248 if (result == null) {
249 debug("profile", "returning default value for " + name);
250 result = default_value;
252 else debug("profile", String.format("option %s=%s", name, result));
256 else return default_value;
258 catch (Exception e) {
259 debug("db", "returning default value for " + name, e);
260 return default_value;
263 public long getLongOption(String name, long default_value) {
265 String result = getOption(name, "");
266 if ((result == null) || result.isEmpty()) {
267 debug("profile", String.format("Returning default value for option %s", name));
268 longResult = default_value;
272 longResult = Long.parseLong(result);
273 debug("profile", String.format("option %s=%s", name, result));
275 catch (Exception e) {
276 debug("profile", String.format("Returning default value for option %s", name), e);
277 longResult = default_value;
283 public void setOption(String name, String value) {
284 debug("profile", String.format("setting option %s=%s", name, value));
285 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
286 new String[]{uuid, name, value});
288 public void setLongOption(String name, long value) {
289 setOption(name, String.valueOf(value));
291 public void removeFromDB() {
292 SQLiteDatabase db = MLDB.getDatabase();
293 debug("db", String.format("removing profile %s from DB", uuid));
294 db.beginTransaction();
296 Object[] uuid_param = new Object[]{uuid};
297 db.execSQL("delete from profiles where uuid=?", uuid_param);
298 db.execSQL("delete from accounts where profile=?", uuid_param);
299 db.execSQL("delete from account_values where profile=?", uuid_param);
300 db.execSQL("delete from transactions where profile=?", uuid_param);
301 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
302 db.setTransactionSuccessful();
309 public LedgerAccount loadAccount(String name) {
310 SQLiteDatabase db = MLDB.getDatabase();
311 return loadAccount(db, name);
314 public LedgerAccount tryLoadAccount(String acct_name) {
315 SQLiteDatabase db = MLDB.getDatabase();
316 return tryLoadAccount(db, acct_name);
319 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
320 LedgerAccount acc = tryLoadAccount(db, accName);
322 if (acc == null) throw new RuntimeException("Unable to load account with name " + accName);
327 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
328 try (Cursor cursor = db.rawQuery(
329 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
330 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
331 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
333 if (cursor.moveToFirst()) {
334 LedgerAccount acc = new LedgerAccount(accName);
335 acc.setHiddenByStar(cursor.getInt(0) == 1);
336 acc.setExpanded(cursor.getInt(1) == 1);
337 acc.setHasSubAccounts(cursor.getInt(2) == 1);
339 try (Cursor c2 = db.rawQuery(
340 "SELECT value, currency FROM account_values WHERE profile = ? " +
341 "AND account = ?", new String[]{uuid, accName}))
343 while (c2.moveToNext()) {
344 acc.addAmount(c2.getFloat(0), c2.getString(1));
353 public LedgerTransaction loadTransaction(int transactionId) {
354 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
355 tr.loadData(MLDB.getDatabase());
359 public int getThemeId() {
360 // debug("profile", String.format("Profile.getThemeId() returning %d", themeId));
363 public void setThemeId(Object o) {
364 setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
366 public void setThemeId(int themeId) {
367 // debug("profile", String.format("Profile.setThemeId(%d) called", themeId));
368 this.themeId = themeId;
370 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
371 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
374 public void markAccountsAsNotPresent(SQLiteDatabase db) {
375 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
376 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
379 public void deleteNotPresentAccounts(SQLiteDatabase db) {
380 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
381 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
383 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
384 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
385 new Object[]{uuid, transaction.getId()
388 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
389 LedgerTransaction transaction) {
390 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
391 new Object[]{uuid, transaction.getId()
395 public void deleteNotPresentTransactions(SQLiteDatabase db) {
396 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
398 public void setLastUpdateStamp() {
399 debug("db", "Updating transaction value stamp");
400 Date now = new Date();
401 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
402 Data.lastUpdateDate.postValue(now);
404 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
405 List<LedgerAccount> result = new ArrayList<>();
406 SQLiteDatabase db = MLDB.getDatabase();
407 try (Cursor c = db.rawQuery(
408 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
409 new String[]{uuid, acc.getName()}))
411 while (c.moveToNext()) {
412 LedgerAccount a = loadAccount(db, c.getString(0));
419 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
420 List<LedgerAccount> result = new ArrayList<>();
421 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
422 visibleList.add(acc);
424 SQLiteDatabase db = MLDB.getDatabase();
425 try (Cursor c = db.rawQuery(
426 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
427 new String[]{uuid, acc.getName()}))
429 while (c.moveToNext()) {
430 LedgerAccount a = loadAccount(db, c.getString(0));
431 if (a.isVisible(visibleList)) {
440 public void wipeAllData() {
441 SQLiteDatabase db = MLDB.getDatabase();
442 db.beginTransaction();
444 String[] pUuid = new String[]{uuid};
445 db.execSQL("delete from options where profile=?", pUuid);
446 db.execSQL("delete from accounts where profile=?", pUuid);
447 db.execSQL("delete from account_values where profile=?", pUuid);
448 db.execSQL("delete from transactions where profile=?", pUuid);
449 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
450 db.setTransactionSuccessful();
451 Logger.debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));