]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemsAdapter.java
more heuristics when filling accounts from a previous transaction
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionItemsAdapter.java
1 /*
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.
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.ui.activity;
19
20 import android.database.Cursor;
21 import android.view.LayoutInflater;
22 import android.view.ViewGroup;
23 import android.widget.LinearLayout;
24
25 import androidx.annotation.NonNull;
26 import androidx.recyclerview.widget.ItemTouchHelper;
27 import androidx.recyclerview.widget.RecyclerView;
28
29 import com.google.android.material.snackbar.Snackbar;
30
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;
39
40 import java.util.ArrayList;
41 import java.util.Locale;
42
43 import static net.ktnx.mobileledger.utils.Logger.debug;
44
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) {
52         super();
53         model = viewModel;
54         mProfile = profile;
55         int size = model.getAccountCount();
56         while (size < 2) {
57             Logger.debug("new-transaction",
58                     String.format(Locale.US, "%d accounts is too little, Calling addRow()", size));
59             size = addRow();
60         }
61
62         NewTransactionItemsAdapter adapter = this;
63
64         touchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
65             @Override
66             public boolean isLongPressDragEnabled() {
67                 return true;
68             }
69             @Override
70             public boolean canDropOver(@NonNull RecyclerView recyclerView,
71                                        @NonNull RecyclerView.ViewHolder current,
72                                        @NonNull RecyclerView.ViewHolder target) {
73                 final int adapterPosition = target.getAdapterPosition();
74
75                 // first and last items are immovable
76                 if (adapterPosition == 0)
77                     return false;
78                 if (adapterPosition == adapter.getItemCount() - 1)
79                     return false;
80
81                 return super.canDropOver(recyclerView, current, target);
82             }
83             @Override
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);
91
92                     if (viewModel.getAccountCount() > 2) {
93                         flags |= makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE,
94                                 ItemTouchHelper.START | ItemTouchHelper.END);
95                     }
96                 }
97
98                 return flags;
99             }
100             @Override
101             public boolean onMove(@NonNull RecyclerView recyclerView,
102                                   @NonNull RecyclerView.ViewHolder viewHolder,
103                                   @NonNull RecyclerView.ViewHolder target) {
104
105                 model.swapItems(viewHolder.getAdapterPosition(), target.getAdapterPosition());
106                 notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
107                 return true;
108             }
109             @Override
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)
115                             .show();
116                 else {
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);
122                 }
123             }
124         });
125     }
126     public void setProfile(MobileLedgerProfile profile) {
127         mProfile = profile;
128     }
129     int addRow() {
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;
137     }
138     @NonNull
139     @Override
140     public NewTransactionItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
141         LinearLayout row = (LinearLayout) LayoutInflater.from(parent.getContext())
142                                                         .inflate(R.layout.new_transaction_row,
143                                                                 parent, false);
144
145         return new NewTransactionItemHolder(row, this);
146     }
147     @Override
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()
153                                                                                           .toString(),
154                 position));
155     }
156     @Override
157     public int getItemCount() {
158         return model.getAccountCount() + 2;
159     }
160     boolean accountListIsEmpty() {
161         for (int i = 0; i < model.getAccountCount(); i++) {
162             LedgerTransactionAccount acc = model.getAccount(i);
163             if (!acc.getAccountName()
164                     .isEmpty())
165                 return false;
166             if (acc.isAmountSet())
167                 return false;
168         }
169
170         return true;
171     }
172     @Override
173     public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
174         super.onAttachedToRecyclerView(recyclerView);
175         this.recyclerView = recyclerView;
176         touchHelper.attachToRecyclerView(recyclerView);
177     }
178     @Override
179     public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
180         touchHelper.attachToRecyclerView(null);
181         super.onDetachedFromRecyclerView(recyclerView);
182         this.recyclerView = null;
183     }
184     public void descriptionSelected(String description) {
185         debug("descr selected", description);
186         if (!accountListIsEmpty())
187             return;
188
189         String accFilter = mProfile.getPreferredAccountsFilter();
190
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);
195
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());
203         }
204
205         sb.append(" ORDER BY date desc limit 1");
206
207         final String sql = sb.toString();
208         debug("descr", sql);
209         debug("descr", params.toString());
210
211         try (Cursor c = App.getDatabase()
212                            .rawQuery(sql, params.toArray(new String[]{})))
213         {
214             if (!c.moveToNext())
215                 return;
216
217             String profileUUID = c.getString(0);
218             int transactionId = c.getInt(1);
219             LedgerTransaction tr;
220             MobileLedgerProfile profile = Data.getProfile(profileUUID);
221             if (profile == null)
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,
225                         description));
226
227             tr = profile.loadTransaction(transactionId);
228             ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
229             NewTransactionModel.Item firstNegative = null;
230             NewTransactionModel.Item firstPositive = null;
231             int singleNegativeIndex = -1;
232             int singlePositiveIndex = -1;
233             int negativeCount = 0;
234             for (int i = 0; i < accounts.size(); i++) {
235                 LedgerTransactionAccount acc = accounts.get(i);
236                 NewTransactionModel.Item item;
237                 if (model.getAccountCount() < i + 1) {
238                     model.addAccount(acc);
239                     notifyItemInserted(i + 1);
240                 }
241                 item = model.getItem(i + 1);
242
243                 item.getAccount()
244                     .setAccountName(acc.getAccountName());
245                 if (acc.isAmountSet()) {
246                     item.getAccount()
247                         .setAmount(acc.getAmount());
248                     if (acc.getAmount() < 0) {
249                         if (firstNegative == null) {
250                             firstNegative = item;
251                             singleNegativeIndex = i;
252                         }
253                         else
254                             singleNegativeIndex = -1;
255                     }
256                     else {
257                         if (firstPositive == null) {
258                             firstPositive = item;
259                             singlePositiveIndex = i;
260                         }
261                         else
262                             singlePositiveIndex = -1;
263                     }
264                 }
265                 else
266                     item.getAccount()
267                         .resetAmount();
268                 notifyItemChanged(i + 1);
269             }
270
271             if (singleNegativeIndex != -1) {
272                 firstNegative.getAccount()
273                              .resetAmount();
274                 model.moveItemLast(singleNegativeIndex);
275             }
276             else if (singlePositiveIndex != -1) {
277                 firstPositive.getAccount()
278                              .resetAmount();
279                 model.moveItemLast(singlePositiveIndex);
280             }
281         }
282         model.checkTransactionSubmittable(this);
283         model.setFocusedItem(1);
284     }
285     public void toggleAllEditing(boolean editable) {
286         // item 0 is the header
287         for (int i = 0; i <= model.getAccountCount(); i++) {
288             model.getItem(i)
289                  .setEditable(editable);
290             notifyItemChanged(i);
291             // TODO perhaps do only one notification about the whole range (notifyDatasetChanged)?
292         }
293     }
294     public void reset() {
295         int presentItemCount = model.getAccountCount();
296         model.reset();
297         notifyItemChanged(0);       // header changed
298         notifyItemRangeChanged(1, 2);    // the two empty rows
299         if (presentItemCount > 2)
300             notifyItemRangeRemoved(3, presentItemCount - 2); // all the rest are gone
301     }
302     public void updateFocusedItem(int position) {
303         model.updateFocusedItem(position);
304     }
305     public void noteFocusIsOnAccount(int position) {
306         model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Account);
307     }
308     public void noteFocusIsOnAmount(int position) {
309         model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Amount);
310     }
311     public void noteFocusIsOnComment(int position) {
312         model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Comment);
313     }
314     public void toggleComment(int position) {
315         model.toggleComment(position);
316     }
317 }