2 * Copyright © 2019 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.ui.activity;
20 import android.database.Cursor;
21 import android.view.LayoutInflater;
22 import android.view.ViewGroup;
23 import android.widget.LinearLayout;
25 import androidx.annotation.NonNull;
26 import androidx.recyclerview.widget.ItemTouchHelper;
27 import androidx.recyclerview.widget.RecyclerView;
29 import com.google.android.material.snackbar.Snackbar;
31 import net.ktnx.mobileledger.App;
32 import net.ktnx.mobileledger.R;
33 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
34 import net.ktnx.mobileledger.model.Data;
35 import net.ktnx.mobileledger.model.LedgerTransaction;
36 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
37 import net.ktnx.mobileledger.model.MobileLedgerProfile;
38 import net.ktnx.mobileledger.utils.Logger;
40 import java.util.ArrayList;
41 import java.util.Locale;
43 import static net.ktnx.mobileledger.utils.Logger.debug;
45 class NewTransactionItemsAdapter extends RecyclerView.Adapter<NewTransactionItemHolder>
46 implements DescriptionSelectedCallback {
47 NewTransactionModel model;
48 private MobileLedgerProfile mProfile;
49 private ItemTouchHelper touchHelper;
50 private RecyclerView recyclerView;
51 NewTransactionItemsAdapter(NewTransactionModel viewModel, MobileLedgerProfile profile) {
55 int size = model.getAccountCount();
57 Logger.debug("new-transaction",
58 String.format(Locale.US, "%d accounts is too little, Calling addRow()", size));
62 NewTransactionItemsAdapter adapter = this;
64 touchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
66 public boolean isLongPressDragEnabled() {
70 public boolean canDropOver(@NonNull RecyclerView recyclerView,
71 @NonNull RecyclerView.ViewHolder current,
72 @NonNull RecyclerView.ViewHolder target) {
73 final int adapterPosition = target.getAdapterPosition();
75 // first and last items are immovable
76 if (adapterPosition == 0)
78 if (adapterPosition == adapter.getItemCount() - 1)
81 return super.canDropOver(recyclerView, current, target);
84 public int getMovementFlags(@NonNull RecyclerView recyclerView,
85 @NonNull RecyclerView.ViewHolder viewHolder) {
86 int flags = makeFlag(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.END);
87 // the top item is always there (date and description)
88 if (viewHolder.getAdapterPosition() > 0) {
89 flags |= makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
90 ItemTouchHelper.UP | ItemTouchHelper.DOWN);
92 if (viewModel.getAccountCount() > 2) {
93 flags |= makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE,
94 ItemTouchHelper.START | ItemTouchHelper.END);
101 public boolean onMove(@NonNull RecyclerView recyclerView,
102 @NonNull RecyclerView.ViewHolder viewHolder,
103 @NonNull RecyclerView.ViewHolder target) {
105 model.swapItems(viewHolder.getAdapterPosition(), target.getAdapterPosition());
106 notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
110 public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
111 if (viewModel.getAccountCount() == 2)
112 Snackbar.make(recyclerView, R.string.msg_at_least_two_accounts_are_required,
113 Snackbar.LENGTH_LONG)
114 .setAction("Action", null)
117 int pos = viewHolder.getAdapterPosition();
118 viewModel.removeItem(pos - 1);
119 notifyItemRemoved(pos);
120 viewModel.sendCountNotifications(); // needed after items re-arrangement
121 viewModel.checkTransactionSubmittable(adapter);
126 public void setProfile(MobileLedgerProfile profile) {
130 final int newAccountCount = model.addAccount(new LedgerTransactionAccount(""));
131 Logger.debug("new-transaction",
132 String.format(Locale.US, "invoking notifyItemInserted(%d)", newAccountCount));
133 // the header is at position 0
134 notifyItemInserted(newAccountCount);
135 model.sendCountNotifications(); // needed after holders' positions have changed
136 return newAccountCount;
140 public NewTransactionItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
141 LinearLayout row = (LinearLayout) LayoutInflater.from(parent.getContext())
142 .inflate(R.layout.new_transaction_row,
145 return new NewTransactionItemHolder(row, this);
148 public void onBindViewHolder(@NonNull NewTransactionItemHolder holder, int position) {
149 Logger.debug("bind", String.format(Locale.US, "Binding item at position %d", position));
150 NewTransactionModel.Item item = model.getItem(position);
151 holder.setData(item);
152 Logger.debug("bind", String.format(Locale.US, "Bound %s item at position %d", item.getType()
157 public int getItemCount() {
158 return model.getAccountCount() + 2;
160 boolean accountListIsEmpty() {
161 for (int i = 0; i < model.getAccountCount(); i++) {
162 LedgerTransactionAccount acc = model.getAccount(i);
163 if (!acc.getAccountName()
166 if (acc.isAmountSet())
173 public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
174 super.onAttachedToRecyclerView(recyclerView);
175 this.recyclerView = recyclerView;
176 touchHelper.attachToRecyclerView(recyclerView);
179 public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
180 touchHelper.attachToRecyclerView(null);
181 super.onDetachedFromRecyclerView(recyclerView);
182 this.recyclerView = null;
184 public void descriptionSelected(String description) {
185 debug("descr selected", description);
186 if (!accountListIsEmpty())
189 String accFilter = mProfile.getPreferredAccountsFilter();
191 ArrayList<String> params = new ArrayList<>();
192 StringBuilder sb = new StringBuilder(
193 "select t.profile, t.id from transactions t where t.description=?");
194 params.add(description);
196 if (accFilter != null) {
197 sb.append(" AND EXISTS (")
198 .append("SELECT 1 FROM transaction_accounts ta ")
199 .append("WHERE ta.profile = t.profile")
200 .append(" AND ta.transaction_id = t.id")
201 .append(" AND UPPER(ta.account_name) LIKE '%'||?||'%')");
202 params.add(accFilter.toUpperCase());
205 sb.append(" ORDER BY date desc limit 1");
207 final String sql = sb.toString();
209 debug("descr", params.toString());
211 try (Cursor c = App.getDatabase()
212 .rawQuery(sql, params.toArray(new String[]{})))
217 String profileUUID = c.getString(0);
218 int transactionId = c.getInt(1);
219 LedgerTransaction tr;
220 MobileLedgerProfile profile = Data.getProfile(profileUUID);
222 throw new RuntimeException(String.format(
223 "Unable to find profile %s, which is supposed to contain " +
224 "transaction %d with description %s", profileUUID, transactionId,
227 tr = profile.loadTransaction(transactionId);
228 ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
229 NewTransactionModel.Item firstNegative = null;
230 boolean singleNegative = false;
231 int negativeCount = 0;
232 for (int i = 0; i < accounts.size(); i++) {
233 LedgerTransactionAccount acc = accounts.get(i);
234 NewTransactionModel.Item item;
235 if (model.getAccountCount() < i + 1) {
236 model.addAccount(acc);
237 notifyItemInserted(i + 1);
239 item = model.getItem(i + 1);
242 .setAccountName(acc.getAccountName());
243 if (acc.isAmountSet()) {
245 .setAmount(acc.getAmount());
246 if (acc.getAmount() < 0) {
247 if (firstNegative == null) {
248 firstNegative = item;
249 singleNegative = true;
252 singleNegative = false;
258 notifyItemChanged(i + 1);
261 if (singleNegative) {
262 firstNegative.getAccount()
266 model.checkTransactionSubmittable(this);
267 model.setFocusedItem(1);
269 public void toggleAllEditing(boolean editable) {
270 // item 0 is the header
271 for (int i = 0; i <= model.getAccountCount(); i++) {
273 .setEditable(editable);
274 notifyItemChanged(i);
275 // TODO perhaps do only one notification about the whole range (notifyDatasetChanged)?
278 public void reset() {
279 int presentItemCount = model.getAccountCount();
281 notifyItemChanged(0); // header changed
282 notifyItemRangeChanged(1, 2); // the two empty rows
283 if (presentItemCount > 2)
284 notifyItemRangeRemoved(3, presentItemCount - 2); // all the rest are gone
286 public void updateFocusedItem(int position) {
287 model.updateFocusedItem(position);
289 public void noteFocusIsOnAccount(int position) {
290 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Account);
292 public void noteFocusIsOnAmount(int position) {
293 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Amount);
295 public void noteFocusIsOnComment(int position) {
296 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Comment);