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