]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
bbcf57fa7696041816c31d705d16996bc7b70ee1
[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(String name) {
184         SQLiteDatabase db = MLDB.getWritableDatabase();
185
186         do {
187             LedgerAccount acc = new LedgerAccount(name);
188             db.execSQL("replace into accounts(profile, name, name_upper, level, keep) values(?, " +
189                        "?, ?, ?, 1)",
190                     new Object[]{this.uuid, name, name.toUpperCase(), acc.getLevel()});
191             name = acc.getParentName();
192         } while (name != null);
193     }
194     public void storeAccountValue(String name, String currency, Float amount) {
195         SQLiteDatabase db = MLDB.getWritableDatabase();
196         db.execSQL("replace into account_values(profile, account, " +
197                    "currency, value, keep) values(?, ?, ?, ?, 1);",
198                 new Object[]{uuid, name, currency, amount});
199     }
200     public void storeTransaction(LedgerTransaction tr) {
201         SQLiteDatabase db = MLDB.getWritableDatabase();
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(), tr.getDate(), tr.getDescription(), tr.getDataHash()
211                 });
212
213         for (LedgerTransactionAccount item : tr.getAccounts()) {
214             db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
215                        "account_name, amount, currency) values(?, ?, ?, ?, ?)",
216                     new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
217                                  item.getCurrency()
218                     });
219         }
220         Log.d("profile", String.format("Transaction %d stored", tr.getId()));
221     }
222     public String get_option_value(String name, String default_value) {
223         SQLiteDatabase db = MLDB.getReadableDatabase();
224         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
225                 new String[]{uuid, name}))
226         {
227             if (cursor.moveToFirst()) {
228                 String result = cursor.getString(0);
229
230                 if (result == null) {
231                     Log.d("profile", "returning default value for " + name);
232                     result = default_value;
233                 }
234                 else Log.d("profile", String.format("option %s=%s", name, result));
235
236                 return result;
237             }
238             else return default_value;
239         }
240         catch (Exception e) {
241             Log.d("db", "returning default value for " + name, e);
242             return default_value;
243         }
244     }
245     public long get_option_value(String name, long default_value) {
246         long longResult;
247         String result = get_option_value(name, "");
248         if ((result == null) || result.isEmpty()) {
249             Log.d("profile", String.format("Returning default value for option %s", name));
250             longResult = default_value;
251         }
252         else {
253             try {
254                 longResult = Long.parseLong(result);
255                 Log.d("profile", String.format("option %s=%s", name, result));
256             }
257             catch (Exception e) {
258                 Log.d("profile", String.format("Returning default value for option %s", name), e);
259                 longResult = default_value;
260             }
261         }
262
263         return longResult;
264     }
265     public void set_option_value(String name, String value) {
266         Log.d("profile", String.format("setting option %s=%s", name, value));
267         SQLiteDatabase db = MLDB.getWritableDatabase();
268         db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
269                 new String[]{uuid, name, value});
270     }
271     public void set_option_value(String name, long value) {
272         set_option_value(name, String.valueOf(value));
273     }
274     public void removeFromDB() {
275         SQLiteDatabase db = MLDB.getWritableDatabase();
276         Log.d("db", String.format("removinf progile %s from DB", uuid));
277         db.execSQL("delete from profiles where uuid=?", new Object[]{uuid});
278     }
279 }