]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionItemsAdapter.java
add UI and API support for sending posting (transaction account) comments
[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             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);
238                 }
239                 item = model.getItem(i + 1);
240
241                 item.getAccount()
242                     .setAccountName(acc.getAccountName());
243                 if (acc.isAmountSet()) {
244                     item.getAccount()
245                         .setAmount(acc.getAmount());
246                     if (acc.getAmount() < 0) {
247                         if (firstNegative == null) {
248                             firstNegative = item;
249                             singleNegative = true;
250                         }
251                         else
252                             singleNegative = false;
253                     }
254                 }
255                 else
256                     item.getAccount()
257                         .resetAmount();
258                 notifyItemChanged(i + 1);
259             }
260
261             if (singleNegative) {
262                 firstNegative.getAccount()
263                              .resetAmount();
264             }
265         }
266         model.checkTransactionSubmittable(this);
267         model.setFocusedItem(1);
268     }
269     public void toggleAllEditing(boolean editable) {
270         // item 0 is the header
271         for (int i = 0; i <= model.getAccountCount(); i++) {
272             model.getItem(i)
273                  .setEditable(editable);
274             notifyItemChanged(i);
275             // TODO perhaps do only one notification about the whole range (notifyDatasetChanged)?
276         }
277     }
278     public void reset() {
279         int presentItemCount = model.getAccountCount();
280         model.reset();
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
285     }
286     public void updateFocusedItem(int position) {
287         model.updateFocusedItem(position);
288     }
289     public void noteFocusIsOnAccount(int position) {
290         model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Account);
291     }
292     public void noteFocusIsOnAmount(int position) {
293         model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Amount);
294     }
295     public void noteFocusIsOnComment(int position) {
296         model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Comment);
297     }
298 }