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.async.SendTransactionTask;
32 import net.ktnx.mobileledger.utils.Globals;
33 import net.ktnx.mobileledger.utils.Logger;
34 import net.ktnx.mobileledger.utils.MLDB;
36 import java.util.ArrayList;
37 import java.util.Date;
38 import java.util.List;
39 import java.util.Locale;
40 import java.util.UUID;
42 import static net.ktnx.mobileledger.utils.Logger.debug;
44 public final class MobileLedgerProfile {
47 private boolean permitPosting;
48 private String preferredAccountsFilter;
50 private boolean authEnabled;
51 private String authUserName;
52 private String authPassword;
54 private int orderNo = -1;
55 private FutureDates futureDates = FutureDates.None;
56 private SendTransactionTask.API apiVersion = SendTransactionTask.API.auto;
57 public MobileLedgerProfile() {
58 this.uuid = String.valueOf(UUID.randomUUID());
60 public MobileLedgerProfile(String uuid) {
63 public MobileLedgerProfile(MobileLedgerProfile origin) {
66 permitPosting = origin.permitPosting;
67 preferredAccountsFilter = origin.preferredAccountsFilter;
69 authEnabled = origin.authEnabled;
70 authUserName = origin.authUserName;
71 authPassword = origin.authPassword;
72 themeId = origin.themeId;
73 orderNo = origin.orderNo;
74 futureDates = origin.futureDates;
75 apiVersion = origin.apiVersion;
77 // loads all profiles into Data.profiles
78 // returns the profile with the given UUID
79 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
80 MobileLedgerProfile result = null;
81 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
82 SQLiteDatabase db = App.getDatabase();
83 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
84 "auth_password, permit_posting, theme, order_no, " +
85 "preferred_accounts_filter, future_dates, api_version " +
86 "FROM " + "profiles order by order_no", null))
88 while (cursor.moveToNext()) {
89 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
90 item.setName(cursor.getString(1));
91 item.setUrl(cursor.getString(2));
92 item.setAuthEnabled(cursor.getInt(3) == 1);
93 item.setAuthUserName(cursor.getString(4));
94 item.setAuthPassword(cursor.getString(5));
95 item.setPostingPermitted(cursor.getInt(6) == 1);
96 item.setThemeId(cursor.getInt(7));
97 item.orderNo = cursor.getInt(8);
98 item.setPreferredAccountsFilter(cursor.getString(9));
99 item.setFutureDates(cursor.getInt(10));
100 item.setApiVersion(cursor.getInt(11));
103 .equals(currentProfileUUID))
107 Data.profiles.setValue(list);
110 public static void storeProfilesOrder() {
111 SQLiteDatabase db = App.getDatabase();
112 db.beginTransaction();
115 for (MobileLedgerProfile p : Data.profiles.getValue()) {
116 db.execSQL("update profiles set order_no=? where uuid=?",
117 new Object[]{orderNo, p.getUuid()});
121 db.setTransactionSuccessful();
127 public SendTransactionTask.API getApiVersion() {
130 public void setApiVersion(SendTransactionTask.API apiVersion) {
131 this.apiVersion = apiVersion;
133 public void setApiVersion(int apiVersion) {
134 this.apiVersion = SendTransactionTask.API.valueOf(apiVersion);
136 public FutureDates getFutureDates() {
139 public void setFutureDates(int anInt) {
140 futureDates = FutureDates.valueOf(anInt);
142 public void setFutureDates(FutureDates futureDates) {
143 this.futureDates = futureDates;
145 public String getPreferredAccountsFilter() {
146 return preferredAccountsFilter;
148 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
149 this.preferredAccountsFilter = preferredAccountsFilter;
151 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
152 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
154 public boolean isPostingPermitted() {
155 return permitPosting;
157 public void setPostingPermitted(boolean permitPosting) {
158 this.permitPosting = permitPosting;
160 public String getUuid() {
163 public String getName() {
166 public void setName(CharSequence text) {
167 setName(String.valueOf(text));
169 public void setName(String name) {
172 public String getUrl() {
175 public void setUrl(CharSequence text) {
176 setUrl(String.valueOf(text));
178 public void setUrl(String url) {
181 public boolean isAuthEnabled() {
184 public void setAuthEnabled(boolean authEnabled) {
185 this.authEnabled = authEnabled;
187 public String getAuthUserName() {
190 public void setAuthUserName(CharSequence text) {
191 setAuthUserName(String.valueOf(text));
193 public void setAuthUserName(String authUserName) {
194 this.authUserName = authUserName;
196 public String getAuthPassword() {
199 public void setAuthPassword(CharSequence text) {
200 setAuthPassword(String.valueOf(text));
202 public void setAuthPassword(String authPassword) {
203 this.authPassword = authPassword;
205 public void storeInDB() {
206 SQLiteDatabase db = App.getDatabase();
207 db.beginTransaction();
209 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
210 // "url=%s, permit_posting=%s, authEnabled=%s, " +
211 // "themeId=%d", uuid, name, url,
212 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
213 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
214 "use_authentication, auth_user, " +
215 "auth_password, theme, order_no, preferred_accounts_filter, future_dates, " +
216 "api_version) " + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
217 new Object[]{uuid, name, permitPosting, url, authEnabled,
218 authEnabled ? authUserName : null,
219 authEnabled ? authPassword : null, themeId, orderNo,
220 preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt()
222 db.setTransactionSuccessful();
228 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
229 // replace into is a bad idea because it would reset hidden to its default value
230 // we like the default, but for new accounts only
231 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
232 "where profile=? and name = ?",
233 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
236 db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, hidden, " +
237 "expanded, keep) " + "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
238 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
239 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
241 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
243 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
244 db.execSQL("replace into account_values(profile, account, " +
245 "currency, value, keep) values(?, ?, ?, ?, 1);",
246 new Object[]{uuid, name, currency, amount});
248 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
250 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
251 new Object[]{uuid, tr.getId()});
252 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
253 new Object[]{uuid, tr.getId()});
255 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
256 "values(?,?,?,?,?,1)",
257 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
258 tr.getDescription(), tr.getDataHash()
261 for (LedgerTransactionAccount item : tr.getAccounts()) {
262 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
263 "account_name, amount, currency) values(?, ?, ?, ?, ?)",
264 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
268 // debug("profile", String.format("Transaction %d stored", tr.getId()));
270 public String getOption(String name, String default_value) {
271 SQLiteDatabase db = App.getDatabase();
272 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
273 new String[]{uuid, name}))
275 if (cursor.moveToFirst()) {
276 String result = cursor.getString(0);
278 if (result == null) {
279 debug("profile", "returning default value for " + name);
280 result = default_value;
283 debug("profile", String.format("option %s=%s", name, result));
288 return default_value;
290 catch (Exception e) {
291 debug("db", "returning default value for " + name, e);
292 return default_value;
295 public long getLongOption(String name, long default_value) {
297 String result = getOption(name, "");
298 if ((result == null) || result.isEmpty()) {
299 debug("profile", String.format("Returning default value for option %s", name));
300 longResult = default_value;
304 longResult = Long.parseLong(result);
305 debug("profile", String.format("option %s=%s", name, result));
307 catch (Exception e) {
308 debug("profile", String.format("Returning default value for option %s", name), e);
309 longResult = default_value;
315 public void setOption(String name, String value) {
316 debug("profile", String.format("setting option %s=%s", name, value));
317 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
318 new String[]{uuid, name, value});
320 public void setLongOption(String name, long value) {
321 setOption(name, String.valueOf(value));
323 public void removeFromDB() {
324 SQLiteDatabase db = App.getDatabase();
325 debug("db", String.format("removing profile %s from DB", uuid));
326 db.beginTransaction();
328 Object[] uuid_param = new Object[]{uuid};
329 db.execSQL("delete from profiles where uuid=?", uuid_param);
330 db.execSQL("delete from accounts where profile=?", uuid_param);
331 db.execSQL("delete from account_values where profile=?", uuid_param);
332 db.execSQL("delete from transactions where profile=?", uuid_param);
333 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
334 db.execSQL("delete from options where profile=?", uuid_param);
335 db.setTransactionSuccessful();
342 public LedgerAccount loadAccount(String name) {
343 SQLiteDatabase db = App.getDatabase();
344 return loadAccount(db, name);
347 public LedgerAccount tryLoadAccount(String acct_name) {
348 SQLiteDatabase db = App.getDatabase();
349 return tryLoadAccount(db, acct_name);
352 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
353 LedgerAccount acc = tryLoadAccount(db, accName);
356 throw new RuntimeException("Unable to load account with name " + accName);
361 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
362 try (Cursor cursor = db.rawQuery(
363 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
364 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
365 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
367 if (cursor.moveToFirst()) {
368 LedgerAccount acc = new LedgerAccount(accName);
369 acc.setHiddenByStar(cursor.getInt(0) == 1);
370 acc.setExpanded(cursor.getInt(1) == 1);
371 acc.setHasSubAccounts(cursor.getInt(2) == 1);
373 try (Cursor c2 = db.rawQuery(
374 "SELECT value, currency FROM account_values WHERE profile = ? " +
375 "AND account = ?", new String[]{uuid, accName}))
377 while (c2.moveToNext()) {
378 acc.addAmount(c2.getFloat(0), c2.getString(1));
387 public LedgerTransaction loadTransaction(int transactionId) {
388 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
389 tr.loadData(App.getDatabase());
393 public int getThemeId() {
394 // debug("profile", String.format("Profile.getThemeId() returning %d", themeId));
397 public void setThemeId(Object o) {
398 setThemeId(Integer.valueOf(String.valueOf(o))
401 public void setThemeId(int themeId) {
402 // debug("profile", String.format("Profile.setThemeId(%d) called", themeId));
403 this.themeId = themeId;
405 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
406 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
409 public void markAccountsAsNotPresent(SQLiteDatabase db) {
410 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
411 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
414 public void deleteNotPresentAccounts(SQLiteDatabase db) {
415 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
416 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
418 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
419 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
420 new Object[]{uuid, transaction.getId()
423 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
424 LedgerTransaction transaction) {
425 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
426 new Object[]{uuid, transaction.getId()
430 public void deleteNotPresentTransactions(SQLiteDatabase db) {
431 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
433 public void setLastUpdateStamp() {
434 debug("db", "Updating transaction value stamp");
435 Date now = new Date();
436 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
437 Data.lastUpdateDate.postValue(now);
439 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
440 List<LedgerAccount> result = new ArrayList<>();
441 SQLiteDatabase db = App.getDatabase();
442 try (Cursor c = db.rawQuery(
443 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
444 new String[]{uuid, acc.getName()}))
446 while (c.moveToNext()) {
447 LedgerAccount a = loadAccount(db, c.getString(0));
454 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
455 List<LedgerAccount> result = new ArrayList<>();
456 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
457 visibleList.add(acc);
459 SQLiteDatabase db = App.getDatabase();
460 try (Cursor c = db.rawQuery(
461 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
462 new String[]{uuid, acc.getName()}))
464 while (c.moveToNext()) {
465 LedgerAccount a = loadAccount(db, c.getString(0));
466 if (a.isVisible(visibleList)) {
475 public void wipeAllData() {
476 SQLiteDatabase db = App.getDatabase();
477 db.beginTransaction();
479 String[] pUuid = new String[]{uuid};
480 db.execSQL("delete from options where profile=?", pUuid);
481 db.execSQL("delete from accounts where profile=?", pUuid);
482 db.execSQL("delete from account_values where profile=?", pUuid);
483 db.execSQL("delete from transactions where profile=?", pUuid);
484 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
485 db.setTransactionSuccessful();
486 Logger.debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
492 public enum FutureDates {
493 None(0), OneMonth(30), TwoMonths(60), ThreeMonths(90), SixMonths(180), OneYear(365),
495 private static SparseArray<FutureDates> map = new SparseArray<>();
498 for (FutureDates item : FutureDates.values()) {
499 map.put(item.value, item);
504 FutureDates(int value) {
507 public static FutureDates valueOf(int i) {
508 return map.get(i, None);
513 public String getText(Resources resources) {
516 return resources.getString(R.string.future_dates_30);
518 return resources.getString(R.string.future_dates_60);
520 return resources.getString(R.string.future_dates_90);
522 return resources.getString(R.string.future_dates_180);
524 return resources.getString(R.string.future_dates_365);
526 return resources.getString(R.string.future_dates_all);
528 return resources.getString(R.string.future_dates_none);