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.App;
24 import net.ktnx.mobileledger.async.DbOpQueue;
25 import net.ktnx.mobileledger.utils.Globals;
26 import net.ktnx.mobileledger.utils.Logger;
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.Locale;
33 import java.util.UUID;
35 import androidx.annotation.NonNull;
36 import androidx.annotation.Nullable;
38 import static net.ktnx.mobileledger.utils.Logger.debug;
40 public final class MobileLedgerProfile {
43 private boolean permitPosting;
44 private String preferredAccountsFilter;
46 private boolean authEnabled;
47 private String authUserName;
48 private String authPassword;
50 private int orderNo = -1;
51 public MobileLedgerProfile() {
52 this.uuid = String.valueOf(UUID.randomUUID());
54 public MobileLedgerProfile(String uuid) {
57 public MobileLedgerProfile(MobileLedgerProfile origin) {
60 permitPosting = origin.permitPosting;
61 preferredAccountsFilter = origin.preferredAccountsFilter;
63 authEnabled = origin.authEnabled;
64 authUserName = origin.authUserName;
65 authPassword = origin.authPassword;
66 themeId = origin.themeId;
67 orderNo = origin.orderNo;
69 // loads all profiles into Data.profiles
70 // returns the profile with the given UUID
71 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
72 MobileLedgerProfile result = null;
73 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
74 SQLiteDatabase db = App.getDatabase();
75 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
76 "auth_password, permit_posting, theme, order_no, " +
77 "preferred_accounts_filter FROM " +
78 "profiles order by order_no", null))
80 while (cursor.moveToNext()) {
81 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
82 item.setName(cursor.getString(1));
83 item.setUrl(cursor.getString(2));
84 item.setAuthEnabled(cursor.getInt(3) == 1);
85 item.setAuthUserName(cursor.getString(4));
86 item.setAuthPassword(cursor.getString(5));
87 item.setPostingPermitted(cursor.getInt(6) == 1);
88 item.setThemeId(cursor.getInt(7));
89 item.orderNo = cursor.getInt(8);
90 item.setPreferredAccountsFilter(cursor.getString(9));
92 if (item.getUuid().equals(currentProfileUUID)) result = item;
95 Data.profiles.setValue(list);
98 public static void storeProfilesOrder() {
99 SQLiteDatabase db = App.getDatabase();
100 db.beginTransaction();
103 for (MobileLedgerProfile p : Data.profiles.getValue()) {
104 db.execSQL("update profiles set order_no=? where uuid=?",
105 new Object[]{orderNo, p.getUuid()});
109 db.setTransactionSuccessful();
115 public String getPreferredAccountsFilter() {
116 return preferredAccountsFilter;
118 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
119 this.preferredAccountsFilter = preferredAccountsFilter;
121 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
122 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
124 public boolean isPostingPermitted() {
125 return permitPosting;
127 public void setPostingPermitted(boolean permitPosting) {
128 this.permitPosting = permitPosting;
130 public String getUuid() {
133 public String getName() {
136 public void setName(CharSequence text) {
137 setName(String.valueOf(text));
139 public void setName(String name) {
142 public String getUrl() {
145 public void setUrl(CharSequence text) {
146 setUrl(String.valueOf(text));
148 public void setUrl(String url) {
151 public boolean isAuthEnabled() {
154 public void setAuthEnabled(boolean authEnabled) {
155 this.authEnabled = authEnabled;
157 public String getAuthUserName() {
160 public void setAuthUserName(CharSequence text) {
161 setAuthUserName(String.valueOf(text));
163 public void setAuthUserName(String authUserName) {
164 this.authUserName = authUserName;
166 public String getAuthPassword() {
169 public void setAuthPassword(CharSequence text) {
170 setAuthPassword(String.valueOf(text));
172 public void setAuthPassword(String authPassword) {
173 this.authPassword = authPassword;
175 public void storeInDB() {
176 SQLiteDatabase db = App.getDatabase();
177 db.beginTransaction();
179 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
180 // "url=%s, permit_posting=%s, authEnabled=%s, " +
181 // "themeId=%d", uuid, name, url,
182 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
183 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
184 "use_authentication, auth_user, " +
185 "auth_password, theme, order_no, preferred_accounts_filter) " +
186 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
187 new Object[]{uuid, name, permitPosting, url, authEnabled,
188 authEnabled ? authUserName : null,
189 authEnabled ? authPassword : null, themeId, orderNo,
190 preferredAccountsFilter
192 db.setTransactionSuccessful();
198 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
199 // replace into is a bad idea because it would reset hidden to its default value
200 // we like the default, but for new accounts only
201 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
202 "where profile=? and name = ?",
203 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
207 "insert into accounts(profile, name, name_upper, parent_name, level, hidden, expanded, keep) " +
208 "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
209 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
210 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
212 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
214 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
215 db.execSQL("replace into account_values(profile, account, " +
216 "currency, value, keep) values(?, ?, ?, ?, 1);",
217 new Object[]{uuid, name, currency, amount});
219 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
221 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
222 new Object[]{uuid, tr.getId()});
223 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
224 new Object[]{uuid, tr.getId()});
226 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
227 "values(?,?,?,?,?,1)",
228 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
229 tr.getDescription(), tr.getDataHash()
232 for (LedgerTransactionAccount item : tr.getAccounts()) {
233 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
234 "account_name, amount, currency) values(?, ?, ?, ?, ?)",
235 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
239 // debug("profile", String.format("Transaction %d stored", tr.getId()));
241 public String getOption(String name, String default_value) {
242 SQLiteDatabase db = App.getDatabase();
243 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
244 new String[]{uuid, name}))
246 if (cursor.moveToFirst()) {
247 String result = cursor.getString(0);
249 if (result == null) {
250 debug("profile", "returning default value for " + name);
251 result = default_value;
253 else debug("profile", String.format("option %s=%s", name, result));
257 else return default_value;
259 catch (Exception e) {
260 debug("db", "returning default value for " + name, e);
261 return default_value;
264 public long getLongOption(String name, long default_value) {
266 String result = getOption(name, "");
267 if ((result == null) || result.isEmpty()) {
268 debug("profile", String.format("Returning default value for option %s", name));
269 longResult = default_value;
273 longResult = Long.parseLong(result);
274 debug("profile", String.format("option %s=%s", name, result));
276 catch (Exception e) {
277 debug("profile", String.format("Returning default value for option %s", name), e);
278 longResult = default_value;
284 public void setOption(String name, String value) {
285 debug("profile", String.format("setting option %s=%s", name, value));
286 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
287 new String[]{uuid, name, value});
289 public void setLongOption(String name, long value) {
290 setOption(name, String.valueOf(value));
292 public void removeFromDB() {
293 SQLiteDatabase db = App.getDatabase();
294 debug("db", String.format("removing profile %s from DB", uuid));
295 db.beginTransaction();
297 Object[] uuid_param = new Object[]{uuid};
298 db.execSQL("delete from profiles where uuid=?", uuid_param);
299 db.execSQL("delete from accounts where profile=?", uuid_param);
300 db.execSQL("delete from account_values where profile=?", uuid_param);
301 db.execSQL("delete from transactions where profile=?", uuid_param);
302 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
303 db.setTransactionSuccessful();
310 public LedgerAccount loadAccount(String name) {
311 SQLiteDatabase db = App.getDatabase();
312 return loadAccount(db, name);
315 public LedgerAccount tryLoadAccount(String acct_name) {
316 SQLiteDatabase db = App.getDatabase();
317 return tryLoadAccount(db, acct_name);
320 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
321 LedgerAccount acc = tryLoadAccount(db, accName);
323 if (acc == null) throw new RuntimeException("Unable to load account with name " + accName);
328 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
329 try (Cursor cursor = db.rawQuery(
330 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
331 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
332 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
334 if (cursor.moveToFirst()) {
335 LedgerAccount acc = new LedgerAccount(accName);
336 acc.setHiddenByStar(cursor.getInt(0) == 1);
337 acc.setExpanded(cursor.getInt(1) == 1);
338 acc.setHasSubAccounts(cursor.getInt(2) == 1);
340 try (Cursor c2 = db.rawQuery(
341 "SELECT value, currency FROM account_values WHERE profile = ? " +
342 "AND account = ?", new String[]{uuid, accName}))
344 while (c2.moveToNext()) {
345 acc.addAmount(c2.getFloat(0), c2.getString(1));
354 public LedgerTransaction loadTransaction(int transactionId) {
355 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
356 tr.loadData(App.getDatabase());
360 public int getThemeId() {
361 // debug("profile", String.format("Profile.getThemeId() returning %d", themeId));
364 public void setThemeId(Object o) {
365 setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
367 public void setThemeId(int themeId) {
368 // debug("profile", String.format("Profile.setThemeId(%d) called", themeId));
369 this.themeId = themeId;
371 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
372 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
375 public void markAccountsAsNotPresent(SQLiteDatabase db) {
376 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
377 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
380 public void deleteNotPresentAccounts(SQLiteDatabase db) {
381 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
382 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
384 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
385 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
386 new Object[]{uuid, transaction.getId()
389 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
390 LedgerTransaction transaction) {
391 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
392 new Object[]{uuid, transaction.getId()
396 public void deleteNotPresentTransactions(SQLiteDatabase db) {
397 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
399 public void setLastUpdateStamp() {
400 debug("db", "Updating transaction value stamp");
401 Date now = new Date();
402 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
403 Data.lastUpdateDate.postValue(now);
405 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
406 List<LedgerAccount> result = new ArrayList<>();
407 SQLiteDatabase db = App.getDatabase();
408 try (Cursor c = db.rawQuery(
409 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
410 new String[]{uuid, acc.getName()}))
412 while (c.moveToNext()) {
413 LedgerAccount a = loadAccount(db, c.getString(0));
420 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
421 List<LedgerAccount> result = new ArrayList<>();
422 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
423 visibleList.add(acc);
425 SQLiteDatabase db = App.getDatabase();
426 try (Cursor c = db.rawQuery(
427 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
428 new String[]{uuid, acc.getName()}))
430 while (c.moveToNext()) {
431 LedgerAccount a = loadAccount(db, c.getString(0));
432 if (a.isVisible(visibleList)) {
441 public void wipeAllData() {
442 SQLiteDatabase db = App.getDatabase();
443 db.beginTransaction();
445 String[] pUuid = new String[]{uuid};
446 db.execSQL("delete from options where profile=?", pUuid);
447 db.execSQL("delete from accounts where profile=?", pUuid);
448 db.execSQL("delete from account_values where profile=?", pUuid);
449 db.execSQL("delete from transactions where profile=?", pUuid);
450 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
451 db.setTransactionSuccessful();
452 Logger.debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));