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.
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.
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/>.
18 package net.ktnx.mobileledger.dao;
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;
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;
41 import java.util.ArrayList;
42 import java.util.List;
43 import java.util.Locale;
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);
55 @Insert(onConflict = OnConflictStrategy.REPLACE)
56 public abstract long insertSync(Transaction item);
59 public abstract void updateSync(Transaction item);
62 public abstract void deleteSync(Transaction item);
65 public abstract void deleteSync(Transaction... items);
68 public abstract void deleteSync(List<Transaction> items);
70 @Query("SELECT * FROM transactions WHERE id = :id")
71 public abstract LiveData<Transaction> getById(long id);
73 @androidx.room.Transaction
74 @Query("SELECT * FROM transactions WHERE id = :transactionId")
75 public abstract LiveData<TransactionWithAccounts> getByIdWithAccounts(long transactionId);
77 @androidx.room.Transaction
78 @Query("SELECT * FROM transactions WHERE id = :transactionId")
79 public abstract TransactionWithAccounts getByIdWithAccountsSync(long transactionId);
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);
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);
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);
102 @Query("SELECT * from transactions WHERE profile_id = :profileId")
103 public abstract List<Transaction> getAllForProfileUnorderedSync(long profileId);
105 @Query("SELECT generation FROM transactions WHERE profile_id = :profileId LIMIT 1")
106 protected abstract TransactionGenerationContainer getGenerationPOJOSync(long profileId);
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);
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);
122 @Query("DELETE FROM transactions WHERE profile_id = :profileId AND generation <> " +
123 ":currentGeneration")
124 public abstract int purgeOldTransactionsSync(long profileId, long currentGeneration);
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);
131 @Query("DELETE FROM transactions WHERE profile_id = :profileId")
132 public abstract int deleteAllSync(long profileId);
134 @Query("SELECT * FROM transactions where profile_id = :profileId AND ledger_id = :ledgerId")
135 public abstract Transaction getByLedgerId(long profileId, long ledgerId);
137 @Query("UPDATE transactions SET generation = :newGeneration WHERE id = :transactionId")
138 public abstract int updateGeneration(long transactionId, long newGeneration);
140 @Query("UPDATE transaction_accounts SET generation = :newGeneration WHERE transaction_id = " +
142 public abstract int updateAccountsGeneration(long transactionId, long newGeneration);
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);
151 public long getGenerationSync(long profileId) {
152 TransactionGenerationContainer result = getGenerationPOJOSync(profileId);
156 return result.generation;
158 public long getMaxLedgerIdSync(long profileId) {
159 LedgerIdContainer result = getMaxLedgerIdPOJOSync(profileId);
163 return result.ledgerId;
165 @androidx.room.Transaction
166 public void storeTransactionsSync(List<TransactionWithAccounts> list, long profileId) {
167 long generation = getGenerationSync(profileId) + 1;
169 for (TransactionWithAccounts tr : list) {
170 tr.transaction.setGeneration(generation);
171 tr.transaction.setProfileId(profileId);
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));
180 removed = purgeOldTransactionAccountsSync(profileId, generation);
181 Logger.debug("Transaction",
182 String.format(Locale.ROOT, "Purged %d transaction accounts", removed));
184 @androidx.room.Transaction
185 void storeSync(TransactionWithAccounts rec) {
186 TransactionAccountDAO trAccDao = DB.get()
187 .getTransactionAccountDAO();
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());
197 existing.copyDataFrom(transaction);
198 updateSync(existing);
200 transaction = existing;
203 transaction.setId(insertSync(transaction));
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);
215 trAcc.setId(trAccDao.insertSync(trAcc));
218 public void storeLast(TransactionWithAccounts rec) {
219 BaseDAO.runAsync(() -> appendSync(rec));
221 @androidx.room.Transaction
222 public void appendSync(TransactionWithAccounts rec) {
223 TransactionAccountDAO trAccDao = DB.get()
224 .getTransactionAccountDAO();
225 AccountDAO accDao = DB.get()
227 AccountValueDAO accValDao = DB.get()
228 .getAccountValueDAO();
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));
236 for (TransactionAccount trAcc : rec.accounts) {
237 trAcc.setTransactionId(transaction.getId());
238 trAcc.setGeneration(transaction.getGeneration());
239 trAcc.setId(trAccDao.insertSync(trAcc));
241 String accName = trAcc.getAccountName();
242 while (accName != null) {
243 Account acc = accDao.getByNameSync(profileId, accName);
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());
253 acc.setId(accDao.insertSync(acc));
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));
266 accVal.setValue(accVal.getValue() + trAcc.getAmount());
267 accValDao.updateSync(accVal);
270 accName = LedgerAccount.extractParentName(accName);
274 static class TransactionGenerationContainer {
277 public TransactionGenerationContainer(long generation) {
278 this.generation = generation;
282 static class LedgerIdContainer {
283 @ColumnInfo(name = "ledger_id")
285 public LedgerIdContainer(long ledgerId) {
286 this.ledgerId = ledgerId;
290 static public class DescriptionContainer {
292 public String description;