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(String uuid, String name, boolean permitPosting, String url,
48 boolean authEnabled, String authUserName, String authPassword) {
49 this(uuid, name, permitPosting, url, authEnabled, authUserName, authPassword, -1);
52 public MobileLedgerProfile(String uuid, String name, boolean permitPosting, String url,
53 boolean authEnabled, String authUserName, String authPassword,
57 this.permitPosting = permitPosting;
59 this.authEnabled = authEnabled;
60 this.authUserName = authUserName;
61 this.authPassword = authPassword;
62 this.themeId = themeId;
65 public MobileLedgerProfile(CharSequence name, boolean permitPosting, CharSequence url,
66 boolean authEnabled, CharSequence authUserName,
67 CharSequence authPassword, int themeId) {
68 this.uuid = String.valueOf(UUID.randomUUID());
69 this.name = String.valueOf(name);
70 this.permitPosting = permitPosting;
71 this.url = String.valueOf(url);
72 this.authEnabled = authEnabled;
73 this.authUserName = String.valueOf(authUserName);
74 this.authPassword = String.valueOf(authPassword);
75 this.themeId = themeId;
78 // loads all profiles into Data.profiles
79 // returns the profile with the given UUID
80 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
81 MobileLedgerProfile result = null;
82 List<MobileLedgerProfile> list = new ArrayList<>();
83 SQLiteDatabase db = MLDB.getDatabase();
84 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
85 "auth_password, permit_posting, theme, order_no FROM " +
86 "profiles order by order_no", null))
88 while (cursor.moveToNext()) {
89 MobileLedgerProfile item =
90 new MobileLedgerProfile(cursor.getString(0), cursor.getString(1),
91 cursor.getInt(6) == 1, cursor.getString(2), cursor.getInt(3) == 1,
92 cursor.getString(4), cursor.getString(5), cursor.getInt(7));
93 item.orderNo = cursor.getInt(8);
95 if (item.getUuid().equals(currentProfileUUID)) result = item;
98 Data.profiles.setList(list);
101 public static void storeProfilesOrder() {
102 SQLiteDatabase db = MLDB.getDatabase();
103 db.beginTransaction();
106 try (LockHolder lh = Data.profiles.lockForReading()) {
107 for (int i = 0; i < Data.profiles.size(); i++) {
108 MobileLedgerProfile p = Data.profiles.get(i);
109 db.execSQL("update profiles set order_no=? where uuid=?",
110 new Object[]{orderNo, p.getUuid()});
115 db.setTransactionSuccessful();
121 public boolean isPostingPermitted() {
122 return permitPosting;
124 public void setPostingPermitted(boolean permitPosting) {
125 this.permitPosting = permitPosting;
127 public String getUuid() {
130 public String getName() {
133 public void setName(CharSequence text) {
134 setName(String.valueOf(text));
136 public void setName(String name) {
139 public String getUrl() {
142 public void setUrl(CharSequence text) {
143 setUrl(String.valueOf(text));
145 public void setUrl(String url) {
148 public boolean isAuthEnabled() {
151 public void setAuthEnabled(boolean authEnabled) {
152 this.authEnabled = authEnabled;
154 public String getAuthUserName() {
157 public void setAuthUserName(CharSequence text) {
158 setAuthUserName(String.valueOf(text));
160 public void setAuthUserName(String authUserName) {
161 this.authUserName = authUserName;
163 public String getAuthPassword() {
166 public void setAuthPassword(CharSequence text) {
167 setAuthPassword(String.valueOf(text));
169 public void setAuthPassword(String authPassword) {
170 this.authPassword = authPassword;
172 public void storeInDB() {
173 SQLiteDatabase db = MLDB.getDatabase();
174 db.beginTransaction();
176 // Log.d("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
177 // "url=%s, permit_posting=%s, authEnabled=%s, " +
178 // "themeId=%d", uuid, name, url,
179 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
180 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
181 "use_authentication, auth_user, " +
182 "auth_password, theme, order_no) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
183 new Object[]{uuid, name, permitPosting, url, authEnabled,
184 authEnabled ? authUserName : null,
185 authEnabled ? authPassword : null, themeId, orderNo
187 db.setTransactionSuccessful();
193 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
194 // replace into is a bad idea because it would reset hidden to its default value
195 // we like the default, but for new accounts only
196 db.execSQL("update accounts set level = ?, keep = 1, hidden=?, expanded=? " +
197 "where profile=? and name = ?",
198 new Object[]{acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded(), uuid,
202 "insert into accounts(profile, name, name_upper, parent_name, level, hidden, expanded, keep) " +
203 "select ?,?,?,?,?,?,?,1 where (select changes() = 0)",
204 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
205 acc.getLevel(), acc.isHiddenByStar(), acc.isExpanded()
207 // Log.d("accounts", String.format("Stored account '%s' in DB [%s]", acc.getName(), uuid));
209 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
210 db.execSQL("replace into account_values(profile, account, " +
211 "currency, value, keep) values(?, ?, ?, ?, 1);",
212 new Object[]{uuid, name, currency, amount});
214 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
216 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
217 new Object[]{uuid, tr.getId()});
218 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
219 new Object[]{uuid, tr.getId()});
221 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
222 "values(?,?,?,?,?,1)",
223 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
224 tr.getDescription(), tr.getDataHash()
227 for (LedgerTransactionAccount item : tr.getAccounts()) {
228 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
229 "account_name, amount, currency) values(?, ?, ?, ?, ?)",
230 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
234 Log.d("profile", String.format("Transaction %d stored", tr.getId()));
236 public String getOption(String name, String default_value) {
237 SQLiteDatabase db = MLDB.getDatabase();
238 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
239 new String[]{uuid, name}))
241 if (cursor.moveToFirst()) {
242 String result = cursor.getString(0);
244 if (result == null) {
245 Log.d("profile", "returning default value for " + name);
246 result = default_value;
248 else Log.d("profile", String.format("option %s=%s", name, result));
252 else return default_value;
254 catch (Exception e) {
255 Log.d("db", "returning default value for " + name, e);
256 return default_value;
259 public long getLongOption(String name, long default_value) {
261 String result = getOption(name, "");
262 if ((result == null) || result.isEmpty()) {
263 Log.d("profile", String.format("Returning default value for option %s", name));
264 longResult = default_value;
268 longResult = Long.parseLong(result);
269 Log.d("profile", String.format("option %s=%s", name, result));
271 catch (Exception e) {
272 Log.d("profile", String.format("Returning default value for option %s", name), e);
273 longResult = default_value;
279 public void setOption(String name, String value) {
280 Log.d("profile", String.format("setting option %s=%s", name, value));
281 DbOpQueue.add("insert or replace into options(profile, name, value) values(?, ?, ?);",
282 new String[]{uuid, name, value});
284 public void setLongOption(String name, long value) {
285 setOption(name, String.valueOf(value));
287 public void removeFromDB() {
288 SQLiteDatabase db = MLDB.getDatabase();
289 Log.d("db", String.format("removing profile %s from DB", uuid));
290 db.beginTransaction();
292 db.execSQL("delete from profiles where uuid=?", new Object[]{uuid});
293 db.execSQL("delete from accounts where profile=?", new Object[]{uuid});
294 db.execSQL("delete from account_values where profile=?", new Object[]{uuid});
295 db.execSQL("delete from transactions where profile=?", new Object[]{uuid});
296 db.execSQL("delete from transaction_accounts where profile=?", new Object[]{uuid});
297 db.setTransactionSuccessful();
304 public LedgerAccount loadAccount(String name) {
305 SQLiteDatabase db = MLDB.getDatabase();
306 return loadAccount(db, name);
309 public LedgerAccount tryLoadAccount(String acct_name) {
310 SQLiteDatabase db = MLDB.getDatabase();
311 return tryLoadAccount(db, acct_name);
314 public LedgerAccount loadAccount(SQLiteDatabase db, String accName) {
315 LedgerAccount acc = tryLoadAccount(db, accName);
317 if (acc == null) throw new RuntimeException("Unable to load account with name " + accName);
322 public LedgerAccount tryLoadAccount(SQLiteDatabase db, String accName) {
323 try (Cursor cursor = db.rawQuery(
324 "SELECT a.hidden, a.expanded, (select 1 from accounts a2 " +
325 "where a2.profile = a.profile and a2.name like a.name||':%' limit 1) " +
326 "FROM accounts a WHERE a.profile = ? and a.name=?", new String[]{uuid, accName}))
328 if (cursor.moveToFirst()) {
329 LedgerAccount acc = new LedgerAccount(accName);
330 acc.setHiddenByStar(cursor.getInt(0) == 1);
331 acc.setExpanded(cursor.getInt(1) == 1);
332 acc.setHasSubAccounts(cursor.getInt(2) == 1);
334 try (Cursor c2 = db.rawQuery(
335 "SELECT value, currency FROM account_values WHERE profile = ? " +
336 "AND account = ?", new String[]{uuid, accName}))
338 while (c2.moveToNext()) {
339 acc.addAmount(c2.getFloat(0), c2.getString(1));
348 public LedgerTransaction loadTransaction(int transactionId) {
349 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
350 tr.loadData(MLDB.getDatabase());
354 public int getThemeId() {
355 // Log.d("profile", String.format("Profile.getThemeId() returning %d", themeId));
358 public void setThemeId(Object o) {
359 setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
361 public void setThemeId(int themeId) {
362 // Log.d("profile", String.format("Profile.setThemeId(%d) called", themeId));
363 this.themeId = themeId;
365 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
366 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
369 public void markAccountsAsNotPresent(SQLiteDatabase db) {
370 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
371 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
374 public void deleteNotPresentAccounts(SQLiteDatabase db) {
375 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
376 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
378 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
379 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
380 new Object[]{uuid, transaction.getId()
383 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
384 LedgerTransaction transaction) {
385 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
386 new Object[]{uuid, transaction.getId()
390 public void deleteNotPresentTransactions(SQLiteDatabase db) {
391 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
393 public void setLastUpdateStamp() {
394 Log.d("db", "Updating transaction value stamp");
395 Date now = new Date();
396 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
397 Data.lastUpdateDate.set(now);
399 public List<LedgerAccount> loadChildAccountsOf(LedgerAccount acc) {
400 List<LedgerAccount> result = new ArrayList<>();
401 SQLiteDatabase db = MLDB.getDatabase();
402 try (Cursor c = db.rawQuery(
403 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
404 new String[]{uuid, acc.getName()}))
406 while (c.moveToNext()) {
407 LedgerAccount a = loadAccount(db, c.getString(0));
414 public List<LedgerAccount> loadVisibleChildAccountsOf(LedgerAccount acc) {
415 List<LedgerAccount> result = new ArrayList<>();
416 ArrayList<LedgerAccount> visibleList = new ArrayList<>();
417 visibleList.add(acc);
419 SQLiteDatabase db = MLDB.getDatabase();
420 try (Cursor c = db.rawQuery(
421 "SELECT a.name FROM accounts a WHERE a.profile = ? and a.name like ?||':%'",
422 new String[]{uuid, acc.getName()}))
424 while (c.moveToNext()) {
425 LedgerAccount a = loadAccount(db, c.getString(0));
426 if (a.isVisible(visibleList)) {