]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
6e5ac129f4da2b87c413ffa09cf03edaab9decc4
[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.MLDB;
25
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.UUID;
29
30 public final class MobileLedgerProfile {
31     private String uuid;
32     private String name;
33     private String url;
34     private boolean authEnabled;
35     private String authUserName;
36     private String authPassword;
37     public MobileLedgerProfile(String uuid, String name, String url, boolean authEnabled,
38                                String authUserName, String authPassword) {
39         this.uuid = uuid;
40         this.name = name;
41         this.url = url;
42         this.authEnabled = authEnabled;
43         this.authUserName = authUserName;
44         this.authPassword = authPassword;
45     }
46     public MobileLedgerProfile(CharSequence name, CharSequence url, boolean authEnabled,
47                                CharSequence authUserName, CharSequence authPassword) {
48         this.uuid = String.valueOf(UUID.randomUUID());
49         this.name = String.valueOf(name);
50         this.url = String.valueOf(url);
51         this.authEnabled = authEnabled;
52         this.authUserName = String.valueOf(authUserName);
53         this.authPassword = String.valueOf(authPassword);
54     }
55     public static List<MobileLedgerProfile> loadAllFromDB() {
56         List<MobileLedgerProfile> result = new ArrayList<>();
57         SQLiteDatabase db = MLDB.getReadableDatabase();
58         try (Cursor cursor = db.rawQuery("SELECT uuid, name, url, use_authentication, auth_user, " +
59                                          "auth_password FROM profiles order by order_no", null))
60         {
61             while (cursor.moveToNext()) {
62                 result.add(new MobileLedgerProfile(cursor.getString(0), cursor.getString(1),
63                         cursor.getString(2), cursor.getInt(3) == 1, cursor.getString(4),
64                         cursor.getString(5)));
65             }
66         }
67         return result;
68     }
69     public static void storeProfilesOrder() {
70         SQLiteDatabase db = MLDB.getWritableDatabase();
71         db.beginTransaction();
72         try {
73             int orderNo = 0;
74             for (MobileLedgerProfile p : Data.profiles.getList()) {
75                 db.execSQL("update profiles set order_no=? where uuid=?",
76                         new Object[]{orderNo, p.getUuid()});
77                 orderNo++;
78             }
79             db.setTransactionSuccessful();
80         }
81         finally {
82             db.endTransaction();
83         }
84     }
85     public static List<MobileLedgerProfile> createInitialProfileList() {
86         List<MobileLedgerProfile> result = new ArrayList<>();
87         MobileLedgerProfile first =
88                 new MobileLedgerProfile(UUID.randomUUID().toString(), "default", "", false, "", "");
89         first.storeInDB();
90         result.add(first);
91
92         return result;
93     }
94     public static MobileLedgerProfile loadUUIDFromDB(String profileUUID) {
95         SQLiteDatabase db = MLDB.getReadableDatabase();
96         String name;
97         String url;
98         String authUser;
99         String authPassword;
100         Boolean useAuthentication;
101         try (Cursor cursor = db.rawQuery("SELECT name, url, use_authentication, auth_user, " +
102                                          "auth_password FROM profiles WHERE uuid=?",
103                 new String[]{profileUUID}))
104         {
105             if (cursor.moveToNext()) {
106                 name = cursor.getString(0);
107                 url = cursor.getString(1);
108                 useAuthentication = cursor.getInt(2) == 1;
109                 authUser = useAuthentication ? cursor.getString(3) : null;
110                 authPassword = useAuthentication ? cursor.getString(4) : null;
111             }
112             else {
113                 name = "Unknown profile";
114                 url = "Https://server/url";
115                 useAuthentication = false;
116                 authUser = authPassword = null;
117             }
118         }
119
120         return new MobileLedgerProfile(profileUUID, name, url, useAuthentication, authUser,
121                 authPassword);
122     }
123     public String getUuid() {
124         return uuid;
125     }
126     public String getName() {
127         return name;
128     }
129     public void setName(CharSequence text) {
130         setName(String.valueOf(text));
131     }
132     public void setName(String name) {
133         this.name = name;
134     }
135     public String getUrl() {
136         return url;
137     }
138     public void setUrl(CharSequence text) {
139         setUrl(String.valueOf(text));
140     }
141     public void setUrl(String url) {
142         this.url = url;
143     }
144     public boolean isAuthEnabled() {
145         return authEnabled;
146     }
147     public void setAuthEnabled(boolean authEnabled) {
148         this.authEnabled = authEnabled;
149     }
150     public String getAuthUserName() {
151         return authUserName;
152     }
153     public void setAuthUserName(CharSequence text) {
154         setAuthUserName(String.valueOf(text));
155     }
156     public void setAuthUserName(String authUserName) {
157         this.authUserName = authUserName;
158     }
159     public String getAuthPassword() {
160         return authPassword;
161     }
162     public void setAuthPassword(CharSequence text) {
163         setAuthPassword(String.valueOf(text));
164     }
165     public void setAuthPassword(String authPassword) {
166         this.authPassword = authPassword;
167     }
168     public void storeInDB() {
169         SQLiteDatabase db = MLDB.getWritableDatabase();
170         db.beginTransaction();
171         try {
172             db.execSQL("REPLACE INTO profiles(uuid, name, url, use_authentication, auth_user, " +
173                        "auth_password) VALUES(?, ?, ?, ?, ?, ?)",
174                     new Object[]{uuid, name, url, authEnabled, authEnabled ? authUserName : null,
175                                  authEnabled ? authPassword : null
176                     });
177             db.setTransactionSuccessful();
178         }
179         finally {
180             db.endTransaction();
181         }
182     }
183     public void storeAccount(LedgerAccount acc) {
184         SQLiteDatabase db = MLDB.getWritableDatabase();
185
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(),
193                              acc.getLevel()
194                 });
195     }
196     public void storeAccountValue(String name, String currency, Float amount) {
197         SQLiteDatabase db = MLDB.getWritableDatabase();
198         db.execSQL("replace into account_values(profile, account, " +
199                    "currency, value, keep) values(?, ?, ?, ?, 1);",
200                 new Object[]{uuid, name, currency, amount});
201     }
202     public void storeTransaction(LedgerTransaction tr) {
203         SQLiteDatabase db = MLDB.getWritableDatabase();
204         tr.fillDataHash();
205         db.execSQL("DELETE from transactions WHERE profile=? and id=?",
206                 new Object[]{uuid, tr.getId()});
207         db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
208                 new Object[]{uuid, tr.getId()});
209
210         db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
211                    "values(?,?,?,?,?,1)",
212                 new Object[]{uuid, tr.getId(), tr.getDate(), 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 }