another major rework, transaction list is fully asynchronous
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / LedgerTransaction.java
1 /*
2  * Copyright © 2018 Damyan Ivanov.
3  * This file is part of Mobile-Ledger.
4  * Mobile-Ledger 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  * Mobile-Ledger 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 Mobile-Ledger. 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
26 import java.nio.charset.Charset;
27 import java.security.NoSuchAlgorithmException;
28 import java.util.ArrayList;
29 import java.util.Comparator;
30
31 public class LedgerTransaction {
32     private static final String DIGEST_TYPE = "SHA-256";
33     public final Comparator<LedgerTransactionAccount> comparator =
34             new Comparator<LedgerTransactionAccount>() {
35                 @Override
36                 public int compare(LedgerTransactionAccount o1, LedgerTransactionAccount o2) {
37                     int res = o1.getAccountName().compareTo(o2.getAccountName());
38                     if (res != 0) return res;
39                     res = o1.getCurrency().compareTo(o2.getCurrency());
40                     if (res != 0) return res;
41                     return Float.compare(o1.getAmount(), o2.getAmount());
42                 }
43             };
44     private Integer id;
45     private String date;
46     private String description;
47     private ArrayList<LedgerTransactionAccount> accounts;
48     public LedgerTransaction(Integer id, String date, String description) {
49         this.id = id;
50         this.date = date;
51         this.description = description;
52         this.accounts = new ArrayList<>();
53         this.dataHash = null;
54         dataLoaded = false;
55     }
56     private String dataHash;
57     private boolean dataLoaded;
58     public ArrayList<LedgerTransactionAccount> getAccounts() {
59         return accounts;
60     }
61     public LedgerTransaction(String date, String description) {
62         this(null, date, description);
63     }
64     public LedgerTransaction(int id) {
65         this(id, null, null);
66     }
67     public void addAccount(LedgerTransactionAccount item) {
68         accounts.add(item);
69         dataHash = null;
70     }
71     public String getDate() {
72         return date;
73     }
74     public void setDate(String date) {
75         this.date = date;
76         dataHash = null;
77     }
78     public String getDescription() {
79         return description;
80     }
81     public void setDescription(String description) {
82         this.description = description;
83         dataHash = null;
84     }
85     public int getId() {
86         return id;
87     }
88     public void insertInto(SQLiteDatabase db) {
89         fillDataHash();
90         db.execSQL("INSERT INTO transactions(id, date, description, data_hash) values(?,?,?,?)",
91                 new Object[]{id, date, description, dataHash});
92
93         for (LedgerTransactionAccount item : accounts) {
94             db.execSQL("INSERT INTO transaction_accounts(transaction_id, account_name, amount, " +
95                        "currency) values(?, ?, ?, ?)",
96                     new Object[]{id, item.getAccountName(), item.getAmount(), item.getCurrency()});
97         }
98     }
99     private void fillDataHash() {
100         if (dataHash != null) return;
101         try {
102             Digest sha = new Digest(DIGEST_TYPE);
103             StringBuilder data = new StringBuilder();
104             data.append(getId());
105             data.append('\0');
106             data.append(getDescription());
107             data.append('\0');
108             for (LedgerTransactionAccount item : accounts) {
109                 data.append(item.getAccountName());
110                 data.append('\0');
111                 data.append(item.getCurrency());
112                 data.append('\0');
113                 data.append(item.getAmount());
114             }
115             sha.update(data.toString().getBytes(Charset.forName("UTF-8")));
116             dataHash = sha.digestToHexString();
117         }
118         catch (NoSuchAlgorithmException e) {
119             throw new RuntimeException(
120                     String.format("Unable to get instance of %s digest", DIGEST_TYPE), e);
121         }
122     }
123     public boolean existsInDb(SQLiteDatabase db) {
124         fillDataHash();
125         try (Cursor c = db
126                 .rawQuery("SELECT 1 from transactions where data_hash = ?", new String[]{dataHash}))
127         {
128             boolean result = c.moveToFirst();
129             Log.d("db", String.format("Transaction %d (%s) %s", id, dataHash,
130                     result ? "already present" : "not present"));
131             return result;
132         }
133     }
134     public void loadData(SQLiteDatabase db) {
135         if (dataLoaded) return;
136
137         try (Cursor cTr = db.rawQuery("SELECT date, description from transactions WHERE id=?",
138                 new String[]{String.valueOf(id)}))
139         {
140             if (cTr.moveToFirst()) {
141                 date = cTr.getString(0);
142                 description = cTr.getString(1);
143
144                 try (Cursor cAcc = db.rawQuery("SELECT account_name, amount, currency FROM " +
145                                                "transaction_accounts WHERE transaction_id = ?",
146                         new String[]{String.valueOf(id)}))
147                 {
148                     while (cAcc.moveToNext()) {
149                         addAccount(new LedgerTransactionAccount(cAcc.getString(0), cAcc.getFloat(1),
150                                 cAcc.getString(2)));
151                     }
152
153                     dataLoaded = true;
154                 }
155             }
156         }
157
158     }
159 }