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 // loads all profiles into Data.profiles
56 // returns the profile with the given UUID
57 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
58 MobileLedgerProfile result = null;
59 List<MobileLedgerProfile> list = new ArrayList<>();
60 SQLiteDatabase db = MLDB.getDatabase();
61 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
62 "auth_password, permit_posting, theme, order_no, " +
63 "preferred_accounts_filter FROM " +
64 "profiles order by order_no", null))
66 while (cursor.moveToNext()) {
67 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
68 item.setName(cursor.getString(1));
69 item.setUrl(cursor.getString(2));
70 item.setAuthEnabled(cursor.getInt(3) == 1);
71 item.setAuthUserName(cursor.getString(4));
72 item.setAuthPassword(cursor.getString(5));
73 item.setPostingPermitted(cursor.getInt(6) == 1);
74 item.setThemeId(cursor.getInt(7));
75 item.orderNo = cursor.getInt(8);
76 item.setPreferredAccountsFilter(cursor.getString(9));
78 if (item.getUuid().equals(currentProfileUUID)) result = item;
81 Data.profiles.setList(list);
84 public static void storeProfilesOrder() {
85 SQLiteDatabase db = MLDB.getDatabase();
86 db.beginTransaction();
89 try (LockHolder lh = Data.profiles.lockForReading()) {
90 for (int i = 0; i < Data.profiles.size(); i++) {
91 MobileLedgerProfile p = Data.profiles.get(i);
92 db.execSQL("update profiles set order_no=? where uuid=?",
93 new Object[]{orderNo, p.getUuid()});
98 db.setTransactionSuccessful();
104 public String getPreferredAccountsFilter() {
105 return preferredAccountsFilter;
107 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
108 this.preferredAccountsFilter = preferredAccountsFilter;
110 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
111 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
113 public boolean isPostingPermitted() {
114 return permitPosting;
116 public void setPostingPermitted(boolean permitPosting) {
117 this.permitPosting = permitPosting;
119 public String getUuid() {
122 public String getName() {
125 public void setName(CharSequence text) {
126 setName(String.valueOf(text));
128 public void setName(String name) {
131 public String getUrl() {
134 public void setUrl(CharSequence text) {
135 setUrl(String.valueOf(text));
137 public void setUrl(String url) {
140 public boolean isAuthEnabled() {
143 public void setAuthEnabled(boolean authEnabled) {
144 this.authEnabled = authEnabled;
146 public String getAuthUserName() {
149 public void setAuthUserName(CharSequence text) {
150 setAuthUserName(String.valueOf(text));
152 public void setAuthUserName(String authUserName) {
153 this.authUserName = authUserName;
155 public String getAuthPassword() {
158 public void setAuthPassword(CharSequence text) {
159 setAuthPassword(String.valueOf(text));
161 public void setAuthPassword(String authPassword) {
162 this.authPassword = authPassword;
164 public void storeInDB() {
165 SQLiteDatabase db = MLDB.getDatabase();
166 db.beginTransaction();
168 // debug("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, preferred_accounts_filter) " +
175 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
176 new Object[]{uuid, name, permitPosting, url, authEnabled,
177 authEnabled ? authUserName : null,
178 authEnabled ? authPassword : null, themeId, orderNo,
179 preferredAccountsFilter
181 db.setTransactionSuccessful();
187 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
188 // replace into is a bad idea because it would reset hidden to its default value
189 // we like the default, but for new accounts only
190 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
191 "where profile=? and name = ?",
192 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
196 "insert into accounts(profile, name, name_upper, parent_name, level, hidden, expanded, keep) " +
197 "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
198 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
199 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
201 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
203 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
204 db.execSQL("replace into account_values(profile, account, " +
205 "currency, value, keep) values(?, ?, ?, ?, 1);",
206 new Object[]{uuid, name, currency, amount});
208 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
210 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
211 new Object[]{uuid, tr.getId()});
212 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
213 new Object[]{uuid, tr.getId()});
215 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
216 "values(?,?,?,?,?,1)",
217 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
218 tr.getDescription(), tr.getDataHash()
221 for (LedgerTransactionAccount item : tr.getAccounts()) {
222 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
223 "account_name, amount, currency) values(?, ?, ?, ?, ?)",
224 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
228 debug("profile", String.format("Transaction %d stored", tr.getId()));
230 public String getOption(String name, String default_value) {
231 SQLiteDatabase db = MLDB.getDatabase();
232 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
233 new String[]{uuid, name}))
235 if (cursor.moveToFirst()) {
236 String result = cursor.getString(0);
238 if (result == null) {
239 debug("profile", "returning default value for " + name);
240 result = default_value;
242 else debug("profile", String.format("option %s=%s", name, result));
246 else return default_value;
248 catch (Exception e) {
249 debug("db", "returning default value for " + name, e);
250 return default_value;
253 public long getLongOption(String name, long default_value) {
255 String result = getOption(name, "");
256 if ((result == null) || result.isEmpty()) {
257 debug("profile", String.format("Returning default value for option %s", name));
258 longResult = default_value;
262 longResult = Long.parseLong(result);
263 debug("profile", String.format("option %s=%s", name, result));
265 catch (Exception e) {
266 debug("profile", String.format("Returning default value for option %s", name), e);
267 longResult = default_value;
273 public void setOption(String name, String value) {
274 debug("profile", String.format("setting option %s=%s", name, value));
275 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
276 new String[]{uuid, name, value});
278 public void setLongOption(String name, long value) {
279 setOption(name, String.valueOf(value));
281 public void removeFromDB() {
282 SQLiteDatabase db = MLDB.getDatabase();
283 debug("db", String.format("removing profile %s from DB", uuid));
284 db.beginTransaction();
286 Object[] uuid_param = new Object[]{uuid};
287 db.execSQL("delete from profiles where uuid=?", uuid_param);
288 db.execSQL("delete from accounts where profile=?", uuid_param);
289 db.execSQL("delete from account_values where profile=?", uuid_param);
290 db.execSQL("delete from transactions where profile=?", uuid_param);
291 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
292 db.setTransactionSuccessful();
299 public LedgerAccount loadAccount(String name) {
300 SQLiteDatabase db = MLDB.getDatabase();
301 return loadAccount(db, name);
304 public LedgerAccount tryLoadAccount(String acct_name) {
305 SQLiteDatabase db = MLDB.getDatabase();
306 return tryLoadAccount(db, acct_name);
309 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
310 LedgerAccount acc = tryLoadAccount(db, accName);
312 if (acc == null) throw new RuntimeException("Unable to load account with name " + accName);
317 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
318 try (Cursor cursor = db.rawQuery(
319 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
320 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
321 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
323 if (cursor.moveToFirst()) {
324 LedgerAccount acc = new LedgerAccount(accName);
325 acc.setHiddenByStar(cursor.getInt(0) == 1);
326 acc.setExpanded(cursor.getInt(1) == 1);
327 acc.setHasSubAccounts(cursor.getInt(2) == 1);
329 try (Cursor c2 = db.rawQuery(
330 "SELECT value, currency FROM account_values WHERE profile = ? " +
331 "AND account = ?", new String[]{uuid, accName}))
333 while (c2.moveToNext()) {
334 acc.addAmount(c2.getFloat(0), c2.getString(1));
343 public LedgerTransaction loadTransaction(int transactionId) {
344 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
345 tr.loadData(MLDB.getDatabase());
349 public int getThemeId() {
350 // debug("profile", String.format("Profile.getThemeId() returning %d", themeId));
353 public void setThemeId(Object o) {
354 setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
356 public void setThemeId(int themeId) {
357 // debug("profile", String.format("Profile.setThemeId(%d) called", themeId));
358 this.themeId = themeId;
360 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
361 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
364 public void markAccountsAsNotPresent(SQLiteDatabase db) {
365 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
366 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
369 public void deleteNotPresentAccounts(SQLiteDatabase db) {
370 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
371 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
373 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
374 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
375 new Object[]{uuid, transaction.getId()
378 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
379 LedgerTransaction transaction) {
380 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
381 new Object[]{uuid, transaction.getId()
385 public void deleteNotPresentTransactions(SQLiteDatabase db) {
386 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
388 public void setLastUpdateStamp() {
389 debug("db", "Updating transaction value stamp");
390 Date now = new Date();
391 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
392 Data.lastUpdateDate.postValue(now);
394 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
395 List<LedgerAccount> result = new ArrayList<>();
396 SQLiteDatabase db = MLDB.getDatabase();
397 try (Cursor c = db.rawQuery(
398 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
399 new String[]{uuid, acc.getName()}))
401 while (c.moveToNext()) {
402 LedgerAccount a = loadAccount(db, c.getString(0));
409 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
410 List<LedgerAccount> result = new ArrayList<>();
411 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
412 visibleList.add(acc);
414 SQLiteDatabase db = MLDB.getDatabase();
415 try (Cursor c = db.rawQuery(
416 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
417 new String[]{uuid, acc.getName()}))
419 while (c.moveToNext()) {
420 LedgerAccount a = loadAccount(db, c.getString(0));
421 if (a.isVisible(visibleList)) {
430 public void wipeAllData() {
431 SQLiteDatabase db = MLDB.getDatabase();
432 db.beginTransaction();
434 String[] pUuid = new String[]{uuid};
435 db.execSQL("delete from options where profile=?", pUuid);
436 db.execSQL("delete from accounts where profile=?", pUuid);
437 db.execSQL("delete from account_values where profile=?", pUuid);
438 db.execSQL("delete from transactions where profile=?", pUuid);
439 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
440 db.setTransactionSuccessful();