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;
20 import android.os.AsyncTask;
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;
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;
42 import java.util.ArrayList;
43 import java.util.List;
44 import java.util.Locale;
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);
56 @Insert(onConflict = OnConflictStrategy.REPLACE)
57 public abstract long insertSync(Transaction item);
60 public abstract void updateSync(Transaction item);
63 public abstract void deleteSync(Transaction item);
66 public abstract void deleteSync(Transaction... items);
69 public abstract void deleteSync(List<Transaction> items);
71 @Query("SELECT * FROM transactions WHERE id = :id")
72 public abstract LiveData<Transaction> getById(long id);
74 @androidx.room.Transaction
75 @Query("SELECT * FROM transactions WHERE id = :transactionId")
76 public abstract LiveData<TransactionWithAccounts> getByIdWithAccounts(long transactionId);
78 @androidx.room.Transaction
79 @Query("SELECT * FROM transactions WHERE id = :transactionId")
80 public abstract TransactionWithAccounts getByIdWithAccountsSync(long transactionId);
82 @Query("SELECT DISTINCT description, CASE WHEN description_upper LIKE :term||'%%' THEN 1 " +
83 " WHEN description_upper LIKE '%%:'||:term||'%%' THEN 2 " +
84 " WHEN description_upper LIKE '%% '||:term||'%%' THEN 3 " +
85 " ELSE 9 END AS ordering " + "FROM description_history " +
86 "WHERE description_upper LIKE '%%'||:term||'%%' " +
87 "ORDER BY ordering, description_upper, rowid ")
88 public abstract List<DescriptionContainer> lookupDescriptionSync(@NonNull String term);
90 @androidx.room.Transaction
91 @Query("SELECT * from transactions WHERE description = :description ORDER BY year desc, month" +
92 " desc, day desc LIMIT 1")
93 public abstract TransactionWithAccounts getFirstByDescriptionSync(@NonNull String description);
95 @androidx.room.Transaction
96 @Query("SELECT tr.id, tr.profile_id, tr.ledger_id, tr.description, tr.data_hash, tr.comment, " +
97 "tr.year, tr.month, tr.day, tr.generation from transactions tr JOIN " +
98 "transaction_accounts t_a ON t_a.transaction_id = tr.id WHERE tr.description = " +
99 ":description AND t_a.account_name LIKE '%'||:accountTerm||'%' ORDER BY year desc, " +
100 "month desc, day desc, tr.ledger_id desc LIMIT 1")
101 public abstract TransactionWithAccounts getFirstByDescriptionHavingAccountSync(
102 @NonNull String description, @NonNull String accountTerm);
104 @Query("SELECT * from transactions WHERE profile_id = :profileId")
105 public abstract List<Transaction> getAllForProfileUnorderedSync(long profileId);
107 @Query("SELECT generation FROM transactions WHERE profile_id = :profileId LIMIT 1")
108 protected abstract TransactionGenerationContainer getGenerationPOJOSync(long profileId);
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 List<TransactionWithAccounts> getAllWithAccountsSync(long profileId);
115 @androidx.room.Transaction
116 @Query("SELECT * FROM transactions WHERE profile_id = :profileId ORDER BY year " +
117 " desc, month desc, day desc, ledger_id desc")
118 public abstract LiveData<List<TransactionWithAccounts>> getAllWithAccounts(long profileId);
120 @androidx.room.Transaction
121 @Query("SELECT distinct(tr.id), tr.ledger_id, tr.profile_id, tr.data_hash, tr.year, tr.month," +
122 " tr.day, tr.description, tr.comment, tr.generation FROM transactions tr JOIN " +
123 "transaction_accounts ta ON ta.transaction_id=tr.id WHERE ta.account_name LIKE " +
124 ":accountName||'%' AND ta.amount <> 0 AND tr.profile_id = :profileId ORDER BY tr.year " +
125 "desc, tr.month desc, tr.day desc, tr.ledger_id desc")
126 public abstract List<TransactionWithAccounts> getAllWithAccountsFilteredSync(long profileId,
129 @androidx.room.Transaction
130 @Query("SELECT distinct(tr.id), tr.ledger_id, tr.profile_id, tr.data_hash, tr.year, tr.month," +
131 " tr.day, tr.description, tr.comment, tr.generation FROM transactions tr JOIN " +
132 "transaction_accounts ta ON ta.transaction_id=tr.id WHERE ta.account_name LIKE " +
133 ":accountName||'%' AND ta.amount <> 0 AND tr.profile_id = :profileId ORDER BY tr.year " +
134 "desc, tr.month desc, tr.day desc, tr.ledger_id desc")
135 public abstract LiveData<List<TransactionWithAccounts>> getAllWithAccountsFiltered(
136 long profileId, String accountName);
138 @Query("DELETE FROM transactions WHERE profile_id = :profileId AND generation <> " +
139 ":currentGeneration")
140 public abstract int purgeOldTransactionsSync(long profileId, long currentGeneration);
142 @Query("DELETE FROM transaction_accounts WHERE EXISTS (SELECT 1 FROM transactions tr WHERE tr" +
143 ".id=transaction_accounts.transaction_id AND tr.profile_id=:profileId) AND generation " +
144 "<> :currentGeneration")
145 public abstract int purgeOldTransactionAccountsSync(long profileId, long currentGeneration);
147 @Query("DELETE FROM transactions WHERE profile_id = :profileId")
148 public abstract int deleteAllSync(long profileId);
150 @Query("SELECT * FROM transactions where profile_id = :profileId AND ledger_id = :ledgerId")
151 public abstract Transaction getByLedgerId(long profileId, long ledgerId);
153 @Query("UPDATE transactions SET generation = :newGeneration WHERE id = :transactionId")
154 public abstract int updateGeneration(long transactionId, long newGeneration);
156 @Query("UPDATE transaction_accounts SET generation = :newGeneration WHERE transaction_id = " +
158 public abstract int updateAccountsGeneration(long transactionId, long newGeneration);
160 @Query("SELECT max(ledger_id) as ledger_id FROM transactions WHERE profile_id = :profileId")
161 public abstract LedgerIdContainer getMaxLedgerIdPOJOSync(long profileId);
162 @androidx.room.Transaction
163 public void updateGenerationWithAccounts(long transactionId, long newGeneration) {
164 updateGeneration(transactionId, newGeneration);
165 updateAccountsGeneration(transactionId, newGeneration);
167 public long getGenerationSync(long profileId) {
168 TransactionGenerationContainer result = getGenerationPOJOSync(profileId);
172 return result.generation;
174 public long getMaxLedgerIdSync(long profileId) {
175 LedgerIdContainer result = getMaxLedgerIdPOJOSync(profileId);
179 return result.ledgerId;
181 @androidx.room.Transaction
182 public void storeTransactionsSync(List<TransactionWithAccounts> list, long profileId) {
183 long generation = getGenerationSync(profileId) + 1;
185 for (TransactionWithAccounts tr : list) {
186 tr.transaction.setGeneration(generation);
187 tr.transaction.setProfileId(profileId);
192 Logger.debug("Transaction", "Purging old transactions");
193 int removed = purgeOldTransactionsSync(profileId, generation);
194 Logger.debug("Transaction", String.format(Locale.ROOT, "Purged %d transactions", removed));
196 removed = purgeOldTransactionAccountsSync(profileId, generation);
197 Logger.debug("Transaction",
198 String.format(Locale.ROOT, "Purged %d transaction accounts", removed));
200 @androidx.room.Transaction
201 void storeSync(TransactionWithAccounts rec) {
202 TransactionAccountDAO trAccDao = DB.get()
203 .getTransactionAccountDAO();
205 Transaction transaction = rec.transaction;
206 Transaction existing = getByLedgerId(transaction.getProfileId(), transaction.getLedgerId());
207 if (existing != null) {
208 if (Misc.equalStrings(transaction.getDataHash(), existing.getDataHash())) {
209 updateGenerationWithAccounts(existing.getId(), rec.transaction.getGeneration());
213 existing.copyDataFrom(transaction);
214 updateSync(existing);
216 transaction = existing;
219 transaction.setId(insertSync(transaction));
221 for (TransactionAccount trAcc : rec.accounts) {
222 trAcc.setTransactionId(transaction.getId());
223 trAcc.setGeneration(transaction.getGeneration());
224 TransactionAccount existingAcc =
225 trAccDao.getByOrderNoSync(trAcc.getTransactionId(), trAcc.getOrderNo());
226 if (existingAcc != null) {
227 existingAcc.copyDataFrom(trAcc);
228 trAccDao.updateSync(existingAcc);
231 trAcc.setId(trAccDao.insertSync(trAcc));
234 public void storeLast(TransactionWithAccounts rec) {
235 AsyncTask.execute(() -> appendSync(rec));
237 @androidx.room.Transaction
238 public void appendSync(TransactionWithAccounts rec) {
239 TransactionAccountDAO trAccDao = DB.get()
240 .getTransactionAccountDAO();
241 AccountDAO accDao = DB.get()
243 AccountValueDAO accValDao = DB.get()
244 .getAccountValueDAO();
246 Transaction transaction = rec.transaction;
247 final long profileId = transaction.getProfileId();
248 transaction.setGeneration(getGenerationSync(profileId));
249 transaction.setLedgerId(getMaxLedgerIdSync(profileId) + 1);
250 transaction.setId(insertSync(transaction));
252 for (TransactionAccount trAcc : rec.accounts) {
253 trAcc.setTransactionId(transaction.getId());
254 trAcc.setGeneration(transaction.getGeneration());
255 trAcc.setId(trAccDao.insertSync(trAcc));
257 Account acc = accDao.getByNameSync(profileId, trAcc.getAccountName());
260 acc.setProfileId(profileId);
261 acc.setName(trAcc.getAccountName());
262 acc.setNameUpper(acc.getName()
264 acc.setParentName(LedgerAccount.extractParentName(acc.getName()));
265 acc.setLevel(LedgerAccount.determineLevel(acc.getName()));
266 acc.setGeneration(trAcc.getGeneration());
268 acc.setId(accDao.insertSync(acc));
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));
281 accVal.setValue(accVal.getValue() + trAcc.getAmount());
282 accValDao.updateSync(accVal);
286 static class TransactionGenerationContainer {
289 public TransactionGenerationContainer(long generation) {
290 this.generation = generation;
294 static class LedgerIdContainer {
295 @ColumnInfo(name = "ledger_id")
297 public LedgerIdContainer(long ledgerId) {
298 this.ledgerId = ledgerId;
302 static public class DescriptionContainer {
304 public String description;