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