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;
22 import android.util.Log;
24 import net.ktnx.mobileledger.async.DbOpQueue;
25 import net.ktnx.mobileledger.utils.Globals;
26 import net.ktnx.mobileledger.utils.LockHolder;
27 import net.ktnx.mobileledger.utils.MLDB;
29 import java.util.ArrayList;
30 import java.util.Date;
31 import java.util.List;
32 import java.util.UUID;
34 import androidx.annotation.NonNull;
35 import androidx.annotation.Nullable;
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 // loads all profiles into Data.profiles
55 // returns the profile with the given UUID
56 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
57 MobileLedgerProfile result = null;
58 List<MobileLedgerProfile> list = new ArrayList<>();
59 SQLiteDatabase db = MLDB.getDatabase();
60 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
61 "auth_password, permit_posting, theme, order_no, " +
62 "preferred_accounts_filter FROM " +
63 "profiles order by order_no", null))
65 while (cursor.moveToNext()) {
66 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
67 item.setName(cursor.getString(1));
68 item.setUrl(cursor.getString(2));
69 item.setAuthEnabled(cursor.getInt(3) == 1);
70 item.setAuthUserName(cursor.getString(4));
71 item.setAuthPassword(cursor.getString(5));
72 item.setPostingPermitted(cursor.getInt(6) == 1);
73 item.setThemeId(cursor.getInt(7));
74 item.orderNo = cursor.getInt(8);
75 item.setPreferredAccountsFilter(cursor.getString(9));
77 if (item.getUuid().equals(currentProfileUUID)) result = item;
80 Data.profiles.setList(list);
83 public static void storeProfilesOrder() {
84 SQLiteDatabase db = MLDB.getDatabase();
85 db.beginTransaction();
88 try (LockHolder lh = Data.profiles.lockForReading()) {
89 for (int i = 0; i < Data.profiles.size(); i++) {
90 MobileLedgerProfile p = Data.profiles.get(i);
91 db.execSQL("update profiles set order_no=? where uuid=?",
92 new Object[]{orderNo, p.getUuid()});
97 db.setTransactionSuccessful();
103 public String getPreferredAccountsFilter() {
104 return preferredAccountsFilter;
106 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
107 this.preferredAccountsFilter = preferredAccountsFilter;
109 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
110 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
112 public boolean isPostingPermitted() {
113 return permitPosting;
115 public void setPostingPermitted(boolean permitPosting) {
116 this.permitPosting = permitPosting;
118 public String getUuid() {
121 public String getName() {
124 public void setName(CharSequence text) {
125 setName(String.valueOf(text));
127 public void setName(String name) {
130 public String getUrl() {
133 public void setUrl(CharSequence text) {
134 setUrl(String.valueOf(text));
136 public void setUrl(String url) {
139 public boolean isAuthEnabled() {
142 public void setAuthEnabled(boolean authEnabled) {
143 this.authEnabled = authEnabled;
145 public String getAuthUserName() {
148 public void setAuthUserName(CharSequence text) {
149 setAuthUserName(String.valueOf(text));
151 public void setAuthUserName(String authUserName) {
152 this.authUserName = authUserName;
154 public String getAuthPassword() {
157 public void setAuthPassword(CharSequence text) {
158 setAuthPassword(String.valueOf(text));
160 public void setAuthPassword(String authPassword) {
161 this.authPassword = authPassword;
163 public void storeInDB() {
164 SQLiteDatabase db = MLDB.getDatabase();
165 db.beginTransaction();
167 // Log.d("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
168 // "url=%s, permit_posting=%s, authEnabled=%s, " +
169 // "themeId=%d", uuid, name, url,
170 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
171 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
172 "use_authentication, auth_user, " +
173 "auth_password, theme, order_no, preferred_accounts_filter) " +
174 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
175 new Object[]{uuid, name, permitPosting, url, authEnabled,
176 authEnabled ? authUserName : null,
177 authEnabled ? authPassword : null, themeId, orderNo,
178 preferredAccountsFilter
180 db.setTransactionSuccessful();
186 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
187 // replace into is a bad idea because it would reset hidden to its default value
188 // we like the default, but for new accounts only
189 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
190 "where profile=? and name = ?",
191 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
195 "insert into accounts(profile, name, name_upper, parent_name, level, hidden, expanded, keep) " +
196 "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
197 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
198 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
200 // Log.d("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
202 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
203 db.execSQL("replace into account_values(profile, account, " +
204 "currency, value, keep) values(?, ?, ?, ?, 1);",
205 new Object[]{uuid, name, currency, amount});
207 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
209 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
210 new Object[]{uuid, tr.getId()});
211 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
212 new Object[]{uuid, tr.getId()});
214 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
215 "values(?,?,?,?,?,1)",
216 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
217 tr.getDescription(), tr.getDataHash()
220 for (LedgerTransactionAccount item : tr.getAccounts()) {
221 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
222 "account_name, amount, currency) values(?, ?, ?, ?, ?)",
223 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
227 Log.d("profile", String.format("Transaction %d stored", tr.getId()));
229 public String getOption(String name, String default_value) {
230 SQLiteDatabase db = MLDB.getDatabase();
231 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
232 new String[]{uuid, name}))
234 if (cursor.moveToFirst()) {
235 String result = cursor.getString(0);
237 if (result == null) {
238 Log.d("profile", "returning default value for " + name);
239 result = default_value;
241 else Log.d("profile", String.format("option %s=%s", name, result));
245 else return default_value;
247 catch (Exception e) {
248 Log.d("db", "returning default value for " + name, e);
249 return default_value;
252 public long getLongOption(String name, long default_value) {
254 String result = getOption(name, "");
255 if ((result == null) || result.isEmpty()) {
256 Log.d("profile", String.format("Returning default value for option %s", name));
257 longResult = default_value;
261 longResult = Long.parseLong(result);
262 Log.d("profile", String.format("option %s=%s", name, result));
264 catch (Exception e) {
265 Log.d("profile", String.format("Returning default value for option %s", name), e);
266 longResult = default_value;
272 public void setOption(String name, String value) {
273 Log.d("profile", String.format("setting option %s=%s", name, value));
274 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
275 new String[]{uuid, name, value});
277 public void setLongOption(String name, long value) {
278 setOption(name, String.valueOf(value));
280 public void removeFromDB() {
281 SQLiteDatabase db = MLDB.getDatabase();
282 Log.d("db", String.format("removing profile %s from DB", uuid));
283 db.beginTransaction();
285 Object[] uuid_param = new Object[]{uuid};
286 db.execSQL("delete from profiles where uuid=?", uuid_param);
287 db.execSQL("delete from accounts where profile=?", uuid_param);
288 db.execSQL("delete from account_values where profile=?", uuid_param);
289 db.execSQL("delete from transactions where profile=?", uuid_param);
290 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
291 db.setTransactionSuccessful();
298 public LedgerAccount loadAccount(String name) {
299 SQLiteDatabase db = MLDB.getDatabase();
300 return loadAccount(db, name);
303 public LedgerAccount tryLoadAccount(String acct_name) {
304 SQLiteDatabase db = MLDB.getDatabase();
305 return tryLoadAccount(db, acct_name);
308 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
309 LedgerAccount acc = tryLoadAccount(db, accName);
311 if (acc == null) throw new RuntimeException("Unable to load account with name " + accName);
316 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
317 try (Cursor cursor = db.rawQuery(
318 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
319 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
320 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
322 if (cursor.moveToFirst()) {
323 LedgerAccount acc = new LedgerAccount(accName);
324 acc.setHiddenByStar(cursor.getInt(0) == 1);
325 acc.setExpanded(cursor.getInt(1) == 1);
326 acc.setHasSubAccounts(cursor.getInt(2) == 1);
328 try (Cursor c2 = db.rawQuery(
329 "SELECT value, currency FROM account_values WHERE profile = ? " +
330 "AND account = ?", new String[]{uuid, accName}))
332 while (c2.moveToNext()) {
333 acc.addAmount(c2.getFloat(0), c2.getString(1));
342 public LedgerTransaction loadTransaction(int transactionId) {
343 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
344 tr.loadData(MLDB.getDatabase());
348 public int getThemeId() {
349 // Log.d("profile", String.format("Profile.getThemeId() returning %d", themeId));
352 public void setThemeId(Object o) {
353 setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
355 public void setThemeId(int themeId) {
356 // Log.d("profile", String.format("Profile.setThemeId(%d) called", themeId));
357 this.themeId = themeId;
359 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
360 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
363 public void markAccountsAsNotPresent(SQLiteDatabase db) {
364 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
365 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
368 public void deleteNotPresentAccounts(SQLiteDatabase db) {
369 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
370 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
372 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
373 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
374 new Object[]{uuid, transaction.getId()
377 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
378 LedgerTransaction transaction) {
379 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
380 new Object[]{uuid, transaction.getId()
384 public void deleteNotPresentTransactions(SQLiteDatabase db) {
385 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
387 public void setLastUpdateStamp() {
388 Log.d("db", "Updating transaction value stamp");
389 Date now = new Date();
390 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
391 Data.lastUpdateDate.set(now);
393 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
394 List<LedgerAccount> result = new ArrayList<>();
395 SQLiteDatabase db = MLDB.getDatabase();
396 try (Cursor c = db.rawQuery(
397 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
398 new String[]{uuid, acc.getName()}))
400 while (c.moveToNext()) {
401 LedgerAccount a = loadAccount(db, c.getString(0));
408 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
409 List<LedgerAccount> result = new ArrayList<>();
410 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
411 visibleList.add(acc);
413 SQLiteDatabase db = MLDB.getDatabase();
414 try (Cursor c = db.rawQuery(
415 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
416 new String[]{uuid, acc.getName()}))
418 while (c.moveToNext()) {
419 LedgerAccount a = loadAccount(db, c.getString(0));
420 if (a.isVisible(visibleList)) {
429 public void wipeAllData() {
430 SQLiteDatabase db = MLDB.getDatabase();
431 db.beginTransaction();
433 String[] pUuid = new String[]{uuid};
434 db.execSQL("delete from options where profile=?", pUuid);
435 db.execSQL("delete from accounts where profile=?", pUuid);
436 db.execSQL("delete from account_values where profile=?", pUuid);
437 db.execSQL("delete from transactions where profile=?", pUuid);
438 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
439 db.setTransactionSuccessful();