2 * Copyright © 2021 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.Context;
21 import android.content.Intent;
22 import android.content.res.Resources;
23 import android.database.Cursor;
24 import android.database.sqlite.SQLiteDatabase;
25 import android.os.AsyncTask;
26 import android.os.Bundle;
27 import android.util.SparseArray;
29 import androidx.annotation.Nullable;
30 import androidx.room.Transaction;
32 import net.ktnx.mobileledger.App;
33 import net.ktnx.mobileledger.R;
34 import net.ktnx.mobileledger.async.DbOpQueue;
35 import net.ktnx.mobileledger.dao.AccountDAO;
36 import net.ktnx.mobileledger.dao.DescriptionHistoryDAO;
37 import net.ktnx.mobileledger.dao.OptionDAO;
38 import net.ktnx.mobileledger.dao.ProfileDAO;
39 import net.ktnx.mobileledger.dao.TransactionDAO;
40 import net.ktnx.mobileledger.db.AccountValue;
41 import net.ktnx.mobileledger.db.AccountWithAmounts;
42 import net.ktnx.mobileledger.db.DB;
43 import net.ktnx.mobileledger.db.Profile;
44 import net.ktnx.mobileledger.json.API;
45 import net.ktnx.mobileledger.ui.profiles.ProfileDetailActivity;
46 import net.ktnx.mobileledger.ui.profiles.ProfileDetailFragment;
47 import net.ktnx.mobileledger.utils.Logger;
48 import net.ktnx.mobileledger.utils.Misc;
49 import net.ktnx.mobileledger.utils.SimpleDate;
51 import org.jetbrains.annotations.Contract;
53 import java.util.ArrayList;
54 import java.util.HashMap;
55 import java.util.List;
57 import java.util.Objects;
59 import static net.ktnx.mobileledger.utils.Logger.debug;
61 public final class MobileLedgerProfile {
62 // N.B. when adding new fields, update the copy-constructor below
63 private final long id;
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 API apiVersion = API.auto;
77 private FutureDates futureDates = FutureDates.None;
78 private boolean accountsLoaded;
79 private boolean transactionsLoaded;
80 private HledgerVersion detectedVersion;
81 // N.B. when adding new fields, update the copy-constructor below
82 transient private AccountAndTransactionListSaver accountAndTransactionListSaver;
83 public MobileLedgerProfile(long id) {
86 public MobileLedgerProfile(MobileLedgerProfile origin) {
89 permitPosting = origin.permitPosting;
90 showCommentsByDefault = origin.showCommentsByDefault;
91 showCommodityByDefault = origin.showCommodityByDefault;
92 preferredAccountsFilter = origin.preferredAccountsFilter;
94 authEnabled = origin.authEnabled;
95 authUserName = origin.authUserName;
96 authPassword = origin.authPassword;
97 themeHue = origin.themeHue;
98 orderNo = origin.orderNo;
99 futureDates = origin.futureDates;
100 apiVersion = origin.apiVersion;
101 defaultCommodity = origin.defaultCommodity;
102 accountsLoaded = origin.accountsLoaded;
103 transactionsLoaded = origin.transactionsLoaded;
104 if (origin.detectedVersion != null)
105 detectedVersion = new HledgerVersion(origin.detectedVersion);
107 // loads all profiles into Data.profiles
108 // returns the profile with the given UUID
109 public static MobileLedgerProfile loadAllFromDB(long currentProfileId) {
110 MobileLedgerProfile result = null;
111 ArrayList<MobileLedgerProfile> list = new ArrayList<>();
112 SQLiteDatabase db = App.getDatabase();
113 try (Cursor cursor = db.rawQuery("SELECT id, name, url, use_authentication, auth_user, " +
114 "auth_password, permit_posting, theme, order_no, " +
115 "preferred_accounts_filter, future_dates, api_version, " +
116 "show_commodity_by_default, default_commodity, " +
117 "show_comments_by_default, detected_version_pre_1_19, " +
118 "detected_version_major, detected_version_minor FROM " +
119 "profiles order by order_no", null))
121 while (cursor.moveToNext()) {
122 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getLong(0));
123 item.setName(cursor.getString(1));
124 item.setUrl(cursor.getString(2));
125 item.setAuthEnabled(cursor.getInt(3) == 1);
126 item.setAuthUserName(cursor.getString(4));
127 item.setAuthPassword(cursor.getString(5));
128 item.setPostingPermitted(cursor.getInt(6) == 1);
129 item.setThemeId(cursor.getInt(7));
130 item.orderNo = cursor.getInt(8);
131 item.setPreferredAccountsFilter(cursor.getString(9));
132 item.setFutureDates(cursor.getInt(10));
133 item.setApiVersion(cursor.getInt(11));
134 item.setShowCommodityByDefault(cursor.getInt(12) == 1);
135 item.setDefaultCommodity(cursor.getString(13));
136 item.setShowCommentsByDefault(cursor.getInt(14) == 1);
138 boolean pre_1_20 = cursor.getInt(15) == 1;
139 int major = cursor.getInt(16);
140 int minor = cursor.getInt(17);
142 if (!pre_1_20 && major == 0 && minor == 0) {
143 item.detectedVersion = null;
146 item.detectedVersion = new HledgerVersion(true);
149 item.detectedVersion = new HledgerVersion(major, minor);
153 if (item.getId() == currentProfileId)
157 Data.profiles.postValue(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 id=?",
167 new Object[]{orderNo, p.getId()});
171 db.setTransactionSuccessful();
177 static public void startEditProfileActivity(Context context, MobileLedgerProfile profile) {
178 Intent intent = new Intent(context, ProfileDetailActivity.class);
179 Bundle args = new Bundle();
180 if (profile != null) {
181 int index = Data.getProfileIndex(profile);
183 intent.putExtra(ProfileDetailFragment.ARG_ITEM_ID, index);
185 intent.putExtras(args);
186 context.startActivity(intent, args);
188 public static MobileLedgerProfile fromDBO(Profile newProfile) {
189 MobileLedgerProfile p = new MobileLedgerProfile(newProfile.getId());
190 p.setDetectedVersion(new HledgerVersion(newProfile.getDetectedVersionMajor(),
191 newProfile.getDetectedVersionMinor()));
192 p.setApiVersion(newProfile.getApiVersion());
193 p.setAuthEnabled(newProfile.useAuthentication());
194 p.setAuthUserName(newProfile.getAuthUser());
195 p.setAuthPassword(newProfile.getAuthPassword());
196 p.setDefaultCommodity(newProfile.getDefaultCommodity());
197 p.setFutureDates(newProfile.getFutureDates());
198 p.setName(newProfile.getName());
199 p.setPostingPermitted(newProfile.permitPosting());
200 p.setPreferredAccountsFilter(newProfile.getPreferredAccountsFilter());
201 p.setShowCommentsByDefault(newProfile.getShowCommentsByDefault());
202 p.setShowCommodityByDefault(newProfile.getShowCommodityByDefault());
203 p.setUrl(newProfile.getUrl());
204 p.setThemeId(newProfile.getTheme());
208 public HledgerVersion getDetectedVersion() {
209 return detectedVersion;
211 public void setDetectedVersion(HledgerVersion detectedVersion) {
212 this.detectedVersion = detectedVersion;
214 @Contract(value = "null -> false", pure = true)
216 public boolean equals(@Nullable Object obj) {
221 if (obj.getClass() != this.getClass())
224 MobileLedgerProfile p = (MobileLedgerProfile) obj;
227 if (!name.equals(p.name))
229 if (permitPosting != p.permitPosting)
231 if (showCommentsByDefault != p.showCommentsByDefault)
233 if (showCommodityByDefault != p.showCommodityByDefault)
235 if (!Objects.equals(defaultCommodity, p.defaultCommodity))
237 if (!Objects.equals(preferredAccountsFilter, p.preferredAccountsFilter))
239 if (!Objects.equals(url, p.url))
241 if (authEnabled != p.authEnabled)
243 if (!Objects.equals(authUserName, p.authUserName))
245 if (!Objects.equals(authPassword, p.authPassword))
247 if (themeHue != p.themeHue)
249 if (apiVersion != p.apiVersion)
251 if (!Objects.equals(detectedVersion, p.detectedVersion))
253 return futureDates == p.futureDates;
255 public boolean getShowCommentsByDefault() {
256 return showCommentsByDefault;
258 public void setShowCommentsByDefault(boolean newValue) {
259 this.showCommentsByDefault = newValue;
261 public boolean getShowCommodityByDefault() {
262 return showCommodityByDefault;
264 public void setShowCommodityByDefault(boolean showCommodityByDefault) {
265 this.showCommodityByDefault = showCommodityByDefault;
267 public String getDefaultCommodity() {
268 return defaultCommodity;
270 public void setDefaultCommodity(String defaultCommodity) {
271 this.defaultCommodity = defaultCommodity;
273 public void setDefaultCommodity(CharSequence defaultCommodity) {
274 if (defaultCommodity == null)
275 this.defaultCommodity = null;
277 this.defaultCommodity = String.valueOf(defaultCommodity);
279 public API getApiVersion() {
282 public void setApiVersion(API apiVersion) {
283 this.apiVersion = apiVersion;
285 public void setApiVersion(int apiVersion) {
286 this.apiVersion = API.valueOf(apiVersion);
288 public FutureDates getFutureDates() {
291 public void setFutureDates(int anInt) {
292 futureDates = FutureDates.valueOf(anInt);
294 public void setFutureDates(FutureDates futureDates) {
295 this.futureDates = futureDates;
297 public String getPreferredAccountsFilter() {
298 return preferredAccountsFilter;
300 public void setPreferredAccountsFilter(String preferredAccountsFilter) {
301 this.preferredAccountsFilter = preferredAccountsFilter;
303 public void setPreferredAccountsFilter(CharSequence preferredAccountsFilter) {
304 setPreferredAccountsFilter(String.valueOf(preferredAccountsFilter));
306 public boolean isPostingPermitted() {
307 return permitPosting;
309 public void setPostingPermitted(boolean permitPosting) {
310 this.permitPosting = permitPosting;
312 public long getId() {
315 public String getName() {
318 public void setName(CharSequence text) {
319 setName(String.valueOf(text));
321 public void setName(String name) {
324 public String getUrl() {
327 public void setUrl(CharSequence text) {
328 setUrl(String.valueOf(text));
330 public void setUrl(String url) {
333 public boolean isAuthEnabled() {
336 public void setAuthEnabled(boolean authEnabled) {
337 this.authEnabled = authEnabled;
339 public String getAuthUserName() {
342 public void setAuthUserName(CharSequence text) {
343 setAuthUserName(String.valueOf(text));
345 public void setAuthUserName(String authUserName) {
346 this.authUserName = authUserName;
348 public String getAuthPassword() {
351 public void setAuthPassword(CharSequence text) {
352 setAuthPassword(String.valueOf(text));
354 public void setAuthPassword(String authPassword) {
355 this.authPassword = authPassword;
357 public void storeInDB() {
358 SQLiteDatabase db = App.getDatabase();
359 db.beginTransactionNonExclusive();
361 // debug("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
362 // "url=%s, permit_posting=%s, authEnabled=%s, " +
363 // "themeHue=%d", uuid, name, url,
364 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeHue));
365 db.execSQL("REPLACE INTO profiles(id, name, permit_posting, url, " +
366 "use_authentication, auth_user, auth_password, theme, order_no, " +
367 "preferred_accounts_filter, future_dates, api_version, " +
368 "show_commodity_by_default, default_commodity, show_comments_by_default," +
369 "detected_version_pre_1_19, detected_version_major, " +
370 "detected_version_minor) " +
371 "VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
372 new Object[]{id, name, permitPosting, url, authEnabled,
373 authEnabled ? authUserName : null,
374 authEnabled ? authPassword : null, themeHue, orderNo,
375 preferredAccountsFilter, futureDates.toInt(), apiVersion.toInt(),
376 showCommodityByDefault, defaultCommodity, showCommentsByDefault,
377 (detectedVersion != null) && detectedVersion.isPre_1_20_1(),
378 (detectedVersion == null) ? 0 : detectedVersion.getMajor(),
379 (detectedVersion == null) ? 0 : detectedVersion.getMinor()
381 db.setTransactionSuccessful();
387 public void storeAccount(SQLiteDatabase db, int generation, LedgerAccount acc,
388 boolean storeUiFields) {
389 // replace into is a bad idea because it would reset hidden to its default value
390 // we like the default, but for new accounts only
391 String sql = "update accounts set generation = ?";
392 List<Object> params = new ArrayList<>();
393 params.add(generation);
395 sql += ", expanded=?";
396 params.add(acc.isExpanded() ? 1 : 0);
398 sql += " where profile_id=? and name=?";
400 params.add(acc.getName());
401 db.execSQL(sql, params.toArray());
403 db.execSQL("insert into accounts(profile_id, name, name_upper, parent_name, level, " +
404 "expanded, generation) select ?,?,?,?,?,0,? where (select changes() = 0)",
405 new Object[]{id, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
406 acc.getLevel(), generation
408 // debug("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
410 public void storeTransaction(SQLiteDatabase db, int generation, LedgerTransaction tr) {
412 // Logger.debug("storeTransaction", String.format(Locale.US, "ID %d", tr.getId()));
413 SimpleDate d = tr.getDate();
414 db.execSQL("UPDATE transactions SET year=?, month=?, day=?, description=?, comment=?, " +
415 "data_hash=?, generation=? WHERE profile_id=? AND ledger_id=?",
416 new Object[]{d.year, d.month, d.day, tr.getDescription(), tr.getComment(),
417 tr.getDataHash(), generation, id, tr.getId()
420 "INSERT INTO transactions(profile_id, ledger_id, year, month, day, description, " +
421 "comment, data_hash, generation) " +
422 "select ?,?,?,?,?,?,?,?,? WHERE (select changes() = 0)",
423 new Object[]{id, tr.getId(), tr.getDate().year, tr.getDate().month,
424 tr.getDate().day, tr.getDescription(), tr.getComment(),
425 tr.getDataHash(), generation
428 int accountOrderNo = 1;
429 for (LedgerTransactionAccount item : tr.getAccounts()) {
430 db.execSQL("UPDATE transaction_accounts SET account_name=?, amount=?, currency=?, " +
431 "comment=?, generation=? " + "WHERE transaction_id=? AND order_no=?",
432 new Object[]{item.getAccountName(), item.getAmount(),
433 Misc.nullIsEmpty(item.getCurrency()), item.getComment(),
434 generation, tr.getId(), accountOrderNo
436 db.execSQL("INSERT INTO transaction_accounts(transaction_id, " +
437 "order_no, account_name, amount, currency, comment, generation) " +
438 "select ?, ?, ?, ?, ?, ?, ? WHERE (select changes() = 0)",
439 new Object[]{tr.getId(), accountOrderNo, item.getAccountName(),
440 item.getAmount(), Misc.nullIsEmpty(item.getCurrency()),
441 item.getComment(), generation
446 // debug("profile", String.format("Transaction %d stored", tr.getId()));
448 public String getOption(String name, String default_value) {
449 SQLiteDatabase db = App.getDatabase();
450 try (Cursor cursor = db.rawQuery(
451 "select value from options where profile_id = ? and name=?",
452 new String[]{String.valueOf(id), name}))
454 if (cursor.moveToFirst()) {
455 String result = cursor.getString(0);
457 if (result == null) {
458 debug("profile", "returning default value for " + name);
459 result = default_value;
462 debug("profile", String.format("option %s=%s", name, result));
467 return default_value;
469 catch (Exception e) {
470 debug("db", "returning default value for " + name, e);
471 return default_value;
474 public long getLongOption(String name, long default_value) {
476 String result = getOption(name, "");
477 if ((result == null) || result.isEmpty()) {
478 debug("profile", String.format("Returning default value for option %s", name));
479 longResult = default_value;
483 longResult = Long.parseLong(result);
484 debug("profile", String.format("option %s=%s", name, result));
486 catch (Exception e) {
487 debug("profile", String.format("Returning default value for option %s", name), e);
488 longResult = default_value;
494 public void setOption(String name, String value) {
495 debug("profile", String.format("setting option %s=%s", name, value));
496 DbOpQueue.add("insert or replace into options(profile_id, name, value) values(?, ?, ?);",
497 new String[]{String.valueOf(id), name, value});
499 public void setLongOption(String name, long value) {
500 setOption(name, String.valueOf(value));
502 public void removeFromDB() {
503 ProfileDAO dao = DB.get()
505 AsyncTask.execute(() -> dao.deleteSync(dao.getByIdSync(id)));
507 public LedgerTransaction loadTransaction(int transactionId) {
508 LedgerTransaction tr = new LedgerTransaction(transactionId, this.id);
509 tr.loadData(App.getDatabase());
513 public int getThemeHue() {
514 // debug("profile", String.format("Profile.getThemeHue() returning %d", themeHue));
515 return this.themeHue;
517 public void setThemeHue(Object o) {
518 setThemeId(Integer.parseInt(String.valueOf(o)));
520 public void setThemeId(int themeHue) {
521 // debug("profile", String.format("Profile.setThemeHue(%d) called", themeHue));
522 this.themeHue = themeHue;
524 public int getNextTransactionsGeneration(SQLiteDatabase db) {
525 try (Cursor c = db.rawQuery(
526 "SELECT generation FROM transactions WHERE profile_id=? LIMIT 1",
527 new String[]{String.valueOf(id)}))
530 return c.getInt(0) + 1;
534 private void deleteNotPresentTransactions(SQLiteDatabase db, int generation) {
535 Logger.debug("db/benchmark", "Deleting obsolete transactions");
537 "DELETE FROM transaction_accounts WHERE (select t.profile_id from transactions t " +
538 "where t.id=transaction_accounts.transaction_id)=? AND generation" + " <> ?",
539 new Object[]{id, generation});
540 db.execSQL("DELETE FROM transactions WHERE profile_id=? AND generation <> ?",
541 new Object[]{id, generation});
542 Logger.debug("db/benchmark", "Done deleting obsolete transactions");
545 public void wipeAllDataSync() {
546 OptionDAO optDao = DB.get()
548 optDao.deleteSync(optDao.allForProfileSync(id));
550 AccountDAO accDao = DB.get()
552 accDao.deleteSync(accDao.allForProfileSync(id));
554 TransactionDAO trnDao = DB.get()
555 .getTransactionDAO();
556 trnDao.deleteSync(trnDao.allForProfileSync(id));
558 DescriptionHistoryDAO descDao = DB.get()
559 .getDescriptionHistoryDAO();
562 public void wipeAllData() {
563 AsyncTask.execute(this::wipeAllDataSync);
565 public List<Currency> getCurrencies() {
566 SQLiteDatabase db = App.getDatabase();
568 ArrayList<Currency> result = new ArrayList<>();
570 try (Cursor c = db.rawQuery("SELECT c.id, c.name, c.position, c.has_gap FROM currencies c",
573 while (c.moveToNext()) {
574 Currency currency = new Currency(c.getInt(0), c.getString(1),
575 Currency.Position.valueOf(c.getString(2)), c.getInt(3) == 1);
576 result.add(currency);
582 Currency loadCurrencyByName(String name) {
583 SQLiteDatabase db = App.getDatabase();
584 Currency result = tryLoadCurrencyByName(db, name);
586 throw new RuntimeException(String.format("Unable to load currency '%s'", name));
589 private Currency tryLoadCurrencyByName(SQLiteDatabase db, String name) {
590 try (Cursor cursor = db.rawQuery(
591 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.name=?",
594 if (cursor.moveToFirst()) {
595 return new Currency(cursor.getInt(0), cursor.getString(1),
596 Currency.Position.valueOf(cursor.getString(2)), cursor.getInt(3) == 1);
601 public void storeAccountAndTransactionListAsync(List<LedgerAccount> accounts,
602 List<LedgerTransaction> transactions) {
603 if (accountAndTransactionListSaver != null)
604 accountAndTransactionListSaver.interrupt();
606 accountAndTransactionListSaver =
607 new AccountAndTransactionListSaver(this, accounts, transactions);
608 accountAndTransactionListSaver.start();
610 private Currency tryLoadCurrencyById(SQLiteDatabase db, int id) {
611 try (Cursor cursor = db.rawQuery(
612 "SELECT c.id, c.name, c.position, c.has_gap FROM currencies c WHERE c.id=?",
613 new String[]{String.valueOf(id)}))
615 if (cursor.moveToFirst()) {
616 return new Currency(cursor.getInt(0), cursor.getString(1),
617 Currency.Position.valueOf(cursor.getString(2)), cursor.getInt(3) == 1);
622 public Currency loadCurrencyById(int id) {
623 SQLiteDatabase db = App.getDatabase();
624 Currency result = tryLoadCurrencyById(db, id);
626 throw new RuntimeException(String.format("Unable to load currency with id '%d'", id));
630 public enum FutureDates {
631 None(0), OneWeek(7), TwoWeeks(14), OneMonth(30), TwoMonths(60), ThreeMonths(90),
632 SixMonths(180), OneYear(365), All(-1);
633 private static final SparseArray<FutureDates> map = new SparseArray<>();
636 for (FutureDates item : FutureDates.values()) {
637 map.put(item.value, item);
641 private final int value;
642 FutureDates(int value) {
645 public static FutureDates valueOf(int i) {
646 return map.get(i, None);
651 public String getText(Resources resources) {
654 return resources.getString(R.string.future_dates_7);
656 return resources.getString(R.string.future_dates_14);
658 return resources.getString(R.string.future_dates_30);
660 return resources.getString(R.string.future_dates_60);
662 return resources.getString(R.string.future_dates_90);
664 return resources.getString(R.string.future_dates_180);
666 return resources.getString(R.string.future_dates_365);
668 return resources.getString(R.string.future_dates_all);
670 return resources.getString(R.string.future_dates_none);
675 private static class AccountAndTransactionListSaver extends Thread {
676 private final MobileLedgerProfile profile;
677 private final List<LedgerAccount> accounts;
678 private final List<LedgerTransaction> transactions;
679 AccountAndTransactionListSaver(MobileLedgerProfile profile, List<LedgerAccount> accounts,
680 List<LedgerTransaction> transactions) {
681 this.accounts = accounts;
682 this.transactions = transactions;
683 this.profile = profile;
685 public int getNextDescriptionsGeneration(SQLiteDatabase db) {
687 try (Cursor c = db.rawQuery("SELECT generation FROM description_history LIMIT 1",
690 if (c.moveToFirst()) {
691 generation = c.getInt(0) + 1;
696 void deleteNotPresentDescriptions(SQLiteDatabase db, int generation) {
697 Logger.debug("db/benchmark", "Deleting obsolete descriptions");
698 db.execSQL("DELETE FROM description_history WHERE generation <> ?",
699 new Object[]{generation});
700 db.execSQL("DELETE FROM description_history WHERE generation <> ?",
701 new Object[]{generation});
702 Logger.debug("db/benchmark", "Done deleting obsolete descriptions");
706 SQLiteDatabase db = App.getDatabase();
707 db.beginTransactionNonExclusive();
709 int transactionsGeneration = profile.getNextTransactionsGeneration(db);
713 for (LedgerTransaction tr : transactions) {
714 profile.storeTransaction(db, transactionsGeneration, tr);
719 profile.deleteNotPresentTransactions(db, transactionsGeneration);
720 if (isInterrupted()) {
724 Map<String, Boolean> unique = new HashMap<>();
726 debug("descriptions", "Starting refresh");
727 int descriptionsGeneration = getNextDescriptionsGeneration(db);
728 try (Cursor c = db.rawQuery("SELECT distinct description from transactions",
731 while (c.moveToNext()) {
732 String description = c.getString(0);
733 String descriptionUpper = description.toUpperCase();
734 if (unique.containsKey(descriptionUpper))
737 storeDescription(db, descriptionsGeneration, description, descriptionUpper);
739 unique.put(descriptionUpper, true);
742 deleteNotPresentDescriptions(db, descriptionsGeneration);
744 db.setTransactionSuccessful();
750 AsyncTask.execute(() -> {
751 List<AccountWithAmounts> list = new ArrayList<>();
753 final AccountDAO dao = DB.get()
756 for (LedgerAccount acc : accounts) {
757 AccountWithAmounts rec = new AccountWithAmounts();
758 rec.account = acc.toDBO();
763 rec.amounts = new ArrayList<>();
764 for (LedgerAmount amt : acc.getAmounts()) {
765 AccountValue av = new AccountValue();
766 av.setCurrency(amt.getCurrency());
767 av.setValue(amt.getAmount());
778 dao.storeAccountsSync(list, profile.getId());
781 private void storeDescription(SQLiteDatabase db, int generation, String description,
782 String descriptionUpper) {
783 db.execSQL("UPDATE description_history SET description=?, generation=? WHERE " +
784 "description_upper=?", new Object[]{description, generation, descriptionUpper
787 "INSERT INTO description_history(description, description_upper, generation) " +
788 "select ?,?,? WHERE (select changes() = 0)",
789 new Object[]{description, descriptionUpper, generation