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 preferredAccountsFilter;
52 private boolean authEnabled;
53 private String authUserName;
54 private String authPassword;
56 private int orderNo = -1;
57 private FutureDates futureDates = FutureDates.None;
58 private SendTransactionTask.API apiVersion = SendTransactionTask.API.auto;
59 public MobileLedgerProfile() {
60 this.uuid = String.valueOf(UUID.randomUUID());
62 public MobileLedgerProfile(String uuid) {
65 public MobileLedgerProfile(MobileLedgerProfile origin) {
68 permitPosting = origin.permitPosting;
69 showCommodityByDefault = origin.showCommodityByDefault;
70 preferredAccountsFilter = origin.preferredAccountsFilter;
72 authEnabled = origin.authEnabled;
73 authUserName = origin.authUserName;
74 authPassword = origin.authPassword;
75 themeHue = origin.themeHue;
76 orderNo = origin.orderNo;
77 futureDates = origin.futureDates;
78 apiVersion = origin.apiVersion;
80 // loads all profiles into Data.profiles
81 // returns the profile with the given UUID
82 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
83 MobileLedgerProfile result = null;
84 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
85 SQLiteDatabase db = App.getDatabase();
86 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
87 "auth_password, permit_posting, theme, order_no, " +
88 "preferred_accounts_filter, future_dates, api_version, " +
89 "show_commodity_by_default FROM " +
90 "profiles order by order_no", null))
92 while (cursor.moveToNext()) {
93 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
94 item.setName(cursor.getString(1));
95 item.setUrl(cursor.getString(2));
96 item.setAuthEnabled(cursor.getInt(3) == 1);
97 item.setAuthUserName(cursor.getString(4));
98 item.setAuthPassword(cursor.getString(5));
99 item.setPostingPermitted(cursor.getInt(6) == 1);
100 item.setThemeId(cursor.getInt(7));
101 item.orderNo = cursor.getInt(8);
102 item.setPreferredAccountsFilter(cursor.getString(9));
103 item.setFutureDates(cursor.getInt(10));
104 item.setApiVersion(cursor.getInt(11));
105 item.setShowCommodityByDefault(cursor.getInt(12) == 1);
108 .equals(currentProfileUUID))
112 Data.profiles.setValue(list);
115 public static void storeProfilesOrder() {
116 SQLiteDatabase db = App.getDatabase();
117 db.beginTransactionNonExclusive();
120 for (MobileLedgerProfile p : Data.profiles.getValue()) {
121 db.execSQL("update profiles set order_no=? where uuid=?",
122 new Object[]{orderNo, p.getUuid()});
126 db.setTransactionSuccessful();
132 public boolean getShowCommodityByDefault() {
133 return showCommodityByDefault;
135 public void setShowCommodityByDefault(boolean showCommodityByDefault) {
136 this.showCommodityByDefault = showCommodityByDefault;
138 public SendTransactionTask.API getApiVersion() {
141 public void setApiVersion(SendTransactionTask.API apiVersion) {
142 this.apiVersion = apiVersion;
144 public void setApiVersion(int apiVersion) {
145 this.apiVersion = SendTransactionTask.API.valueOf(apiVersion);
147 public FutureDates getFutureDates() {
150 public void setFutureDates(int anInt) {
151 futureDates = FutureDates.valueOf(anInt);
153 public void setFutureDates(FutureDates futureDates) {
154 this.futureDates = futureDates;
156 public String getPreferredAccountsFilter() {
157 return preferredAccountsFilter;
159 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
160 this.preferredAccountsFilter = preferredAccountsFilter;
162 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
163 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
165 public boolean isPostingPermitted() {
166 return permitPosting;
168 public void setPostingPermitted(boolean permitPosting) {
169 this.permitPosting = permitPosting;
171 public String getUuid() {
174 public String getName() {
177 public void setName(CharSequence text) {
178 setName(String.valueOf(text));
180 public void setName(String name) {
183 public String getUrl() {
186 public void setUrl(CharSequence text) {
187 setUrl(String.valueOf(text));
189 public void setUrl(String url) {
192 public boolean isAuthEnabled() {
195 public void setAuthEnabled(boolean authEnabled) {
196 this.authEnabled = authEnabled;
198 public String getAuthUserName() {
201 public void setAuthUserName(CharSequence text) {
202 setAuthUserName(String.valueOf(text));
204 public void setAuthUserName(String authUserName) {
205 this.authUserName = authUserName;
207 public String getAuthPassword() {
210 public void setAuthPassword(CharSequence text) {
211 setAuthPassword(String.valueOf(text));
213 public void setAuthPassword(String authPassword) {
214 this.authPassword = authPassword;
216 public void storeInDB() {
217 SQLiteDatabase db = App.getDatabase();
218 db.beginTransactionNonExclusive();
220 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
221 // "url=%s, permit_posting=%s, authEnabled=%s, " +
222 // "themeHue=%d", uuid, name, url,
223 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeHue));
224 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
225 "use_authentication, auth_user, auth_password, theme, order_no, " +
226 "preferred_accounts_filter, future_dates, api_version, " +
227 "show_commodity_by_default) " +
228 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
229 new Object[]{uuid, name, permitPosting, url, authEnabled,
230 authEnabled ? authUserName : null,
231 authEnabled ? authPassword : null, themeHue, orderNo,
232 preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt(),
233 showCommodityByDefault
235 db.setTransactionSuccessful();
241 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
242 // replace into is a bad idea because it would reset hidden to its default value
243 // we like the default, but for new accounts only
244 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
245 "where profile=? and name = ?",
246 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
249 db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, hidden, " +
250 "expanded, keep) " + "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
251 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
252 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
254 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
256 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
257 db.execSQL("replace into account_values(profile, account, " +
258 "currency, value, keep) values(?, ?, ?, ?, 1);",
259 new Object[]{uuid, name, Misc.emptyIsNull(currency), amount});
261 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
263 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
264 new Object[]{uuid, tr.getId()});
265 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
266 new Object[]{uuid, tr.getId()});
268 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
269 "values(?,?,?,?,?,1)",
270 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
271 tr.getDescription(), tr.getDataHash()
274 for (LedgerTransactionAccount item : tr.getAccounts()) {
275 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
276 "account_name, amount, currency, comment) values(?, ?, ?, ?, ?, ?)",
277 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
278 Misc.nullIsEmpty(item.getCurrency()), item.getComment()
281 // debug("profile", String.format("Transaction %d stored", tr.getId()));
283 public String getOption(String name, String default_value) {
284 SQLiteDatabase db = App.getDatabase();
285 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
286 new String[]{uuid, name}))
288 if (cursor.moveToFirst()) {
289 String result = cursor.getString(0);
291 if (result == null) {
292 debug("profile", "returning default value for " + name);
293 result = default_value;
296 debug("profile", String.format("option %s=%s", name, result));
301 return default_value;
303 catch (Exception e) {
304 debug("db", "returning default value for " + name, e);
305 return default_value;
308 public long getLongOption(String name, long default_value) {
310 String result = getOption(name, "");
311 if ((result == null) || result.isEmpty()) {
312 debug("profile", String.format("Returning default value for option %s", name));
313 longResult = default_value;
317 longResult = Long.parseLong(result);
318 debug("profile", String.format("option %s=%s", name, result));
320 catch (Exception e) {
321 debug("profile", String.format("Returning default value for option %s", name), e);
322 longResult = default_value;
328 public void setOption(String name, String value) {
329 debug("profile", String.format("setting option %s=%s", name, value));
330 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
331 new String[]{uuid, name, value});
333 public void setLongOption(String name, long value) {
334 setOption(name, String.valueOf(value));
336 public void removeFromDB() {
337 SQLiteDatabase db = App.getDatabase();
338 debug("db", String.format("removing profile %s from DB", uuid));
339 db.beginTransactionNonExclusive();
341 Object[] uuid_param = new Object[]{uuid};
342 db.execSQL("delete from profiles where uuid=?", uuid_param);
343 db.execSQL("delete from accounts where profile=?", uuid_param);
344 db.execSQL("delete from account_values where profile=?", uuid_param);
345 db.execSQL("delete from transactions where profile=?", uuid_param);
346 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
347 db.execSQL("delete from options where profile=?", uuid_param);
348 db.setTransactionSuccessful();
355 public LedgerAccount loadAccount(String name) {
356 SQLiteDatabase db = App.getDatabase();
357 return loadAccount(db, name);
360 public LedgerAccount tryLoadAccount(String acct_name) {
361 SQLiteDatabase db = App.getDatabase();
362 return tryLoadAccount(db, acct_name);
365 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
366 LedgerAccount acc = tryLoadAccount(db, accName);
369 throw new RuntimeException("Unable to load account with name " + accName);
374 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
375 try (Cursor cursor = db.rawQuery(
376 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
377 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
378 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
380 if (cursor.moveToFirst()) {
381 LedgerAccount acc = new LedgerAccount(accName);
382 acc.setHiddenByStar(cursor.getInt(0) == 1);
383 acc.setExpanded(cursor.getInt(1) == 1);
384 acc.setHasSubAccounts(cursor.getInt(2) == 1);
386 try (Cursor c2 = db.rawQuery(
387 "SELECT value, currency FROM account_values WHERE profile = ? " +
388 "AND account = ?", new String[]{uuid, accName}))
390 while (c2.moveToNext()) {
391 acc.addAmount(c2.getFloat(0), c2.getString(1));
400 public LedgerTransaction loadTransaction(int transactionId) {
401 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
402 tr.loadData(App.getDatabase());
406 public int getThemeHue() {
407 // debug("profile", String.format("Profile.getThemeHue() returning %d", themeHue));
408 return this.themeHue;
410 public void setThemeHue(Object o) {
411 setThemeId(Integer.valueOf(String.valueOf(o)));
413 public void setThemeId(int themeHue) {
414 // debug("profile", String.format("Profile.setThemeHue(%d) called", themeHue));
415 this.themeHue = themeHue;
417 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
418 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
421 public void markAccountsAsNotPresent(SQLiteDatabase db) {
422 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
423 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
426 public void deleteNotPresentAccounts(SQLiteDatabase db) {
427 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
428 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
430 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
431 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
432 new Object[]{uuid, transaction.getId()
435 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
436 LedgerTransaction transaction) {
437 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
438 new Object[]{uuid, transaction.getId()
442 public void deleteNotPresentTransactions(SQLiteDatabase db) {
443 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
445 public void setLastUpdateStamp() {
446 debug("db", "Updating transaction value stamp");
447 Date now = new Date();
448 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
449 Data.lastUpdateDate.postValue(now);
451 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
452 List<LedgerAccount> result = new ArrayList<>();
453 SQLiteDatabase db = App.getDatabase();
454 try (Cursor c = db.rawQuery(
455 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
456 new String[]{uuid, acc.getName()}))
458 while (c.moveToNext()) {
459 LedgerAccount a = loadAccount(db, c.getString(0));
466 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
467 List<LedgerAccount> result = new ArrayList<>();
468 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
469 visibleList.add(acc);
471 SQLiteDatabase db = App.getDatabase();
472 try (Cursor c = db.rawQuery(
473 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
474 new String[]{uuid, acc.getName()}))
476 while (c.moveToNext()) {
477 LedgerAccount a = loadAccount(db, c.getString(0));
478 if (a.isVisible(visibleList)) {
487 public void wipeAllData() {
488 SQLiteDatabase db = App.getDatabase();
489 db.beginTransaction();
491 String[] pUuid = new String[]{uuid};
492 db.execSQL("delete from options where profile=?", pUuid);
493 db.execSQL("delete from accounts where profile=?", pUuid);
494 db.execSQL("delete from account_values where profile=?", pUuid);
495 db.execSQL("delete from transactions where profile=?", pUuid);
496 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
497 db.setTransactionSuccessful();
498 Logger.debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
504 public List<Currency> getCurrencies() {
505 SQLiteDatabase db = App.getDatabase();
507 ArrayList<Currency> result = new ArrayList<>();
509 try (Cursor c = db.rawQuery("SELECT c.id, c.name, c.position, c.has_gap FROM currencies c",
512 while (c.moveToNext()) {
513 Currency currency = new Currency(c.getInt(0), c.getString(1),
514 Currency.Position.valueOf(c.getInt(2)), c.getInt(3) == 1);
515 result.add(currency);
521 Currency loadCurrencyByName(String name) {
522 SQLiteDatabase db = App.getDatabase();
523 Currency result = tryLoadCurrencyByName(db, name);
525 throw new RuntimeException(String.format("Unable to load currency '%s'", name));
528 private Currency tryLoadCurrencyByName(SQLiteDatabase db, String name) {
529 try (Cursor cursor = db.rawQuery(
530 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.name=?",
533 if (cursor.moveToFirst()) {
534 return new Currency(cursor.getInt(0), cursor.getString(1),
535 Currency.Position.valueOf(cursor.getInt(2)), cursor.getInt(3) == 1);
540 public enum FutureDates {
541 None(0), OneWeek(7), TwoWeeks(14), OneMonth(30), TwoMonths(60), ThreeMonths(90),
542 SixMonths(180), OneYear(365), All(-1);
543 private static SparseArray<FutureDates> map = new SparseArray<>();
546 for (FutureDates item : FutureDates.values()) {
547 map.put(item.value, item);
552 FutureDates(int value) {
555 public static FutureDates valueOf(int i) {
556 return map.get(i, None);
561 public String getText(Resources resources) {
564 return resources.getString(R.string.future_dates_7);
566 return resources.getString(R.string.future_dates_14);
568 return resources.getString(R.string.future_dates_30);
570 return resources.getString(R.string.future_dates_60);
572 return resources.getString(R.string.future_dates_90);
574 return resources.getString(R.string.future_dates_180);
576 return resources.getString(R.string.future_dates_365);
578 return resources.getString(R.string.future_dates_all);
580 return resources.getString(R.string.future_dates_none);