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;
35 import net.ktnx.mobileledger.utils.Misc;
37 import java.util.ArrayList;
38 import java.util.Date;
39 import java.util.List;
40 import java.util.Locale;
41 import java.util.UUID;
43 import static net.ktnx.mobileledger.utils.Logger.debug;
45 public final class MobileLedgerProfile {
48 private boolean permitPosting;
49 private String preferredAccountsFilter;
51 private boolean authEnabled;
52 private String authUserName;
53 private String authPassword;
55 private int orderNo = -1;
56 private FutureDates futureDates = FutureDates.None;
57 private SendTransactionTask.API apiVersion = SendTransactionTask.API.auto;
58 public MobileLedgerProfile() {
59 this.uuid = String.valueOf(UUID.randomUUID());
61 public MobileLedgerProfile(String uuid) {
64 public MobileLedgerProfile(MobileLedgerProfile origin) {
67 permitPosting = origin.permitPosting;
68 preferredAccountsFilter = origin.preferredAccountsFilter;
70 authEnabled = origin.authEnabled;
71 authUserName = origin.authUserName;
72 authPassword = origin.authPassword;
73 themeHue = origin.themeHue;
74 orderNo = origin.orderNo;
75 futureDates = origin.futureDates;
76 apiVersion = origin.apiVersion;
78 // loads all profiles into Data.profiles
79 // returns the profile with the given UUID
80 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
81 MobileLedgerProfile result = null;
82 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
83 SQLiteDatabase db = App.getDatabase();
84 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
85 "auth_password, permit_posting, theme, order_no, " +
86 "preferred_accounts_filter, future_dates, api_version " +
87 "FROM " + "profiles order by order_no", null))
89 while (cursor.moveToNext()) {
90 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
91 item.setName(cursor.getString(1));
92 item.setUrl(cursor.getString(2));
93 item.setAuthEnabled(cursor.getInt(3) == 1);
94 item.setAuthUserName(cursor.getString(4));
95 item.setAuthPassword(cursor.getString(5));
96 item.setPostingPermitted(cursor.getInt(6) == 1);
97 item.setThemeId(cursor.getInt(7));
98 item.orderNo = cursor.getInt(8);
99 item.setPreferredAccountsFilter(cursor.getString(9));
100 item.setFutureDates(cursor.getInt(10));
101 item.setApiVersion(cursor.getInt(11));
104 .equals(currentProfileUUID))
108 Data.profiles.setValue(list);
111 public static void storeProfilesOrder() {
112 SQLiteDatabase db = App.getDatabase();
113 db.beginTransactionNonExclusive();
116 for (MobileLedgerProfile p : Data.profiles.getValue()) {
117 db.execSQL("update profiles set order_no=? where uuid=?",
118 new Object[]{orderNo, p.getUuid()});
122 db.setTransactionSuccessful();
128 public SendTransactionTask.API getApiVersion() {
131 public void setApiVersion(SendTransactionTask.API apiVersion) {
132 this.apiVersion = apiVersion;
134 public void setApiVersion(int apiVersion) {
135 this.apiVersion = SendTransactionTask.API.valueOf(apiVersion);
137 public FutureDates getFutureDates() {
140 public void setFutureDates(int anInt) {
141 futureDates = FutureDates.valueOf(anInt);
143 public void setFutureDates(FutureDates futureDates) {
144 this.futureDates = futureDates;
146 public String getPreferredAccountsFilter() {
147 return preferredAccountsFilter;
149 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
150 this.preferredAccountsFilter = preferredAccountsFilter;
152 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
153 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
155 public boolean isPostingPermitted() {
156 return permitPosting;
158 public void setPostingPermitted(boolean permitPosting) {
159 this.permitPosting = permitPosting;
161 public String getUuid() {
164 public String getName() {
167 public void setName(CharSequence text) {
168 setName(String.valueOf(text));
170 public void setName(String name) {
173 public String getUrl() {
176 public void setUrl(CharSequence text) {
177 setUrl(String.valueOf(text));
179 public void setUrl(String url) {
182 public boolean isAuthEnabled() {
185 public void setAuthEnabled(boolean authEnabled) {
186 this.authEnabled = authEnabled;
188 public String getAuthUserName() {
191 public void setAuthUserName(CharSequence text) {
192 setAuthUserName(String.valueOf(text));
194 public void setAuthUserName(String authUserName) {
195 this.authUserName = authUserName;
197 public String getAuthPassword() {
200 public void setAuthPassword(CharSequence text) {
201 setAuthPassword(String.valueOf(text));
203 public void setAuthPassword(String authPassword) {
204 this.authPassword = authPassword;
206 public void storeInDB() {
207 SQLiteDatabase db = App.getDatabase();
208 db.beginTransactionNonExclusive();
210 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
211 // "url=%s, permit_posting=%s, authEnabled=%s, " +
212 // "themeHue=%d", uuid, name, url,
213 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeHue));
214 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
215 "use_authentication, auth_user, " +
216 "auth_password, theme, order_no, preferred_accounts_filter, future_dates, " +
217 "api_version) " + "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
218 new Object[]{uuid, name, permitPosting, url, authEnabled,
219 authEnabled ? authUserName : null,
220 authEnabled ? authPassword : null, themeHue, orderNo,
221 preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt()
223 db.setTransactionSuccessful();
229 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
230 // replace into is a bad idea because it would reset hidden to its default value
231 // we like the default, but for new accounts only
232 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
233 "where profile=? and name = ?",
234 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
237 db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, hidden, " +
238 "expanded, keep) " + "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
239 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
240 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
242 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
244 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
245 db.execSQL("replace into account_values(profile, account, " +
246 "currency, value, keep) values(?, ?, ?, ?, 1);",
247 new Object[]{uuid, name, Misc.emptyIsNull(currency), amount});
249 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
251 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
252 new Object[]{uuid, tr.getId()});
253 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
254 new Object[]{uuid, tr.getId()});
256 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
257 "values(?,?,?,?,?,1)",
258 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
259 tr.getDescription(), tr.getDataHash()
262 for (LedgerTransactionAccount item : tr.getAccounts()) {
263 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
264 "account_name, amount, currency, comment) values(?, ?, ?, ?, ?, ?)",
265 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
266 Misc.nullIsEmpty(item.getCurrency()), item.getComment()
269 // debug("profile", String.format("Transaction %d stored", tr.getId()));
271 public String getOption(String name, String default_value) {
272 SQLiteDatabase db = App.getDatabase();
273 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
274 new String[]{uuid, name}))
276 if (cursor.moveToFirst()) {
277 String result = cursor.getString(0);
279 if (result == null) {
280 debug("profile", "returning default value for " + name);
281 result = default_value;
284 debug("profile", String.format("option %s=%s", name, result));
289 return default_value;
291 catch (Exception e) {
292 debug("db", "returning default value for " + name, e);
293 return default_value;
296 public long getLongOption(String name, long default_value) {
298 String result = getOption(name, "");
299 if ((result == null) || result.isEmpty()) {
300 debug("profile", String.format("Returning default value for option %s", name));
301 longResult = default_value;
305 longResult = Long.parseLong(result);
306 debug("profile", String.format("option %s=%s", name, result));
308 catch (Exception e) {
309 debug("profile", String.format("Returning default value for option %s", name), e);
310 longResult = default_value;
316 public void setOption(String name, String value) {
317 debug("profile", String.format("setting option %s=%s", name, value));
318 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
319 new String[]{uuid, name, value});
321 public void setLongOption(String name, long value) {
322 setOption(name, String.valueOf(value));
324 public void removeFromDB() {
325 SQLiteDatabase db = App.getDatabase();
326 debug("db", String.format("removing profile %s from DB", uuid));
327 db.beginTransactionNonExclusive();
329 Object[] uuid_param = new Object[]{uuid};
330 db.execSQL("delete from profiles where uuid=?", uuid_param);
331 db.execSQL("delete from accounts where profile=?", uuid_param);
332 db.execSQL("delete from account_values where profile=?", uuid_param);
333 db.execSQL("delete from transactions where profile=?", uuid_param);
334 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
335 db.execSQL("delete from options where profile=?", uuid_param);
336 db.setTransactionSuccessful();
343 public LedgerAccount loadAccount(String name) {
344 SQLiteDatabase db = App.getDatabase();
345 return loadAccount(db, name);
348 public LedgerAccount tryLoadAccount(String acct_name) {
349 SQLiteDatabase db = App.getDatabase();
350 return tryLoadAccount(db, acct_name);
353 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
354 LedgerAccount acc = tryLoadAccount(db, accName);
357 throw new RuntimeException("Unable to load account with name " + accName);
362 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
363 try (Cursor cursor = db.rawQuery(
364 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
365 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
366 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
368 if (cursor.moveToFirst()) {
369 LedgerAccount acc = new LedgerAccount(accName);
370 acc.setHiddenByStar(cursor.getInt(0) == 1);
371 acc.setExpanded(cursor.getInt(1) == 1);
372 acc.setHasSubAccounts(cursor.getInt(2) == 1);
374 try (Cursor c2 = db.rawQuery(
375 "SELECT value, currency FROM account_values WHERE profile = ? " +
376 "AND account = ?", new String[]{uuid, accName}))
378 while (c2.moveToNext()) {
379 acc.addAmount(c2.getFloat(0), c2.getString(1));
388 public LedgerTransaction loadTransaction(int transactionId) {
389 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
390 tr.loadData(App.getDatabase());
394 public int getThemeHue() {
395 // debug("profile", String.format("Profile.getThemeHue() returning %d", themeHue));
396 return this.themeHue;
398 public void setThemeHue(Object o) {
399 setThemeId(Integer.valueOf(String.valueOf(o)));
401 public void setThemeId(int themeHue) {
402 // debug("profile", String.format("Profile.setThemeHue(%d) called", themeHue));
403 this.themeHue = themeHue;
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 List<Currency> getCurrencies() {
493 SQLiteDatabase db = App.getDatabase();
495 ArrayList<Currency> result = new ArrayList<>();
497 try (Cursor c = db.rawQuery("SELECT c.id, c.name, c.position, c.has_gap FROM currencies c",
500 while (c.moveToNext()) {
501 Currency currency = new Currency(c.getInt(0), c.getString(1),
502 Currency.Position.valueOf(c.getInt(2)), c.getInt(3) == 1);
503 result.add(currency);
509 public enum FutureDates {
510 None(0), OneWeek(7), TwoWeeks(14), OneMonth(30), TwoMonths(60), ThreeMonths(90),
511 SixMonths(180), OneYear(365), All(-1);
512 private static SparseArray<FutureDates> map = new SparseArray<>();
515 for (FutureDates item : FutureDates.values()) {
516 map.put(item.value, item);
521 FutureDates(int value) {
524 public static FutureDates valueOf(int i) {
525 return map.get(i, None);
530 public String getText(Resources resources) {
533 return resources.getString(R.string.future_dates_7);
535 return resources.getString(R.string.future_dates_14);
537 return resources.getString(R.string.future_dates_30);
539 return resources.getString(R.string.future_dates_60);
541 return resources.getString(R.string.future_dates_90);
543 return resources.getString(R.string.future_dates_180);
545 return resources.getString(R.string.future_dates_365);
547 return resources.getString(R.string.future_dates_all);
549 return resources.getString(R.string.future_dates_none);