]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/LedgerTransaction.java
include posting comment in transaction hash
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / LedgerTransaction.java
1 /*
2  * Copyright © 2019 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 net.ktnx.mobileledger.utils.Digest;
24 import net.ktnx.mobileledger.utils.Globals;
25
26 import java.nio.charset.Charset;
27 import java.security.NoSuchAlgorithmException;
28 import java.text.ParseException;
29 import java.util.ArrayList;
30 import java.util.Comparator;
31 import java.util.Date;
32
33 public class LedgerTransaction {
34     private static final String DIGEST_TYPE = "SHA-256";
35     public final Comparator<LedgerTransactionAccount> comparator =
36             new Comparator<LedgerTransactionAccount>() {
37                 @Override
38                 public int compare(LedgerTransactionAccount o1, LedgerTransactionAccount o2) {
39                     int res = o1.getAccountName()
40                                 .compareTo(o2.getAccountName());
41                     if (res != 0)
42                         return res;
43                     res = o1.getCurrency()
44                             .compareTo(o2.getCurrency());
45                     if (res != 0)
46                         return res;
47                     return Float.compare(o1.getAmount(), o2.getAmount());
48                 }
49             };
50     private String profile;
51     private Integer id;
52     private Date date;
53     private String description;
54     private ArrayList<LedgerTransactionAccount> accounts;
55     private String dataHash;
56     private boolean dataLoaded;
57     public LedgerTransaction(Integer id, String dateString, String description)
58             throws ParseException {
59         this(id, Globals.parseLedgerDate(dateString), description);
60     }
61     public LedgerTransaction(Integer id, Date date, String description,
62                              MobileLedgerProfile profile) {
63         this.profile = profile.getUuid();
64         this.id = id;
65         this.date = date;
66         this.description = description;
67         this.accounts = new ArrayList<>();
68         this.dataHash = null;
69         dataLoaded = false;
70     }
71     public LedgerTransaction(Integer id, Date date, String description) {
72         this(id, date, description, Data.profile.getValue());
73     }
74     public LedgerTransaction(Date date, String description) {
75         this(null, date, description);
76     }
77     public LedgerTransaction(int id) {
78         this(id, (Date) null, null);
79     }
80     public LedgerTransaction(int id, String profileUUID) {
81         this.profile = profileUUID;
82         this.id = id;
83         this.date = null;
84         this.description = null;
85         this.accounts = new ArrayList<>();
86         this.dataHash = null;
87         this.dataLoaded = false;
88     }
89     public ArrayList<LedgerTransactionAccount> getAccounts() {
90         return accounts;
91     }
92     public void addAccount(LedgerTransactionAccount item) {
93         accounts.add(item);
94         dataHash = null;
95     }
96     public Date getDate() {
97         return date;
98     }
99     public void setDate(Date date) {
100         this.date = date;
101         dataHash = null;
102     }
103     public String getDescription() {
104         return description;
105     }
106     public void setDescription(String description) {
107         this.description = description;
108         dataHash = null;
109     }
110     public int getId() {
111         return id;
112     }
113     protected void fillDataHash() {
114         if (dataHash != null)
115             return;
116         try {
117             Digest sha = new Digest(DIGEST_TYPE);
118             StringBuilder data = new StringBuilder();
119             data.append(profile);
120             data.append(getId());
121             data.append('\0');
122             data.append(getDescription());
123             data.append('\0');
124             data.append(Globals.formatLedgerDate(getDate()));
125             data.append('\0');
126             for (LedgerTransactionAccount item : accounts) {
127                 data.append(item.getAccountName());
128                 data.append('\0');
129                 data.append(item.getCurrency());
130                 data.append('\0');
131                 data.append(item.getAmount());
132                 data.append('\0');
133                 data.append(item.getComment());
134             }
135             sha.update(data.toString()
136                            .getBytes(Charset.forName("UTF-8")));
137             dataHash = sha.digestToHexString();
138         }
139         catch (NoSuchAlgorithmException e) {
140             throw new RuntimeException(
141                     String.format("Unable to get instance of %s digest", DIGEST_TYPE), e);
142         }
143     }
144     public boolean existsInDb(SQLiteDatabase db) {
145         fillDataHash();
146         try (Cursor c = db.rawQuery("SELECT 1 from transactions where data_hash = ?",
147                 new String[]{dataHash}))
148         {
149             boolean result = c.moveToFirst();
150 //            debug("db", String.format("Transaction %d (%s) %s", id, dataHash,
151 //                    result ? "already present" : "not present"));
152             return result;
153         }
154     }
155     public void loadData(SQLiteDatabase db) {
156         if (dataLoaded)
157             return;
158
159         try (Cursor cTr = db.rawQuery(
160                 "SELECT date, description from transactions WHERE profile=? AND id=?",
161                 new String[]{profile, String.valueOf(id)}))
162         {
163             if (cTr.moveToFirst()) {
164                 String dateString = cTr.getString(0);
165                 try {
166                     date = Globals.parseLedgerDate(dateString);
167                 }
168                 catch (ParseException e) {
169                     e.printStackTrace();
170                     throw new RuntimeException(
171                             String.format("Error parsing date '%s' from " + "transacion %d",
172                                     dateString, id));
173                 }
174                 description = cTr.getString(1);
175
176                 try (Cursor cAcc = db.rawQuery("SELECT account_name, amount, currency, comment FROM " +
177                                                "transaction_accounts WHERE " +
178                                                "profile=? AND transaction_id = ?",
179                         new String[]{profile, String.valueOf(id)}))
180                 {
181                     while (cAcc.moveToNext()) {
182 //                        debug("transactions",
183 //                                String.format("Loaded %d: %s %1.2f %s", id, cAcc.getString(0),
184 //                                        cAcc.getFloat(1), cAcc.getString(2)));
185                         addAccount(new LedgerTransactionAccount(cAcc.getString(0), cAcc.getFloat(1),
186                                 cAcc.getString(2), cAcc.getString(3)));
187                     }
188
189                     finishLoading();
190                 }
191             }
192         }
193
194     }
195     public String getDataHash() {
196         return dataHash;
197     }
198     public void finishLoading() {
199         dataLoaded = true;
200     }
201 }