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