2 * Copyright © 2019 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
9 * MoLe is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License terms for details.
14 * You should have received a copy of the GNU General Public License
15 * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.model;
20 import android.database.Cursor;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.util.Log;
24 import net.ktnx.mobileledger.utils.Globals;
25 import net.ktnx.mobileledger.utils.MLDB;
27 import java.util.ArrayList;
28 import java.util.Date;
29 import java.util.List;
30 import java.util.UUID;
32 import androidx.annotation.NonNull;
33 import androidx.annotation.Nullable;
35 public final class MobileLedgerProfile {
38 private boolean permitPosting;
40 private boolean authEnabled;
41 private String authUserName;
42 private String authPassword;
44 private int orderNo = -1;
45 public MobileLedgerProfile(String uuid, String name, boolean permitPosting, String url,
46 boolean authEnabled, String authUserName, String authPassword) {
47 this(uuid, name, permitPosting, url, authEnabled, authUserName, authPassword, -1);
50 public MobileLedgerProfile(String uuid, String name, boolean permitPosting, String url,
51 boolean authEnabled, String authUserName, String authPassword,
55 this.permitPosting = permitPosting;
57 this.authEnabled = authEnabled;
58 this.authUserName = authUserName;
59 this.authPassword = authPassword;
60 this.themeId = themeId;
63 public MobileLedgerProfile(CharSequence name, boolean permitPosting, CharSequence url,
64 boolean authEnabled, CharSequence authUserName,
65 CharSequence authPassword, int themeId) {
66 this.uuid = String.valueOf(UUID.randomUUID());
67 this.name = String.valueOf(name);
68 this.permitPosting = permitPosting;
69 this.url = String.valueOf(url);
70 this.authEnabled = authEnabled;
71 this.authUserName = String.valueOf(authUserName);
72 this.authPassword = String.valueOf(authPassword);
73 this.themeId = themeId;
76 // loads all profiles into Data.profiles
77 // returns the profile with the given UUID
78 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
79 MobileLedgerProfile result = null;
80 List<MobileLedgerProfile> list = new ArrayList<>();
81 SQLiteDatabase db = MLDB.getReadableDatabase();
82 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
83 "auth_password, permit_posting, theme, order_no FROM " +
84 "profiles order by order_no", null))
86 while (cursor.moveToNext()) {
87 MobileLedgerProfile item =
88 new MobileLedgerProfile(cursor.getString(0), cursor.getString(1),
89 cursor.getInt(6) == 1, cursor.getString(2), cursor.getInt(3) == 1,
90 cursor.getString(4), cursor.getString(5), cursor.getInt(7));
91 item.orderNo = cursor.getInt(8);
93 if (item.getUuid().equals(currentProfileUUID)) result = item;
96 Data.profiles.setList(list);
99 public static void storeProfilesOrder() {
100 SQLiteDatabase db = MLDB.getWritableDatabase();
101 db.beginTransaction();
104 for (MobileLedgerProfile p : Data.profiles.getList()) {
105 db.execSQL("update profiles set order_no=? where uuid=?",
106 new Object[]{orderNo, p.getUuid()});
110 db.setTransactionSuccessful();
116 public boolean isPostingPermitted() {
117 return permitPosting;
119 public void setPostingPermitted(boolean permitPosting) {
120 this.permitPosting = permitPosting;
122 public String getUuid() {
125 public String getName() {
128 public void setName(String name) {
131 public void setName(CharSequence text) {
132 setName(String.valueOf(text));
134 public String getUrl() {
137 public void setUrl(String url) {
140 public void setUrl(CharSequence text) {
141 setUrl(String.valueOf(text));
143 public boolean isAuthEnabled() {
146 public void setAuthEnabled(boolean authEnabled) {
147 this.authEnabled = authEnabled;
149 public String getAuthUserName() {
152 public void setAuthUserName(String authUserName) {
153 this.authUserName = authUserName;
155 public void setAuthUserName(CharSequence text) {
156 setAuthUserName(String.valueOf(text));
158 public String getAuthPassword() {
161 public void setAuthPassword(String authPassword) {
162 this.authPassword = authPassword;
164 public void setAuthPassword(CharSequence text) {
165 setAuthPassword(String.valueOf(text));
167 public void storeInDB() {
168 SQLiteDatabase db = MLDB.getWritableDatabase();
169 db.beginTransaction();
171 // Log.d("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
172 // "url=%s, permit_posting=%s, authEnabled=%s, " +
173 // "themeId=%d", uuid, name, url,
174 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
175 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
176 "use_authentication, auth_user, " +
177 "auth_password, theme, order_no) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
178 new Object[]{uuid, name, permitPosting, url, authEnabled,
179 authEnabled ? authUserName : null,
180 authEnabled ? authPassword : null, themeId, orderNo
182 db.setTransactionSuccessful();
188 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
189 // replace into is a bad idea because it would reset hidden to its default value
190 // we like the default, but for new accounts only
191 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
192 "where profile=? and name = ?",
193 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
197 "insert into accounts(profile, name, name_upper, parent_name, level, hidden, expanded, keep) " +
198 "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
199 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
200 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
202 // Log.d("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
204 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
205 db.execSQL("replace into account_values(profile, account, " +
206 "currency, value, keep) values(?, ?, ?, ?, 1);",
207 new Object[]{uuid, name, currency, amount});
209 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
211 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
212 new Object[]{uuid, tr.getId()});
213 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
214 new Object[]{uuid, tr.getId()});
216 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
217 "values(?,?,?,?,?,1)",
218 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
219 tr.getDescription(), tr.getDataHash()
222 for (LedgerTransactionAccount item : tr.getAccounts()) {
223 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
224 "account_name, amount, currency) values(?, ?, ?, ?, ?)",
225 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
229 Log.d("profile", String.format("Transaction %d stored", tr.getId()));
231 public String getOption(String name, String default_value) {
232 SQLiteDatabase db = MLDB.getReadableDatabase();
233 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
234 new String[]{uuid, name}))
236 if (cursor.moveToFirst()) {
237 String result = cursor.getString(0);
239 if (result == null) {
240 Log.d("profile", "returning default value for " + name);
241 result = default_value;
243 else Log.d("profile", String.format("option %s=%s", name, result));
247 else return default_value;
249 catch (Exception e) {
250 Log.d("db", "returning default value for " + name, e);
251 return default_value;
254 public long getLongOption(String name, long default_value) {
256 String result = getOption(name, "");
257 if ((result == null) || result.isEmpty()) {
258 Log.d("profile", String.format("Returning default value for option %s", name));
259 longResult = default_value;
263 longResult = Long.parseLong(result);
264 Log.d("profile", String.format("option %s=%s", name, result));
266 catch (Exception e) {
267 Log.d("profile", String.format("Returning default value for option %s", name), e);
268 longResult = default_value;
274 public void setOption(String name, String value) {
275 Log.d("profile", String.format("setting option %s=%s", name, value));
276 SQLiteDatabase db = MLDB.getWritableDatabase();
277 db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
278 new String[]{uuid, name, value});
280 public void setLongOption(String name, long value) {
281 setOption(name, String.valueOf(value));
283 public void removeFromDB() {
284 SQLiteDatabase db = MLDB.getWritableDatabase();
285 Log.d("db", String.format("removing profile %s from DB", uuid));
287 db.beginTransaction();
288 db.execSQL("delete from profiles where uuid=?", new Object[]{uuid});
289 db.execSQL("delete from accounts where profile=?", new Object[]{uuid});
290 db.execSQL("delete from account_values where profile=?", new Object[]{uuid});
291 db.execSQL("delete from transactions where profile=?", new Object[]{uuid});
292 db.execSQL("delete from transaction_accounts where profile=?", new Object[]{uuid});
293 db.setTransactionSuccessful();
300 public LedgerAccount loadAccount(String name) {
301 SQLiteDatabase db = MLDB.getReadableDatabase();
302 return loadAccount(db, name);
305 public LedgerAccount tryLoadAccount(String acct_name) {
306 SQLiteDatabase db = MLDB.getReadableDatabase();
307 return tryLoadAccount(db, acct_name);
310 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
311 LedgerAccount acc = tryLoadAccount(db, accName);
313 if (acc == null) throw new RuntimeException("Unable to load account with name " + accName);
318 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
319 try (Cursor cursor = db.rawQuery(
320 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
321 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
322 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
324 if (cursor.moveToFirst()) {
325 LedgerAccount acc = new LedgerAccount(accName);
326 acc.setHiddenByStar(cursor.getInt(0) == 1);
327 acc.setExpanded(cursor.getInt(1) == 1);
328 acc.setHasSubAccounts(cursor.getInt(2) == 1);
330 try (Cursor c2 = db.rawQuery(
331 "SELECT value, currency FROM account_values WHERE profile = ? " +
332 "AND account = ?", new String[]{uuid, accName}))
334 while (c2.moveToNext()) {
335 acc.addAmount(c2.getFloat(0), c2.getString(1));
344 public LedgerTransaction loadTransaction(int transactionId) {
345 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
346 tr.loadData(MLDB.getReadableDatabase());
350 public int getThemeId() {
351 // Log.d("profile", String.format("Profile.getThemeId() returning %d", themeId));
354 public void setThemeId(int themeId) {
355 // Log.d("profile", String.format("Profile.setThemeId(%d) called", themeId));
356 this.themeId = themeId;
358 public void setThemeId(Object o) {
359 setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
361 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
362 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
365 public void markAccountsAsNotPresent(SQLiteDatabase db) {
366 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
367 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
370 public void deleteNotPresentAccounts(SQLiteDatabase db) {
371 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
372 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
374 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
375 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
376 new Object[]{uuid, transaction.getId()
379 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
380 LedgerTransaction transaction) {
381 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
382 new Object[]{uuid, transaction.getId()
386 public void deleteNotPresentTransactions(SQLiteDatabase db) {
387 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
389 public void setLastUpdateStamp() {
390 Log.d("db", "Updating transaction value stamp");
391 Date now = new Date();
392 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
393 Data.lastUpdateDate.set(now);
395 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
396 List<LedgerAccount> result = new ArrayList<>();
397 SQLiteDatabase db = MLDB.getReadableDatabase();
398 try (Cursor c = db.rawQuery(
399 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
400 new String[]{uuid, acc.getName()}))
402 while (c.moveToNext()) {
403 LedgerAccount a = loadAccount(db, c.getString(0));
410 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
411 List<LedgerAccount> result = new ArrayList<>();
412 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
413 visibleList.add(acc);
415 SQLiteDatabase db = MLDB.getReadableDatabase();
416 try (Cursor c = db.rawQuery(
417 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
418 new String[]{uuid, acc.getName()}))
420 while (c.moveToNext()) {
421 LedgerAccount a = loadAccount(db, c.getString(0));
422 if (a.isVisible(visibleList)) {