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