]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/LedgerTransaction.java
fix a crash when returning to the new transaction activity with the date picker dialo...
[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 String comment;
55     private ArrayList<LedgerTransactionAccount> accounts;
56     private String dataHash;
57     private boolean dataLoaded;
58     public LedgerTransaction(Integer id, String dateString, String description)
59             throws ParseException {
60         this(id, Globals.parseLedgerDate(dateString), description);
61     }
62     public LedgerTransaction(Integer id, Date date, String description,
63                              MobileLedgerProfile profile) {
64         this.profile = profile.getUuid();
65         this.id = id;
66         this.date = date;
67         this.description = description;
68         this.accounts = new ArrayList<>();
69         this.dataHash = null;
70         dataLoaded = false;
71     }
72     public LedgerTransaction(Integer id, Date date, String description) {
73         this(id, date, description, Data.profile.getValue());
74     }
75     public LedgerTransaction(Date date, String description) {
76         this(null, date, description);
77     }
78     public LedgerTransaction(int id) {
79         this(id, (Date) null, null);
80     }
81     public LedgerTransaction(int id, String profileUUID) {
82         this.profile = profileUUID;
83         this.id = id;
84         this.date = null;
85         this.description = null;
86         this.accounts = new ArrayList<>();
87         this.dataHash = null;
88         this.dataLoaded = false;
89     }
90     public ArrayList<LedgerTransactionAccount> getAccounts() {
91         return accounts;
92     }
93     public void addAccount(LedgerTransactionAccount item) {
94         accounts.add(item);
95         dataHash = null;
96     }
97     public Date getDate() {
98         return date;
99     }
100     public void setDate(Date date) {
101         this.date = date;
102         dataHash = null;
103     }
104     public String getDescription() {
105         return description;
106     }
107     public void setDescription(String description) {
108         this.description = description;
109         dataHash = null;
110     }
111     public String getComment() {
112         return comment;
113     }
114     public void setComment(String comment) {
115         this.comment = comment;
116     }
117     public int getId() {
118         return id;
119     }
120     protected void fillDataHash() {
121         if (dataHash != null)
122             return;
123         try {
124             Digest sha = new Digest(DIGEST_TYPE);
125             StringBuilder data = new StringBuilder();
126             data.append(profile);
127             data.append(getId());
128             data.append('\0');
129             data.append(getDescription());
130             data.append('\0');
131             data.append(Globals.formatLedgerDate(getDate()));
132             data.append('\0');
133             for (LedgerTransactionAccount item : accounts) {
134                 data.append(item.getAccountName());
135                 data.append('\0');
136                 data.append(item.getCurrency());
137                 data.append('\0');
138                 data.append(item.getAmount());
139                 data.append('\0');
140                 data.append(item.getComment());
141             }
142             sha.update(data.toString()
143                            .getBytes(Charset.forName("UTF-8")));
144             dataHash = sha.digestToHexString();
145         }
146         catch (NoSuchAlgorithmException e) {
147             throw new RuntimeException(
148                     String.format("Unable to get instance of %s digest", DIGEST_TYPE), e);
149         }
150     }
151     public boolean existsInDb(SQLiteDatabase db) {
152         fillDataHash();
153         try (Cursor c = db.rawQuery("SELECT 1 from transactions where data_hash = ?",
154                 new String[]{dataHash}))
155         {
156             boolean result = c.moveToFirst();
157 //            debug("db", String.format("Transaction %d (%s) %s", id, dataHash,
158 //                    result ? "already present" : "not present"));
159             return result;
160         }
161     }
162     public void loadData(SQLiteDatabase db) {
163         if (dataLoaded)
164             return;
165
166         try (Cursor cTr = db.rawQuery(
167                 "SELECT date, description from transactions WHERE profile=? AND id=?",
168                 new String[]{profile, String.valueOf(id)}))
169         {
170             if (cTr.moveToFirst()) {
171                 String dateString = cTr.getString(0);
172                 try {
173                     date = Globals.parseLedgerDate(dateString);
174                 }
175                 catch (ParseException e) {
176                     e.printStackTrace();
177                     throw new RuntimeException(
178                             String.format("Error parsing date '%s' from " + "transaction %d",
179                                     dateString, id));
180                 }
181                 description = cTr.getString(1);
182
183                 try (Cursor cAcc = db.rawQuery(
184                         "SELECT account_name, amount, currency, comment FROM " +
185                         "transaction_accounts WHERE profile=? AND transaction_id = ?",
186                         new String[]{profile, String.valueOf(id)}))
187                 {
188                     while (cAcc.moveToNext()) {
189 //                        debug("transactions",
190 //                                String.format("Loaded %d: %s %1.2f %s", id, cAcc.getString(0),
191 //                                        cAcc.getFloat(1), cAcc.getString(2)));
192                         addAccount(new LedgerTransactionAccount(cAcc.getString(0), cAcc.getFloat(1),
193                                 cAcc.getString(2), cAcc.getString(3)));
194                     }
195
196                     finishLoading();
197                 }
198             }
199         }
200
201     }
202     public String getDataHash() {
203         return dataHash;
204     }
205     public void finishLoading() {
206         dataLoaded = true;
207     }
208 }