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 net.ktnx.mobileledger.App;
26 import net.ktnx.mobileledger.R;
27 import net.ktnx.mobileledger.async.DbOpQueue;
28 import net.ktnx.mobileledger.utils.Globals;
29 import net.ktnx.mobileledger.utils.Logger;
30 import net.ktnx.mobileledger.utils.MLDB;
32 import java.util.ArrayList;
33 import java.util.Date;
34 import java.util.List;
35 import java.util.Locale;
36 import java.util.UUID;
38 import androidx.annotation.NonNull;
39 import androidx.annotation.Nullable;
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));
98 if (item.getUuid().equals(currentProfileUUID)) result = item;
101 Data.profiles.setValue(list);
104 public static void storeProfilesOrder() {
105 SQLiteDatabase db = App.getDatabase();
106 db.beginTransaction();
109 for (MobileLedgerProfile p : Data.profiles.getValue()) {
110 db.execSQL("update profiles set order_no=? where uuid=?",
111 new Object[]{orderNo, p.getUuid()});
115 db.setTransactionSuccessful();
121 public FutureDates getFutureDates() {
124 public void setFutureDates(int anInt) {
125 futureDates = FutureDates.valueOf(anInt);
127 public void setFutureDates(FutureDates futureDates) {
128 this.futureDates = futureDates;
130 public String getPreferredAccountsFilter() {
131 return preferredAccountsFilter;
133 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
134 this.preferredAccountsFilter = preferredAccountsFilter;
136 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
137 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
139 public boolean isPostingPermitted() {
140 return permitPosting;
142 public void setPostingPermitted(boolean permitPosting) {
143 this.permitPosting = permitPosting;
145 public String getUuid() {
148 public String getName() {
151 public void setName(CharSequence text) {
152 setName(String.valueOf(text));
154 public void setName(String name) {
157 public String getUrl() {
160 public void setUrl(CharSequence text) {
161 setUrl(String.valueOf(text));
163 public void setUrl(String url) {
166 public boolean isAuthEnabled() {
169 public void setAuthEnabled(boolean authEnabled) {
170 this.authEnabled = authEnabled;
172 public String getAuthUserName() {
175 public void setAuthUserName(CharSequence text) {
176 setAuthUserName(String.valueOf(text));
178 public void setAuthUserName(String authUserName) {
179 this.authUserName = authUserName;
181 public String getAuthPassword() {
184 public void setAuthPassword(CharSequence text) {
185 setAuthPassword(String.valueOf(text));
187 public void setAuthPassword(String authPassword) {
188 this.authPassword = authPassword;
190 public void storeInDB() {
191 SQLiteDatabase db = App.getDatabase();
192 db.beginTransaction();
194 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
195 // "url=%s, permit_posting=%s, authEnabled=%s, " +
196 // "themeId=%d", uuid, name, url,
197 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
198 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
199 "use_authentication, auth_user, " +
200 "auth_password, theme, order_no, preferred_accounts_filter, future_dates) " +
201 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
202 new Object[]{uuid, name, permitPosting, url, authEnabled,
203 authEnabled ? authUserName : null,
204 authEnabled ? authPassword : null, themeId, orderNo,
205 preferredAccountsFilter, futureDates.toInt()
207 db.setTransactionSuccessful();
213 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
214 // replace into is a bad idea because it would reset hidden to its default value
215 // we like the default, but for new accounts only
216 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
217 "where profile=? and name = ?",
218 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
221 db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, hidden, " +
222 "expanded, keep) " + "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
223 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
224 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
226 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
228 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
229 db.execSQL("replace into account_values(profile, account, " +
230 "currency, value, keep) values(?, ?, ?, ?, 1);",
231 new Object[]{uuid, name, currency, amount});
233 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
235 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
236 new Object[]{uuid, tr.getId()});
237 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
238 new Object[]{uuid, tr.getId()});
240 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
241 "values(?,?,?,?,?,1)",
242 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
243 tr.getDescription(), tr.getDataHash()
246 for (LedgerTransactionAccount item : tr.getAccounts()) {
247 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
248 "account_name, amount, currency) values(?, ?, ?, ?, ?)",
249 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
253 // debug("profile", String.format("Transaction %d stored", tr.getId()));
255 public String getOption(String name, String default_value) {
256 SQLiteDatabase db = App.getDatabase();
257 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
258 new String[]{uuid, name}))
260 if (cursor.moveToFirst()) {
261 String result = cursor.getString(0);
263 if (result == null) {
264 debug("profile", "returning default value for " + name);
265 result = default_value;
267 else debug("profile", String.format("option %s=%s", name, result));
271 else return default_value;
273 catch (Exception e) {
274 debug("db", "returning default value for " + name, e);
275 return default_value;
278 public long getLongOption(String name, long default_value) {
280 String result = getOption(name, "");
281 if ((result == null) || result.isEmpty()) {
282 debug("profile", String.format("Returning default value for option %s", name));
283 longResult = default_value;
287 longResult = Long.parseLong(result);
288 debug("profile", String.format("option %s=%s", name, result));
290 catch (Exception e) {
291 debug("profile", String.format("Returning default value for option %s", name), e);
292 longResult = default_value;
298 public void setOption(String name, String value) {
299 debug("profile", String.format("setting option %s=%s", name, value));
300 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
301 new String[]{uuid, name, value});
303 public void setLongOption(String name, long value) {
304 setOption(name, String.valueOf(value));
306 public void removeFromDB() {
307 SQLiteDatabase db = App.getDatabase();
308 debug("db", String.format("removing profile %s from DB", uuid));
309 db.beginTransaction();
311 Object[] uuid_param = new Object[]{uuid};
312 db.execSQL("delete from profiles where uuid=?", uuid_param);
313 db.execSQL("delete from accounts where profile=?", uuid_param);
314 db.execSQL("delete from account_values where profile=?", uuid_param);
315 db.execSQL("delete from transactions where profile=?", uuid_param);
316 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
317 db.setTransactionSuccessful();
324 public LedgerAccount loadAccount(String name) {
325 SQLiteDatabase db = App.getDatabase();
326 return loadAccount(db, name);
329 public LedgerAccount tryLoadAccount(String acct_name) {
330 SQLiteDatabase db = App.getDatabase();
331 return tryLoadAccount(db, acct_name);
334 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
335 LedgerAccount acc = tryLoadAccount(db, accName);
337 if (acc == null) throw new RuntimeException("Unable to load account with name " + accName);
342 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
343 try (Cursor cursor = db.rawQuery(
344 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
345 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
346 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
348 if (cursor.moveToFirst()) {
349 LedgerAccount acc = new LedgerAccount(accName);
350 acc.setHiddenByStar(cursor.getInt(0) == 1);
351 acc.setExpanded(cursor.getInt(1) == 1);
352 acc.setHasSubAccounts(cursor.getInt(2) == 1);
354 try (Cursor c2 = db.rawQuery(
355 "SELECT value, currency FROM account_values WHERE profile = ? " +
356 "AND account = ?", new String[]{uuid, accName}))
358 while (c2.moveToNext()) {
359 acc.addAmount(c2.getFloat(0), c2.getString(1));
368 public LedgerTransaction loadTransaction(int transactionId) {
369 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
370 tr.loadData(App.getDatabase());
374 public int getThemeId() {
375 // debug("profile", String.format("Profile.getThemeId() returning %d", themeId));
378 public void setThemeId(Object o) {
379 setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
381 public void setThemeId(int themeId) {
382 // debug("profile", String.format("Profile.setThemeId(%d) called", themeId));
383 this.themeId = themeId;
385 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
386 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
389 public void markAccountsAsNotPresent(SQLiteDatabase db) {
390 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
391 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
394 public void deleteNotPresentAccounts(SQLiteDatabase db) {
395 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
396 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
398 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
399 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
400 new Object[]{uuid, transaction.getId()
403 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
404 LedgerTransaction transaction) {
405 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
406 new Object[]{uuid, transaction.getId()
410 public void deleteNotPresentTransactions(SQLiteDatabase db) {
411 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
413 public void setLastUpdateStamp() {
414 debug("db", "Updating transaction value stamp");
415 Date now = new Date();
416 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
417 Data.lastUpdateDate.postValue(now);
419 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
420 List<LedgerAccount> result = new ArrayList<>();
421 SQLiteDatabase db = App.getDatabase();
422 try (Cursor c = db.rawQuery(
423 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
424 new String[]{uuid, acc.getName()}))
426 while (c.moveToNext()) {
427 LedgerAccount a = loadAccount(db, c.getString(0));
434 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
435 List<LedgerAccount> result = new ArrayList<>();
436 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
437 visibleList.add(acc);
439 SQLiteDatabase db = App.getDatabase();
440 try (Cursor c = db.rawQuery(
441 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
442 new String[]{uuid, acc.getName()}))
444 while (c.moveToNext()) {
445 LedgerAccount a = loadAccount(db, c.getString(0));
446 if (a.isVisible(visibleList)) {
455 public void wipeAllData() {
456 SQLiteDatabase db = App.getDatabase();
457 db.beginTransaction();
459 String[] pUuid = new String[]{uuid};
460 db.execSQL("delete from options where profile=?", pUuid);
461 db.execSQL("delete from accounts where profile=?", pUuid);
462 db.execSQL("delete from account_values where profile=?", pUuid);
463 db.execSQL("delete from transactions where profile=?", pUuid);
464 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
465 db.setTransactionSuccessful();
466 Logger.debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
472 public enum FutureDates {
473 None(0), OneMonth(30), TwoMonths(60), ThreeMonths(90), SixMonths(180), OneYear(365),
475 private static SparseArray<FutureDates> map = new SparseArray<>();
478 for (FutureDates item : FutureDates.values()) {
479 map.put(item.value, item);
484 FutureDates(int value) {
487 public static FutureDates valueOf(int i) {
488 return map.get(i, None);
493 public String getText(Resources resources) {
496 return resources.getString(R.string.future_dates_30);
498 return resources.getString(R.string.future_dates_60);
500 return resources.getString(R.string.future_dates_90);
502 return resources.getString(R.string.future_dates_180);
504 return resources.getString(R.string.future_dates_365);
506 return resources.getString(R.string.future_dates_all);
508 return resources.getString(R.string.future_dates_none);