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