]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
set keep=1 when inserting new accounts
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / MobileLedgerProfile.java
1 /*
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.model;
19
20 import android.database.Cursor;
21 import android.database.sqlite.SQLiteDatabase;
22 import android.util.Log;
23
24 import net.ktnx.mobileledger.utils.Globals;
25 import net.ktnx.mobileledger.utils.MLDB;
26
27 import java.util.ArrayList;
28 import java.util.Date;
29 import java.util.List;
30 import java.util.UUID;
31
32 public final class MobileLedgerProfile {
33     private String uuid;
34     private String name;
35     private boolean permitPosting;
36     private String url;
37     private boolean authEnabled;
38     private String authUserName;
39     private String authPassword;
40     private int themeId;
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);
45
46     }
47     public MobileLedgerProfile(String uuid, String name, boolean permitPosting, String url,
48                                boolean authEnabled, String authUserName, String authPassword,
49                                int themeId) {
50         this.uuid = uuid;
51         this.name = name;
52         this.permitPosting = permitPosting;
53         this.url = url;
54         this.authEnabled = authEnabled;
55         this.authUserName = authUserName;
56         this.authPassword = authPassword;
57         this.themeId = themeId;
58         this.orderNo = -1;
59     }
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;
71         this.orderNo = -1;
72     }
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))
82         {
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);
89                 list.add(item);
90                 if (item.getUuid().equals(currentProfileUUID)) result = item;
91             }
92         }
93         Data.profiles.setList(list);
94         return result;
95     }
96     public static void storeProfilesOrder() {
97         SQLiteDatabase db = MLDB.getWritableDatabase();
98         db.beginTransaction();
99         try {
100             int orderNo = 0;
101             for (MobileLedgerProfile p : Data.profiles.getList()) {
102                 db.execSQL("update profiles set order_no=? where uuid=?",
103                         new Object[]{orderNo, p.getUuid()});
104                 p.orderNo = orderNo;
105                 orderNo++;
106             }
107             db.setTransactionSuccessful();
108         }
109         finally {
110             db.endTransaction();
111         }
112     }
113     public boolean isPostingPermitted() {
114         return permitPosting;
115     }
116     public void setPostingPermitted(boolean permitPosting) {
117         this.permitPosting = permitPosting;
118     }
119     public String getUuid() {
120         return uuid;
121     }
122     public String getName() {
123         return name;
124     }
125     public void setName(String name) {
126         this.name = name;
127     }
128     public void setName(CharSequence text) {
129         setName(String.valueOf(text));
130     }
131     public String getUrl() {
132         return url;
133     }
134     public void setUrl(String url) {
135         this.url = url;
136     }
137     public void setUrl(CharSequence text) {
138         setUrl(String.valueOf(text));
139     }
140     public boolean isAuthEnabled() {
141         return authEnabled;
142     }
143     public void setAuthEnabled(boolean authEnabled) {
144         this.authEnabled = authEnabled;
145     }
146     public String getAuthUserName() {
147         return authUserName;
148     }
149     public void setAuthUserName(String authUserName) {
150         this.authUserName = authUserName;
151     }
152     public void setAuthUserName(CharSequence text) {
153         setAuthUserName(String.valueOf(text));
154     }
155     public String getAuthPassword() {
156         return authPassword;
157     }
158     public void setAuthPassword(String authPassword) {
159         this.authPassword = authPassword;
160     }
161     public void setAuthPassword(CharSequence text) {
162         setAuthPassword(String.valueOf(text));
163     }
164     public void storeInDB() {
165         SQLiteDatabase db = MLDB.getWritableDatabase();
166         db.beginTransaction();
167         try {
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
178                     });
179             db.setTransactionSuccessful();
180         }
181         finally {
182             db.endTransaction();
183         }
184     }
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, keep) " +
191                    "select ?,?,?,?,?,1 where (select changes() = 0)",
192                 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
193                              acc.getLevel()
194                 });
195     }
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});
200     }
201     public void storeTransaction(SQLiteDatabase db, LedgerTransaction tr) {
202         tr.fillDataHash();
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()});
207
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()
212                 });
213
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(),
218                                  item.getCurrency()
219                     });
220         }
221         Log.d("profile", String.format("Transaction %d stored", tr.getId()));
222     }
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}))
227         {
228             if (cursor.moveToFirst()) {
229                 String result = cursor.getString(0);
230
231                 if (result == null) {
232                     Log.d("profile", "returning default value for " + name);
233                     result = default_value;
234                 }
235                 else Log.d("profile", String.format("option %s=%s", name, result));
236
237                 return result;
238             }
239             else return default_value;
240         }
241         catch (Exception e) {
242             Log.d("db", "returning default value for " + name, e);
243             return default_value;
244         }
245     }
246     public long getLongOption(String name, long default_value) {
247         long longResult;
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;
252         }
253         else {
254             try {
255                 longResult = Long.parseLong(result);
256                 Log.d("profile", String.format("option %s=%s", name, result));
257             }
258             catch (Exception e) {
259                 Log.d("profile", String.format("Returning default value for option %s", name), e);
260                 longResult = default_value;
261             }
262         }
263
264         return longResult;
265     }
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});
271     }
272     public void setLongOption(String name, long value) {
273         setOption(name, String.valueOf(value));
274     }
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});
279     }
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}))
284         {
285             if (cursor.moveToFirst()) {
286                 LedgerAccount acc = new LedgerAccount(name);
287                 acc.setHidden(cursor.getInt(0) == 1);
288
289                 return acc;
290             }
291         }
292
293         return null;
294     }
295     public LedgerTransaction loadTransaction(int transactionId) {
296         LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
297         tr.loadData(MLDB.getReadableDatabase());
298
299         return tr;
300     }
301     public int getThemeId() {
302 //        Log.d("profile", String.format("Profile.getThemeId() returning %d", themeId));
303         return this.themeId;
304     }
305     public void setThemeId(int themeId) {
306 //        Log.d("profile", String.format("Profile.setThemeId(%d) called", themeId));
307         this.themeId = themeId;
308     }
309     public void setThemeId(Object o) {
310         setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
311     }
312     public void markTransactionsAsNotPresent(SQLiteDatabase db) {
313         db.execSQL("UPDATE transactions set keep=0 where profile=?", new String[]{uuid});
314
315     }
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});
319
320     }
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});
324     }
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()
328                 });
329     }
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()
334                 });
335
336     }
337     public void deleteNotPresentTransactions(SQLiteDatabase db) {
338         db.execSQL("DELETE FROM transactions WHERE profile=? AND keep = 0", new String[]{uuid});
339     }
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);
345     }
346 }