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;
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.MLDB;
33 import net.ktnx.mobileledger.utils.Misc;
35 import java.util.ArrayList;
36 import java.util.Calendar;
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 {
45 // N.B. when adding new fields, update the copy-constructor below
48 private boolean permitPosting;
49 private boolean showCommentsByDefault;
50 private boolean showCommodityByDefault;
51 private String defaultCommodity;
52 private String preferredAccountsFilter;
54 private boolean authEnabled;
55 private String authUserName;
56 private String authPassword;
58 private int orderNo = -1;
59 // N.B. when adding new fields, update the copy-constructor below
60 private FutureDates futureDates = FutureDates.None;
61 private SendTransactionTask.API apiVersion = SendTransactionTask.API.auto;
62 private Calendar firstTransactionDate;
63 private Calendar lastTransactionDate;
64 public MobileLedgerProfile() {
65 this.uuid = String.valueOf(UUID.randomUUID());
67 public MobileLedgerProfile(String uuid) {
70 public MobileLedgerProfile(MobileLedgerProfile origin) {
73 permitPosting = origin.permitPosting;
74 showCommentsByDefault = origin.showCommentsByDefault;
75 showCommodityByDefault = origin.showCommodityByDefault;
76 preferredAccountsFilter = origin.preferredAccountsFilter;
78 authEnabled = origin.authEnabled;
79 authUserName = origin.authUserName;
80 authPassword = origin.authPassword;
81 themeHue = origin.themeHue;
82 orderNo = origin.orderNo;
83 futureDates = origin.futureDates;
84 apiVersion = origin.apiVersion;
85 defaultCommodity = origin.defaultCommodity;
87 // loads all profiles into Data.profiles
88 // returns the profile with the given UUID
89 public static MobileLedgerProfile loadAllFromDB(@Nullable String currentProfileUUID) {
90 MobileLedgerProfile result = null;
91 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
92 SQLiteDatabase db = App.getDatabase();
93 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
94 "auth_password, permit_posting, theme, order_no, " +
95 "preferred_accounts_filter, future_dates, api_version, " +
96 "show_commodity_by_default, default_commodity, " +
97 "show_comments_by_default FROM " +
98 "profiles order by order_no", null))
100 while (cursor.moveToNext()) {
101 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
102 item.setName(cursor.getString(1));
103 item.setUrl(cursor.getString(2));
104 item.setAuthEnabled(cursor.getInt(3) == 1);
105 item.setAuthUserName(cursor.getString(4));
106 item.setAuthPassword(cursor.getString(5));
107 item.setPostingPermitted(cursor.getInt(6) == 1);
108 item.setThemeId(cursor.getInt(7));
109 item.orderNo = cursor.getInt(8);
110 item.setPreferredAccountsFilter(cursor.getString(9));
111 item.setFutureDates(cursor.getInt(10));
112 item.setApiVersion(cursor.getInt(11));
113 item.setShowCommodityByDefault(cursor.getInt(12) == 1);
114 item.setDefaultCommodity(cursor.getString(13));
115 item.setShowCommentsByDefault(cursor.getInt(14) == 1);
118 .equals(currentProfileUUID))
122 Data.profiles.setValue(list);
125 public static void storeProfilesOrder() {
126 SQLiteDatabase db = App.getDatabase();
127 db.beginTransactionNonExclusive();
130 for (MobileLedgerProfile p : Data.profiles.getValue()) {
131 db.execSQL("update profiles set order_no=? where uuid=?",
132 new Object[]{orderNo, p.getUuid()});
136 db.setTransactionSuccessful();
142 public boolean getShowCommentsByDefault() {
143 return showCommentsByDefault;
145 public void setShowCommentsByDefault(boolean newValue) {
146 this.showCommentsByDefault = newValue;
148 public boolean getShowCommodityByDefault() {
149 return showCommodityByDefault;
151 public void setShowCommodityByDefault(boolean showCommodityByDefault) {
152 this.showCommodityByDefault = showCommodityByDefault;
154 public String getDefaultCommodity() {
155 return defaultCommodity;
157 public void setDefaultCommodity(String defaultCommodity) {
158 this.defaultCommodity = defaultCommodity;
160 public void setDefaultCommodity(CharSequence defaultCommodity) {
161 if (defaultCommodity == null)
162 this.defaultCommodity = null;
164 this.defaultCommodity = String.valueOf(defaultCommodity);
166 public SendTransactionTask.API getApiVersion() {
169 public void setApiVersion(SendTransactionTask.API apiVersion) {
170 this.apiVersion = apiVersion;
172 public void setApiVersion(int apiVersion) {
173 this.apiVersion = SendTransactionTask.API.valueOf(apiVersion);
175 public FutureDates getFutureDates() {
178 public void setFutureDates(int anInt) {
179 futureDates = FutureDates.valueOf(anInt);
181 public void setFutureDates(FutureDates futureDates) {
182 this.futureDates = futureDates;
184 public String getPreferredAccountsFilter() {
185 return preferredAccountsFilter;
187 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
188 this.preferredAccountsFilter = preferredAccountsFilter;
190 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
191 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
193 public boolean isPostingPermitted() {
194 return permitPosting;
196 public void setPostingPermitted(boolean permitPosting) {
197 this.permitPosting = permitPosting;
199 public String getUuid() {
202 public String getName() {
205 public void setName(CharSequence text) {
206 setName(String.valueOf(text));
208 public void setName(String name) {
211 public String getUrl() {
214 public void setUrl(CharSequence text) {
215 setUrl(String.valueOf(text));
217 public void setUrl(String url) {
220 public boolean isAuthEnabled() {
223 public void setAuthEnabled(boolean authEnabled) {
224 this.authEnabled = authEnabled;
226 public String getAuthUserName() {
229 public void setAuthUserName(CharSequence text) {
230 setAuthUserName(String.valueOf(text));
232 public void setAuthUserName(String authUserName) {
233 this.authUserName = authUserName;
235 public String getAuthPassword() {
238 public void setAuthPassword(CharSequence text) {
239 setAuthPassword(String.valueOf(text));
241 public void setAuthPassword(String authPassword) {
242 this.authPassword = authPassword;
244 public void storeInDB() {
245 SQLiteDatabase db = App.getDatabase();
246 db.beginTransactionNonExclusive();
248 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
249 // "url=%s, permit_posting=%s, authEnabled=%s, " +
250 // "themeHue=%d", uuid, name, url,
251 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeHue));
252 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
253 "use_authentication, auth_user, auth_password, theme, order_no, " +
254 "preferred_accounts_filter, future_dates, api_version, " +
255 "show_commodity_by_default, default_commodity, show_comments_by_default) " +
256 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
257 new Object[]{uuid, name, permitPosting, url, authEnabled,
258 authEnabled ? authUserName : null,
259 authEnabled ? authPassword : null, themeHue, orderNo,
260 preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt(),
261 showCommodityByDefault, defaultCommodity, showCommentsByDefault
263 db.setTransactionSuccessful();
269 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
270 // replace into is a bad idea because it would reset hidden to its default value
271 // we like the default, but for new accounts only
272 db.execSQL("update accounts set level = ?, keep = 1, expanded=? " +
273 "where profile=? and name = ?",
274 new Object[]{acc.getLevel(), acc.isExpanded(), uuid, acc.getName()
276 db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, " +
277 "expanded, keep) " + "select ?,?,?,?,?,?,1 where (select changes() = 0)",
278 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
279 acc.getLevel(), acc.isExpanded()
281 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
283 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
284 db.execSQL("replace into account_values(profile, account, " +
285 "currency, value, keep) values(?, ?, ?, ?, 1);",
286 new Object[]{uuid, name, Misc.emptyIsNull(currency), amount});
288 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
290 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
291 new Object[]{uuid, tr.getId()});
292 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
293 new Object[]{uuid, tr.getId()});
296 "INSERT INTO transactions(profile, id, year, month, day, description, "+
297 "comment, data_hash, keep) " +
298 "values(?,?,?,?,?,?,?,?,1)",
299 new Object[]{uuid, tr.getId(), tr.getDate().year, tr.getDate().month,
300 tr.getDate().day, tr.getDescription(),
301 tr.getComment(), tr.getDataHash()
304 for (LedgerTransactionAccount item : tr.getAccounts()) {
305 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
306 "account_name, amount, currency, comment) values(?, ?, ?, ?, ?, ?)",
307 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
308 Misc.nullIsEmpty(item.getCurrency()), item.getComment()
311 // debug("profile", String.format("Transaction %d stored", tr.getId()));
313 public String getOption(String name, String default_value) {
314 SQLiteDatabase db = App.getDatabase();
315 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
316 new String[]{uuid, name}))
318 if (cursor.moveToFirst()) {
319 String result = cursor.getString(0);
321 if (result == null) {
322 debug("profile", "returning default value for " + name);
323 result = default_value;
326 debug("profile", String.format("option %s=%s", name, result));
331 return default_value;
333 catch (Exception e) {
334 debug("db", "returning default value for " + name, e);
335 return default_value;
338 public long getLongOption(String name, long default_value) {
340 String result = getOption(name, "");
341 if ((result == null) || result.isEmpty()) {
342 debug("profile", String.format("Returning default value for option %s", name));
343 longResult = default_value;
347 longResult = Long.parseLong(result);
348 debug("profile", String.format("option %s=%s", name, result));
350 catch (Exception e) {
351 debug("profile", String.format("Returning default value for option %s", name), e);
352 longResult = default_value;
358 public void setOption(String name, String value) {
359 debug("profile", String.format("setting option %s=%s", name, value));
360 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
361 new String[]{uuid, name, value});
363 public void setLongOption(String name, long value) {
364 setOption(name, String.valueOf(value));
366 public void removeFromDB() {
367 SQLiteDatabase db = App.getDatabase();
368 debug("db", String.format("removing profile %s from DB", uuid));
369 db.beginTransactionNonExclusive();
371 Object[] uuid_param = new Object[]{uuid};
372 db.execSQL("delete from profiles where uuid=?", uuid_param);
373 db.execSQL("delete from accounts where profile=?", uuid_param);
374 db.execSQL("delete from account_values where profile=?", uuid_param);
375 db.execSQL("delete from transactions where profile=?", uuid_param);
376 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
377 db.execSQL("delete from options where profile=?", uuid_param);
378 db.setTransactionSuccessful();
385 public LedgerAccount loadAccount(String name) {
386 SQLiteDatabase db = App.getDatabase();
387 return loadAccount(db, name);
390 public LedgerAccount tryLoadAccount(String acct_name) {
391 SQLiteDatabase db = App.getDatabase();
392 return tryLoadAccount(db, acct_name);
395 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
396 LedgerAccount acc = tryLoadAccount(db, accName);
399 throw new RuntimeException("Unable to load account with name " + accName);
404 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
405 try (Cursor cursor = db.rawQuery("SELECT a.expanded, (select 1 from accounts a2 " +
406 "where a2.profile = a.profile and a2.name like a" +
407 ".name||':%' limit 1) " +
408 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
410 if (cursor.moveToFirst()) {
411 LedgerAccount acc = new LedgerAccount(accName);
412 acc.setExpanded(cursor.getInt(0) == 1);
413 acc.setHasSubAccounts(cursor.getInt(1) == 1);
415 try (Cursor c2 = db.rawQuery(
416 "SELECT value, currency FROM account_values WHERE profile = ? " +
417 "AND account = ?", new String[]{uuid, accName}))
419 while (c2.moveToNext()) {
420 acc.addAmount(c2.getFloat(0), c2.getString(1));
429 public LedgerTransaction loadTransaction(int transactionId) {
430 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
431 tr.loadData(App.getDatabase());
435 public int getThemeHue() {
436 // debug("profile", String.format("Profile.getThemeHue() returning %d", themeHue));
437 return this.themeHue;
439 public void setThemeHue(Object o) {
440 setThemeId(Integer.parseInt(String.valueOf(o)));
442 public void setThemeId(int themeHue) {
443 // debug("profile", String.format("Profile.setThemeHue(%d) called", themeHue));
444 this.themeHue = themeHue;
446 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
447 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
450 public void markAccountsAsNotPresent(SQLiteDatabase db) {
451 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
452 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
455 public void deleteNotPresentAccounts(SQLiteDatabase db) {
456 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
457 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
459 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
460 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
461 new Object[]{uuid, transaction.getId()
464 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
465 LedgerTransaction transaction) {
466 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
467 new Object[]{uuid, transaction.getId()
471 public void deleteNotPresentTransactions(SQLiteDatabase db) {
472 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
474 public void setLastUpdateStamp() {
475 debug("db", "Updating transaction value stamp");
476 Date now = new Date();
477 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
478 Data.lastUpdateDate.postValue(now);
480 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
481 List<LedgerAccount> result = new ArrayList<>();
482 SQLiteDatabase db = App.getDatabase();
483 try (Cursor c = db.rawQuery(
484 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
485 new String[]{uuid, acc.getName()}))
487 while (c.moveToNext()) {
488 LedgerAccount a = loadAccount(db, c.getString(0));
495 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
496 List<LedgerAccount> result = new ArrayList<>();
497 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
498 visibleList.add(acc);
500 SQLiteDatabase db = App.getDatabase();
501 try (Cursor c = db.rawQuery(
502 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
503 new String[]{uuid, acc.getName()}))
505 while (c.moveToNext()) {
506 LedgerAccount a = loadAccount(db, c.getString(0));
507 if (a.isVisible(visibleList)) {
516 public void wipeAllData() {
517 SQLiteDatabase db = App.getDatabase();
518 db.beginTransaction();
520 String[] pUuid = new String[]{uuid};
521 db.execSQL("delete from options where profile=?", pUuid);
522 db.execSQL("delete from accounts where profile=?", pUuid);
523 db.execSQL("delete from account_values where profile=?", pUuid);
524 db.execSQL("delete from transactions where profile=?", pUuid);
525 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
526 db.setTransactionSuccessful();
527 debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
533 public List<Currency> getCurrencies() {
534 SQLiteDatabase db = App.getDatabase();
536 ArrayList<Currency> result = new ArrayList<>();
538 try (Cursor c = db.rawQuery("SELECT c.id, c.name, c.position, c.has_gap FROM currencies c",
541 while (c.moveToNext()) {
542 Currency currency = new Currency(c.getInt(0), c.getString(1),
543 Currency.Position.valueOf(c.getInt(2)), c.getInt(3) == 1);
544 result.add(currency);
550 Currency loadCurrencyByName(String name) {
551 SQLiteDatabase db = App.getDatabase();
552 Currency result = tryLoadCurrencyByName(db, name);
554 throw new RuntimeException(String.format("Unable to load currency '%s'", name));
557 private Currency tryLoadCurrencyByName(SQLiteDatabase db, String name) {
558 try (Cursor cursor = db.rawQuery(
559 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.name=?",
562 if (cursor.moveToFirst()) {
563 return new Currency(cursor.getInt(0), cursor.getString(1),
564 Currency.Position.valueOf(cursor.getInt(2)), cursor.getInt(3) == 1);
569 public Calendar getFirstTransactionDate() {
570 return firstTransactionDate;
572 public Calendar getLastTransactionDate() {
573 return lastTransactionDate;
575 public enum FutureDates {
576 None(0), OneWeek(7), TwoWeeks(14), OneMonth(30), TwoMonths(60), ThreeMonths(90),
577 SixMonths(180), OneYear(365), All(-1);
578 private static SparseArray<FutureDates> map = new SparseArray<>();
581 for (FutureDates item : FutureDates.values()) {
582 map.put(item.value, item);
587 FutureDates(int value) {
590 public static FutureDates valueOf(int i) {
591 return map.get(i, None);
596 public String getText(Resources resources) {
599 return resources.getString(R.string.future_dates_7);
601 return resources.getString(R.string.future_dates_14);
603 return resources.getString(R.string.future_dates_30);
605 return resources.getString(R.string.future_dates_60);
607 return resources.getString(R.string.future_dates_90);
609 return resources.getString(R.string.future_dates_180);
611 return resources.getString(R.string.future_dates_365);
613 return resources.getString(R.string.future_dates_all);
615 return resources.getString(R.string.future_dates_none);