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 public final class MobileLedgerProfile {
35 private boolean permitPosting;
37 private boolean authEnabled;
38 private String authUserName;
39 private String authPassword;
41 private int orderNo = -1;
42 public MobileLedgerProfile(String uuid, String name, boolean permitPosting, String url,
43 boolean authEnabled, String authUserName, String authPassword) {
44 this(uuid, name, permitPosting, url, authEnabled, authUserName, authPassword, -1);
47 public MobileLedgerProfile(String uuid, String name, boolean permitPosting, String url,
48 boolean authEnabled, String authUserName, String authPassword,
52 this.permitPosting = permitPosting;
54 this.authEnabled = authEnabled;
55 this.authUserName = authUserName;
56 this.authPassword = authPassword;
57 this.themeId = themeId;
60 public MobileLedgerProfile(CharSequence name, boolean permitPosting, CharSequence url,
61 boolean authEnabled, CharSequence authUserName,
62 CharSequence authPassword, int themeId) {
63 this.uuid = String.valueOf(UUID.randomUUID());
64 this.name = String.valueOf(name);
65 this.permitPosting = permitPosting;
66 this.url = String.valueOf(url);
67 this.authEnabled = authEnabled;
68 this.authUserName = String.valueOf(authUserName);
69 this.authPassword = String.valueOf(authPassword);
70 this.themeId = themeId;
73 // loads all profiles into Data.profiles
74 // returns the profile with the given UUID
75 public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
76 MobileLedgerProfile result = null;
77 List<MobileLedgerProfile> list = new ArrayList<>();
78 SQLiteDatabase db = MLDB.getReadableDatabase();
79 try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
80 "auth_password, permit_posting, theme, order_no FROM " +
81 "profiles order by order_no", null))
83 while (cursor.moveToNext()) {
84 MobileLedgerProfile item =
85 new MobileLedgerProfile(cursor.getString(0), cursor.getString(1),
86 cursor.getInt(6) == 1, cursor.getString(2), cursor.getInt(3) == 1,
87 cursor.getString(4), cursor.getString(5), cursor.getInt(7));
88 item.orderNo = cursor.getInt(8);
90 if (item.getUuid().equals(currentProfileUUID)) result = item;
93 Data.profiles.setList(list);
96 public static void storeProfilesOrder() {
97 SQLiteDatabase db = MLDB.getWritableDatabase();
98 db.beginTransaction();
101 for (MobileLedgerProfile p : Data.profiles.getList()) {
102 db.execSQL("update profiles set order_no=? where uuid=?",
103 new Object[]{orderNo, p.getUuid()});
107 db.setTransactionSuccessful();
113 public boolean isPostingPermitted() {
114 return permitPosting;
116 public void setPostingPermitted(boolean permitPosting) {
117 this.permitPosting = permitPosting;
119 public String getUuid() {
122 public String getName() {
125 public void setName(String name) {
128 public void setName(CharSequence text) {
129 setName(String.valueOf(text));
131 public String getUrl() {
134 public void setUrl(String url) {
137 public void setUrl(CharSequence text) {
138 setUrl(String.valueOf(text));
140 public boolean isAuthEnabled() {
143 public void setAuthEnabled(boolean authEnabled) {
144 this.authEnabled = authEnabled;
146 public String getAuthUserName() {
149 public void setAuthUserName(String authUserName) {
150 this.authUserName = authUserName;
152 public void setAuthUserName(CharSequence text) {
153 setAuthUserName(String.valueOf(text));
155 public String getAuthPassword() {
158 public void setAuthPassword(String authPassword) {
159 this.authPassword = authPassword;
161 public void setAuthPassword(CharSequence text) {
162 setAuthPassword(String.valueOf(text));
164 public void storeInDB() {
165 SQLiteDatabase db = MLDB.getWritableDatabase();
166 db.beginTransaction();
168 // Log.d("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
169 // "url=%s, permit_posting=%s, authEnabled=%s, " +
170 // "themeId=%d", uuid, name, url,
171 // permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
172 db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
173 "use_authentication, auth_user, " +
174 "auth_password, theme, order_no) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
175 new Object[]{uuid, name, permitPosting, url, authEnabled,
176 authEnabled ? authUserName : null,
177 authEnabled ? authPassword : null, themeId, orderNo
179 db.setTransactionSuccessful();
185 public void storeAccount(SQLiteDatabase db, LedgerAccount acc) {
186 // replace into is a bad idea because it would reset hidden to its default value
187 // we like the default, but for new accounts only
188 db.execSQL("update accounts set level = ?, keep = 1 where profile=? and name = ?",
189 new Object[]{acc.getLevel(), uuid, acc.getName()});
190 db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level) " +
191 "select ?,?,?,?,? where (select changes() = 0)",
192 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
196 public void storeAccountValue(SQLiteDatabase db, String name, String currency, Float amount) {
197 db.execSQL("replace into account_values(profile, account, " +
198 "currency, value, keep) values(?, ?, ?, ?, 1);",
199 new Object[]{uuid, name, currency, amount});
201 public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
203 db.execSQL("DELETE from transactions WHERE profile=? and id=?",
204 new Object[]{uuid, tr.getId()});
205 db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
206 new Object[]{uuid, tr.getId()});
208 db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
209 "values(?,?,?,?,?,1)",
210 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
211 tr.getDescription(), tr.getDataHash()
214 for (LedgerTransactionAccount item : tr.getAccounts()) {
215 db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
216 "account_name, amount, currency) values(?, ?, ?, ?, ?)",
217 new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
221 Log.d("profile", String.format("Transaction %d stored", tr.getId()));
223 public String getOption(String name, String default_value) {
224 SQLiteDatabase db = MLDB.getReadableDatabase();
225 try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
226 new String[]{uuid, name}))
228 if (cursor.moveToFirst()) {
229 String result = cursor.getString(0);
231 if (result == null) {
232 Log.d("profile", "returning default value for " + name);
233 result = default_value;
235 else Log.d("profile", String.format("option %s=%s", name, result));
239 else return default_value;
241 catch (Exception e) {
242 Log.d("db", "returning default value for " + name, e);
243 return default_value;
246 public long getLongOption(String name, long default_value) {
248 String result = getOption(name, "");
249 if ((result == null) || result.isEmpty()) {
250 Log.d("profile", String.format("Returning default value for option %s", name));
251 longResult = default_value;
255 longResult = Long.parseLong(result);
256 Log.d("profile", String.format("option %s=%s", name, result));
258 catch (Exception e) {
259 Log.d("profile", String.format("Returning default value for option %s", name), e);
260 longResult = default_value;
266 public void setOption(String name, String value) {
267 Log.d("profile", String.format("setting option %s=%s", name, value));
268 SQLiteDatabase db = MLDB.getWritableDatabase();
269 db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
270 new String[]{uuid, name, value});
272 public void setLongOption(String name, long value) {
273 setOption(name, String.valueOf(value));
275 public void removeFromDB() {
276 SQLiteDatabase db = MLDB.getWritableDatabase();
277 Log.d("db", String.format("removing progile %s from DB", uuid));
278 db.execSQL("delete from profiles where uuid=?", new Object[]{uuid});
280 public LedgerAccount loadAccount(String name) {
281 SQLiteDatabase db = MLDB.getReadableDatabase();
282 try (Cursor cursor = db.rawQuery("SELECT hidden from accounts where profile=? and name=?",
283 new String[]{uuid, name}))
285 if (cursor.moveToFirst()) {
286 LedgerAccount acc = new LedgerAccount(name);
287 acc.setHidden(cursor.getInt(0) == 1);
295 public LedgerTransaction loadTransaction(int transactionId) {
296 LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
297 tr.loadData(MLDB.getReadableDatabase());
301 public int getThemeId() {
302 // Log.d("profile", String.format("Profile.getThemeId() returning %d", themeId));
305 public void setThemeId(int themeId) {
306 // Log.d("profile", String.format("Profile.setThemeId(%d) called", themeId));
307 this.themeId = themeId;
309 public void setThemeId(Object o) {
310 setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
312 public void markTransactionsAsNotPresent(SQLiteDatabase db) {
313 db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
316 public void markAccountsAsNotPresent(SQLiteDatabase db) {
317 db.execSQL("update account_values set keep=0 where profile=?;", new String[]{uuid});
318 db.execSQL("update accounts set keep=0 where profile=?;", new String[]{uuid});
321 public void deleteNotPresentAccounts(SQLiteDatabase db) {
322 db.execSQL("delete from account_values where keep=0 and profile=?", new String[]{uuid});
323 db.execSQL("delete from accounts where keep=0 and profile=?", new String[]{uuid});
325 public void markTransactionAsPresent(SQLiteDatabase db, LedgerTransaction transaction) {
326 db.execSQL("UPDATE transactions SET keep = 1 WHERE profile = ? and id=?",
327 new Object[]{uuid, transaction.getId()
330 public void markTransactionsBeforeTransactionAsPresent(SQLiteDatabase db,
331 LedgerTransaction transaction) {
332 db.execSQL("UPDATE transactions SET keep=1 WHERE profile = ? and id < ?",
333 new Object[]{uuid, transaction.getId()
337 public void deleteNotPresentTransactions(SQLiteDatabase db) {
338 db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
340 public void setLastUpdateStamp() {
341 Log.d("db", "Updating transaction value stamp");
342 Date now = new Date();
343 setLongOption(MLDB.OPT_LAST_SCRAPE, now.getTime());
344 Data.lastUpdateDate.set(now);