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