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.async.DbOpQueue;
25 import net.ktnx.mobileledger.utils.Globals;
26 import net.ktnx.mobileledger.utils.LockHolder;
27 import net.ktnx.mobileledger.utils.MLDB;
29 import java.util.ArrayList;
30 import java.util.Date;
31 import java.util.List;
32 import java.util.UUID;
34 import androidx.annotation.NonNull;
35 import androidx.annotation.Nullable;
37 public final class MobileLedgerProfile {
40 private boolean permitPosting;
42 private boolean authEnabled;
43 private String authUserName;
44 private String authPassword;
46 private int orderNo = -1;
47 public MobileLedgerProfile() {
48 this.uuid = String.valueOf(UUID.randomUUID());
50 public MobileLedgerProfile(String uuid) {
53 // loads all profiles into Data.profiles
54 // returns the profile with the given UUID
55 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
56 MobileLedgerProfile result = null;
57 List<MobileLedgerProfile> list = new ArrayList<>();
58 SQLiteDatabase db = MLDB.getDatabase();
59 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
60 "auth_password, permit_posting, theme, order_no FROM " +
61 "profiles order by order_no", null))
63 while (cursor.moveToNext()) {
64 MobileLedgerProfile item = new MobileLedgerProfile(cursor.getString(0));
65 item.setName(cursor.getString(1));
66 item.setUrl(cursor.getString(2));
67 item.setAuthEnabled(cursor.getInt(3) == 1);
68 item.setAuthUserName(cursor.getString(4));
69 item.setAuthPassword(cursor.getString(5));
70 item.setPostingPermitted(cursor.getInt(6) == 1);
71 item.setThemeId(cursor.getInt(7));
72 item.orderNo = cursor.getInt(8);
74 if (item.getUuid().equals(currentProfileUUID)) result = item;
77 Data.profiles.setList(list);
80 public static void storeProfilesOrder() {
81 SQLiteDatabase db = MLDB.getDatabase();
82 db.beginTransaction();
85 try (LockHolder lh = Data.profiles.lockForReading()) {
86 for (int i = 0; i < Data.profiles.size(); i++) {
87 MobileLedgerProfile p = Data.profiles.get(i);
88 db.execSQL("update profiles set order_no=? where uuid=?",
89 new Object[]{orderNo, p.getUuid()});
94 db.setTransactionSuccessful();
100 public boolean isPostingPermitted() {
101 return permitPosting;
103 public void setPostingPermitted(boolean permitPosting) {
104 this.permitPosting = permitPosting;
106 public String getUuid() {
109 public String getName() {
112 public void setName(CharSequence text) {
113 setName(String.valueOf(text));
115 public void setName(String name) {
118 public String getUrl() {
121 public void setUrl(CharSequence text) {
122 setUrl(String.valueOf(text));
124 public void setUrl(String url) {
127 public boolean isAuthEnabled() {
130 public void setAuthEnabled(boolean authEnabled) {
131 this.authEnabled = authEnabled;
133 public String getAuthUserName() {
136 public void setAuthUserName(CharSequence text) {
137 setAuthUserName(String.valueOf(text));
139 public void setAuthUserName(String authUserName) {
140 this.authUserName = authUserName;
142 public String getAuthPassword() {
145 public void setAuthPassword(CharSequence text) {
146 setAuthPassword(String.valueOf(text));
148 public void setAuthPassword(String authPassword) {
149 this.authPassword = authPassword;
151 public void storeInDB() {
152 SQLiteDatabase db = MLDB.getDatabase();
153 db.beginTransaction();
155 // Log.d("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
156 // "url=%s, permit_posting=%s, authEnabled=%s, " +
157 // "themeId=%d", uuid, name, url,
158 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
159 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
160 "use_authentication, auth_user, " +
161 "auth_password, theme, order_no) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
162 new Object[]{uuid, name, permitPosting, url, authEnabled,
163 authEnabled ? authUserName : null,
164 authEnabled ? authPassword : null, themeId, orderNo
166 db.setTransactionSuccessful();
172 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
173 // replace into is a bad idea because it would reset hidden to its default value
174 // we like the default, but for new accounts only
175 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
176 "where profile=? and name = ?",
177 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
181 "insert into accounts(profile, name, name_upper, parent_name, level, hidden, expanded, keep) " +
182 "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
183 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
184 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
186 // Log.d("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
188 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
189 db.execSQL("replace into account_values(profile, account, " +
190 "currency, value, keep) values(?, ?, ?, ?, 1);",
191 new Object[]{uuid, name, currency, amount});
193 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
195 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
196 new Object[]{uuid, tr.getId()});
197 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
198 new Object[]{uuid, tr.getId()});
200 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
201 "values(?,?,?,?,?,1)",
202 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
203 tr.getDescription(), tr.getDataHash()
206 for (LedgerTransactionAccount item : tr.getAccounts()) {
207 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
208 "account_name, amount, currency) values(?, ?, ?, ?, ?)",
209 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
213 Log.d("profile", String.format("Transaction %d stored", tr.getId()));
215 public String getOption(String name, String default_value) {
216 SQLiteDatabase db = MLDB.getDatabase();
217 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
218 new String[]{uuid, name}))
220 if (cursor.moveToFirst()) {
221 String result = cursor.getString(0);
223 if (result == null) {
224 Log.d("profile", "returning default value for " + name);
225 result = default_value;
227 else Log.d("profile", String.format("option %s=%s", name, result));
231 else return default_value;
233 catch (Exception e) {
234 Log.d("db", "returning default value for " + name, e);
235 return default_value;
238 public long getLongOption(String name, long default_value) {
240 String result = getOption(name, "");
241 if ((result == null) || result.isEmpty()) {
242 Log.d("profile", String.format("Returning default value for option %s", name));
243 longResult = default_value;
247 longResult = Long.parseLong(result);
248 Log.d("profile", String.format("option %s=%s", name, result));
250 catch (Exception e) {
251 Log.d("profile", String.format("Returning default value for option %s", name), e);
252 longResult = default_value;
258 public void setOption(String name, String value) {
259 Log.d("profile", String.format("setting option %s=%s", name, value));
260 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
261 new String[]{uuid, name, value});
263 public void setLongOption(String name, long value) {
264 setOption(name, String.valueOf(value));
266 public void removeFromDB() {
267 SQLiteDatabase db = MLDB.getDatabase();
268 Log.d("db", String.format("removing profile %s from DB", uuid));
269 db.beginTransaction();
271 db.execSQL("delete from profiles where uuid=?", new Object[]{uuid});
272 db.execSQL("delete from accounts where profile=?", new Object[]{uuid});
273 db.execSQL("delete from account_values where profile=?", new Object[]{uuid});
274 db.execSQL("delete from transactions where profile=?", new Object[]{uuid});
275 db.execSQL("delete from transaction_accounts where profile=?", new Object[]{uuid});
276 db.setTransactionSuccessful();
283 public LedgerAccount loadAccount(String name) {
284 SQLiteDatabase db = MLDB.getDatabase();
285 return loadAccount(db, name);
288 public LedgerAccount tryLoadAccount(String acct_name) {
289 SQLiteDatabase db = MLDB.getDatabase();
290 return tryLoadAccount(db, acct_name);
293 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
294 LedgerAccount acc = tryLoadAccount(db, accName);
296 if (acc == null) throw new RuntimeException("Unable to load account with name " + accName);
301 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
302 try (Cursor cursor = db.rawQuery(
303 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
304 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
305 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
307 if (cursor.moveToFirst()) {
308 LedgerAccount acc = new LedgerAccount(accName);
309 acc.setHiddenByStar(cursor.getInt(0) == 1);
310 acc.setExpanded(cursor.getInt(1) == 1);
311 acc.setHasSubAccounts(cursor.getInt(2) == 1);
313 try (Cursor c2 = db.rawQuery(
314 "SELECT value, currency FROM account_values WHERE profile = ? " +
315 "AND account = ?", new String[]{uuid, accName}))
317 while (c2.moveToNext()) {
318 acc.addAmount(c2.getFloat(0), c2.getString(1));
327 public LedgerTransaction loadTransaction(int transactionId) {
328 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
329 tr.loadData(MLDB.getDatabase());
333 public int getThemeId() {
334 // Log.d("profile", String.format("Profile.getThemeId() returning %d", themeId));
337 public void setThemeId(Object o) {
338 setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
340 public void setThemeId(int themeId) {
341 // Log.d("profile", String.format("Profile.setThemeId(%d) called", themeId));
342 this.themeId = themeId;
344 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
345 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
348 public void markAccountsAsNotPresent(SQLiteDatabase db) {
349 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
350 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
353 public void deleteNotPresentAccounts(SQLiteDatabase db) {
354 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
355 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
357 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
358 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
359 new Object[]{uuid, transaction.getId()
362 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
363 LedgerTransaction transaction) {
364 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
365 new Object[]{uuid, transaction.getId()
369 public void deleteNotPresentTransactions(SQLiteDatabase db) {
370 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
372 public void setLastUpdateStamp() {
373 Log.d("db", "Updating transaction value stamp");
374 Date now = new Date();
375 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
376 Data.lastUpdateDate.set(now);
378 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
379 List<LedgerAccount> result = new ArrayList<>();
380 SQLiteDatabase db = MLDB.getDatabase();
381 try (Cursor c = db.rawQuery(
382 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
383 new String[]{uuid, acc.getName()}))
385 while (c.moveToNext()) {
386 LedgerAccount a = loadAccount(db, c.getString(0));
393 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
394 List<LedgerAccount> result = new ArrayList<>();
395 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
396 visibleList.add(acc);
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));
405 if (a.isVisible(visibleList)) {