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