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