]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/dao/TransactionDAO.java
fix ordering of transactions when loaded from database
[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.DB;
31 import net.ktnx.mobileledger.db.Transaction;
32 import net.ktnx.mobileledger.db.TransactionAccount;
33 import net.ktnx.mobileledger.db.TransactionWithAccounts;
34 import net.ktnx.mobileledger.utils.Logger;
35 import net.ktnx.mobileledger.utils.Misc;
36
37 import java.util.ArrayList;
38 import java.util.List;
39 import java.util.Locale;
40
41 @Dao
42 public abstract class TransactionDAO extends BaseDAO<Transaction> {
43     static public List<String> unbox(List<DescriptionContainer> list) {
44         ArrayList<String> result = new ArrayList<>(list.size());
45         for (DescriptionContainer item : list) {
46             result.add(item.description);
47         }
48
49         return result;
50     }
51     @Insert(onConflict = OnConflictStrategy.REPLACE)
52     public abstract long insertSync(Transaction item);
53
54     @Update
55     public abstract void updateSync(Transaction item);
56
57     @Delete
58     public abstract void deleteSync(Transaction item);
59
60     @Delete
61     public abstract void deleteSync(Transaction... items);
62
63     @Delete
64     public abstract void deleteSync(List<Transaction> items);
65
66     @Query("SELECT * FROM transactions WHERE id = :id")
67     public abstract LiveData<Transaction> getById(long id);
68
69     @androidx.room.Transaction
70     @Query("SELECT * FROM transactions WHERE id = :transactionId")
71     public abstract LiveData<TransactionWithAccounts> getByIdWithAccounts(long transactionId);
72
73     @androidx.room.Transaction
74     @Query("SELECT * FROM transactions WHERE id = :transactionId")
75     public abstract TransactionWithAccounts getByIdWithAccountsSync(long transactionId);
76
77     @Query("SELECT DISTINCT description, CASE WHEN description_upper LIKE :term||'%%' THEN 1 " +
78            "               WHEN description_upper LIKE '%%:'||:term||'%%' THEN 2 " +
79            "               WHEN description_upper LIKE '%% '||:term||'%%' THEN 3 " +
80            "               ELSE 9 END AS ordering " + "FROM description_history " +
81            "WHERE description_upper LIKE '%%'||:term||'%%' " +
82            "ORDER BY ordering, description_upper, rowid ")
83     public abstract List<DescriptionContainer> lookupDescriptionSync(@NonNull String term);
84
85     @androidx.room.Transaction
86     @Query("SELECT * from transactions WHERE description = :description ORDER BY year desc, month" +
87            " desc, day desc LIMIT 1")
88     public abstract TransactionWithAccounts getFirstByDescriptionSync(@NonNull String description);
89
90     @androidx.room.Transaction
91     @Query("SELECT tr.id, tr.profile_id, tr.ledger_id, tr.description, tr.data_hash, tr.comment, " +
92            "tr.year, tr.month, tr.day, tr.generation from transactions tr JOIN " +
93            "transaction_accounts t_a ON t_a.transaction_id = tr.id WHERE tr.description = " +
94            ":description AND t_a.account_name LIKE '%'||:accountTerm||'%' ORDER BY year desc, " +
95            "month desc, day desc, tr.ledger_id desc LIMIT 1")
96     public abstract TransactionWithAccounts getFirstByDescriptionHavingAccountSync(
97             @NonNull String description, @NonNull String accountTerm);
98
99     @Query("SELECT * from transactions WHERE profile_id = :profileId")
100     public abstract List<Transaction> getAllForProfileUnorderedSync(long profileId);
101
102     @Query("SELECT generation FROM transactions WHERE profile_id = :profileId LIMIT 1")
103     protected abstract TransactionGenerationContainer getGenerationPOJOSync(long profileId);
104
105     @androidx.room.Transaction
106     @Query("SELECT * FROM transactions WHERE profile_id = :profileId ORDER BY year " +
107            " desc, month desc, day desc, ledger_id desc")
108     public abstract List<TransactionWithAccounts> getAllWithAccountsSync(long profileId);
109
110     @androidx.room.Transaction
111     @Query("SELECT * FROM transactions WHERE profile_id = :profileId ORDER BY year " +
112            " desc, month desc, day desc, ledger_id desc")
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.comment, tr.generation FROM transactions tr JOIN " +
118            "transaction_accounts ta ON ta.transaction_id=tr.id WHERE ta.account_name LIKE " +
119            ":accountName||'%' AND ta.amount <> 0 AND tr.profile_id = :profileId ORDER BY tr.year " +
120            "desc, tr.month desc, tr.day desc, tr.ledger_id desc")
121     public abstract List<TransactionWithAccounts> getAllWithAccountsFilteredSync(long profileId,
122                                                                                  String accountName);
123
124     @androidx.room.Transaction
125     @Query("SELECT distinct(tr.id), tr.ledger_id, tr.profile_id, tr.data_hash, tr.year, tr.month," +
126            " tr.day, tr.description, tr.comment, tr.generation FROM transactions tr JOIN " +
127            "transaction_accounts ta ON ta.transaction_id=tr.id WHERE ta.account_name LIKE " +
128            ":accountName||'%' AND ta.amount <> 0 AND tr.profile_id = :profileId ORDER BY tr.year " +
129            "desc, tr.month desc, tr.day desc, tr.ledger_id desc")
130     public abstract LiveData<List<TransactionWithAccounts>> getAllWithAccountsFiltered(
131             long profileId, String accountName);
132
133     @Query("DELETE FROM transactions WHERE profile_id = :profileId AND generation <> " +
134            ":currentGeneration")
135     public abstract int purgeOldTransactionsSync(long profileId, long currentGeneration);
136
137     @Query("DELETE FROM transaction_accounts WHERE EXISTS (SELECT 1 FROM transactions tr WHERE tr" +
138            ".id=transaction_accounts.transaction_id AND tr.profile_id=:profileId) AND generation " +
139            "<> :currentGeneration")
140     public abstract int purgeOldTransactionAccountsSync(long profileId, long currentGeneration);
141
142     @Query("DELETE FROM transactions WHERE profile_id = :profileId")
143     public abstract int deleteAllSync(long profileId);
144
145     @Query("SELECT * FROM transactions where profile_id = :profileId AND ledger_id = :ledgerId")
146     public abstract Transaction getByLedgerId(long profileId, long ledgerId);
147
148     @Query("UPDATE transactions SET generation = :newGeneration WHERE id = :transactionId")
149     public abstract int updateGeneration(long transactionId, long newGeneration);
150
151     @Query("UPDATE transaction_accounts SET generation = :newGeneration WHERE transaction_id = " +
152            ":transactionId")
153     public abstract int updateAccountsGeneration(long transactionId, long newGeneration);
154     @androidx.room.Transaction
155     public void updateGenerationWithAccounts(long transactionId, long newGeneration) {
156         updateGeneration(transactionId, newGeneration);
157         updateAccountsGeneration(transactionId, newGeneration);
158     }
159     public long getGenerationSync(long profileId) {
160         TransactionGenerationContainer result = getGenerationPOJOSync(profileId);
161
162         if (result == null)
163             return 0;
164         return result.generation;
165     }
166     @androidx.room.Transaction
167     public void storeTransactionsSync(List<TransactionWithAccounts> list, long profileId) {
168         long generation = getGenerationSync(profileId) + 1;
169
170         for (TransactionWithAccounts tr : list) {
171             tr.transaction.setGeneration(generation);
172             tr.transaction.setProfileId(profileId);
173
174             storeSync(tr);
175         }
176
177         Logger.debug("Transaction", "Purging old transactions");
178         int removed = purgeOldTransactionsSync(profileId, generation);
179         Logger.debug("Transaction", String.format(Locale.ROOT, "Purged %d transactions", removed));
180
181         removed = purgeOldTransactionAccountsSync(profileId, generation);
182         Logger.debug("Transaction",
183                 String.format(Locale.ROOT, "Purged %d transaction accounts", removed));
184     }
185     @androidx.room.Transaction
186     void storeSync(TransactionWithAccounts rec) {
187         TransactionAccountDAO trAccDao = DB.get()
188                                            .getTransactionAccountDAO();
189
190         Transaction transaction = rec.transaction;
191         Transaction existing = getByLedgerId(transaction.getProfileId(), transaction.getLedgerId());
192         if (existing != null) {
193             if (Misc.equalStrings(transaction.getDataHash(), existing.getDataHash())) {
194                 updateGenerationWithAccounts(existing.getId(), rec.transaction.getGeneration());
195                 return;
196             }
197
198             existing.copyDataFrom(transaction);
199             updateSync(existing);
200
201             transaction = existing;
202         }
203         else
204             transaction.setId(insertSync(transaction));
205
206         for (TransactionAccount trAcc : rec.accounts) {
207             trAcc.setTransactionId(transaction.getId());
208             trAcc.setGeneration(transaction.getGeneration());
209             TransactionAccount existingAcc =
210                     trAccDao.getByOrderNoSync(trAcc.getTransactionId(), trAcc.getOrderNo());
211             if (existingAcc != null) {
212                 existingAcc.copyDataFrom(trAcc);
213                 trAccDao.updateSync(existingAcc);
214             }
215             else
216                 trAcc.setId(trAccDao.insertSync(trAcc));
217         }
218     }
219     static class TransactionGenerationContainer {
220         @ColumnInfo
221         long generation;
222         public TransactionGenerationContainer(long generation) {
223             this.generation = generation;
224         }
225     }
226
227     static public class DescriptionContainer {
228         @ColumnInfo
229         public String description;
230         @ColumnInfo
231         public int ordering;
232     }
233 }