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