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