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