]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemsAdapter.java
NT: new rules for determining whether transaction can be submitted (not quite finished)
[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 net.ktnx.mobileledger.App;
30 import net.ktnx.mobileledger.R;
31 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
32 import net.ktnx.mobileledger.model.Data;
33 import net.ktnx.mobileledger.model.LedgerTransaction;
34 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
35 import net.ktnx.mobileledger.model.MobileLedgerProfile;
36 import net.ktnx.mobileledger.utils.Logger;
37
38 import java.util.ArrayList;
39 import java.util.Locale;
40
41 import static net.ktnx.mobileledger.utils.Logger.debug;
42
43 class NewTransactionItemsAdapter extends RecyclerView.Adapter<NewTransactionItemHolder>
44         implements DescriptionSelectedCallback {
45     NewTransactionModel model;
46     private MobileLedgerProfile mProfile;
47     private ItemTouchHelper touchHelper;
48     private RecyclerView recyclerView;
49     NewTransactionItemsAdapter(NewTransactionModel viewModel, MobileLedgerProfile profile) {
50         super();
51         model = viewModel;
52         mProfile = profile;
53         int size = model.getAccountCount();
54         while (size < 2) {
55             Logger.debug("new-transaction",
56                     String.format(Locale.US, "%d accounts is too little, Calling addRow()", size));
57             size = addRow();
58         }
59
60         NewTransactionItemsAdapter adapter = this;
61
62         touchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
63             @Override
64             public boolean isLongPressDragEnabled() {
65                 return true;
66             }
67             @Override
68             public boolean canDropOver(@NonNull RecyclerView recyclerView,
69                                        @NonNull RecyclerView.ViewHolder current,
70                                        @NonNull RecyclerView.ViewHolder target) {
71                 final int adapterPosition = target.getAdapterPosition();
72
73                 // first and last items are immovable
74                 if (adapterPosition == 0)
75                     return false;
76                 if (adapterPosition == adapter.getItemCount() - 1)
77                     return false;
78
79                 return super.canDropOver(recyclerView, current, target);
80             }
81             @Override
82             public int getMovementFlags(@NonNull RecyclerView recyclerView,
83                                         @NonNull RecyclerView.ViewHolder viewHolder) {
84                 int flags = makeFlag(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.END);
85                 // the top (date and description) and the bottom (padding) items are always there
86                 final int adapterPosition = viewHolder.getAdapterPosition();
87                 if ((adapterPosition > 0) && (adapterPosition < adapter.getItemCount() - 1)) {
88                     flags |= makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
89                             ItemTouchHelper.UP | ItemTouchHelper.DOWN) |
90                              makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE,
91                                      ItemTouchHelper.START | ItemTouchHelper.END);
92                 }
93
94                 return flags;
95             }
96             @Override
97             public boolean onMove(@NonNull RecyclerView recyclerView,
98                                   @NonNull RecyclerView.ViewHolder viewHolder,
99                                   @NonNull RecyclerView.ViewHolder target) {
100
101                 model.swapItems(viewHolder.getAdapterPosition(), target.getAdapterPosition());
102                 notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
103                 return true;
104             }
105             @Override
106             public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
107                 int pos = viewHolder.getAdapterPosition();
108                 viewModel.removeItem(pos - 1);
109                 notifyItemRemoved(pos);
110                 viewModel.sendCountNotifications(); // needed after items re-arrangement
111                 viewModel.checkTransactionSubmittable(adapter);
112             }
113         });
114     }
115     public void setProfile(MobileLedgerProfile profile) {
116         mProfile = profile;
117     }
118     int addRow() {
119         return addRow(null);
120     }
121     int addRow(String commodity) {
122         final int newAccountCount = model.addAccount(new LedgerTransactionAccount("", commodity));
123         Logger.debug("new-transaction",
124                 String.format(Locale.US, "invoking notifyItemInserted(%d)", newAccountCount));
125         // the header is at position 0
126         notifyItemInserted(newAccountCount);
127         model.sendCountNotifications(); // needed after holders' positions have changed
128         return newAccountCount;
129     }
130     @NonNull
131     @Override
132     public NewTransactionItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
133         LinearLayout row = (LinearLayout) LayoutInflater.from(parent.getContext())
134                                                         .inflate(R.layout.new_transaction_row,
135                                                                 parent, false);
136
137         return new NewTransactionItemHolder(row, this);
138     }
139     @Override
140     public void onBindViewHolder(@NonNull NewTransactionItemHolder holder, int position) {
141         Logger.debug("bind", String.format(Locale.US, "Binding item at position %d", position));
142         NewTransactionModel.Item item = model.getItem(position);
143         holder.setData(item);
144         Logger.debug("bind", String.format(Locale.US, "Bound %s item at position %d", item.getType()
145                                                                                           .toString(),
146                 position));
147     }
148     @Override
149     public int getItemCount() {
150         return model.getAccountCount() + 2;
151     }
152     boolean accountListIsEmpty() {
153         for (int i = 0; i < model.getAccountCount(); i++) {
154             LedgerTransactionAccount acc = model.getAccount(i);
155             if (!acc.getAccountName()
156                     .isEmpty())
157                 return false;
158             if (acc.isAmountSet())
159                 return false;
160         }
161
162         return true;
163     }
164     @Override
165     public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
166         super.onAttachedToRecyclerView(recyclerView);
167         this.recyclerView = recyclerView;
168         touchHelper.attachToRecyclerView(recyclerView);
169     }
170     @Override
171     public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
172         touchHelper.attachToRecyclerView(null);
173         super.onDetachedFromRecyclerView(recyclerView);
174         this.recyclerView = null;
175     }
176     public void descriptionSelected(String description) {
177         debug("descr selected", description);
178         if (!accountListIsEmpty())
179             return;
180
181         String accFilter = mProfile.getPreferredAccountsFilter();
182
183         ArrayList<String> params = new ArrayList<>();
184         StringBuilder sb = new StringBuilder(
185                 "select t.profile, t.id from transactions t where t.description=?");
186         params.add(description);
187
188         if (accFilter != null) {
189             sb.append(" AND EXISTS (")
190               .append("SELECT 1 FROM transaction_accounts ta ")
191               .append("WHERE ta.profile = t.profile")
192               .append(" AND ta.transaction_id = t.id")
193               .append(" AND UPPER(ta.account_name) LIKE '%'||?||'%')");
194             params.add(accFilter.toUpperCase());
195         }
196
197         sb.append(" ORDER BY date desc limit 1");
198
199         final String sql = sb.toString();
200         debug("descr", sql);
201         debug("descr", params.toString());
202
203         try (Cursor c = App.getDatabase()
204                            .rawQuery(sql, params.toArray(new String[]{})))
205         {
206             if (!c.moveToNext())
207                 return;
208
209             String profileUUID = c.getString(0);
210             int transactionId = c.getInt(1);
211             LedgerTransaction tr;
212             MobileLedgerProfile profile = Data.getProfile(profileUUID);
213             if (profile == null)
214                 throw new RuntimeException(String.format(
215                         "Unable to find profile %s, which is supposed to contain " +
216                         "transaction %d with description %s", profileUUID, transactionId,
217                         description));
218
219             tr = profile.loadTransaction(transactionId);
220             ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
221             NewTransactionModel.Item firstNegative = null;
222             NewTransactionModel.Item firstPositive = null;
223             int singleNegativeIndex = -1;
224             int singlePositiveIndex = -1;
225             int negativeCount = 0;
226             for (int i = 0; i < accounts.size(); i++) {
227                 LedgerTransactionAccount acc = accounts.get(i);
228                 NewTransactionModel.Item item;
229                 if (model.getAccountCount() < i + 1) {
230                     model.addAccount(acc);
231                     notifyItemInserted(i + 1);
232                 }
233                 item = model.getItem(i + 1);
234
235                 item.getAccount()
236                     .setAccountName(acc.getAccountName());
237                 if (acc.isAmountSet()) {
238                     item.getAccount()
239                         .setAmount(acc.getAmount());
240                     if (acc.getAmount() < 0) {
241                         if (firstNegative == null) {
242                             firstNegative = item;
243                             singleNegativeIndex = i;
244                         }
245                         else
246                             singleNegativeIndex = -1;
247                     }
248                     else {
249                         if (firstPositive == null) {
250                             firstPositive = item;
251                             singlePositiveIndex = i;
252                         }
253                         else
254                             singlePositiveIndex = -1;
255                     }
256                 }
257                 else
258                     item.getAccount()
259                         .resetAmount();
260                 notifyItemChanged(i + 1);
261             }
262
263             if (singleNegativeIndex != -1) {
264                 firstNegative.getAccount()
265                              .resetAmount();
266                 model.moveItemLast(singleNegativeIndex);
267             }
268             else if (singlePositiveIndex != -1) {
269                 firstPositive.getAccount()
270                              .resetAmount();
271                 model.moveItemLast(singlePositiveIndex);
272             }
273         }
274         model.checkTransactionSubmittable(this);
275         model.setFocusedItem(1);
276     }
277     public void toggleAllEditing(boolean editable) {
278         // item 0 is the header
279         for (int i = 0; i <= model.getAccountCount(); i++) {
280             model.getItem(i)
281                  .setEditable(editable);
282             notifyItemChanged(i);
283             // TODO perhaps do only one notification about the whole range (notifyDatasetChanged)?
284         }
285     }
286     public void reset() {
287         int presentItemCount = model.getAccountCount();
288         model.reset();
289         notifyItemChanged(0);       // header changed
290         notifyItemRangeChanged(1, 2);    // the two empty rows
291         if (presentItemCount > 2)
292             notifyItemRangeRemoved(3, presentItemCount - 2); // all the rest are gone
293     }
294     public void updateFocusedItem(int position) {
295         model.updateFocusedItem(position);
296     }
297     public void noteFocusIsOnAccount(int position) {
298         model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Account);
299     }
300     public void noteFocusIsOnAmount(int position) {
301         model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Amount);
302     }
303     public void noteFocusIsOnComment(int position) {
304         model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Comment);
305     }
306     public void toggleComment(int position) {
307         model.toggleComment(position);
308     }
309 }