2 * Copyright © 2020 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;
27 import androidx.lifecycle.LiveData;
28 import androidx.lifecycle.MutableLiveData;
30 import net.ktnx.mobileledger.App;
31 import net.ktnx.mobileledger.R;
32 import net.ktnx.mobileledger.async.DbOpQueue;
33 import net.ktnx.mobileledger.async.SendTransactionTask;
34 import net.ktnx.mobileledger.utils.Logger;
35 import net.ktnx.mobileledger.utils.MLDB;
36 import net.ktnx.mobileledger.utils.Misc;
38 import java.util.ArrayList;
39 import java.util.Calendar;
40 import java.util.Date;
41 import java.util.List;
42 import java.util.Locale;
43 import java.util.UUID;
45 import static net.ktnx.mobileledger.utils.Logger.debug;
47 public final class MobileLedgerProfile {
48 // N.B. when adding new fields, update the copy-constructor below
51 private boolean permitPosting;
52 private boolean showCommentsByDefault;
53 private boolean showCommodityByDefault;
54 private String defaultCommodity;
55 private String preferredAccountsFilter;
57 private boolean authEnabled;
58 private String authUserName;
59 private String authPassword;
61 private int orderNo = -1;
62 // N.B. when adding new fields, update the copy-constructor below
63 private FutureDates futureDates = FutureDates.None;
64 private SendTransactionTask.API apiVersion = SendTransactionTask.API.auto;
65 private Calendar firstTransactionDate;
66 private Calendar lastTransactionDate;
67 private MutableLiveData<ArrayList<LedgerAccount>> accounts =
68 new MutableLiveData<>(new ArrayList<>());
69 private AccountListLoader loader = null;
70 public MobileLedgerProfile() {
71 this.uuid = String.valueOf(UUID.randomUUID());
73 public MobileLedgerProfile(String uuid) {
76 public MobileLedgerProfile(MobileLedgerProfile origin) {
79 permitPosting = origin.permitPosting;
80 showCommentsByDefault = origin.showCommentsByDefault;
81 showCommodityByDefault = origin.showCommodityByDefault;
82 preferredAccountsFilter = origin.preferredAccountsFilter;
84 authEnabled = origin.authEnabled;
85 authUserName = origin.authUserName;
86 authPassword = origin.authPassword;
87 themeHue = origin.themeHue;
88 orderNo = origin.orderNo;
89 futureDates = origin.futureDates;
90 apiVersion = origin.apiVersion;
91 defaultCommodity = origin.defaultCommodity;
92 firstTransactionDate = origin.firstTransactionDate;
93 lastTransactionDate = origin.lastTransactionDate;
95 // loads all profiles into Data.profiles
96 // returns the profile with the given UUID
97 public static MobileLedgerProfile loadAllFromDB(@Nullable String currentProfileUUID) {
98 MobileLedgerProfile result = null;
99 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
100 SQLiteDatabase db = App.getDatabase();
101 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
102 "auth_password, permit_posting, theme, order_no, " +
103 "preferred_accounts_filter, future_dates, api_version, " +
104 "show_commodity_by_default, default_commodity, " +
105 "show_comments_by_default FROM " +
106 "profiles order by order_no", null))
108 while (cursor.moveToNext()) {
109 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
110 item.setName(cursor.getString(1));
111 item.setUrl(cursor.getString(2));
112 item.setAuthEnabled(cursor.getInt(3) == 1);
113 item.setAuthUserName(cursor.getString(4));
114 item.setAuthPassword(cursor.getString(5));
115 item.setPostingPermitted(cursor.getInt(6) == 1);
116 item.setThemeId(cursor.getInt(7));
117 item.orderNo = cursor.getInt(8);
118 item.setPreferredAccountsFilter(cursor.getString(9));
119 item.setFutureDates(cursor.getInt(10));
120 item.setApiVersion(cursor.getInt(11));
121 item.setShowCommodityByDefault(cursor.getInt(12) == 1);
122 item.setDefaultCommodity(cursor.getString(13));
123 item.setShowCommentsByDefault(cursor.getInt(14) == 1);
126 .equals(currentProfileUUID))
130 Data.profiles.setValue(list);
133 public static void storeProfilesOrder() {
134 SQLiteDatabase db = App.getDatabase();
135 db.beginTransactionNonExclusive();
138 for (MobileLedgerProfile p : Data.profiles.getValue()) {
139 db.execSQL("update profiles set order_no=? where uuid=?",
140 new Object[]{orderNo, p.getUuid()});
144 db.setTransactionSuccessful();
150 public LiveData<ArrayList<LedgerAccount>> getAccounts() {
153 synchronized public void scheduleAccountListReload() {
154 Logger.debug("async-acc", "scheduleAccountListReload() enter");
155 if ((loader != null) && loader.isAlive()) {
156 Logger.debug("async-acc", "returning early - loader already active");
160 Logger.debug("async-acc", "Starting AccountListLoader");
161 loader = new AccountListLoader(this);
164 synchronized public void abortAccountListReload() {
170 public boolean getShowCommentsByDefault() {
171 return showCommentsByDefault;
173 public void setShowCommentsByDefault(boolean newValue) {
174 this.showCommentsByDefault = newValue;
176 public boolean getShowCommodityByDefault() {
177 return showCommodityByDefault;
179 public void setShowCommodityByDefault(boolean showCommodityByDefault) {
180 this.showCommodityByDefault = showCommodityByDefault;
182 public String getDefaultCommodity() {
183 return defaultCommodity;
185 public void setDefaultCommodity(String defaultCommodity) {
186 this.defaultCommodity = defaultCommodity;
188 public void setDefaultCommodity(CharSequence defaultCommodity) {
189 if (defaultCommodity == null)
190 this.defaultCommodity = null;
192 this.defaultCommodity = String.valueOf(defaultCommodity);
194 public SendTransactionTask.API getApiVersion() {
197 public void setApiVersion(SendTransactionTask.API apiVersion) {
198 this.apiVersion = apiVersion;
200 public void setApiVersion(int apiVersion) {
201 this.apiVersion = SendTransactionTask.API.valueOf(apiVersion);
203 public FutureDates getFutureDates() {
206 public void setFutureDates(int anInt) {
207 futureDates = FutureDates.valueOf(anInt);
209 public void setFutureDates(FutureDates futureDates) {
210 this.futureDates = futureDates;
212 public String getPreferredAccountsFilter() {
213 return preferredAccountsFilter;
215 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
216 this.preferredAccountsFilter = preferredAccountsFilter;
218 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
219 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
221 public boolean isPostingPermitted() {
222 return permitPosting;
224 public void setPostingPermitted(boolean permitPosting) {
225 this.permitPosting = permitPosting;
227 public String getUuid() {
230 public String getName() {
233 public void setName(CharSequence text) {
234 setName(String.valueOf(text));
236 public void setName(String name) {
239 public String getUrl() {
242 public void setUrl(CharSequence text) {
243 setUrl(String.valueOf(text));
245 public void setUrl(String url) {
248 public boolean isAuthEnabled() {
251 public void setAuthEnabled(boolean authEnabled) {
252 this.authEnabled = authEnabled;
254 public String getAuthUserName() {
257 public void setAuthUserName(CharSequence text) {
258 setAuthUserName(String.valueOf(text));
260 public void setAuthUserName(String authUserName) {
261 this.authUserName = authUserName;
263 public String getAuthPassword() {
266 public void setAuthPassword(CharSequence text) {
267 setAuthPassword(String.valueOf(text));
269 public void setAuthPassword(String authPassword) {
270 this.authPassword = authPassword;
272 public void storeInDB() {
273 SQLiteDatabase db = App.getDatabase();
274 db.beginTransactionNonExclusive();
276 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
277 // "url=%s, permit_posting=%s, authEnabled=%s, " +
278 // "themeHue=%d", uuid, name, url,
279 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeHue));
280 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
281 "use_authentication, auth_user, auth_password, theme, order_no, " +
282 "preferred_accounts_filter, future_dates, api_version, " +
283 "show_commodity_by_default, default_commodity, show_comments_by_default) " +
284 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
285 new Object[]{uuid, name, permitPosting, url, authEnabled,
286 authEnabled ? authUserName : null,
287 authEnabled ? authPassword : null, themeHue, orderNo,
288 preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt(),
289 showCommodityByDefault, defaultCommodity, showCommentsByDefault
291 db.setTransactionSuccessful();
297 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
298 // replace into is a bad idea because it would reset hidden to its default value
299 // we like the default, but for new accounts only
300 db.execSQL("update accounts set level = ?, keep = 1, expanded=? " +
301 "where profile=? and name = ?",
302 new Object[]{acc.getLevel(), acc.isExpanded(), uuid, acc.getName()
304 db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, " +
305 "expanded, keep) " + "select ?,?,?,?,?,?,1 where (select changes() = 0)",
306 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
307 acc.getLevel(), acc.isExpanded()
309 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
311 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
312 db.execSQL("replace into account_values(profile, account, " +
313 "currency, value, keep) values(?, ?, ?, ?, 1);",
314 new Object[]{uuid, name, Misc.emptyIsNull(currency), amount});
316 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
318 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
319 new Object[]{uuid, tr.getId()});
320 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
321 new Object[]{uuid, tr.getId()});
323 db.execSQL("INSERT INTO transactions(profile, id, year, month, day, description, " +
324 "comment, data_hash, keep) values(?,?,?,?,?,?,?,?,1)",
325 new Object[]{uuid, tr.getId(), tr.getDate().year, tr.getDate().month,
326 tr.getDate().day, tr.getDescription(), tr.getComment(),
330 for (LedgerTransactionAccount item : tr.getAccounts()) {
331 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
332 "account_name, amount, currency, comment) values(?, ?, ?, ?, ?, ?)",
333 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
334 Misc.nullIsEmpty(item.getCurrency()), item.getComment()
337 // debug("profile", String.format("Transaction %d stored", tr.getId()));
339 public String getOption(String name, String default_value) {
340 SQLiteDatabase db = App.getDatabase();
341 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
342 new String[]{uuid, name}))
344 if (cursor.moveToFirst()) {
345 String result = cursor.getString(0);
347 if (result == null) {
348 debug("profile", "returning default value for " + name);
349 result = default_value;
352 debug("profile", String.format("option %s=%s", name, result));
357 return default_value;
359 catch (Exception e) {
360 debug("db", "returning default value for " + name, e);
361 return default_value;
364 public long getLongOption(String name, long default_value) {
366 String result = getOption(name, "");
367 if ((result == null) || result.isEmpty()) {
368 debug("profile", String.format("Returning default value for option %s", name));
369 longResult = default_value;
373 longResult = Long.parseLong(result);
374 debug("profile", String.format("option %s=%s", name, result));
376 catch (Exception e) {
377 debug("profile", String.format("Returning default value for option %s", name), e);
378 longResult = default_value;
384 public void setOption(String name, String value) {
385 debug("profile", String.format("setting option %s=%s", name, value));
386 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
387 new String[]{uuid, name, value});
389 public void setLongOption(String name, long value) {
390 setOption(name, String.valueOf(value));
392 public void removeFromDB() {
393 SQLiteDatabase db = App.getDatabase();
394 debug("db", String.format("removing profile %s from DB", uuid));
395 db.beginTransactionNonExclusive();
397 Object[] uuid_param = new Object[]{uuid};
398 db.execSQL("delete from profiles where uuid=?", uuid_param);
399 db.execSQL("delete from accounts where profile=?", uuid_param);
400 db.execSQL("delete from account_values where profile=?", uuid_param);
401 db.execSQL("delete from transactions where profile=?", uuid_param);
402 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
403 db.execSQL("delete from options where profile=?", uuid_param);
404 db.setTransactionSuccessful();
411 public LedgerAccount loadAccount(String name) {
412 SQLiteDatabase db = App.getDatabase();
413 return loadAccount(db, name);
416 public LedgerAccount tryLoadAccount(String acct_name) {
417 SQLiteDatabase db = App.getDatabase();
418 return tryLoadAccount(db, acct_name);
421 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
422 LedgerAccount acc = tryLoadAccount(db, accName);
425 throw new RuntimeException("Unable to load account with name " + accName);
430 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
431 try (Cursor cursor = db.rawQuery("SELECT a.expanded, a.amounts_expanded, (select 1 from accounts a2 " +
432 "where a2.profile = a.profile and a2.name like a" +
433 ".name||':%' limit 1) " +
434 "FROM accounts a WHERE a.profile = ? and a.name=?",
435 new String[]{uuid, accName}))
437 if (cursor.moveToFirst()) {
438 LedgerAccount acc = new LedgerAccount(this, accName);
439 acc.setExpanded(cursor.getInt(0) == 1);
440 acc.setAmountsExpanded(cursor.getInt(1) == 1);
441 acc.setHasSubAccounts(cursor.getInt(2) == 1);
443 try (Cursor c2 = db.rawQuery(
444 "SELECT value, currency FROM account_values WHERE profile = ? " +
445 "AND account = ?", new String[]{uuid, accName}))
447 while (c2.moveToNext()) {
448 acc.addAmount(c2.getFloat(0), c2.getString(1));
457 public LedgerTransaction loadTransaction(int transactionId) {
458 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
459 tr.loadData(App.getDatabase());
463 public int getThemeHue() {
464 // debug("profile", String.format("Profile.getThemeHue() returning %d", themeHue));
465 return this.themeHue;
467 public void setThemeHue(Object o) {
468 setThemeId(Integer.parseInt(String.valueOf(o)));
470 public void setThemeId(int themeHue) {
471 // debug("profile", String.format("Profile.setThemeHue(%d) called", themeHue));
472 this.themeHue = themeHue;
474 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
475 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
478 public void markAccountsAsNotPresent(SQLiteDatabase db) {
479 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
480 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
483 public void deleteNotPresentAccounts(SQLiteDatabase db) {
484 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
485 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
487 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
488 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
489 new Object[]{uuid, transaction.getId()
492 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
493 LedgerTransaction transaction) {
494 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
495 new Object[]{uuid, transaction.getId()
499 public void deleteNotPresentTransactions(SQLiteDatabase db) {
500 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
502 public void setLastUpdateStamp() {
503 debug("db", "Updating transaction value stamp");
504 Date now = new Date();
505 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
506 Data.lastUpdateDate.postValue(now);
508 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
509 List<LedgerAccount> result = new ArrayList<>();
510 SQLiteDatabase db = App.getDatabase();
511 try (Cursor c = db.rawQuery(
512 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
513 new String[]{uuid, acc.getName()}))
515 while (c.moveToNext()) {
516 LedgerAccount a = loadAccount(db, c.getString(0));
523 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
524 List<LedgerAccount> result = new ArrayList<>();
525 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
526 visibleList.add(acc);
528 SQLiteDatabase db = App.getDatabase();
529 try (Cursor c = db.rawQuery(
530 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
531 new String[]{uuid, acc.getName()}))
533 while (c.moveToNext()) {
534 LedgerAccount a = loadAccount(db, c.getString(0));
535 if (a.isVisible(visibleList)) {
544 public void wipeAllData() {
545 SQLiteDatabase db = App.getDatabase();
546 db.beginTransaction();
548 String[] pUuid = new String[]{uuid};
549 db.execSQL("delete from options where profile=?", pUuid);
550 db.execSQL("delete from accounts where profile=?", pUuid);
551 db.execSQL("delete from account_values where profile=?", pUuid);
552 db.execSQL("delete from transactions where profile=?", pUuid);
553 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
554 db.setTransactionSuccessful();
555 debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
561 public List<Currency> getCurrencies() {
562 SQLiteDatabase db = App.getDatabase();
564 ArrayList<Currency> result = new ArrayList<>();
566 try (Cursor c = db.rawQuery("SELECT c.id, c.name, c.position, c.has_gap FROM currencies c",
569 while (c.moveToNext()) {
570 Currency currency = new Currency(c.getInt(0), c.getString(1),
571 Currency.Position.valueOf(c.getInt(2)), c.getInt(3) == 1);
572 result.add(currency);
578 Currency loadCurrencyByName(String name) {
579 SQLiteDatabase db = App.getDatabase();
580 Currency result = tryLoadCurrencyByName(db, name);
582 throw new RuntimeException(String.format("Unable to load currency '%s'", name));
585 private Currency tryLoadCurrencyByName(SQLiteDatabase db, String name) {
586 try (Cursor cursor = db.rawQuery(
587 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.name=?",
590 if (cursor.moveToFirst()) {
591 return new Currency(cursor.getInt(0), cursor.getString(1),
592 Currency.Position.valueOf(cursor.getInt(2)), cursor.getInt(3) == 1);
597 public Calendar getFirstTransactionDate() {
598 return firstTransactionDate;
600 public Calendar getLastTransactionDate() {
601 return lastTransactionDate;
603 public void setAccounts(ArrayList<LedgerAccount> list) {
604 accounts.postValue(list);
606 public enum FutureDates {
607 None(0), OneWeek(7), TwoWeeks(14), OneMonth(30), TwoMonths(60), ThreeMonths(90),
608 SixMonths(180), OneYear(365), All(-1);
609 private static SparseArray<FutureDates> map = new SparseArray<>();
612 for (FutureDates item : FutureDates.values()) {
613 map.put(item.value, item);
618 FutureDates(int value) {
621 public static FutureDates valueOf(int i) {
622 return map.get(i, None);
627 public String getText(Resources resources) {
630 return resources.getString(R.string.future_dates_7);
632 return resources.getString(R.string.future_dates_14);
634 return resources.getString(R.string.future_dates_30);
636 return resources.getString(R.string.future_dates_60);
638 return resources.getString(R.string.future_dates_90);
640 return resources.getString(R.string.future_dates_180);
642 return resources.getString(R.string.future_dates_365);
644 return resources.getString(R.string.future_dates_all);
646 return resources.getString(R.string.future_dates_none);
651 static class AccountListLoader extends Thread {
652 MobileLedgerProfile profile;
653 AccountListLoader(MobileLedgerProfile profile) {
654 this.profile = profile;
658 Logger.debug("async-acc", "AccountListLoader::run() entered");
659 String profileUUID = profile.getUuid();
660 ArrayList<LedgerAccount> newList = new ArrayList<>();
662 String sql = "SELECT a.name from accounts a WHERE a.profile = ?";
663 sql += " ORDER BY a.name";
665 SQLiteDatabase db = App.getDatabase();
666 try (Cursor cursor = db.rawQuery(sql, new String[]{profileUUID})) {
667 while (cursor.moveToNext()) {
671 final String accName = cursor.getString(0);
673 // String.format("Read account '%s' from DB [%s]", accName,
675 LedgerAccount acc = profile.loadAccount(db, accName);
676 if (acc.isVisible(newList))
684 Logger.debug("async-acc", "AccountListLoader::run() posting new list");
685 profile.accounts.postValue(newList);