]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/model/LedgerTransaction.java
5bc8456bb4b81b8939e3b088ad1c9470ad8db0ca
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / model / LedgerTransaction.java
1 /*
2  * Copyright © 2020 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
23 import androidx.annotation.NonNull;
24
25 import net.ktnx.mobileledger.App;
26 import net.ktnx.mobileledger.utils.Digest;
27 import net.ktnx.mobileledger.utils.Globals;
28 import net.ktnx.mobileledger.utils.SimpleDate;
29
30 import java.nio.charset.StandardCharsets;
31 import java.security.NoSuchAlgorithmException;
32 import java.text.ParseException;
33 import java.util.ArrayList;
34 import java.util.Comparator;
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()
43                                 .compareTo(o2.getAccountName());
44                     if (res != 0)
45                         return res;
46                     res = o1.getCurrency()
47                             .compareTo(o2.getCurrency());
48                     if (res != 0)
49                         return res;
50                     res = o1.getComment()
51                             .compareTo(o2.getComment());
52                     if (res != 0)
53                         return res;
54                     return Float.compare(o1.getAmount(), o2.getAmount());
55                 }
56             };
57     private String profile;
58     private Integer id;
59     private SimpleDate date;
60     private String description;
61     private String comment;
62     private ArrayList<LedgerTransactionAccount> accounts;
63     private String dataHash;
64     private boolean dataLoaded;
65     public LedgerTransaction(Integer id, String dateString, String description)
66             throws ParseException {
67         this(id, Globals.parseLedgerDate(dateString), description);
68     }
69     public LedgerTransaction(Integer id, SimpleDate date, String description,
70                              MobileLedgerProfile profile) {
71         this.profile = profile.getUuid();
72         this.id = id;
73         this.date = date;
74         this.description = description;
75         this.accounts = new ArrayList<>();
76         this.dataHash = null;
77         dataLoaded = false;
78     }
79     public LedgerTransaction(Integer id, SimpleDate date, String description) {
80         this(id, date, description, Data.profile.getValue());
81     }
82     public LedgerTransaction(SimpleDate date, String description) {
83         this(null, date, description);
84     }
85     public LedgerTransaction(int id) {
86         this(id, (SimpleDate) null, null);
87     }
88     public LedgerTransaction(int id, String profileUUID) {
89         this.profile = profileUUID;
90         this.id = id;
91         this.date = null;
92         this.description = null;
93         this.accounts = new ArrayList<>();
94         this.dataHash = null;
95         this.dataLoaded = false;
96     }
97     public ArrayList<LedgerTransactionAccount> getAccounts() {
98         return accounts;
99     }
100     public void addAccount(LedgerTransactionAccount item) {
101         accounts.add(item);
102         dataHash = null;
103     }
104     @NonNull
105     public SimpleDate getDate() {
106         loadData(App.getDatabase());
107         if (date == null)
108             throw new IllegalStateException("Transaction has no date");
109         return date;
110     }
111     public void setDate(SimpleDate date) {
112         this.date = date;
113         dataHash = null;
114     }
115     public String getDescription() {
116         return description;
117     }
118     public void setDescription(String description) {
119         this.description = description;
120         dataHash = null;
121     }
122     public String getComment() {
123         return comment;
124     }
125     public void setComment(String comment) {
126         this.comment = comment;
127     }
128     public int getId() {
129         return id;
130     }
131     protected void fillDataHash() {
132         if (dataHash != null)
133             return;
134         try {
135             Digest sha = new Digest(DIGEST_TYPE);
136             StringBuilder data = new StringBuilder();
137             data.append("ver1");
138             data.append(profile);
139             data.append(getId());
140             data.append('\0');
141             data.append(getDescription());
142             data.append('\0');
143             data.append(getComment());
144             data.append('\0');
145             data.append(Globals.formatLedgerDate(getDate()));
146             data.append('\0');
147             for (LedgerTransactionAccount item : accounts) {
148                 data.append(item.getAccountName());
149                 data.append('\0');
150                 data.append(item.getCurrency());
151                 data.append('\0');
152                 data.append(item.getAmount());
153                 data.append('\0');
154                 data.append(item.getComment());
155             }
156             sha.update(data.toString()
157                            .getBytes(StandardCharsets.UTF_8));
158             dataHash = sha.digestToHexString();
159         }
160         catch (NoSuchAlgorithmException e) {
161             throw new RuntimeException(
162                     String.format("Unable to get instance of %s digest", DIGEST_TYPE), e);
163         }
164     }
165     public boolean existsInDb(SQLiteDatabase db) {
166         fillDataHash();
167         try (Cursor c = db.rawQuery("SELECT 1 from transactions where data_hash = ?",
168                 new String[]{dataHash}))
169         {
170             boolean result = c.moveToFirst();
171 //            debug("db", String.format("Transaction %d (%s) %s", id, dataHash,
172 //                    result ? "already present" : "not present"));
173             return result;
174         }
175     }
176     public void loadData(SQLiteDatabase db) {
177         if (dataLoaded)
178             return;
179
180         try (Cursor cTr = db.rawQuery(
181                 "SELECT year, month, day, description, comment from transactions WHERE profile=? " +
182                 "AND id=?", new String[]{profile, String.valueOf(id)}))
183         {
184             if (cTr.moveToFirst()) {
185                 date = new SimpleDate(cTr.getInt(0), cTr.getInt(1), cTr.getInt(2));
186                 description = cTr.getString(3);
187                 comment = cTr.getString(4);
188
189                 accounts.clear();
190
191                 try (Cursor cAcc = db.rawQuery(
192                         "SELECT account_name, amount, currency, comment FROM " +
193                         "transaction_accounts WHERE profile=? AND transaction_id = ?",
194                         new String[]{profile, String.valueOf(id)}))
195                 {
196                     while (cAcc.moveToNext()) {
197 //                        debug("transactions",
198 //                                String.format("Loaded %d: %s %1.2f %s", id, cAcc.getString(0),
199 //                                        cAcc.getFloat(1), cAcc.getString(2)));
200                         addAccount(new LedgerTransactionAccount(cAcc.getString(0), cAcc.getFloat(1),
201                                 cAcc.getString(2), cAcc.getString(3)));
202                     }
203
204                     finishLoading();
205                 }
206             }
207         }
208
209     }
210     public String getDataHash() {
211         fillDataHash();
212         return dataHash;
213     }
214     public void finishLoading() {
215         dataLoaded = true;
216     }
217 }