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