progressive update of transaction list in DB, stop after 100 matches
[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 import java.util.Iterator;
31
32 public class LedgerTransaction {
33     private static final String DIGEST_TYPE = "SHA-256";
34     public final Comparator<LedgerTransactionItem> comparator =
35             new Comparator<LedgerTransactionItem>() {
36                 @Override
37                 public int compare(LedgerTransactionItem o1, LedgerTransactionItem o2) {
38                     int res = o1.getAccountName().compareTo(o2.getAccountName());
39                     if (res != 0) return res;
40                     res = o1.getCurrency().compareTo(o2.getCurrency());
41                     if (res != 0) return res;
42                     return Float.compare(o1.getAmount(), o2.getAmount());
43                 }
44             };
45     private Integer id;
46     private String date;
47     private String description;
48     private ArrayList<LedgerTransactionItem> items;
49     private String dataHash;
50     private boolean dataLoaded;
51     public LedgerTransaction(Integer id, String date, String description) {
52         this.id = id;
53         this.date = date;
54         this.description = description;
55         this.items = new ArrayList<>();
56         this.dataHash = null;
57         dataLoaded = false;
58     }
59     public LedgerTransaction(String date, String description) {
60         this(null, date, description);
61     }
62     public LedgerTransaction(int id) {
63         this(id, null, null);
64     }
65     public void add_item(LedgerTransactionItem item) {
66         items.add(item);
67         dataHash = null;
68     }
69     public String getDate() {
70         return date;
71     }
72     public void setDate(String date) {
73         this.date = date;
74         dataHash = null;
75     }
76     public String getDescription() {
77         return description;
78     }
79     public void setDescription(String description) {
80         this.description = description;
81         dataHash = null;
82     }
83     public Iterator<LedgerTransactionItem> getItemsIterator() {
84         return new Iterator<LedgerTransactionItem>() {
85             private int pointer = 0;
86             @Override
87             public boolean hasNext() {
88                 return pointer < items.size();
89             }
90
91             @Override
92             public LedgerTransactionItem next() {
93                 return hasNext() ? items.get(pointer++) : null;
94             }
95         };
96     }
97     public int getId() {
98         return id;
99     }
100     public void insertInto(SQLiteDatabase db) {
101         fillDataHash();
102         db.execSQL("INSERT INTO transactions(id, date, description, data_hash) values(?,?,?,?)",
103                 new Object[]{id, date, description, dataHash});
104
105         for (LedgerTransactionItem item : items) {
106             db.execSQL("INSERT INTO transaction_accounts(transaction_id, account_name, amount, " +
107                        "currency) values(?, ?, ?, ?)",
108                     new Object[]{id, item.getAccountName(), item.getAmount(), item.getCurrency()});
109         }
110     }
111     private void fillDataHash() {
112         if (dataHash != null) return;
113         try {
114             Digest sha = new Digest(DIGEST_TYPE);
115             StringBuilder data = new StringBuilder();
116             data.append(getId());
117             data.append('\0');
118             data.append(getDescription());
119             data.append('\0');
120             for (LedgerTransactionItem item : items) {
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("transactions", 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.rawQuery("SELECT date, description from transactions WHERE id=?",
150                 new String[]{String.valueOf(id)}))
151         {
152             if (cTr.moveToFirst()) {
153                 date = cTr.getString(0);
154                 description = cTr.getString(1);
155
156                 try (Cursor cAcc = db.rawQuery("SELECT account_name, amount, currency FROM " +
157                                                "transaction_accounts WHERE transaction_id = ?",
158                         new String[]{String.valueOf(id)}))
159                 {
160                     while (cAcc.moveToNext()) {
161                         add_item(new LedgerTransactionItem(cAcc.getString(0), cAcc.getFloat(1),
162                                 cAcc.getString(2)));
163                     }
164
165                     dataLoaded = true;
166                 }
167             }
168         }
169
170     }
171 }