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