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