]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
3489c28a0385bd729bafcf134f6709e70009e7f5
[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.List;
29 import java.util.UUID;
30
31 public final class MobileLedgerProfile {
32     private String uuid;
33     private String name;
34     private boolean permitPosting;
35     private String url;
36     private boolean authEnabled;
37     private String authUserName;
38     private String authPassword;
39     private int themeId;
40     public MobileLedgerProfile(String uuid, String name, boolean permitPosting, String url,
41                                boolean authEnabled, String authUserName, String authPassword) {
42         this(uuid, name, permitPosting, url, authEnabled, authUserName, authPassword, -1);
43
44     }
45     public MobileLedgerProfile(String uuid, String name, boolean permitPosting, String url,
46                                boolean authEnabled, String authUserName, String authPassword,
47                                int themeId) {
48         this.uuid = uuid;
49         this.name = name;
50         this.permitPosting = permitPosting;
51         this.url = url;
52         this.authEnabled = authEnabled;
53         this.authUserName = authUserName;
54         this.authPassword = authPassword;
55         this.themeId = themeId;
56     }
57     public MobileLedgerProfile(CharSequence name, boolean permitPosting, CharSequence url,
58                                boolean authEnabled, CharSequence authUserName,
59                                CharSequence authPassword, int themeId) {
60         this.uuid = String.valueOf(UUID.randomUUID());
61         this.name = String.valueOf(name);
62         this.permitPosting = permitPosting;
63         this.url = String.valueOf(url);
64         this.authEnabled = authEnabled;
65         this.authUserName = String.valueOf(authUserName);
66         this.authPassword = String.valueOf(authPassword);
67         this.themeId = themeId;
68     }
69         // loads all profiles into Data.profiles
70     // returns the profile with the given UUID
71     public static MobileLedgerProfile loadAllFromDB(String currentProfileUUID) {
72         MobileLedgerProfile result = null;
73         List<MobileLedgerProfile> list = new ArrayList<>();
74         SQLiteDatabase db = MLDB.getReadableDatabase();
75         try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
76                                          "auth_password, permit_posting, theme FROM profiles " +
77                                          "order by order_no", null))
78         {
79             while (cursor.moveToNext()) {
80                 MobileLedgerProfile item =
81                         new MobileLedgerProfile(cursor.getString(0), cursor.getString(1),
82                                 cursor.getInt(6) == 1, cursor.getString(2), cursor.getInt(3) == 1,
83                                 cursor.getString(4), cursor.getString(5), cursor.getInt(7));
84                 list.add(item);
85                 if (item.getUuid().equals(currentProfileUUID)) result = item;
86             }
87         }
88         Data.profiles.setList(list);
89         return result;
90     }
91     public static void storeProfilesOrder() {
92         SQLiteDatabase db = MLDB.getWritableDatabase();
93         db.beginTransaction();
94         try {
95             int orderNo = 0;
96             for (MobileLedgerProfile p : Data.profiles.getList()) {
97                 db.execSQL("update profiles set order_no=? where uuid=?",
98                         new Object[]{orderNo, p.getUuid()});
99                 orderNo++;
100             }
101             db.setTransactionSuccessful();
102         }
103         finally {
104             db.endTransaction();
105         }
106     }
107     public boolean isPostingPermitted() {
108         return permitPosting;
109     }
110     public void setPostingPermitted(boolean permitPosting) {
111         this.permitPosting = permitPosting;
112     }
113     public String getUuid() {
114         return uuid;
115     }
116     public String getName() {
117         return name;
118     }
119     public void setName(String name) {
120         this.name = name;
121     }
122     public void setName(CharSequence text) {
123         setName(String.valueOf(text));
124     }
125     public String getUrl() {
126         return url;
127     }
128     public void setUrl(String url) {
129         this.url = url;
130     }
131     public void setUrl(CharSequence text) {
132         setUrl(String.valueOf(text));
133     }
134     public boolean isAuthEnabled() {
135         return authEnabled;
136     }
137     public void setAuthEnabled(boolean authEnabled) {
138         this.authEnabled = authEnabled;
139     }
140     public String getAuthUserName() {
141         return authUserName;
142     }
143     public void setAuthUserName(String authUserName) {
144         this.authUserName = authUserName;
145     }
146     public void setAuthUserName(CharSequence text) {
147         setAuthUserName(String.valueOf(text));
148     }
149     public String getAuthPassword() {
150         return authPassword;
151     }
152     public void setAuthPassword(String authPassword) {
153         this.authPassword = authPassword;
154     }
155     public void setAuthPassword(CharSequence text) {
156         setAuthPassword(String.valueOf(text));
157     }
158     public void storeInDB() {
159         SQLiteDatabase db = MLDB.getWritableDatabase();
160         db.beginTransaction();
161         try {
162 //            Log.d("profiles", String.format("Storing profile in DB: uuid=%s, name=%s, " +
163 //                                            "url=%s, permit_posting=%s, authEnabled=%s, " +
164 //                                            "themeId=%d", uuid, name, url,
165 //                    permitPosting ? "TRUE" : "FALSE", authEnabled ? "TRUE" : "FALSE", themeId));
166             db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
167                        "use_authentication, auth_user, " +
168                        "auth_password, theme) VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
169                     new Object[]{uuid, name, permitPosting, url, authEnabled,
170                                  authEnabled ? authUserName : null,
171                                  authEnabled ? authPassword : null, themeId
172                     });
173             db.setTransactionSuccessful();
174         }
175         finally {
176             db.endTransaction();
177         }
178     }
179     public void storeAccount(LedgerAccount acc) {
180         SQLiteDatabase db = MLDB.getWritableDatabase();
181
182         // replace into is a bad idea because it would reset hidden to its default value
183         // we like the default, but for new accounts only
184         db.execSQL("update accounts set level = ?, keep = 1 where profile=? and name = ?",
185                 new Object[]{acc.getLevel(), uuid, acc.getName()});
186         db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level) " +
187                    "select ?,?,?,?,? where (select changes() = 0)",
188                 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
189                              acc.getLevel()
190                 });
191     }
192     public void storeAccountValue(String name, String currency, Float amount) {
193         SQLiteDatabase db = MLDB.getWritableDatabase();
194         db.execSQL("replace into account_values(profile, account, " +
195                    "currency, value, keep) values(?, ?, ?, ?, 1);",
196                 new Object[]{uuid, name, currency, amount});
197     }
198     public void storeTransaction(LedgerTransaction tr) {
199         SQLiteDatabase db = MLDB.getWritableDatabase();
200         tr.fillDataHash();
201         db.execSQL("DELETE from transactions WHERE profile=? and id=?",
202                 new Object[]{uuid, tr.getId()});
203         db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
204                 new Object[]{uuid, tr.getId()});
205
206         db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
207                    "values(?,?,?,?,?,1)",
208                 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
209                              tr.getDescription(), tr.getDataHash()
210                 });
211
212         for (LedgerTransactionAccount item : tr.getAccounts()) {
213             db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
214                        "account_name, amount, currency) values(?, ?, ?, ?, ?)",
215                     new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
216                                  item.getCurrency()
217                     });
218         }
219         Log.d("profile", String.format("Transaction %d stored", tr.getId()));
220     }
221     public String getOption(String name, String default_value) {
222         SQLiteDatabase db = MLDB.getReadableDatabase();
223         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
224                 new String[]{uuid, name}))
225         {
226             if (cursor.moveToFirst()) {
227                 String result = cursor.getString(0);
228
229                 if (result == null) {
230                     Log.d("profile", "returning default value for " + name);
231                     result = default_value;
232                 }
233                 else Log.d("profile", String.format("option %s=%s", name, result));
234
235                 return result;
236             }
237             else return default_value;
238         }
239         catch (Exception e) {
240             Log.d("db", "returning default value for " + name, e);
241             return default_value;
242         }
243     }
244     public long getLongOption(String name, long default_value) {
245         long longResult;
246         String result = getOption(name, "");
247         if ((result == null) || result.isEmpty()) {
248             Log.d("profile", String.format("Returning default value for option %s", name));
249             longResult = default_value;
250         }
251         else {
252             try {
253                 longResult = Long.parseLong(result);
254                 Log.d("profile", String.format("option %s=%s", name, result));
255             }
256             catch (Exception e) {
257                 Log.d("profile", String.format("Returning default value for option %s", name), e);
258                 longResult = default_value;
259             }
260         }
261
262         return longResult;
263     }
264     public void setOption(String name, String value) {
265         Log.d("profile", String.format("setting option %s=%s", name, value));
266         SQLiteDatabase db = MLDB.getWritableDatabase();
267         db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
268                 new String[]{uuid, name, value});
269     }
270     public void setLongOption(String name, long value) {
271         setOption(name, String.valueOf(value));
272     }
273     public void removeFromDB() {
274         SQLiteDatabase db = MLDB.getWritableDatabase();
275         Log.d("db", String.format("removing progile %s from DB", uuid));
276         db.execSQL("delete from profiles where uuid=?", new Object[]{uuid});
277     }
278     public LedgerAccount loadAccount(String name) {
279         SQLiteDatabase db = MLDB.getReadableDatabase();
280         try (Cursor cursor = db.rawQuery("SELECT hidden from accounts where profile=? and name=?",
281                 new String[]{uuid, name}))
282         {
283             if (cursor.moveToFirst()) {
284                 LedgerAccount acc = new LedgerAccount(name);
285                 acc.setHidden(cursor.getInt(0) == 1);
286
287                 return acc;
288             }
289         }
290
291         return null;
292     }
293     public LedgerTransaction loadTransaction(int transactionId) {
294         LedgerTransaction tr = new LedgerTransaction(transactionId, this.uuid);
295         tr.loadData(MLDB.getReadableDatabase());
296
297         return tr;
298     }
299     public int getThemeId() {
300 //        Log.d("profile", String.format("Profile.getThemeId() returning %d", themeId));
301         return this.themeId;
302     }
303     public void setThemeId(int themeId) {
304 //        Log.d("profile", String.format("Profile.setThemeId(%d) called", themeId));
305         this.themeId = themeId;
306     }
307     public void setThemeId(Object o) {
308         setThemeId(Integer.valueOf(String.valueOf(o)).intValue());
309     }
310 }