]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/dao/TransactionDAO.java
001976d3b1ee08393c2ac48d6fbc5d634566a403
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / dao / TransactionDAO.java
1 /*
2  * Copyright © 2021 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.dao;
19
20 import androidx.annotation.NonNull;
21 import androidx.lifecycle.LiveData;
22 import androidx.room.ColumnInfo;
23 import androidx.room.Dao;
24 import androidx.room.Delete;
25 import androidx.room.Insert;
26 import androidx.room.OnConflictStrategy;
27 import androidx.room.Query;
28 import androidx.room.Update;
29
30 import net.ktnx.mobileledger.db.Account;
31 import net.ktnx.mobileledger.db.AccountValue;
32 import net.ktnx.mobileledger.db.DB;
33 import net.ktnx.mobileledger.db.Transaction;
34 import net.ktnx.mobileledger.db.TransactionAccount;
35 import net.ktnx.mobileledger.db.TransactionWithAccounts;
36 import net.ktnx.mobileledger.model.LedgerAccount;
37 import net.ktnx.mobileledger.utils.Logger;
38 import net.ktnx.mobileledger.utils.Misc;
39
40 import java.util.ArrayList;
41 import java.util.List;
42 import java.util.Locale;
43
44 @Dao
45 public abstract class TransactionDAO extends BaseDAO<Transaction> {
46     static public List<String> unbox(List<DescriptionContainer> list) {
47         ArrayList<String> result = new ArrayList<>(list.size());
48         for (DescriptionContainer item : list) {
49             result.add(item.description);
50         }
51
52         return result;
53     }
54     @Insert(onConflict = OnConflictStrategy.REPLACE)
55     public abstract long insertSync(Transaction item);
56
57     @Update
58     public abstract void updateSync(Transaction item);
59
60     @Delete
61     public abstract void deleteSync(Transaction item);
62
63     @Delete
64     public abstract void deleteSync(Transaction... items);
65
66     @Delete
67     public abstract void deleteSync(List<Transaction> items);
68
69     @Query("DELETE FROM transactions")
70     public abstract void deleteAllSync();
71
72     @Query("SELECT * FROM transactions WHERE id = :id")
73     public abstract LiveData<Transaction> getById(long id);
74
75     @androidx.room.Transaction
76     @Query("SELECT * FROM transactions WHERE id = :transactionId")
77     public abstract LiveData<TransactionWithAccounts> getByIdWithAccounts(long transactionId);
78
79     @androidx.room.Transaction
80     @Query("SELECT * FROM transactions WHERE id = :transactionId")
81     public abstract TransactionWithAccounts getByIdWithAccountsSync(long transactionId);
82
83     @Query("SELECT DISTINCT description, CASE WHEN description_uc LIKE :term||'%%' THEN 1 " +
84            "               WHEN description_uc LIKE '%%:'||:term||'%%' THEN 2 " +
85            "               WHEN description_uc LIKE '%% '||:term||'%%' THEN 3 " +
86            "               ELSE 9 END AS ordering FROM transactions " +
87            "WHERE description_uc LIKE '%%'||:term||'%%' ORDER BY ordering, description_uc, rowid ")
88     public abstract List<DescriptionContainer> lookupDescriptionSync(@NonNull String term);
89
90     @androidx.room.Transaction
91     @Query("SELECT * from transactions WHERE description = :description ORDER BY year desc, month" +
92            " desc, day desc LIMIT 1")
93     public abstract TransactionWithAccounts getFirstByDescriptionSync(@NonNull String description);
94
95     @androidx.room.Transaction
96     @Query("SELECT tr.id, tr.profile_id, tr.ledger_id, tr.description, tr.description_uc, tr" +
97            ".data_hash, tr.comment, tr.year, tr.month, tr.day, tr.generation from transactions tr" +
98            " JOIN transaction_accounts t_a ON t_a.transaction_id = tr.id WHERE tr.description = " +
99            ":description AND t_a.account_name LIKE '%'||:accountTerm||'%' ORDER BY year desc, " +
100            "month desc, day desc, tr.ledger_id desc LIMIT 1")
101     public abstract TransactionWithAccounts getFirstByDescriptionHavingAccountSync(
102             @NonNull String description, @NonNull String accountTerm);
103
104     @Query("SELECT * from transactions WHERE profile_id = :profileId")
105     public abstract List<Transaction> getAllForProfileUnorderedSync(long profileId);
106
107     @Query("SELECT generation FROM transactions WHERE profile_id = :profileId LIMIT 1")
108     protected abstract TransactionGenerationContainer getGenerationPOJOSync(long profileId);
109
110     @androidx.room.Transaction
111     @Query("SELECT * FROM transactions WHERE profile_id = :profileId ORDER BY year " +
112            " asc, month asc, day asc, ledger_id asc")
113     public abstract LiveData<List<TransactionWithAccounts>> getAllWithAccounts(long profileId);
114
115     @androidx.room.Transaction
116     @Query("SELECT distinct(tr.id), tr.ledger_id, tr.profile_id, tr.data_hash, tr.year, tr.month," +
117            " tr.day, tr.description, tr.description_uc, tr.comment, tr.generation FROM " +
118            "transactions tr JOIN transaction_accounts ta ON ta.transaction_id=tr.id WHERE ta" +
119            ".account_name LIKE :accountName||'%' AND ta.amount <> 0 AND tr.profile_id = " +
120            ":profileId ORDER BY tr.year asc, tr.month asc, tr.day asc, tr.ledger_id asc")
121     public abstract LiveData<List<TransactionWithAccounts>> getAllWithAccountsFiltered(
122             long profileId, String accountName);
123
124     @Query("DELETE FROM transactions WHERE profile_id = :profileId AND generation <> " +
125            ":currentGeneration")
126     public abstract int purgeOldTransactionsSync(long profileId, long currentGeneration);
127
128     @Query("DELETE FROM transaction_accounts WHERE EXISTS (SELECT 1 FROM transactions tr WHERE tr" +
129            ".id=transaction_accounts.transaction_id AND tr.profile_id=:profileId) AND generation " +
130            "<> :currentGeneration")
131     public abstract int purgeOldTransactionAccountsSync(long profileId, long currentGeneration);
132
133     @Query("DELETE FROM transactions WHERE profile_id = :profileId")
134     public abstract int deleteAllSync(long profileId);
135
136     @Query("SELECT * FROM transactions where profile_id = :profileId AND ledger_id = :ledgerId")
137     public abstract Transaction getByLedgerId(long profileId, long ledgerId);
138
139     @Query("UPDATE transactions SET generation = :newGeneration WHERE id = :transactionId")
140     public abstract int updateGeneration(long transactionId, long newGeneration);
141
142     @Query("UPDATE transaction_accounts SET generation = :newGeneration WHERE transaction_id = " +
143            ":transactionId")
144     public abstract int updateAccountsGeneration(long transactionId, long newGeneration);
145
146     @Query("SELECT max(ledger_id) as ledger_id FROM transactions WHERE profile_id = :profileId")
147     public abstract LedgerIdContainer getMaxLedgerIdPOJOSync(long profileId);
148     @androidx.room.Transaction
149     public void updateGenerationWithAccounts(long transactionId, long newGeneration) {
150         updateGeneration(transactionId, newGeneration);
151         updateAccountsGeneration(transactionId, newGeneration);
152     }
153     public long getGenerationSync(long profileId) {
154         TransactionGenerationContainer result = getGenerationPOJOSync(profileId);
155
156         if (result == null)
157             return 0;
158         return result.generation;
159     }
160     public long getMaxLedgerIdSync(long profileId) {
161         LedgerIdContainer result = getMaxLedgerIdPOJOSync(profileId);
162
163         if (result == null)
164             return 0;
165         return result.ledgerId;
166     }
167     @androidx.room.Transaction
168     public void storeTransactionsSync(List<TransactionWithAccounts> list, long profileId) {
169         long generation = getGenerationSync(profileId) + 1;
170
171         for (TransactionWithAccounts tr : list) {
172             tr.transaction.setGeneration(generation);
173             tr.transaction.setProfileId(profileId);
174
175             storeSync(tr);
176         }
177
178         Logger.debug("Transaction", "Purging old transactions");
179         int removed = purgeOldTransactionsSync(profileId, generation);
180         Logger.debug("Transaction", String.format(Locale.ROOT, "Purged %d transactions", removed));
181
182         removed = purgeOldTransactionAccountsSync(profileId, generation);
183         Logger.debug("Transaction",
184                 String.format(Locale.ROOT, "Purged %d transaction accounts", removed));
185     }
186     @androidx.room.Transaction
187     void storeSync(TransactionWithAccounts rec) {
188         TransactionAccountDAO trAccDao = DB.get()
189                                            .getTransactionAccountDAO();
190
191         Transaction transaction = rec.transaction;
192         Transaction existing = getByLedgerId(transaction.getProfileId(), transaction.getLedgerId());
193         if (existing != null) {
194             if (Misc.equalStrings(transaction.getDataHash(), existing.getDataHash())) {
195                 updateGenerationWithAccounts(existing.getId(), rec.transaction.getGeneration());
196                 return;
197             }
198
199             existing.copyDataFrom(transaction);
200             updateSync(existing);
201
202             transaction = existing;
203         }
204         else
205             transaction.setId(insertSync(transaction));
206
207         for (TransactionAccount trAcc : rec.accounts) {
208             trAcc.setTransactionId(transaction.getId());
209             trAcc.setGeneration(transaction.getGeneration());
210             TransactionAccount existingAcc =
211                     trAccDao.getByOrderNoSync(trAcc.getTransactionId(), trAcc.getOrderNo());
212             if (existingAcc != null) {
213                 existingAcc.copyDataFrom(trAcc);
214                 trAccDao.updateSync(existingAcc);
215             }
216             else
217                 trAcc.setId(trAccDao.insertSync(trAcc));
218         }
219     }
220     public void storeLast(TransactionWithAccounts rec) {
221         BaseDAO.runAsync(() -> appendSync(rec));
222     }
223     @androidx.room.Transaction
224     public void appendSync(TransactionWithAccounts rec) {
225         TransactionAccountDAO trAccDao = DB.get()
226                                            .getTransactionAccountDAO();
227         AccountDAO accDao = DB.get()
228                               .getAccountDAO();
229         AccountValueDAO accValDao = DB.get()
230                                       .getAccountValueDAO();
231
232         Transaction transaction = rec.transaction;
233         final long profileId = transaction.getProfileId();
234         transaction.setGeneration(getGenerationSync(profileId));
235         transaction.setLedgerId(getMaxLedgerIdSync(profileId) + 1);
236         transaction.setId(insertSync(transaction));
237
238         for (TransactionAccount trAcc : rec.accounts) {
239             trAcc.setTransactionId(transaction.getId());
240             trAcc.setGeneration(transaction.getGeneration());
241             trAcc.setId(trAccDao.insertSync(trAcc));
242
243             String accName = trAcc.getAccountName();
244             while (accName != null) {
245                 Account acc = accDao.getByNameSync(profileId, accName);
246                 if (acc == null) {
247                     acc = new Account();
248                     acc.setProfileId(profileId);
249                     acc.setName(accName);
250                     acc.setNameUpper(accName.toUpperCase());
251                     acc.setParentName(LedgerAccount.extractParentName(accName));
252                     acc.setLevel(LedgerAccount.determineLevel(acc.getName()));
253                     acc.setGeneration(trAcc.getGeneration());
254
255                     acc.setId(accDao.insertSync(acc));
256                 }
257
258                 AccountValue accVal = accValDao.getByCurrencySync(acc.getId(), trAcc.getCurrency());
259                 if (accVal == null) {
260                     accVal = new AccountValue();
261                     accVal.setAccountId(acc.getId());
262                     accVal.setGeneration(trAcc.getGeneration());
263                     accVal.setCurrency(trAcc.getCurrency());
264                     accVal.setValue(trAcc.getAmount());
265                     accVal.setId(accValDao.insertSync(accVal));
266                 }
267                 else {
268                     accVal.setValue(accVal.getValue() + trAcc.getAmount());
269                     accValDao.updateSync(accVal);
270                 }
271
272                 accName = LedgerAccount.extractParentName(accName);
273             }
274         }
275     }
276     static class TransactionGenerationContainer {
277         @ColumnInfo
278         long generation;
279         public TransactionGenerationContainer(long generation) {
280             this.generation = generation;
281         }
282     }
283
284     static class LedgerIdContainer {
285         @ColumnInfo(name = "ledger_id")
286         long ledgerId;
287         public LedgerIdContainer(long ledgerId) {
288             this.ledgerId = ledgerId;
289         }
290     }
291
292     static public class DescriptionContainer {
293         @ColumnInfo
294         public String description;
295         @ColumnInfo
296         public int ordering;
297     }
298 }