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