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.Nullable;
27 import net.ktnx.mobileledger.App;
28 import net.ktnx.mobileledger.R;
29 import net.ktnx.mobileledger.async.DbOpQueue;
30 import net.ktnx.mobileledger.async.SendTransactionTask;
31 import net.ktnx.mobileledger.utils.Logger;
32 import net.ktnx.mobileledger.utils.Misc;
33 import net.ktnx.mobileledger.utils.SimpleDate;
35 import org.jetbrains.annotations.Contract;
37 import java.util.ArrayList;
38 import java.util.HashMap;
39 import java.util.List;
40 import java.util.Locale;
42 import java.util.Objects;
44 import static net.ktnx.mobileledger.utils.Logger.debug;
46 public final class MobileLedgerProfile {
47 // N.B. when adding new fields, update the copy-constructor below
48 private final String uuid;
50 private boolean permitPosting;
51 private boolean showCommentsByDefault;
52 private boolean showCommodityByDefault;
53 private String defaultCommodity;
54 private String preferredAccountsFilter;
56 private boolean authEnabled;
57 private String authUserName;
58 private String authPassword;
60 private int orderNo = -1;
61 private SendTransactionTask.API apiVersion = SendTransactionTask.API.auto;
62 private FutureDates futureDates = FutureDates.None;
63 private boolean accountsLoaded;
64 private boolean transactionsLoaded;
65 // N.B. when adding new fields, update the copy-constructor below
66 transient private AccountAndTransactionListSaver accountAndTransactionListSaver;
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;
86 accountsLoaded = origin.accountsLoaded;
87 transactionsLoaded = origin.transactionsLoaded;
89 // loads all profiles into Data.profiles
90 // returns the profile with the given UUID
91 public static MobileLedgerProfile loadAllFromDB(@Nullable String currentProfileUUID) {
92 MobileLedgerProfile result = null;
93 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
94 SQLiteDatabase db = App.getDatabase();
95 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
96 "auth_password, permit_posting, theme, order_no, " +
97 "preferred_accounts_filter, future_dates, api_version, " +
98 "show_commodity_by_default, default_commodity, " +
99 "show_comments_by_default FROM " +
100 "profiles order by order_no", null))
102 while (cursor.moveToNext()) {
103 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
104 item.setName(cursor.getString(1));
105 item.setUrl(cursor.getString(2));
106 item.setAuthEnabled(cursor.getInt(3) == 1);
107 item.setAuthUserName(cursor.getString(4));
108 item.setAuthPassword(cursor.getString(5));
109 item.setPostingPermitted(cursor.getInt(6) == 1);
110 item.setThemeId(cursor.getInt(7));
111 item.orderNo = cursor.getInt(8);
112 item.setPreferredAccountsFilter(cursor.getString(9));
113 item.setFutureDates(cursor.getInt(10));
114 item.setApiVersion(cursor.getInt(11));
115 item.setShowCommodityByDefault(cursor.getInt(12) == 1);
116 item.setDefaultCommodity(cursor.getString(13));
117 item.setShowCommentsByDefault(cursor.getInt(14) == 1);
120 .equals(currentProfileUUID))
124 Data.profiles.setValue(list);
127 public static void storeProfilesOrder() {
128 SQLiteDatabase db = App.getDatabase();
129 db.beginTransactionNonExclusive();
132 for (MobileLedgerProfile p : Objects.requireNonNull(Data.profiles.getValue())) {
133 db.execSQL("update profiles set order_no=? where uuid=?",
134 new Object[]{orderNo, p.getUuid()});
138 db.setTransactionSuccessful();
144 @Contract(value = "null -> false", pure = true)
146 public boolean equals(@Nullable Object obj) {
151 if (obj.getClass() != this.getClass())
154 MobileLedgerProfile p = (MobileLedgerProfile) obj;
155 if (!uuid.equals(p.uuid))
157 if (!name.equals(p.name))
159 if (permitPosting != p.permitPosting)
161 if (showCommentsByDefault != p.showCommentsByDefault)
163 if (showCommodityByDefault != p.showCommodityByDefault)
165 if (!Objects.equals(defaultCommodity, p.defaultCommodity))
167 if (!Objects.equals(preferredAccountsFilter, p.preferredAccountsFilter))
169 if (!Objects.equals(url, p.url))
171 if (authEnabled != p.authEnabled)
173 if (!Objects.equals(authUserName, p.authUserName))
175 if (!Objects.equals(authPassword, p.authPassword))
177 if (themeHue != p.themeHue)
179 if (apiVersion != p.apiVersion)
181 return futureDates == p.futureDates;
183 public boolean getShowCommentsByDefault() {
184 return showCommentsByDefault;
186 public void setShowCommentsByDefault(boolean newValue) {
187 this.showCommentsByDefault = newValue;
189 public boolean getShowCommodityByDefault() {
190 return showCommodityByDefault;
192 public void setShowCommodityByDefault(boolean showCommodityByDefault) {
193 this.showCommodityByDefault = showCommodityByDefault;
195 public String getDefaultCommodity() {
196 return defaultCommodity;
198 public void setDefaultCommodity(String defaultCommodity) {
199 this.defaultCommodity = defaultCommodity;
201 public void setDefaultCommodity(CharSequence defaultCommodity) {
202 if (defaultCommodity == null)
203 this.defaultCommodity = null;
205 this.defaultCommodity = String.valueOf(defaultCommodity);
207 public SendTransactionTask.API getApiVersion() {
210 public void setApiVersion(SendTransactionTask.API apiVersion) {
211 this.apiVersion = apiVersion;
213 public void setApiVersion(int apiVersion) {
214 this.apiVersion = SendTransactionTask.API.valueOf(apiVersion);
216 public FutureDates getFutureDates() {
219 public void setFutureDates(int anInt) {
220 futureDates = FutureDates.valueOf(anInt);
222 public void setFutureDates(FutureDates futureDates) {
223 this.futureDates = futureDates;
225 public String getPreferredAccountsFilter() {
226 return preferredAccountsFilter;
228 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
229 this.preferredAccountsFilter = preferredAccountsFilter;
231 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
232 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
234 public boolean isPostingPermitted() {
235 return permitPosting;
237 public void setPostingPermitted(boolean permitPosting) {
238 this.permitPosting = permitPosting;
240 public String getUuid() {
243 public String getName() {
246 public void setName(CharSequence text) {
247 setName(String.valueOf(text));
249 public void setName(String name) {
252 public String getUrl() {
255 public void setUrl(CharSequence text) {
256 setUrl(String.valueOf(text));
258 public void setUrl(String url) {
261 public boolean isAuthEnabled() {
264 public void setAuthEnabled(boolean authEnabled) {
265 this.authEnabled = authEnabled;
267 public String getAuthUserName() {
270 public void setAuthUserName(CharSequence text) {
271 setAuthUserName(String.valueOf(text));
273 public void setAuthUserName(String authUserName) {
274 this.authUserName = authUserName;
276 public String getAuthPassword() {
279 public void setAuthPassword(CharSequence text) {
280 setAuthPassword(String.valueOf(text));
282 public void setAuthPassword(String authPassword) {
283 this.authPassword = authPassword;
285 public void storeInDB() {
286 SQLiteDatabase db = App.getDatabase();
287 db.beginTransactionNonExclusive();
289 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
290 // "url=%s, permit_posting=%s, authEnabled=%s, " +
291 // "themeHue=%d", uuid, name, url,
292 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeHue));
293 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
294 "use_authentication, auth_user, auth_password, theme, order_no, " +
295 "preferred_accounts_filter, future_dates, api_version, " +
296 "show_commodity_by_default, default_commodity, show_comments_by_default) " +
297 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
298 new Object[]{uuid, name, permitPosting, url, authEnabled,
299 authEnabled ? authUserName : null,
300 authEnabled ? authPassword : null, themeHue, orderNo,
301 preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt(),
302 showCommodityByDefault, defaultCommodity, showCommentsByDefault
304 db.setTransactionSuccessful();
310 public void storeAccount(SQLiteDatabase db, int generation, LedgerAccount acc,
311 boolean storeUiFields) {
312 // replace into is a bad idea because it would reset hidden to its default value
313 // we like the default, but for new accounts only
314 String sql = "update accounts set generation = ?";
315 List<Object> params = new ArrayList<>();
316 params.add(generation);
318 sql += ", expanded=?";
319 params.add(acc.isExpanded() ? 1 : 0);
321 sql += " where profile=? and name=?";
323 params.add(acc.getName());
324 db.execSQL(sql, params.toArray());
326 db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, " +
327 "expanded, generation) select ?,?,?,?,?,0,? where (select changes() = 0)",
328 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
329 acc.getLevel(), generation
331 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
333 public void storeAccountValue(SQLiteDatabase db, int generation, String name, String currency,
335 db.execSQL("replace into account_values(profile, account, " +
336 "currency, value, generation) values(?, ?, ?, ?, ?);",
337 new Object[]{uuid, name, Misc.emptyIsNull(currency), amount, generation});
339 public void storeTransaction(SQLiteDatabase db, int generation, LedgerTransaction tr) {
341 // Logger.debug("storeTransaction", String.format(Locale.US, "ID %d", tr.getId()));
342 SimpleDate d = tr.getDate();
343 db.execSQL("UPDATE transactions SET year=?, month=?, day=?, description=?, comment=?, " +
344 "data_hash=?, generation=? WHERE profile=? AND id=?",
345 new Object[]{d.year, d.month, d.day, tr.getDescription(), tr.getComment(),
346 tr.getDataHash(), generation, uuid, tr.getId()
348 db.execSQL("INSERT INTO transactions(profile, id, year, month, day, description, " +
349 "comment, data_hash, generation) " +
350 "select ?,?,?,?,?,?,?,?,? WHERE (select changes() = 0)",
351 new Object[]{uuid, tr.getId(), tr.getDate().year, tr.getDate().month,
352 tr.getDate().day, tr.getDescription(), tr.getComment(),
353 tr.getDataHash(), generation
356 int accountOrderNo = 1;
357 for (LedgerTransactionAccount item : tr.getAccounts()) {
358 db.execSQL("UPDATE transaction_accounts SET account_name=?, amount=?, currency=?, " +
359 "comment=?, generation=? " +
360 "WHERE profile=? AND transaction_id=? AND order_no=?",
361 new Object[]{item.getAccountName(), item.getAmount(),
362 Misc.nullIsEmpty(item.getCurrency()), item.getComment(),
363 generation, uuid, tr.getId(), accountOrderNo
365 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
366 "order_no, account_name, amount, currency, comment, generation) " +
367 "select ?, ?, ?, ?, ?, ?, ?, ? WHERE (select changes() = 0)",
368 new Object[]{uuid, tr.getId(), accountOrderNo, item.getAccountName(),
369 item.getAmount(), Misc.nullIsEmpty(item.getCurrency()),
370 item.getComment(), generation
375 // debug("profile", String.format("Transaction %d stored", tr.getId()));
377 public String getOption(String name, String default_value) {
378 SQLiteDatabase db = App.getDatabase();
379 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
380 new String[]{uuid, name}))
382 if (cursor.moveToFirst()) {
383 String result = cursor.getString(0);
385 if (result == null) {
386 debug("profile", "returning default value for " + name);
387 result = default_value;
390 debug("profile", String.format("option %s=%s", name, result));
395 return default_value;
397 catch (Exception e) {
398 debug("db", "returning default value for " + name, e);
399 return default_value;
402 public long getLongOption(String name, long default_value) {
404 String result = getOption(name, "");
405 if ((result == null) || result.isEmpty()) {
406 debug("profile", String.format("Returning default value for option %s", name));
407 longResult = default_value;
411 longResult = Long.parseLong(result);
412 debug("profile", String.format("option %s=%s", name, result));
414 catch (Exception e) {
415 debug("profile", String.format("Returning default value for option %s", name), e);
416 longResult = default_value;
422 public void setOption(String name, String value) {
423 debug("profile", String.format("setting option %s=%s", name, value));
424 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
425 new String[]{uuid, name, value});
427 public void setLongOption(String name, long value) {
428 setOption(name, String.valueOf(value));
430 public void removeFromDB() {
431 SQLiteDatabase db = App.getDatabase();
432 debug("db", String.format("removing profile %s from DB", uuid));
433 db.beginTransactionNonExclusive();
435 Object[] uuid_param = new Object[]{uuid};
436 db.execSQL("delete from profiles where uuid=?", uuid_param);
437 db.execSQL("delete from accounts where profile=?", uuid_param);
438 db.execSQL("delete from account_values where profile=?", uuid_param);
439 db.execSQL("delete from transactions where profile=?", uuid_param);
440 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
441 db.execSQL("delete from options where profile=?", uuid_param);
442 db.setTransactionSuccessful();
448 public LedgerTransaction loadTransaction(int transactionId) {
449 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
450 tr.loadData(App.getDatabase());
454 public int getThemeHue() {
455 // debug("profile", String.format("Profile.getThemeHue() returning %d", themeHue));
456 return this.themeHue;
458 public void setThemeHue(Object o) {
459 setThemeId(Integer.parseInt(String.valueOf(o)));
461 public void setThemeId(int themeHue) {
462 // debug("profile", String.format("Profile.setThemeHue(%d) called", themeHue));
463 this.themeHue = themeHue;
465 public int getNextTransactionsGeneration(SQLiteDatabase db) {
467 try (Cursor c = db.rawQuery("SELECT generation FROM transactions WHERE profile=? LIMIT 1",
470 if (c.moveToFirst()) {
471 generation = c.getInt(0) + 1;
476 private int getNextAccountsGeneration(SQLiteDatabase db) {
478 try (Cursor c = db.rawQuery("SELECT generation FROM accounts WHERE profile=? LIMIT 1",
481 if (c.moveToFirst()) {
482 generation = c.getInt(0) + 1;
487 private void deleteNotPresentAccounts(SQLiteDatabase db, int generation) {
488 Logger.debug("db/benchmark", "Deleting obsolete accounts");
489 db.execSQL("DELETE FROM account_values WHERE profile=? AND generation <> ?",
490 new Object[]{uuid, generation});
491 db.execSQL("DELETE FROM accounts WHERE profile=? AND generation <> ?",
492 new Object[]{uuid, generation});
493 Logger.debug("db/benchmark", "Done deleting obsolete accounts");
495 private void deleteNotPresentTransactions(SQLiteDatabase db, int generation) {
496 Logger.debug("db/benchmark", "Deleting obsolete transactions");
497 db.execSQL("DELETE FROM transaction_accounts WHERE profile=? AND generation <> ?",
498 new Object[]{uuid, generation});
499 db.execSQL("DELETE FROM transactions WHERE profile=? AND generation <> ?",
500 new Object[]{uuid, generation});
501 Logger.debug("db/benchmark", "Done deleting obsolete transactions");
503 public void wipeAllData() {
504 SQLiteDatabase db = App.getDatabase();
505 db.beginTransaction();
507 String[] pUuid = new String[]{uuid};
508 db.execSQL("delete from options where profile=?", pUuid);
509 db.execSQL("delete from accounts where profile=?", pUuid);
510 db.execSQL("delete from account_values where profile=?", pUuid);
511 db.execSQL("delete from transactions where profile=?", pUuid);
512 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
513 db.setTransactionSuccessful();
514 debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
520 public List<Currency> getCurrencies() {
521 SQLiteDatabase db = App.getDatabase();
523 ArrayList<Currency> result = new ArrayList<>();
525 try (Cursor c = db.rawQuery("SELECT c.id, c.name, c.position, c.has_gap FROM currencies c",
528 while (c.moveToNext()) {
529 Currency currency = new Currency(c.getInt(0), c.getString(1),
530 Currency.Position.valueOf(c.getString(2)), c.getInt(3) == 1);
531 result.add(currency);
537 Currency loadCurrencyByName(String name) {
538 SQLiteDatabase db = App.getDatabase();
539 Currency result = tryLoadCurrencyByName(db, name);
541 throw new RuntimeException(String.format("Unable to load currency '%s'", name));
544 private Currency tryLoadCurrencyByName(SQLiteDatabase db, String name) {
545 try (Cursor cursor = db.rawQuery(
546 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.name=?",
549 if (cursor.moveToFirst()) {
550 return new Currency(cursor.getInt(0), cursor.getString(1),
551 Currency.Position.valueOf(cursor.getString(2)), cursor.getInt(3) == 1);
556 public void storeAccountAndTransactionListAsync(List<LedgerAccount> accounts,
557 List<LedgerTransaction> transactions) {
558 if (accountAndTransactionListSaver != null)
559 accountAndTransactionListSaver.interrupt();
561 accountAndTransactionListSaver =
562 new AccountAndTransactionListSaver(this, accounts, transactions);
563 accountAndTransactionListSaver.start();
566 public enum FutureDates {
567 None(0), OneWeek(7), TwoWeeks(14), OneMonth(30), TwoMonths(60), ThreeMonths(90),
568 SixMonths(180), OneYear(365), All(-1);
569 private static final SparseArray<FutureDates> map = new SparseArray<>();
572 for (FutureDates item : FutureDates.values()) {
573 map.put(item.value, item);
578 FutureDates(int value) {
581 public static FutureDates valueOf(int i) {
582 return map.get(i, None);
587 public String getText(Resources resources) {
590 return resources.getString(R.string.future_dates_7);
592 return resources.getString(R.string.future_dates_14);
594 return resources.getString(R.string.future_dates_30);
596 return resources.getString(R.string.future_dates_60);
598 return resources.getString(R.string.future_dates_90);
600 return resources.getString(R.string.future_dates_180);
602 return resources.getString(R.string.future_dates_365);
604 return resources.getString(R.string.future_dates_all);
606 return resources.getString(R.string.future_dates_none);
611 private static class AccountAndTransactionListSaver extends Thread {
612 private final MobileLedgerProfile profile;
613 private final List<LedgerAccount> accounts;
614 private final List<LedgerTransaction> transactions;
615 AccountAndTransactionListSaver(MobileLedgerProfile profile, List<LedgerAccount> accounts,
616 List<LedgerTransaction> transactions) {
617 this.accounts = accounts;
618 this.transactions = transactions;
619 this.profile = profile;
621 public int getNextDescriptionsGeneration(SQLiteDatabase db) {
623 try (Cursor c = db.rawQuery("SELECT generation FROM description_history LIMIT 1",
626 if (c.moveToFirst()) {
627 generation = c.getInt(0) + 1;
632 void deleteNotPresentDescriptions(SQLiteDatabase db, int generation) {
633 Logger.debug("db/benchmark", "Deleting obsolete descriptions");
634 db.execSQL("DELETE FROM description_history WHERE generation <> ?",
635 new Object[]{generation});
636 db.execSQL("DELETE FROM description_history WHERE generation <> ?",
637 new Object[]{generation});
638 Logger.debug("db/benchmark", "Done deleting obsolete descriptions");
642 SQLiteDatabase db = App.getDatabase();
643 db.beginTransactionNonExclusive();
645 int accountsGeneration = profile.getNextAccountsGeneration(db);
649 int transactionsGeneration = profile.getNextTransactionsGeneration(db);
653 for (LedgerAccount acc : accounts) {
654 profile.storeAccount(db, accountsGeneration, acc, false);
657 for (LedgerAmount amt : acc.getAmounts()) {
658 profile.storeAccountValue(db, accountsGeneration, acc.getName(),
659 amt.getCurrency(), amt.getAmount());
665 for (LedgerTransaction tr : transactions) {
666 profile.storeTransaction(db, transactionsGeneration, tr);
671 profile.deleteNotPresentTransactions(db, transactionsGeneration);
672 if (isInterrupted()) {
675 profile.deleteNotPresentAccounts(db, accountsGeneration);
679 Map<String, Boolean> unique = new HashMap<>();
681 debug("descriptions", "Starting refresh");
682 int descriptionsGeneration = getNextDescriptionsGeneration(db);
683 try (Cursor c = db.rawQuery("SELECT distinct description from transactions",
686 while (c.moveToNext()) {
687 String description = c.getString(0);
688 String descriptionUpper = description.toUpperCase();
689 if (unique.containsKey(descriptionUpper))
692 storeDescription(db, descriptionsGeneration, description, descriptionUpper);
694 unique.put(descriptionUpper, true);
697 deleteNotPresentDescriptions(db, descriptionsGeneration);
699 db.setTransactionSuccessful();
705 private void storeDescription(SQLiteDatabase db, int generation, String description,
706 String descriptionUpper) {
707 db.execSQL("UPDATE description_history SET description=?, generation=? WHERE " +
708 "description_upper=?", new Object[]{description, generation, descriptionUpper
711 "INSERT INTO description_history(description, description_upper, generation) " +
712 "select ?,?,? WHERE (select changes() = 0)",
713 new Object[]{description, descriptionUpper, generation