]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/MobileLedgerProfile.java
fix the 'Posting committed' switch in the profile editor
[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     public boolean isPostingPermitted() {
99         return permitPosting;
100     }
101     public void setPostingPermitted(boolean permitPosting) {
102         this.permitPosting = permitPosting;
103     }
104     public String getUuid() {
105         return uuid;
106     }
107     public String getName() {
108         return name;
109     }
110     public void setName(String name) {
111         this.name = name;
112     }
113     public void setName(CharSequence text) {
114         setName(String.valueOf(text));
115     }
116     public String getUrl() {
117         return url;
118     }
119     public void setUrl(String url) {
120         this.url = url;
121     }
122     public void setUrl(CharSequence text) {
123         setUrl(String.valueOf(text));
124     }
125     public boolean isAuthEnabled() {
126         return authEnabled;
127     }
128     public void setAuthEnabled(boolean authEnabled) {
129         this.authEnabled = authEnabled;
130     }
131     public String getAuthUserName() {
132         return authUserName;
133     }
134     public void setAuthUserName(String authUserName) {
135         this.authUserName = authUserName;
136     }
137     public void setAuthUserName(CharSequence text) {
138         setAuthUserName(String.valueOf(text));
139     }
140     public String getAuthPassword() {
141         return authPassword;
142     }
143     public void setAuthPassword(String authPassword) {
144         this.authPassword = authPassword;
145     }
146     public void setAuthPassword(CharSequence text) {
147         setAuthPassword(String.valueOf(text));
148     }
149     public void storeInDB() {
150         SQLiteDatabase db = MLDB.getWritableDatabase();
151         db.beginTransaction();
152         try {
153             db.execSQL("REPLACE INTO profiles(uuid, name, permit_posting, url, " +
154                        "use_authentication, auth_user, " +
155                        "auth_password) VALUES(?, ?, ?, ?, ?, ?, ?)",
156                     new Object[]{uuid, name, permitPosting, url, authEnabled,
157                                  authEnabled ? authUserName : null,
158                                  authEnabled ? authPassword : null
159                     });
160             db.setTransactionSuccessful();
161         }
162         finally {
163             db.endTransaction();
164         }
165     }
166     public void storeAccount(LedgerAccount acc) {
167         SQLiteDatabase db = MLDB.getWritableDatabase();
168
169         // replace into is a bad idea because it would reset hidden to its default value
170         // we like the default, but for new accounts only
171         db.execSQL("update accounts set level = ?, keep = 1 where profile=? and name = ?",
172                 new Object[]{acc.getLevel(), uuid, acc.getName()});
173         db.execSQL("insert into accounts(profile, name, name_upper, parent_name, level) " +
174                    "select ?,?,?,?,? where (select changes() = 0)",
175                 new Object[]{uuid, acc.getName(), acc.getName().toUpperCase(), acc.getParentName(),
176                              acc.getLevel()
177                 });
178     }
179     public void storeAccountValue(String name, String currency, Float amount) {
180         SQLiteDatabase db = MLDB.getWritableDatabase();
181         db.execSQL("replace into account_values(profile, account, " +
182                    "currency, value, keep) values(?, ?, ?, ?, 1);",
183                 new Object[]{uuid, name, currency, amount});
184     }
185     public void storeTransaction(LedgerTransaction tr) {
186         SQLiteDatabase db = MLDB.getWritableDatabase();
187         tr.fillDataHash();
188         db.execSQL("DELETE from transactions WHERE profile=? and id=?",
189                 new Object[]{uuid, tr.getId()});
190         db.execSQL("DELETE from transaction_accounts WHERE profile = ? and transaction_id=?",
191                 new Object[]{uuid, tr.getId()});
192
193         db.execSQL("INSERT INTO transactions(profile, id, date, description, data_hash, keep) " +
194                    "values(?,?,?,?,?,1)",
195                 new Object[]{uuid, tr.getId(), Globals.formatLedgerDate(tr.getDate()),
196                              tr.getDescription(), tr.getDataHash()
197                 });
198
199         for (LedgerTransactionAccount item : tr.getAccounts()) {
200             db.execSQL("INSERT INTO transaction_accounts(profile, transaction_id, " +
201                        "account_name, amount, currency) values(?, ?, ?, ?, ?)",
202                     new Object[]{uuid, tr.getId(), item.getAccountName(), item.getAmount(),
203                                  item.getCurrency()
204                     });
205         }
206         Log.d("profile", String.format("Transaction %d stored", tr.getId()));
207     }
208     public String getOption(String name, String default_value) {
209         SQLiteDatabase db = MLDB.getReadableDatabase();
210         try (Cursor cursor = db.rawQuery("select value from options where profile = ? and name=?",
211                 new String[]{uuid, name}))
212         {
213             if (cursor.moveToFirst()) {
214                 String result = cursor.getString(0);
215
216                 if (result == null) {
217                     Log.d("profile", "returning default value for " + name);
218                     result = default_value;
219                 }
220                 else Log.d("profile", String.format("option %s=%s", name, result));
221
222                 return result;
223             }
224             else return default_value;
225         }
226         catch (Exception e) {
227             Log.d("db", "returning default value for " + name, e);
228             return default_value;
229         }
230     }
231     public long getLongOption(String name, long default_value) {
232         long longResult;
233         String result = getOption(name, "");
234         if ((result == null) || result.isEmpty()) {
235             Log.d("profile", String.format("Returning default value for option %s", name));
236             longResult = default_value;
237         }
238         else {
239             try {
240                 longResult = Long.parseLong(result);
241                 Log.d("profile", String.format("option %s=%s", name, result));
242             }
243             catch (Exception e) {
244                 Log.d("profile", String.format("Returning default value for option %s", name), e);
245                 longResult = default_value;
246             }
247         }
248
249         return longResult;
250     }
251     public void setOption(String name, String value) {
252         Log.d("profile", String.format("setting option %s=%s", name, value));
253         SQLiteDatabase db = MLDB.getWritableDatabase();
254         db.execSQL("insert or replace into options(profile, name, value) values(?, ?, ?);",
255                 new String[]{uuid, name, value});
256     }
257     public void setLongOption(String name, long value) {
258         setOption(name, String.valueOf(value));
259     }
260     public void removeFromDB() {
261         SQLiteDatabase db = MLDB.getWritableDatabase();
262         Log.d("db", String.format("removing progile %s from DB", uuid));
263         db.execSQL("delete from profiles where uuid=?", new Object[]{uuid});
264     }
265     public LedgerAccount loadAccount(String name) {
266         SQLiteDatabase db = MLDB.getReadableDatabase();
267         try (Cursor cursor = db.rawQuery("SELECT hidden from accounts where profile=? and name=?",
268                 new String[]{uuid, name}))
269         {
270             if (cursor.moveToFirst()) {
271                 LedgerAccount acc = new LedgerAccount(name);
272                 acc.setHidden(cursor.getInt(0) == 1);
273
274                 return acc;
275             }
276         }
277
278         return null;
279     }
280 }