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