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.os.Build;
24 import android.text.TextUtils;
25 import android.util.SparseArray;
27 import androidx.annotation.Nullable;
28 import androidx.lifecycle.LiveData;
29 import androidx.lifecycle.MutableLiveData;
31 import net.ktnx.mobileledger.App;
32 import net.ktnx.mobileledger.R;
33 import net.ktnx.mobileledger.async.DbOpQueue;
34 import net.ktnx.mobileledger.async.SendTransactionTask;
35 import net.ktnx.mobileledger.utils.LockHolder;
36 import net.ktnx.mobileledger.utils.Locker;
37 import net.ktnx.mobileledger.utils.Logger;
38 import net.ktnx.mobileledger.utils.MLDB;
39 import net.ktnx.mobileledger.utils.Misc;
40 import net.ktnx.mobileledger.utils.SimpleDate;
42 import org.jetbrains.annotations.Contract;
44 import java.util.ArrayList;
45 import java.util.Calendar;
46 import java.util.Date;
47 import java.util.HashMap;
48 import java.util.Iterator;
49 import java.util.List;
50 import java.util.Locale;
52 import java.util.Objects;
54 import static net.ktnx.mobileledger.utils.Logger.debug;
56 public final class MobileLedgerProfile {
57 private final MutableLiveData<List<LedgerAccount>> displayedAccounts;
58 private final MutableLiveData<List<LedgerTransaction>> allTransactions;
59 private final MutableLiveData<List<LedgerTransaction>> displayedTransactions;
60 // N.B. when adding new fields, update the copy-constructor below
61 private final String uuid;
62 private final Locker accountsLocker = new Locker();
63 private List<LedgerAccount> allAccounts;
65 private boolean permitPosting;
66 private boolean showCommentsByDefault;
67 private boolean showCommodityByDefault;
68 private String defaultCommodity;
69 private String preferredAccountsFilter;
71 private boolean authEnabled;
72 private String authUserName;
73 private String authPassword;
75 private int orderNo = -1;
76 private SendTransactionTask.API apiVersion = SendTransactionTask.API.auto;
77 private Calendar firstTransactionDate;
78 private Calendar lastTransactionDate;
79 private FutureDates futureDates = FutureDates.None;
80 private boolean accountsLoaded;
81 private boolean transactionsLoaded;
82 // N.B. when adding new fields, update the copy-constructor below
83 transient private AccountListLoader loader = null;
84 transient private Thread displayedAccountsUpdater;
85 transient private AccountListSaver accountListSaver;
86 transient private TransactionListSaver transactionListSaver;
87 transient private AccountAndTransactionListSaver accountAndTransactionListSaver;
88 private Map<String, LedgerAccount> accountMap = new HashMap<>();
89 public MobileLedgerProfile(String uuid) {
91 allAccounts = new ArrayList<>();
92 displayedAccounts = new MutableLiveData<>();
93 allTransactions = new MutableLiveData<>(new ArrayList<>());
94 displayedTransactions = new MutableLiveData<>(new ArrayList<>());
96 public MobileLedgerProfile(MobileLedgerProfile origin) {
99 permitPosting = origin.permitPosting;
100 showCommentsByDefault = origin.showCommentsByDefault;
101 showCommodityByDefault = origin.showCommodityByDefault;
102 preferredAccountsFilter = origin.preferredAccountsFilter;
104 authEnabled = origin.authEnabled;
105 authUserName = origin.authUserName;
106 authPassword = origin.authPassword;
107 themeHue = origin.themeHue;
108 orderNo = origin.orderNo;
109 futureDates = origin.futureDates;
110 apiVersion = origin.apiVersion;
111 defaultCommodity = origin.defaultCommodity;
112 firstTransactionDate = origin.firstTransactionDate;
113 lastTransactionDate = origin.lastTransactionDate;
114 displayedAccounts = origin.displayedAccounts;
115 allAccounts = origin.allAccounts;
116 accountMap = origin.accountMap;
117 displayedTransactions = origin.displayedTransactions;
118 allTransactions = origin.allTransactions;
119 accountsLoaded = origin.accountsLoaded;
120 transactionsLoaded = origin.transactionsLoaded;
122 // loads all profiles into Data.profiles
123 // returns the profile with the given UUID
124 public static MobileLedgerProfile loadAllFromDB(@Nullable String currentProfileUUID) {
125 MobileLedgerProfile result = null;
126 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
127 SQLiteDatabase db = App.getDatabase();
128 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
129 "auth_password, permit_posting, theme, order_no, " +
130 "preferred_accounts_filter, future_dates, api_version, " +
131 "show_commodity_by_default, default_commodity, " +
132 "show_comments_by_default FROM " +
133 "profiles order by order_no", null))
135 while (cursor.moveToNext()) {
136 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
137 item.setName(cursor.getString(1));
138 item.setUrl(cursor.getString(2));
139 item.setAuthEnabled(cursor.getInt(3) == 1);
140 item.setAuthUserName(cursor.getString(4));
141 item.setAuthPassword(cursor.getString(5));
142 item.setPostingPermitted(cursor.getInt(6) == 1);
143 item.setThemeId(cursor.getInt(7));
144 item.orderNo = cursor.getInt(8);
145 item.setPreferredAccountsFilter(cursor.getString(9));
146 item.setFutureDates(cursor.getInt(10));
147 item.setApiVersion(cursor.getInt(11));
148 item.setShowCommodityByDefault(cursor.getInt(12) == 1);
149 item.setDefaultCommodity(cursor.getString(13));
150 item.setShowCommentsByDefault(cursor.getInt(14) == 1);
153 .equals(currentProfileUUID))
157 Data.profiles.setValue(list);
160 public static void storeProfilesOrder() {
161 SQLiteDatabase db = App.getDatabase();
162 db.beginTransactionNonExclusive();
165 for (MobileLedgerProfile p : Objects.requireNonNull(Data.profiles.getValue())) {
166 db.execSQL("update profiles set order_no=? where uuid=?",
167 new Object[]{orderNo, p.getUuid()});
171 db.setTransactionSuccessful();
177 public static ArrayList<LedgerAccount> mergeAccountListsFromWeb(List<LedgerAccount> oldList,
178 List<LedgerAccount> newList) {
179 LedgerAccount oldAcc, newAcc;
180 ArrayList<LedgerAccount> merged = new ArrayList<>();
182 Iterator<LedgerAccount> oldIterator = oldList.iterator();
183 Iterator<LedgerAccount> newIterator = newList.iterator();
186 if (!oldIterator.hasNext()) {
187 // the rest of the incoming are new
188 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
189 newIterator.forEachRemaining(merged::add);
192 while (newIterator.hasNext())
193 merged.add(newIterator.next());
197 oldAcc = oldIterator.next();
199 if (!newIterator.hasNext()) {
200 // no more incoming accounts. ignore the rest of the old
203 newAcc = newIterator.next();
205 // ignore now missing old items
207 .compareTo(newAcc.getName()) < 0)
210 // add newly found items
212 .compareTo(newAcc.getName()) > 0)
218 // two items with same account names; forward-merge UI-controlled fields
219 // it is important that the result list contains a new LedgerAccount instance
220 // so that the change is propagated to the UI
221 newAcc.setExpanded(oldAcc.isExpanded());
222 newAcc.setAmountsExpanded(oldAcc.amountsExpanded());
228 public void mergeAccountListFromWeb(List<LedgerAccount> newList) {
230 try (LockHolder l = accountsLocker.lockForWriting()) {
231 allAccounts = mergeAccountListsFromWeb(allAccounts, newList);
232 updateAccountsMap(allAccounts);
235 public LiveData<List<LedgerAccount>> getDisplayedAccounts() {
236 return displayedAccounts;
238 @Contract(value = "null -> false", pure = true)
240 public boolean equals(@Nullable Object obj) {
245 if (obj.getClass() != this.getClass())
248 MobileLedgerProfile p = (MobileLedgerProfile) obj;
249 if (!uuid.equals(p.uuid))
251 if (!name.equals(p.name))
253 if (permitPosting != p.permitPosting)
255 if (showCommentsByDefault != p.showCommentsByDefault)
257 if (showCommodityByDefault != p.showCommodityByDefault)
259 if (!Objects.equals(defaultCommodity, p.defaultCommodity))
261 if (!Objects.equals(preferredAccountsFilter, p.preferredAccountsFilter))
263 if (!Objects.equals(url, p.url))
265 if (authEnabled != p.authEnabled)
267 if (!Objects.equals(authUserName, p.authUserName))
269 if (!Objects.equals(authPassword, p.authPassword))
271 if (themeHue != p.themeHue)
273 if (apiVersion != p.apiVersion)
275 if (!Objects.equals(firstTransactionDate, p.firstTransactionDate))
277 if (!Objects.equals(lastTransactionDate, p.lastTransactionDate))
279 return futureDates == p.futureDates;
281 synchronized public void scheduleAccountListReload() {
282 Logger.debug("async-acc", "scheduleAccountListReload() enter");
283 if ((loader != null) && loader.isAlive()) {
284 Logger.debug("async-acc", "returning early - loader already active");
288 Logger.debug("async-acc", "Starting AccountListLoader");
289 loader = new AccountListLoader(this);
292 synchronized public void abortAccountListReload() {
298 public boolean getShowCommentsByDefault() {
299 return showCommentsByDefault;
301 public void setShowCommentsByDefault(boolean newValue) {
302 this.showCommentsByDefault = newValue;
304 public boolean getShowCommodityByDefault() {
305 return showCommodityByDefault;
307 public void setShowCommodityByDefault(boolean showCommodityByDefault) {
308 this.showCommodityByDefault = showCommodityByDefault;
310 public String getDefaultCommodity() {
311 return defaultCommodity;
313 public void setDefaultCommodity(String defaultCommodity) {
314 this.defaultCommodity = defaultCommodity;
316 public void setDefaultCommodity(CharSequence defaultCommodity) {
317 if (defaultCommodity == null)
318 this.defaultCommodity = null;
320 this.defaultCommodity = String.valueOf(defaultCommodity);
322 public SendTransactionTask.API getApiVersion() {
325 public void setApiVersion(SendTransactionTask.API apiVersion) {
326 this.apiVersion = apiVersion;
328 public void setApiVersion(int apiVersion) {
329 this.apiVersion = SendTransactionTask.API.valueOf(apiVersion);
331 public FutureDates getFutureDates() {
334 public void setFutureDates(int anInt) {
335 futureDates = FutureDates.valueOf(anInt);
337 public void setFutureDates(FutureDates futureDates) {
338 this.futureDates = futureDates;
340 public String getPreferredAccountsFilter() {
341 return preferredAccountsFilter;
343 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
344 this.preferredAccountsFilter = preferredAccountsFilter;
346 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
347 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
349 public boolean isPostingPermitted() {
350 return permitPosting;
352 public void setPostingPermitted(boolean permitPosting) {
353 this.permitPosting = permitPosting;
355 public String getUuid() {
358 public String getName() {
361 public void setName(CharSequence text) {
362 setName(String.valueOf(text));
364 public void setName(String name) {
367 public String getUrl() {
370 public void setUrl(CharSequence text) {
371 setUrl(String.valueOf(text));
373 public void setUrl(String url) {
376 public boolean isAuthEnabled() {
379 public void setAuthEnabled(boolean authEnabled) {
380 this.authEnabled = authEnabled;
382 public String getAuthUserName() {
385 public void setAuthUserName(CharSequence text) {
386 setAuthUserName(String.valueOf(text));
388 public void setAuthUserName(String authUserName) {
389 this.authUserName = authUserName;
391 public String getAuthPassword() {
394 public void setAuthPassword(CharSequence text) {
395 setAuthPassword(String.valueOf(text));
397 public void setAuthPassword(String authPassword) {
398 this.authPassword = authPassword;
400 public void storeInDB() {
401 SQLiteDatabase db = App.getDatabase();
402 db.beginTransactionNonExclusive();
404 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
405 // "url=%s, permit_posting=%s, authEnabled=%s, " +
406 // "themeHue=%d", uuid, name, url,
407 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeHue));
408 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
409 "use_authentication, auth_user, auth_password, theme, order_no, " +
410 "preferred_accounts_filter, future_dates, api_version, " +
411 "show_commodity_by_default, default_commodity, show_comments_by_default) " +
412 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
413 new Object[]{uuid, name, permitPosting, url, authEnabled,
414 authEnabled ? authUserName : null,
415 authEnabled ? authPassword : null, themeHue, orderNo,
416 preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt(),
417 showCommodityByDefault, defaultCommodity, showCommentsByDefault
419 db.setTransactionSuccessful();
425 public void storeAccount(SQLiteDatabase db, int generation, LedgerAccount acc,
426 boolean storeUiFields) {
427 // replace into is a bad idea because it would reset hidden to its default value
428 // we like the default, but for new accounts only
429 String sql = "update accounts set generation = ?";
430 List<Object> params = new ArrayList<>();
431 params.add(generation);
433 sql += ", expanded=?";
434 params.add(acc.isExpanded() ? 1 : 0);
436 sql += " where profile=? and name=?";
438 params.add(acc.getName());
439 db.execSQL(sql, params.toArray());
441 db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level, " +
442 "expanded, generation) select ?,?,?,?,?,0,? where (select changes() = 0)",
443 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
444 acc.getLevel(), generation
446 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
448 public void storeAccountValue(SQLiteDatabase db, int generation, String name, String currency,
450 db.execSQL("replace into account_values(profile, account, " +
451 "currency, value, generation) values(?, ?, ?, ?, ?);",
452 new Object[]{uuid, name, Misc.emptyIsNull(currency), amount, generation});
454 public void storeTransaction(SQLiteDatabase db, int generation, LedgerTransaction tr) {
456 SimpleDate d = tr.getDate();
457 db.execSQL("UPDATE transactions SET year=?, month=?, day=?, description=?, comment=?, " +
458 "data_hash=?, generation=? WHERE profile=? AND id=?",
459 new Object[]{d.year, d.month, d.day, tr.getDescription(), tr.getComment(),
460 tr.getDataHash(), generation, uuid, tr.getId()
462 db.execSQL("INSERT INTO transactions(profile, id, year, month, day, description, " +
463 "comment, data_hash, generation) " +
464 "select ?,?,?,?,?,?,?,?,? WHERE (select changes() = 0)",
465 new Object[]{uuid, tr.getId(), tr.getDate().year, tr.getDate().month,
466 tr.getDate().day, tr.getDescription(), tr.getComment(),
467 tr.getDataHash(), generation
470 int accountOrderNo = 1;
471 for (LedgerTransactionAccount item : tr.getAccounts()) {
472 db.execSQL("UPDATE transaction_accounts SET account_name=?, amount=?, currency=?, " +
473 "comment=?, generation=? " +
474 "WHERE profile=? AND transaction_id=? AND order_no=?",
475 new Object[]{item.getAccountName(), item.getAmount(),
476 Misc.nullIsEmpty(item.getCurrency()), item.getComment(),
477 generation, uuid, tr.getId(), accountOrderNo
479 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
480 "order_no, account_name, amount, currency, comment, generation) " +
481 "select ?, ?, ?, ?, ?, ?, ?, ? WHERE (select changes() = 0)",
482 new Object[]{uuid, tr.getId(), accountOrderNo, item.getAccountName(),
483 item.getAmount(), Misc.nullIsEmpty(item.getCurrency()),
484 item.getComment(), generation
489 // debug("profile", String.format("Transaction %d stored", tr.getId()));
491 public String getOption(String name, String default_value) {
492 SQLiteDatabase db = App.getDatabase();
493 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
494 new String[]{uuid, name}))
496 if (cursor.moveToFirst()) {
497 String result = cursor.getString(0);
499 if (result == null) {
500 debug("profile", "returning default value for " + name);
501 result = default_value;
504 debug("profile", String.format("option %s=%s", name, result));
509 return default_value;
511 catch (Exception e) {
512 debug("db", "returning default value for " + name, e);
513 return default_value;
516 public long getLongOption(String name, long default_value) {
518 String result = getOption(name, "");
519 if ((result == null) || result.isEmpty()) {
520 debug("profile", String.format("Returning default value for option %s", name));
521 longResult = default_value;
525 longResult = Long.parseLong(result);
526 debug("profile", String.format("option %s=%s", name, result));
528 catch (Exception e) {
529 debug("profile", String.format("Returning default value for option %s", name), e);
530 longResult = default_value;
536 public void setOption(String name, String value) {
537 debug("profile", String.format("setting option %s=%s", name, value));
538 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
539 new String[]{uuid, name, value});
541 public void setLongOption(String name, long value) {
542 setOption(name, String.valueOf(value));
544 public void removeFromDB() {
545 SQLiteDatabase db = App.getDatabase();
546 debug("db", String.format("removing profile %s from DB", uuid));
547 db.beginTransactionNonExclusive();
549 Object[] uuid_param = new Object[]{uuid};
550 db.execSQL("delete from profiles where uuid=?", uuid_param);
551 db.execSQL("delete from accounts where profile=?", uuid_param);
552 db.execSQL("delete from account_values where profile=?", uuid_param);
553 db.execSQL("delete from transactions where profile=?", uuid_param);
554 db.execSQL("delete from transaction_accounts where profile=?", uuid_param);
555 db.execSQL("delete from options where profile=?", uuid_param);
556 db.setTransactionSuccessful();
562 public LedgerTransaction loadTransaction(int transactionId) {
563 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
564 tr.loadData(App.getDatabase());
568 public int getThemeHue() {
569 // debug("profile", String.format("Profile.getThemeHue() returning %d", themeHue));
570 return this.themeHue;
572 public void setThemeHue(Object o) {
573 setThemeId(Integer.parseInt(String.valueOf(o)));
575 public void setThemeId(int themeHue) {
576 // debug("profile", String.format("Profile.setThemeHue(%d) called", themeHue));
577 this.themeHue = themeHue;
579 public int getNextTransactionsGeneration(SQLiteDatabase db) {
581 try (Cursor c = db.rawQuery("SELECT generation FROM transactions WHERE profile=? LIMIT 1",
584 if (c.moveToFirst()) {
585 generation = c.getInt(0) + 1;
590 private int getNextAccountsGeneration(SQLiteDatabase db) {
592 try (Cursor c = db.rawQuery("SELECT generation FROM accounts WHERE profile=? LIMIT 1",
595 if (c.moveToFirst()) {
596 generation = c.getInt(0) + 1;
601 private void deleteNotPresentAccounts(SQLiteDatabase db, int generation) {
602 Logger.debug("db/benchmark", "Deleting obsolete accounts");
603 db.execSQL("DELETE FROM account_values WHERE profile=? AND generation <> ?",
604 new Object[]{uuid, generation});
605 db.execSQL("DELETE FROM accounts WHERE profile=? AND generation <> ?",
606 new Object[]{uuid, generation});
607 Logger.debug("db/benchmark", "Done deleting obsolete accounts");
609 private void deleteNotPresentTransactions(SQLiteDatabase db, int generation) {
610 Logger.debug("db/benchmark", "Deleting obsolete transactions");
611 db.execSQL("DELETE FROM transaction_accounts WHERE profile=? AND generation <> ?",
612 new Object[]{uuid, generation});
613 db.execSQL("DELETE FROM transactions WHERE profile=? AND generation <> ?",
614 new Object[]{uuid, generation});
615 Logger.debug("db/benchmark", "Done deleting obsolete transactions");
617 private void setLastUpdateStamp() {
618 debug("db", "Updating transaction value stamp");
619 Date now = new Date();
620 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
621 Data.lastUpdateDate.postValue(now);
623 public void wipeAllData() {
624 SQLiteDatabase db = App.getDatabase();
625 db.beginTransaction();
627 String[] pUuid = new String[]{uuid};
628 db.execSQL("delete from options where profile=?", pUuid);
629 db.execSQL("delete from accounts where profile=?", pUuid);
630 db.execSQL("delete from account_values where profile=?", pUuid);
631 db.execSQL("delete from transactions where profile=?", pUuid);
632 db.execSQL("delete from transaction_accounts where profile=?", pUuid);
633 db.setTransactionSuccessful();
634 debug("wipe", String.format(Locale.ENGLISH, "Profile %s wiped out", pUuid[0]));
640 public List<Currency> getCurrencies() {
641 SQLiteDatabase db = App.getDatabase();
643 ArrayList<Currency> result = new ArrayList<>();
645 try (Cursor c = db.rawQuery("SELECT c.id, c.name, c.position, c.has_gap FROM currencies c",
648 while (c.moveToNext()) {
649 Currency currency = new Currency(c.getInt(0), c.getString(1),
650 Currency.Position.valueOf(c.getInt(2)), c.getInt(3) == 1);
651 result.add(currency);
657 Currency loadCurrencyByName(String name) {
658 SQLiteDatabase db = App.getDatabase();
659 Currency result = tryLoadCurrencyByName(db, name);
661 throw new RuntimeException(String.format("Unable to load currency '%s'", name));
664 private Currency tryLoadCurrencyByName(SQLiteDatabase db, String name) {
665 try (Cursor cursor = db.rawQuery(
666 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.name=?",
669 if (cursor.moveToFirst()) {
670 return new Currency(cursor.getInt(0), cursor.getString(1),
671 Currency.Position.valueOf(cursor.getInt(2)), cursor.getInt(3) == 1);
676 public Calendar getFirstTransactionDate() {
677 return firstTransactionDate;
679 public Calendar getLastTransactionDate() {
680 return lastTransactionDate;
682 private void applyTransactionFilter(List<LedgerTransaction> list) {
683 final String accFilter = Data.accountFilter.getValue();
684 if (TextUtils.isEmpty(accFilter)) {
685 displayedTransactions.postValue(list);
688 ArrayList<LedgerTransaction> newList = new ArrayList<>();
689 for (LedgerTransaction tr : list) {
690 if (tr.hasAccountNamedLike(accFilter))
693 displayedTransactions.postValue(newList);
696 synchronized public void storeAccountListAsync(List<LedgerAccount> list,
697 boolean storeUiFields) {
698 if (accountListSaver != null)
699 accountListSaver.interrupt();
700 accountListSaver = new AccountListSaver(this, list, storeUiFields);
701 accountListSaver.start();
703 public void setAndStoreAccountListFromWeb(ArrayList<LedgerAccount> list) {
704 SQLiteDatabase db = App.getDatabase();
705 db.beginTransactionNonExclusive();
707 Logger.debug("db/benchmark",
708 String.format(Locale.US, "Storing %d accounts", list.size()));
709 int gen = getNextAccountsGeneration(db);
710 Logger.debug("db/benckmark",
711 String.format(Locale.US, "Got next generation of %d", gen));
712 for (LedgerAccount acc : list) {
713 storeAccount(db, gen, acc, false);
714 for (LedgerAmount amt : acc.getAmounts()) {
715 storeAccountValue(db, gen, acc.getName(), amt.getCurrency(), amt.getAmount());
718 Logger.debug("db/benchmark", "Done storing accounts");
719 deleteNotPresentAccounts(db, gen);
720 setLastUpdateStamp();
721 db.setTransactionSuccessful();
727 mergeAccountListFromWeb(list);
728 updateDisplayedAccounts();
730 public synchronized Locker lockAccountsForWriting() {
731 accountsLocker.lockForWriting();
732 return accountsLocker;
734 public void setAndStoreTransactionList(ArrayList<LedgerTransaction> list) {
735 storeTransactionListAsync(this, list);
737 allTransactions.postValue(list);
739 private void storeTransactionListAsync(MobileLedgerProfile mobileLedgerProfile,
740 List<LedgerTransaction> list) {
741 if (transactionListSaver != null)
742 transactionListSaver.interrupt();
744 transactionListSaver = new TransactionListSaver(this, list);
745 transactionListSaver.start();
747 public void setAndStoreAccountAndTransactionListFromWeb(List<LedgerAccount> accounts,
748 List<LedgerTransaction> transactions) {
749 storeAccountAndTransactionListAsync(accounts, transactions, false);
751 mergeAccountListFromWeb(accounts);
752 updateDisplayedAccounts();
754 allTransactions.postValue(transactions);
756 private void storeAccountAndTransactionListAsync(List<LedgerAccount> accounts,
757 List<LedgerTransaction> transactions,
758 boolean storeAccUiFields) {
759 if (accountAndTransactionListSaver != null)
760 accountAndTransactionListSaver.interrupt();
762 accountAndTransactionListSaver =
763 new AccountAndTransactionListSaver(this, accounts, transactions, storeAccUiFields);
764 accountAndTransactionListSaver.start();
766 synchronized public void updateDisplayedAccounts() {
767 if (displayedAccountsUpdater != null) {
768 displayedAccountsUpdater.interrupt();
770 displayedAccountsUpdater = new AccountListDisplayedFilter(this, allAccounts);
771 displayedAccountsUpdater.start();
773 public List<LedgerAccount> getAllAccounts() {
776 private void updateAccountsMap(List<LedgerAccount> newAccounts) {
778 for (LedgerAccount acc : newAccounts) {
779 accountMap.put(acc.getName(), acc);
783 public LedgerAccount locateAccount(String name) {
784 return accountMap.get(name);
787 public enum FutureDates {
788 None(0), OneWeek(7), TwoWeeks(14), OneMonth(30), TwoMonths(60), ThreeMonths(90),
789 SixMonths(180), OneYear(365), All(-1);
790 private static SparseArray<FutureDates> map = new SparseArray<>();
793 for (FutureDates item : FutureDates.values()) {
794 map.put(item.value, item);
799 FutureDates(int value) {
802 public static FutureDates valueOf(int i) {
803 return map.get(i, None);
808 public String getText(Resources resources) {
811 return resources.getString(R.string.future_dates_7);
813 return resources.getString(R.string.future_dates_14);
815 return resources.getString(R.string.future_dates_30);
817 return resources.getString(R.string.future_dates_60);
819 return resources.getString(R.string.future_dates_90);
821 return resources.getString(R.string.future_dates_180);
823 return resources.getString(R.string.future_dates_365);
825 return resources.getString(R.string.future_dates_all);
827 return resources.getString(R.string.future_dates_none);
832 static class AccountListLoader extends Thread {
833 MobileLedgerProfile profile;
834 AccountListLoader(MobileLedgerProfile profile) {
835 this.profile = profile;
839 Logger.debug("async-acc", "AccountListLoader::run() entered");
840 String profileUUID = profile.getUuid();
841 ArrayList<LedgerAccount> list = new ArrayList<>();
842 HashMap<String, LedgerAccount> map = new HashMap<>();
844 String sql = "SELECT a.name, a.expanded, a.amounts_expanded";
845 sql += " from accounts a WHERE a.profile = ?";
846 sql += " ORDER BY a.name";
848 SQLiteDatabase db = App.getDatabase();
849 Logger.debug("async-acc", "AccountListLoader::run() connected to DB");
850 try (Cursor cursor = db.rawQuery(sql, new String[]{profileUUID})) {
851 Logger.debug("async-acc", "AccountListLoader::run() executed query");
852 while (cursor.moveToNext()) {
856 final String accName = cursor.getString(0);
858 // String.format("Read account '%s' from DB [%s]", accName,
860 String parentName = LedgerAccount.extractParentName(accName);
861 LedgerAccount parent;
862 if (parentName != null) {
863 parent = map.get(parentName);
865 throw new IllegalStateException(
866 String.format("Can't load account '%s': parent '%s' not loaded",
867 accName, parentName));
868 parent.setHasSubAccounts(true);
873 LedgerAccount acc = new LedgerAccount(profile, accName, parent);
874 acc.setExpanded(cursor.getInt(1) == 1);
875 acc.setAmountsExpanded(cursor.getInt(2) == 1);
876 acc.setHasSubAccounts(false);
878 try (Cursor c2 = db.rawQuery(
879 "SELECT value, currency FROM account_values WHERE profile = ?" + " " +
880 "AND account = ?", new String[]{profileUUID, accName}))
882 while (c2.moveToNext()) {
883 acc.addAmount(c2.getFloat(0), c2.getString(1));
888 map.put(accName, acc);
890 Logger.debug("async-acc", "AccountListLoader::run() query execution done");
896 Logger.debug("async-acc", "AccountListLoader::run() posting new list");
897 profile.allAccounts = list;
898 profile.updateAccountsMap(list);
899 profile.updateDisplayedAccounts();
903 static class AccountListDisplayedFilter extends Thread {
904 private final MobileLedgerProfile profile;
905 private final List<LedgerAccount> list;
906 AccountListDisplayedFilter(MobileLedgerProfile profile, List<LedgerAccount> list) {
907 this.profile = profile;
912 List<LedgerAccount> newDisplayed = new ArrayList<>();
913 Logger.debug("dFilter", "waiting for synchronized block");
914 Logger.debug("dFilter", String.format(Locale.US,
915 "entered synchronized block (about to examine %d accounts)", list.size()));
916 for (LedgerAccount a : list) {
917 if (isInterrupted()) {
925 if (!isInterrupted()) {
926 profile.displayedAccounts.postValue(newDisplayed);
928 Logger.debug("dFilter", "left synchronized block");
932 private static class AccountListSaver extends Thread {
933 private final MobileLedgerProfile profile;
934 private final List<LedgerAccount> list;
935 private final boolean storeUiFields;
936 AccountListSaver(MobileLedgerProfile profile, List<LedgerAccount> list,
937 boolean storeUiFields) {
939 this.profile = profile;
940 this.storeUiFields = storeUiFields;
944 SQLiteDatabase db = App.getDatabase();
945 db.beginTransactionNonExclusive();
947 int generation = profile.getNextAccountsGeneration(db);
950 for (LedgerAccount acc : list) {
951 profile.storeAccount(db, generation, acc, storeUiFields);
955 profile.deleteNotPresentAccounts(db, generation);
958 profile.setLastUpdateStamp();
959 db.setTransactionSuccessful();
967 private static class TransactionListSaver extends Thread {
968 private final MobileLedgerProfile profile;
969 private final List<LedgerTransaction> list;
970 TransactionListSaver(MobileLedgerProfile profile, List<LedgerTransaction> list) {
972 this.profile = profile;
976 SQLiteDatabase db = App.getDatabase();
977 db.beginTransactionNonExclusive();
979 Logger.debug("db/benchmark",
980 String.format(Locale.US, "Storing %d transactions", list.size()));
981 int generation = profile.getNextTransactionsGeneration(db);
982 Logger.debug("db/benchmark",
983 String.format(Locale.US, "Got next generation of %d", generation));
986 for (LedgerTransaction tr : list) {
987 profile.storeTransaction(db, generation, tr);
991 Logger.debug("db/benchmark", "Done storing transactions");
992 profile.deleteNotPresentTransactions(db, generation);
995 profile.setLastUpdateStamp();
996 db.setTransactionSuccessful();
1004 private static class AccountAndTransactionListSaver extends Thread {
1005 private final MobileLedgerProfile profile;
1006 private final List<LedgerAccount> accounts;
1007 private final List<LedgerTransaction> transactions;
1008 private final boolean storeAccUiFields;
1009 AccountAndTransactionListSaver(MobileLedgerProfile profile, List<LedgerAccount> accounts,
1010 List<LedgerTransaction> transactions,
1011 boolean storeAccUiFields) {
1012 this.accounts = accounts;
1013 this.transactions = transactions;
1014 this.profile = profile;
1015 this.storeAccUiFields = storeAccUiFields;
1019 SQLiteDatabase db = App.getDatabase();
1020 db.beginTransactionNonExclusive();
1022 int accountsGeneration = profile.getNextAccountsGeneration(db);
1023 if (isInterrupted())
1026 int transactionsGeneration = profile.getNextTransactionsGeneration(db);
1027 if (isInterrupted()) {
1031 for (LedgerAccount acc : accounts) {
1032 profile.storeAccount(db, accountsGeneration, acc, storeAccUiFields);
1033 if (isInterrupted())
1037 for (LedgerTransaction tr : transactions) {
1038 profile.storeTransaction(db, transactionsGeneration, tr);
1039 if (isInterrupted()) {
1044 profile.deleteNotPresentAccounts(db, accountsGeneration);
1045 if (isInterrupted()) {
1048 profile.deleteNotPresentTransactions(db, transactionsGeneration);
1049 if (isInterrupted())
1052 profile.setLastUpdateStamp();
1054 db.setTransactionSuccessful();
1057 db.endTransaction();