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 boolean showCommodityByDefault;
50 private String defaultCommodity;
51 private String preferredAccountsFilter;
53 private boolean authEnabled;
54 private String authUserName;
55 private String authPassword;
57 private int orderNo = -1;
58 private FutureDates futureDates = FutureDates.None;
59 private SendTransactionTask.API apiVersion = SendTransactionTask.API.auto;
60 public MobileLedgerProfile() {
61 this.uuid = String.valueOf(UUID.randomUUID());
63 public MobileLedgerProfile(String uuid) {
66 public MobileLedgerProfile(MobileLedgerProfile origin) {
69 permitPosting = origin.permitPosting;
70 showCommodityByDefault = origin.showCommodityByDefault;
71 preferredAccountsFilter = origin.preferredAccountsFilter;
73 authEnabled = origin.authEnabled;
74 authUserName = origin.authUserName;
75 authPassword = origin.authPassword;
76 themeHue = origin.themeHue;
77 orderNo = origin.orderNo;
78 futureDates = origin.futureDates;
79 apiVersion = origin.apiVersion;
80 defaultCommodity = origin.defaultCommodity;
82 // loads all profiles into Data.profiles
83 // returns the profile with the given UUID
84 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
85 MobileLedgerProfile result = null;
86 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
87 SQLiteDatabase db = App.getDatabase();
88 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
89 "auth_password, permit_posting, theme, order_no, " +
90 "preferred_accounts_filter, future_dates, api_version, " +
91 "show_commodity_by_default, default_commodity FROM " +
92 "profiles order by order_no", null))
94 while (cursor.moveToNext()) {
95 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
96 item.setName(cursor.getString(1));
97 item.setUrl(cursor.getString(2));
98 item.setAuthEnabled(cursor.getInt(3) == 1);
99 item.setAuthUserName(cursor.getString(4));
100 item.setAuthPassword(cursor.getString(5));
101 item.setPostingPermitted(cursor.getInt(6) == 1);
102 item.setThemeId(cursor.getInt(7));
103 item.orderNo = cursor.getInt(8);
104 item.setPreferredAccountsFilter(cursor.getString(9));
105 item.setFutureDates(cursor.getInt(10));
106 item.setApiVersion(cursor.getInt(11));
107 item.setShowCommodityByDefault(cursor.getInt(12) == 1);
108 item.setDefaultCommodity(cursor.getString(13));
111 .equals(currentProfileUUID))
115 Data.profiles.setValue(list);
118 public static void storeProfilesOrder() {
119 SQLiteDatabase db = App.getDatabase();
120 db.beginTransactionNonExclusive();
123 for (MobileLedgerProfile p : Data.profiles.getValue()) {
124 db.execSQL("update profiles set order_no=? where uuid=?",
125 new Object[]{orderNo, p.getUuid()});
129 db.setTransactionSuccessful();
135 public boolean getShowCommodityByDefault() {
136 return showCommodityByDefault;
138 public void setShowCommodityByDefault(boolean showCommodityByDefault) {
139 this.showCommodityByDefault = showCommodityByDefault;
141 public String getDefaultCommodity() {
142 return defaultCommodity;
144 public void setDefaultCommodity(String defaultCommodity) {
145 this.defaultCommodity = defaultCommodity;
147 public void setDefaultCommodity(CharSequence defaultCommodity) {
148 if (defaultCommodity == null)
149 this.defaultCommodity = null;
151 this.defaultCommodity = String.valueOf(defaultCommodity);
153 public SendTransactionTask.API getApiVersion() {
156 public void setApiVersion(SendTransactionTask.API apiVersion) {
157 this.apiVersion = apiVersion;
159 public void setApiVersion(int apiVersion) {
160 this.apiVersion = SendTransactionTask.API.valueOf(apiVersion);
162 public FutureDates getFutureDates() {
165 public void setFutureDates(int anInt) {
166 futureDates = FutureDates.valueOf(anInt);
168 public void setFutureDates(FutureDates futureDates) {
169 this.futureDates = futureDates;
171 public String getPreferredAccountsFilter() {
172 return preferredAccountsFilter;
174 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
175 this.preferredAccountsFilter = preferredAccountsFilter;
177 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
178 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
180 public boolean isPostingPermitted() {
181 return permitPosting;
183 public void setPostingPermitted(boolean permitPosting) {
184 this.permitPosting = permitPosting;
186 public String getUuid() {
189 public String getName() {
192 public void setName(CharSequence text) {
193 setName(String.valueOf(text));
195 public void setName(String name) {
198 public String getUrl() {
201 public void setUrl(CharSequence text) {
202 setUrl(String.valueOf(text));
204 public void setUrl(String url) {
207 public boolean isAuthEnabled() {
210 public void setAuthEnabled(boolean authEnabled) {
211 this.authEnabled = authEnabled;
213 public String getAuthUserName() {
216 public void setAuthUserName(CharSequence text) {
217 setAuthUserName(String.valueOf(text));
219 public void setAuthUserName(String authUserName) {
220 this.authUserName = authUserName;
222 public String getAuthPassword() {
225 public void setAuthPassword(CharSequence text) {
226 setAuthPassword(String.valueOf(text));
228 public void setAuthPassword(String authPassword) {
229 this.authPassword = authPassword;
231 public void storeInDB() {
232 SQLiteDatabase db = App.getDatabase();
233 db.beginTransactionNonExclusive();
235 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
236 // "url=%s, permit_posting=%s, authEnabled=%s, " +
237 // "themeHue=%d", uuid, name, url,
238 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeHue));
239 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
240 "use_authentication, auth_user, auth_password, theme, order_no, " +
241 "preferred_accounts_filter, future_dates, api_version, " +
242 "show_commodity_by_default, default_commodity) " +
243 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
244 new Object[]{uuid, name, permitPosting, url, authEnabled,
245 authEnabled ? authUserName : null,
246 authEnabled ? authPassword : null, themeHue, orderNo,
247 preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt(),
248 showCommodityByDefault, defaultCommodity
250 db.setTransactionSuccessful();
256 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
257 // replace into is a bad idea because it would reset hidden to its default value
258 // we like the default, but for new accounts only
259 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
260 "where profile=? and name = ?",
261 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
264 db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, hidden, " +
265 "expanded, keep) " + "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
266 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
267 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
269 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
271 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
272 db.execSQL("replace into account_values(profile, account, " +
273 "currency, value, keep) values(?, ?, ?, ?, 1);",
274 new Object[]{uuid, name, Misc.emptyIsNull(currency), amount});
276 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
278 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
279 new Object[]{uuid, tr.getId()});
280 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
281 new Object[]{uuid, tr.getId()});
283 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
284 "values(?,?,?,?,?,1)",
285 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
286 tr.getDescription(), tr.getDataHash()
289 for (LedgerTransactionAccount item : tr.getAccounts()) {
290 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
291 "account_name, amount, currency, comment) values(?, ?, ?, ?, ?, ?)",
292 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
293 Misc.nullIsEmpty(item.getCurrency()), item.getComment()
296 // debug("profile", String.format("Transaction %d stored", tr.getId()));
298 public String getOption(String name, String default_value) {
299 SQLiteDatabase db = App.getDatabase();
300 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
301 new String[]{uuid, name}))
303 if (cursor.moveToFirst()) {
304 String result = cursor.getString(0);
306 if (result == null) {
307 debug("profile", "returning default value for " + name);
308 result = default_value;
311 debug("profile", String.format("option %s=%s", name, result));
316 return default_value;
318 catch (Exception e) {
319 debug("db", "returning default value for " + name, e);
320 return default_value;
323 public long getLongOption(String name, long default_value) {
325 String result = getOption(name, "");
326 if ((result == null) || result.isEmpty()) {
327 debug("profile", String.format("Returning default value for option %s", name));
328 longResult = default_value;
332 longResult = Long.parseLong(result);
333 debug("profile", String.format("option %s=%s", name, result));
335 catch (Exception e) {
336 debug("profile", String.format("Returning default value for option %s", name), e);
337 longResult = default_value;
343 public void setOption(String name, String value) {
344 debug("profile", String.format("setting option %s=%s", name, value));
345 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
346 new String[]{uuid, name, value});
348 public void setLongOption(String name, long value) {
349 setOption(name, String.valueOf(value));
351 public void removeFromDB() {
352 SQLiteDatabase db = App.getDatabase();
353 debug("db", String.format("removing profile %s from DB", uuid));
354 db.beginTransactionNonExclusive();
356 Object[] uuid_param = new Object[]{uuid};
357 db.execSQL("delete from profiles where uuid=?", uuid_param);
358 db.execSQL("delete from accounts where profile=?", uuid_param);
359 db.execSQL("delete from account_values where profile=?", uuid_param);
360 db.execSQL("delete from transactions where profile=?", uuid_param);
361 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
362 db.execSQL("delete from options where profile=?", uuid_param);
363 db.setTransactionSuccessful();
370 public LedgerAccount loadAccount(String name) {
371 SQLiteDatabase db = App.getDatabase();
372 return loadAccount(db, name);
375 public LedgerAccount tryLoadAccount(String acct_name) {
376 SQLiteDatabase db = App.getDatabase();
377 return tryLoadAccount(db, acct_name);
380 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
381 LedgerAccount acc = tryLoadAccount(db, accName);
384 throw new RuntimeException("Unable to load account with name " + accName);
389 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
390 try (Cursor cursor = db.rawQuery(
391 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
392 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
393 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
395 if (cursor.moveToFirst()) {
396 LedgerAccount acc = new LedgerAccount(accName);
397 acc.setHiddenByStar(cursor.getInt(0) == 1);
398 acc.setExpanded(cursor.getInt(1) == 1);
399 acc.setHasSubAccounts(cursor.getInt(2) == 1);
401 try (Cursor c2 = db.rawQuery(
402 "SELECT value, currency FROM account_values WHERE profile = ? " +
403 "AND account = ?", new String[]{uuid, accName}))
405 while (c2.moveToNext()) {
406 acc.addAmount(c2.getFloat(0), c2.getString(1));
415 public LedgerTransaction loadTransaction(int transactionId) {
416 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
417 tr.loadData(App.getDatabase());
421 public int getThemeHue() {
422 // debug("profile", String.format("Profile.getThemeHue() returning %d", themeHue));
423 return this.themeHue;
425 public void setThemeHue(Object o) {
426 setThemeId(Integer.parseInt(String.valueOf(o)));
428 public void setThemeId(int themeHue) {
429 // debug("profile", String.format("Profile.setThemeHue(%d) called", themeHue));
430 this.themeHue = themeHue;
432 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
433 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
436 public void markAccountsAsNotPresent(SQLiteDatabase db) {
437 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
438 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
441 public void deleteNotPresentAccounts(SQLiteDatabase db) {
442 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
443 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
445 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
446 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
447 new Object[]{uuid, transaction.getId()
450 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
451 LedgerTransaction transaction) {
452 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
453 new Object[]{uuid, transaction.getId()
457 public void deleteNotPresentTransactions(SQLiteDatabase db) {
458 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
460 public void setLastUpdateStamp() {
461 debug("db", "Updating transaction value stamp");
462 Date now = new Date();
463 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
464 Data.lastUpdateDate.postValue(now);
466 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
467 List<LedgerAccount> result = new ArrayList<>();
468 SQLiteDatabase db = App.getDatabase();
469 try (Cursor c = db.rawQuery(
470 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
471 new String[]{uuid, acc.getName()}))
473 while (c.moveToNext()) {
474 LedgerAccount a = loadAccount(db, c.getString(0));
481 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
482 List<LedgerAccount> result = new ArrayList<>();
483 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
484 visibleList.add(acc);
486 SQLiteDatabase db = App.getDatabase();
487 try (Cursor c = db.rawQuery(
488 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
489 new String[]{uuid, acc.getName()}))
491 while (c.moveToNext()) {
492 LedgerAccount a = loadAccount(db, c.getString(0));
493 if (a.isVisible(visibleList)) {
502 public void wipeAllData() {
503 SQLiteDatabase db = App.getDatabase();
504 db.beginTransaction();
506 String[] pUuid = new String[]{uuid};
507 db.execSQL("delete from options where profile=?", pUuid);
508 db.execSQL("delete from accounts where profile=?", pUuid);
509 db.execSQL("delete from account_values where profile=?", pUuid);
510 db.execSQL("delete from transactions where profile=?", pUuid);
511 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
512 db.setTransactionSuccessful();
513 Logger.debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
519 public List<Currency> getCurrencies() {
520 SQLiteDatabase db = App.getDatabase();
522 ArrayList<Currency> result = new ArrayList<>();
524 try (Cursor c = db.rawQuery("SELECT c.id, c.name, c.position, c.has_gap FROM currencies c",
527 while (c.moveToNext()) {
528 Currency currency = new Currency(c.getInt(0), c.getString(1),
529 Currency.Position.valueOf(c.getInt(2)), c.getInt(3) == 1);
530 result.add(currency);
536 Currency loadCurrencyByName(String name) {
537 SQLiteDatabase db = App.getDatabase();
538 Currency result = tryLoadCurrencyByName(db, name);
540 throw new RuntimeException(String.format("Unable to load currency '%s'", name));
543 private Currency tryLoadCurrencyByName(SQLiteDatabase db, String name) {
544 try (Cursor cursor = db.rawQuery(
545 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.name=?",
548 if (cursor.moveToFirst()) {
549 return new Currency(cursor.getInt(0), cursor.getString(1),
550 Currency.Position.valueOf(cursor.getInt(2)), cursor.getInt(3) == 1);
555 public enum FutureDates {
556 None(0), OneWeek(7), TwoWeeks(14), OneMonth(30), TwoMonths(60), ThreeMonths(90),
557 SixMonths(180), OneYear(365), All(-1);
558 private static SparseArray<FutureDates> map = new SparseArray<>();
561 for (FutureDates item : FutureDates.values()) {
562 map.put(item.value, item);
567 FutureDates(int value) {
570 public static FutureDates valueOf(int i) {
571 return map.get(i, None);
576 public String getText(Resources resources) {
579 return resources.getString(R.string.future_dates_7);
581 return resources.getString(R.string.future_dates_14);
583 return resources.getString(R.string.future_dates_30);
585 return resources.getString(R.string.future_dates_60);
587 return resources.getString(R.string.future_dates_90);
589 return resources.getString(R.string.future_dates_180);
591 return resources.getString(R.string.future_dates_365);
593 return resources.getString(R.string.future_dates_all);
595 return resources.getString(R.string.future_dates_none);