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.getDatabase();
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.getDatabase();
101 db.beginTransaction();
104 for (int i = 0; i < Data.profiles.size(); i++) {
105 MobileLedgerProfile p = Data.profiles.get(i);
106 db.execSQL("update profiles set order_no=? where uuid=?",
107 new Object[]{orderNo, p.getUuid()});
111 db.setTransactionSuccessful();
117 public boolean isPostingPermitted() {
118 return permitPosting;
120 public void setPostingPermitted(boolean permitPosting) {
121 this.permitPosting = permitPosting;
123 public String getUuid() {
126 public String getName() {
129 public void setName(String name) {
132 public void setName(CharSequence text) {
133 setName(String.valueOf(text));
135 public String getUrl() {
138 public void setUrl(String url) {
141 public void setUrl(CharSequence text) {
142 setUrl(String.valueOf(text));
144 public boolean isAuthEnabled() {
147 public void setAuthEnabled(boolean authEnabled) {
148 this.authEnabled = authEnabled;
150 public String getAuthUserName() {
153 public void setAuthUserName(String authUserName) {
154 this.authUserName = authUserName;
156 public void setAuthUserName(CharSequence text) {
157 setAuthUserName(String.valueOf(text));
159 public String getAuthPassword() {
162 public void setAuthPassword(String authPassword) {
163 this.authPassword = authPassword;
165 public void setAuthPassword(CharSequence text) {
166 setAuthPassword(String.valueOf(text));
168 public void storeInDB() {
169 SQLiteDatabase db = MLDB.getDatabase();
170 db.beginTransaction();
172 // Log.d("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
173 // "url=%s, permit_posting=%s, authEnabled=%s, " +
174 // "themeId=%d", uuid, name, url,
175 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
176 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
177 "use_authentication, auth_user, " +
178 "auth_password, theme, order_no) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
179 new Object[]{uuid, name, permitPosting, url, authEnabled,
180 authEnabled ? authUserName : null,
181 authEnabled ? authPassword : null, themeId, orderNo
183 db.setTransactionSuccessful();
189 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
190 // replace into is a bad idea because it would reset hidden to its default value
191 // we like the default, but for new accounts only
192 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
193 "where profile=? and name = ?",
194 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
198 "insert into accounts(profile, name, name_upper, parent_name, level, hidden, expanded, keep) " +
199 "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
200 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
201 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
203 // Log.d("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
205 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
206 db.execSQL("replace into account_values(profile, account, " +
207 "currency, value, keep) values(?, ?, ?, ?, 1);",
208 new Object[]{uuid, name, currency, amount});
210 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
212 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
213 new Object[]{uuid, tr.getId()});
214 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
215 new Object[]{uuid, tr.getId()});
217 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
218 "values(?,?,?,?,?,1)",
219 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
220 tr.getDescription(), tr.getDataHash()
223 for (LedgerTransactionAccount item : tr.getAccounts()) {
224 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
225 "account_name, amount, currency) values(?, ?, ?, ?, ?)",
226 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
230 Log.d("profile", String.format("Transaction %d stored", tr.getId()));
232 public String getOption(String name, String default_value) {
233 SQLiteDatabase db = MLDB.getDatabase();
234 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
235 new String[]{uuid, name}))
237 if (cursor.moveToFirst()) {
238 String result = cursor.getString(0);
240 if (result == null) {
241 Log.d("profile", "returning default value for " + name);
242 result = default_value;
244 else Log.d("profile", String.format("option %s=%s", name, result));
248 else return default_value;
250 catch (Exception e) {
251 Log.d("db", "returning default value for " + name, e);
252 return default_value;
255 public long getLongOption(String name, long default_value) {
257 String result = getOption(name, "");
258 if ((result == null) || result.isEmpty()) {
259 Log.d("profile", String.format("Returning default value for option %s", name));
260 longResult = default_value;
264 longResult = Long.parseLong(result);
265 Log.d("profile", String.format("option %s=%s", name, result));
267 catch (Exception e) {
268 Log.d("profile", String.format("Returning default value for option %s", name), e);
269 longResult = default_value;
275 public void setOption(String name, String value) {
276 Log.d("profile", String.format("setting option %s=%s", name, value));
277 SQLiteDatabase db = MLDB.getDatabase();
278 db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
279 new String[]{uuid, name, value});
281 public void setLongOption(String name, long value) {
282 setOption(name, String.valueOf(value));
284 public void removeFromDB() {
285 SQLiteDatabase db = MLDB.getDatabase();
286 Log.d("db", String.format("removing profile %s from DB", uuid));
287 db.beginTransaction();
289 db.execSQL("delete from profiles where uuid=?", new Object[]{uuid});
290 db.execSQL("delete from accounts where profile=?", new Object[]{uuid});
291 db.execSQL("delete from account_values where profile=?", new Object[]{uuid});
292 db.execSQL("delete from transactions where profile=?", new Object[]{uuid});
293 db.execSQL("delete from transaction_accounts where profile=?", new Object[]{uuid});
294 db.setTransactionSuccessful();
301 public LedgerAccount loadAccount(String name) {
302 SQLiteDatabase db = MLDB.getDatabase();
303 return loadAccount(db, name);
306 public LedgerAccount tryLoadAccount(String acct_name) {
307 SQLiteDatabase db = MLDB.getDatabase();
308 return tryLoadAccount(db, acct_name);
311 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
312 LedgerAccount acc = tryLoadAccount(db, accName);
314 if (acc == null) throw new RuntimeException("Unable to load account with name " + accName);
319 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
320 try (Cursor cursor = db.rawQuery(
321 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
322 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
323 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
325 if (cursor.moveToFirst()) {
326 LedgerAccount acc = new LedgerAccount(accName);
327 acc.setHiddenByStar(cursor.getInt(0) == 1);
328 acc.setExpanded(cursor.getInt(1) == 1);
329 acc.setHasSubAccounts(cursor.getInt(2) == 1);
331 try (Cursor c2 = db.rawQuery(
332 "SELECT value, currency FROM account_values WHERE profile = ? " +
333 "AND account = ?", new String[]{uuid, accName}))
335 while (c2.moveToNext()) {
336 acc.addAmount(c2.getFloat(0), c2.getString(1));
345 public LedgerTransaction loadTransaction(int transactionId) {
346 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
347 tr.loadData(MLDB.getDatabase());
351 public int getThemeId() {
352 // Log.d("profile", String.format("Profile.getThemeId() returning %d", themeId));
355 public void setThemeId(int themeId) {
356 // Log.d("profile", String.format("Profile.setThemeId(%d) called", themeId));
357 this.themeId = themeId;
359 public void setThemeId(Object o) {
360 setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
362 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
363 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
366 public void markAccountsAsNotPresent(SQLiteDatabase db) {
367 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
368 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
371 public void deleteNotPresentAccounts(SQLiteDatabase db) {
372 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
373 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
375 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
376 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
377 new Object[]{uuid, transaction.getId()
380 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
381 LedgerTransaction transaction) {
382 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
383 new Object[]{uuid, transaction.getId()
387 public void deleteNotPresentTransactions(SQLiteDatabase db) {
388 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
390 public void setLastUpdateStamp() {
391 Log.d("db", "Updating transaction value stamp");
392 Date now = new Date();
393 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
394 Data.lastUpdateDate.set(now);
396 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
397 List<LedgerAccount> result = new ArrayList<>();
398 SQLiteDatabase db = MLDB.getDatabase();
399 try (Cursor c = db.rawQuery(
400 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
401 new String[]{uuid, acc.getName()}))
403 while (c.moveToNext()) {
404 LedgerAccount a = loadAccount(db, c.getString(0));
411 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
412 List<LedgerAccount> result = new ArrayList<>();
413 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
414 visibleList.add(acc);
416 SQLiteDatabase db = MLDB.getDatabase();
417 try (Cursor c = db.rawQuery(
418 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
419 new String[]{uuid, acc.getName()}))
421 while (c.moveToNext()) {
422 LedgerAccount a = loadAccount(db, c.getString(0));
423 if (a.isVisible(visibleList)) {