]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/LedgerTransaction.java
001c107e0193b2a5c5a272bb6c60ec232a1a5e74
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / LedgerTransaction.java
1 /*
2  * Copyright © 2021 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe 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  * MoLe 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 MoLe. 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
23 import androidx.annotation.NonNull;
24 import androidx.annotation.Nullable;
25
26 import net.ktnx.mobileledger.App;
27 import net.ktnx.mobileledger.utils.Digest;
28 import net.ktnx.mobileledger.utils.Globals;
29 import net.ktnx.mobileledger.utils.SimpleDate;
30
31 import java.nio.charset.StandardCharsets;
32 import java.security.NoSuchAlgorithmException;
33 import java.text.ParseException;
34 import java.util.ArrayList;
35 import java.util.Comparator;
36 import java.util.List;
37
38 public class LedgerTransaction {
39     private static final String DIGEST_TYPE = "SHA-256";
40     public final Comparator<LedgerTransactionAccount> comparator = (o1, o2) -> {
41         int res = o1.getAccountName()
42                     .compareTo(o2.getAccountName());
43         if (res != 0)
44             return res;
45         res = o1.getCurrency()
46                 .compareTo(o2.getCurrency());
47         if (res != 0)
48             return res;
49         res = o1.getComment()
50                 .compareTo(o2.getComment());
51         if (res != 0)
52             return res;
53         return Float.compare(o1.getAmount(), o2.getAmount());
54     };
55     private final long profile;
56     private final long id;
57     private final List<LedgerTransactionAccount> accounts;
58     private SimpleDate date;
59     private String description;
60     private String comment;
61     private String dataHash;
62     private boolean dataLoaded;
63     public LedgerTransaction(long id, String dateString, String description) throws ParseException {
64         this(id, Globals.parseLedgerDate(dateString), description);
65     }
66     public LedgerTransaction(long id, SimpleDate date, String description,
67                              MobileLedgerProfile profile) {
68         this.profile = profile.getId();
69         this.id = id;
70         this.date = date;
71         this.description = description;
72         this.accounts = new ArrayList<>();
73         this.dataHash = null;
74         dataLoaded = false;
75     }
76     public LedgerTransaction(long id, SimpleDate date, String description) {
77         this(id, date, description, Data.getProfile());
78     }
79     public LedgerTransaction(SimpleDate date, String description) {
80         this(0, date, description);
81     }
82     public LedgerTransaction(int id) {
83         this(id, (SimpleDate) null, null);
84     }
85     public LedgerTransaction(int id, long profileId) {
86         this.profile = profileId;
87         this.id = id;
88         this.date = null;
89         this.description = null;
90         this.accounts = new ArrayList<>();
91         this.dataHash = null;
92         this.dataLoaded = false;
93     }
94     public List<LedgerTransactionAccount> getAccounts() {
95         return accounts;
96     }
97     public void addAccount(LedgerTransactionAccount item) {
98         accounts.add(item);
99         dataHash = null;
100     }
101     @Nullable
102     public SimpleDate getDateIfAny() {
103         return date;
104     }
105     @NonNull
106     public SimpleDate getDate() {
107         if (date == null)
108             throw new IllegalStateException("Transaction has no date");
109         return date;
110     }
111     public void setDate(SimpleDate date) {
112         this.date = date;
113         dataHash = null;
114     }
115     public String getDescription() {
116         return description;
117     }
118     public void setDescription(String description) {
119         this.description = description;
120         dataHash = null;
121     }
122     public String getComment() {
123         return comment;
124     }
125     public void setComment(String comment) {
126         this.comment = comment;
127     }
128     public long getId() {
129         return id;
130     }
131     protected void fillDataHash() {
132         loadData(App.getDatabase());
133         if (dataHash != null)
134             return;
135         try {
136             Digest sha = new Digest(DIGEST_TYPE);
137             StringBuilder data = new StringBuilder();
138             data.append("ver1");
139             data.append(profile);
140             data.append(getId());
141             data.append('\0');
142             data.append(getDescription());
143             data.append('\0');
144             data.append(getComment());
145             data.append('\0');
146             data.append(Globals.formatLedgerDate(getDate()));
147             data.append('\0');
148             for (LedgerTransactionAccount item : accounts) {
149                 data.append(item.getAccountName());
150                 data.append('\0');
151                 data.append(item.getCurrency());
152                 data.append('\0');
153                 data.append(item.getAmount());
154                 data.append('\0');
155                 data.append(item.getComment());
156             }
157             sha.update(data.toString()
158                            .getBytes(StandardCharsets.UTF_8));
159             dataHash = sha.digestToHexString();
160         }
161         catch (NoSuchAlgorithmException e) {
162             throw new RuntimeException(
163                     String.format("Unable to get instance of %s digest", DIGEST_TYPE), e);
164         }
165     }
166     public synchronized void loadData(SQLiteDatabase db) {
167         if (dataLoaded)
168             return;
169
170         try (Cursor cTr = db.rawQuery(
171                 "SELECT year, month, day, description, comment from transactions WHERE id=?",
172                 new String[]{String.valueOf(id)}))
173         {
174             if (cTr.moveToFirst()) {
175                 date = new SimpleDate(cTr.getInt(0), cTr.getInt(1), cTr.getInt(2));
176                 description = cTr.getString(3);
177                 comment = cTr.getString(4);
178
179                 accounts.clear();
180
181                 try (Cursor cAcc = db.rawQuery(
182                         "SELECT account_name, amount, currency, comment FROM " +
183                         "transaction_accounts WHERE transaction_id = ?",
184                         new String[]{String.valueOf(id)}))
185                 {
186                     while (cAcc.moveToNext()) {
187 //                        debug("transactions",
188 //                                String.format("Loaded %d: %s %1.2f %s", id, cAcc.getString(0),
189 //                                        cAcc.getFloat(1), cAcc.getString(2)));
190                         addAccount(new LedgerTransactionAccount(cAcc.getString(0), cAcc.getFloat(1),
191                                 cAcc.getString(2), cAcc.getString(3)));
192                     }
193
194                     finishLoading();
195                 }
196             }
197         }
198
199     }
200     public String getDataHash() {
201         fillDataHash();
202         return dataHash;
203     }
204     public void finishLoading() {
205         dataLoaded = true;
206     }
207     @Override
208     public boolean equals(@Nullable Object obj) {
209         if (obj == null)
210             return false;
211         if (!obj.getClass()
212                 .equals(this.getClass()))
213             return false;
214
215         return ((LedgerTransaction) obj).getDataHash()
216                                         .equals(getDataHash());
217     }
218
219     public boolean hasAccountNamedLike(String name) {
220         name = name.toUpperCase();
221         for (LedgerTransactionAccount acc : accounts) {
222             if (acc.getAccountName()
223                    .toUpperCase()
224                    .contains(name))
225                 return true;
226         }
227
228         return false;
229     }
230     public void markDataAsLoaded() {
231         dataLoaded = true;
232     }
233 }