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.content.res.Resources;
21 import android.database.Cursor;
22 import android.database.sqlite.SQLiteDatabase;
23 import android.util.SparseArray;
25 import androidx.annotation.NonNull;
26 import androidx.annotation.Nullable;
28 import net.ktnx.mobileledger.App;
29 import net.ktnx.mobileledger.R;
30 import net.ktnx.mobileledger.async.DbOpQueue;
31 import net.ktnx.mobileledger.utils.Globals;
32 import net.ktnx.mobileledger.utils.Logger;
33 import net.ktnx.mobileledger.utils.MLDB;
35 import java.util.ArrayList;
36 import java.util.Date;
37 import java.util.List;
38 import java.util.Locale;
39 import java.util.UUID;
41 import static net.ktnx.mobileledger.utils.Logger.debug;
43 public final class MobileLedgerProfile {
46 private boolean permitPosting;
47 private String preferredAccountsFilter;
49 private boolean authEnabled;
50 private String authUserName;
51 private String authPassword;
53 private int orderNo = -1;
54 private FutureDates futureDates = FutureDates.None;
55 public MobileLedgerProfile() {
56 this.uuid = String.valueOf(UUID.randomUUID());
58 public MobileLedgerProfile(String uuid) {
61 public MobileLedgerProfile(MobileLedgerProfile origin) {
64 permitPosting = origin.permitPosting;
65 preferredAccountsFilter = origin.preferredAccountsFilter;
67 authEnabled = origin.authEnabled;
68 authUserName = origin.authUserName;
69 authPassword = origin.authPassword;
70 themeId = origin.themeId;
71 orderNo = origin.orderNo;
72 futureDates = origin.futureDates;
74 // loads all profiles into Data.profiles
75 // returns the profile with the given UUID
76 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
77 MobileLedgerProfile result = null;
78 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
79 SQLiteDatabase db = App.getDatabase();
80 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
81 "auth_password, permit_posting, theme, order_no, " +
82 "preferred_accounts_filter, future_dates FROM " +
83 "profiles order by order_no", null))
85 while (cursor.moveToNext()) {
86 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
87 item.setName(cursor.getString(1));
88 item.setUrl(cursor.getString(2));
89 item.setAuthEnabled(cursor.getInt(3) == 1);
90 item.setAuthUserName(cursor.getString(4));
91 item.setAuthPassword(cursor.getString(5));
92 item.setPostingPermitted(cursor.getInt(6) == 1);
93 item.setThemeId(cursor.getInt(7));
94 item.orderNo = cursor.getInt(8);
95 item.setPreferredAccountsFilter(cursor.getString(9));
96 item.setFutureDates(cursor.getInt(10));
99 .equals(currentProfileUUID))
103 Data.profiles.setValue(list);
106 public static void storeProfilesOrder() {
107 SQLiteDatabase db = App.getDatabase();
108 db.beginTransaction();
111 for (MobileLedgerProfile p : Data.profiles.getValue()) {
112 db.execSQL("update profiles set order_no=? where uuid=?",
113 new Object[]{orderNo, p.getUuid()});
117 db.setTransactionSuccessful();
123 public FutureDates getFutureDates() {
126 public void setFutureDates(int anInt) {
127 futureDates = FutureDates.valueOf(anInt);
129 public void setFutureDates(FutureDates futureDates) {
130 this.futureDates = futureDates;
132 public String getPreferredAccountsFilter() {
133 return preferredAccountsFilter;
135 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
136 this.preferredAccountsFilter = preferredAccountsFilter;
138 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
139 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
141 public boolean isPostingPermitted() {
142 return permitPosting;
144 public void setPostingPermitted(boolean permitPosting) {
145 this.permitPosting = permitPosting;
147 public String getUuid() {
150 public String getName() {
153 public void setName(CharSequence text) {
154 setName(String.valueOf(text));
156 public void setName(String name) {
159 public String getUrl() {
162 public void setUrl(CharSequence text) {
163 setUrl(String.valueOf(text));
165 public void setUrl(String url) {
168 public boolean isAuthEnabled() {
171 public void setAuthEnabled(boolean authEnabled) {
172 this.authEnabled = authEnabled;
174 public String getAuthUserName() {
177 public void setAuthUserName(CharSequence text) {
178 setAuthUserName(String.valueOf(text));
180 public void setAuthUserName(String authUserName) {
181 this.authUserName = authUserName;
183 public String getAuthPassword() {
186 public void setAuthPassword(CharSequence text) {
187 setAuthPassword(String.valueOf(text));
189 public void setAuthPassword(String authPassword) {
190 this.authPassword = authPassword;
192 public void storeInDB() {
193 SQLiteDatabase db = App.getDatabase();
194 db.beginTransaction();
196 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
197 // "url=%s, permit_posting=%s, authEnabled=%s, " +
198 // "themeId=%d", uuid, name, url,
199 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
200 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
201 "use_authentication, auth_user, " +
202 "auth_password, theme, order_no, preferred_accounts_filter, future_dates) " +
203 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
204 new Object[]{uuid, name, permitPosting, url, authEnabled,
205 authEnabled ? authUserName : null,
206 authEnabled ? authPassword : null, themeId, orderNo,
207 preferredAccountsFilter, futureDates.toInt()
209 db.setTransactionSuccessful();
215 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
216 // replace into is a bad idea because it would reset hidden to its default value
217 // we like the default, but for new accounts only
218 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
219 "where profile=? and name = ?",
220 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
223 db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, hidden, " +
224 "expanded, keep) " + "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
225 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
226 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
228 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
230 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
231 db.execSQL("replace into account_values(profile, account, " +
232 "currency, value, keep) values(?, ?, ?, ?, 1);",
233 new Object[]{uuid, name, currency, amount});
235 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
237 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
238 new Object[]{uuid, tr.getId()});
239 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
240 new Object[]{uuid, tr.getId()});
242 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
243 "values(?,?,?,?,?,1)",
244 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
245 tr.getDescription(), tr.getDataHash()
248 for (LedgerTransactionAccount item : tr.getAccounts()) {
249 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
250 "account_name, amount, currency) values(?, ?, ?, ?, ?)",
251 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
255 // debug("profile", String.format("Transaction %d stored", tr.getId()));
257 public String getOption(String name, String default_value) {
258 SQLiteDatabase db = App.getDatabase();
259 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
260 new String[]{uuid, name}))
262 if (cursor.moveToFirst()) {
263 String result = cursor.getString(0);
265 if (result == null) {
266 debug("profile", "returning default value for " + name);
267 result = default_value;
270 debug("profile", String.format("option %s=%s", name, result));
275 return default_value;
277 catch (Exception e) {
278 debug("db", "returning default value for " + name, e);
279 return default_value;
282 public long getLongOption(String name, long default_value) {
284 String result = getOption(name, "");
285 if ((result == null) || result.isEmpty()) {
286 debug("profile", String.format("Returning default value for option %s", name));
287 longResult = default_value;
291 longResult = Long.parseLong(result);
292 debug("profile", String.format("option %s=%s", name, result));
294 catch (Exception e) {
295 debug("profile", String.format("Returning default value for option %s", name), e);
296 longResult = default_value;
302 public void setOption(String name, String value) {
303 debug("profile", String.format("setting option %s=%s", name, value));
304 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
305 new String[]{uuid, name, value});
307 public void setLongOption(String name, long value) {
308 setOption(name, String.valueOf(value));
310 public void removeFromDB() {
311 SQLiteDatabase db = App.getDatabase();
312 debug("db", String.format("removing profile %s from DB", uuid));
313 db.beginTransaction();
315 Object[] uuid_param = new Object[]{uuid};
316 db.execSQL("delete from profiles where uuid=?", uuid_param);
317 db.execSQL("delete from accounts where profile=?", uuid_param);
318 db.execSQL("delete from account_values where profile=?", uuid_param);
319 db.execSQL("delete from transactions where profile=?", uuid_param);
320 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
321 db.execSQL("delete from options where profile=?", uuid_param);
322 db.setTransactionSuccessful();
329 public LedgerAccount loadAccount(String name) {
330 SQLiteDatabase db = App.getDatabase();
331 return loadAccount(db, name);
334 public LedgerAccount tryLoadAccount(String acct_name) {
335 SQLiteDatabase db = App.getDatabase();
336 return tryLoadAccount(db, acct_name);
339 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
340 LedgerAccount acc = tryLoadAccount(db, accName);
343 throw new RuntimeException("Unable to load account with name " + accName);
348 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
349 try (Cursor cursor = db.rawQuery(
350 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
351 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
352 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
354 if (cursor.moveToFirst()) {
355 LedgerAccount acc = new LedgerAccount(accName);
356 acc.setHiddenByStar(cursor.getInt(0) == 1);
357 acc.setExpanded(cursor.getInt(1) == 1);
358 acc.setHasSubAccounts(cursor.getInt(2) == 1);
360 try (Cursor c2 = db.rawQuery(
361 "SELECT value, currency FROM account_values WHERE profile = ? " +
362 "AND account = ?", new String[]{uuid, accName}))
364 while (c2.moveToNext()) {
365 acc.addAmount(c2.getFloat(0), c2.getString(1));
374 public LedgerTransaction loadTransaction(int transactionId) {
375 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
376 tr.loadData(App.getDatabase());
380 public int getThemeId() {
381 // debug("profile", String.format("Profile.getThemeId() returning %d", themeId));
384 public void setThemeId(Object o) {
385 setThemeId(Integer.valueOf(String.valueOf(o))
388 public void setThemeId(int themeId) {
389 // debug("profile", String.format("Profile.setThemeId(%d) called", themeId));
390 this.themeId = themeId;
392 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
393 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
396 public void markAccountsAsNotPresent(SQLiteDatabase db) {
397 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
398 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
401 public void deleteNotPresentAccounts(SQLiteDatabase db) {
402 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
403 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
405 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
406 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
407 new Object[]{uuid, transaction.getId()
410 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
411 LedgerTransaction transaction) {
412 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
413 new Object[]{uuid, transaction.getId()
417 public void deleteNotPresentTransactions(SQLiteDatabase db) {
418 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
420 public void setLastUpdateStamp() {
421 debug("db", "Updating transaction value stamp");
422 Date now = new Date();
423 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
424 Data.lastUpdateDate.postValue(now);
426 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
427 List<LedgerAccount> result = new ArrayList<>();
428 SQLiteDatabase db = App.getDatabase();
429 try (Cursor c = db.rawQuery(
430 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
431 new String[]{uuid, acc.getName()}))
433 while (c.moveToNext()) {
434 LedgerAccount a = loadAccount(db, c.getString(0));
441 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
442 List<LedgerAccount> result = new ArrayList<>();
443 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
444 visibleList.add(acc);
446 SQLiteDatabase db = App.getDatabase();
447 try (Cursor c = db.rawQuery(
448 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
449 new String[]{uuid, acc.getName()}))
451 while (c.moveToNext()) {
452 LedgerAccount a = loadAccount(db, c.getString(0));
453 if (a.isVisible(visibleList)) {
462 public void wipeAllData() {
463 SQLiteDatabase db = App.getDatabase();
464 db.beginTransaction();
466 String[] pUuid = new String[]{uuid};
467 db.execSQL("delete from options where profile=?", pUuid);
468 db.execSQL("delete from accounts where profile=?", pUuid);
469 db.execSQL("delete from account_values where profile=?", pUuid);
470 db.execSQL("delete from transactions where profile=?", pUuid);
471 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
472 db.setTransactionSuccessful();
473 Logger.debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
479 public enum FutureDates {
480 None(0), OneMonth(30), TwoMonths(60), ThreeMonths(90), SixMonths(180), OneYear(365),
482 private static SparseArray<FutureDates> map = new SparseArray<>();
485 for (FutureDates item : FutureDates.values()) {
486 map.put(item.value, item);
491 FutureDates(int value) {
494 public static FutureDates valueOf(int i) {
495 return map.get(i, None);
500 public String getText(Resources resources) {
503 return resources.getString(R.string.future_dates_30);
505 return resources.getString(R.string.future_dates_60);
507 return resources.getString(R.string.future_dates_90);
509 return resources.getString(R.string.future_dates_180);
511 return resources.getString(R.string.future_dates_365);
513 return resources.getString(R.string.future_dates_all);
515 return resources.getString(R.string.future_dates_none);