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.ui.new_transaction;
20 import android.annotation.SuppressLint;
21 import android.app.Activity;
22 import android.database.Cursor;
23 import android.text.TextUtils;
24 import android.view.LayoutInflater;
25 import android.view.ViewGroup;
27 import androidx.annotation.NonNull;
28 import androidx.annotation.Nullable;
29 import androidx.recyclerview.widget.ItemTouchHelper;
30 import androidx.recyclerview.widget.RecyclerView;
32 import com.google.android.material.snackbar.Snackbar;
34 import net.ktnx.mobileledger.BuildConfig;
35 import net.ktnx.mobileledger.R;
36 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
37 import net.ktnx.mobileledger.databinding.NewTransactionRowBinding;
38 import net.ktnx.mobileledger.model.Currency;
39 import net.ktnx.mobileledger.model.Data;
40 import net.ktnx.mobileledger.model.LedgerTransaction;
41 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
42 import net.ktnx.mobileledger.model.MobileLedgerProfile;
43 import net.ktnx.mobileledger.utils.Logger;
44 import net.ktnx.mobileledger.utils.MLDB;
45 import net.ktnx.mobileledger.utils.Misc;
47 import java.util.ArrayList;
48 import java.util.HashMap;
49 import java.util.List;
50 import java.util.Locale;
53 import static net.ktnx.mobileledger.utils.Logger.debug;
55 class NewTransactionItemsAdapter extends RecyclerView.Adapter<NewTransactionItemHolder>
56 implements DescriptionSelectedCallback {
57 private final NewTransactionModel model;
58 private final ItemTouchHelper touchHelper;
59 private MobileLedgerProfile mProfile;
60 private RecyclerView recyclerView;
61 private int checkHoldCounter = 0;
62 NewTransactionItemsAdapter(NewTransactionModel viewModel, MobileLedgerProfile profile) {
66 int size = model.getAccountCount();
68 Logger.debug("new-transaction",
69 String.format(Locale.US, "%d accounts is too little, Calling addRow()", size));
73 NewTransactionItemsAdapter adapter = this;
75 touchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
77 public boolean isLongPressDragEnabled() {
81 public boolean canDropOver(@NonNull RecyclerView recyclerView,
82 @NonNull RecyclerView.ViewHolder current,
83 @NonNull RecyclerView.ViewHolder target) {
84 final int adapterPosition = target.getAdapterPosition();
86 // first and last items are immovable
87 if (adapterPosition == 0)
89 if (adapterPosition == adapter.getItemCount() - 1)
92 return super.canDropOver(recyclerView, current, target);
95 public int getMovementFlags(@NonNull RecyclerView recyclerView,
96 @NonNull RecyclerView.ViewHolder viewHolder) {
97 int flags = makeFlag(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.END);
98 // the top (date and description) and the bottom (padding) items are always there
99 final int adapterPosition = viewHolder.getAdapterPosition();
100 if ((adapterPosition > 0) && (adapterPosition < adapter.getItemCount() - 1)) {
101 flags |= makeFlag(ItemTouchHelper.ACTION_STATE_DRAG,
102 ItemTouchHelper.UP | ItemTouchHelper.DOWN) |
103 makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE,
104 ItemTouchHelper.START | ItemTouchHelper.END);
110 public boolean onMove(@NonNull RecyclerView recyclerView,
111 @NonNull RecyclerView.ViewHolder viewHolder,
112 @NonNull RecyclerView.ViewHolder target) {
114 model.swapItems(viewHolder.getAdapterPosition(), target.getAdapterPosition());
115 notifyItemMoved(viewHolder.getAdapterPosition(), target.getAdapterPosition());
119 public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
120 int pos = viewHolder.getAdapterPosition();
121 viewModel.removeItem(pos - 1);
122 notifyItemRemoved(pos);
123 viewModel.sendCountNotifications(); // needed after items re-arrangement
124 checkTransactionSubmittable();
128 public void setProfile(MobileLedgerProfile profile) {
131 private int addRow() {
134 private int addRow(String commodity) {
135 final int newAccountCount = model.addAccount(new LedgerTransactionAccount("", commodity));
136 Logger.debug("new-transaction",
137 String.format(Locale.US, "invoking notifyItemInserted(%d)", newAccountCount));
138 // the header is at position 0
139 notifyItemInserted(newAccountCount);
140 model.sendCountNotifications(); // needed after holders' positions have changed
141 return newAccountCount;
145 public NewTransactionItemHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
146 NewTransactionRowBinding b =
147 NewTransactionRowBinding.inflate(LayoutInflater.from(parent.getContext()), parent,
150 return new NewTransactionItemHolder(b, this);
153 public void onBindViewHolder(@NonNull NewTransactionItemHolder holder, int position) {
154 Logger.debug("bind", String.format(Locale.US, "Binding item at position %d", position));
155 NewTransactionModel.Item item = model.getItem(position);
156 holder.setData(item);
157 Logger.debug("bind", String.format(Locale.US, "Bound %s item at position %d", item.getType()
162 public int getItemCount() {
163 return model.getAccountCount() + 2;
165 private boolean accountListIsEmpty() {
166 for (int i = 0; i < model.getAccountCount(); i++) {
167 LedgerTransactionAccount acc = model.getAccount(i);
168 if (!acc.getAccountName()
171 if (acc.isAmountSet())
178 public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
179 super.onAttachedToRecyclerView(recyclerView);
180 this.recyclerView = recyclerView;
181 touchHelper.attachToRecyclerView(recyclerView);
184 public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {
185 touchHelper.attachToRecyclerView(null);
186 super.onDetachedFromRecyclerView(recyclerView);
187 this.recyclerView = null;
189 public void descriptionSelected(String description) {
190 debug("description selected", description);
191 if (!accountListIsEmpty())
194 String accFilter = mProfile.getPreferredAccountsFilter();
196 ArrayList<String> params = new ArrayList<>();
197 StringBuilder sb = new StringBuilder("select t.profile, t.id from transactions t");
199 if (!TextUtils.isEmpty(accFilter)) {
200 sb.append(" JOIN transaction_accounts ta")
201 .append(" ON ta.profile = t.profile")
202 .append(" AND ta.transaction_id = t.id");
205 sb.append(" WHERE t.description=?");
206 params.add(description);
208 if (!TextUtils.isEmpty(accFilter)) {
209 sb.append(" AND ta.account_name LIKE '%'||?||'%'");
210 params.add(accFilter);
213 sb.append(" ORDER BY t.year desc, t.month desc, t.day desc LIMIT 1");
215 final String sql = sb.toString();
216 debug("description", sql);
217 debug("description", params.toString());
219 Activity activity = (Activity) recyclerView.getContext();
220 // FIXME: handle exceptions?
221 MLDB.queryInBackground(sql, params.toArray(new String[]{}), new MLDB.CallbackHelper() {
223 public void onStart() {
224 model.incrementBusyCounter();
227 public void onDone() {
228 model.decrementBusyCounter();
231 public boolean onRow(@NonNull Cursor cursor) {
232 final String profileUUID = cursor.getString(0);
233 final int transactionId = cursor.getInt(1);
234 activity.runOnUiThread(() -> loadTransactionIntoModel(profileUUID, transactionId));
235 return false; // limit 1, by the way
238 public void onNoRows() {
239 if (TextUtils.isEmpty(accFilter))
242 debug("description", "Trying transaction search without preferred account filter");
244 final String broaderSql =
245 "select t.profile, t.id from transactions t where t.description=?" +
246 " ORDER BY year desc, month desc, day desc LIMIT 1";
248 debug("description", broaderSql);
249 debug("description", description);
251 activity.runOnUiThread(
252 () -> Snackbar.make(recyclerView, R.string.ignoring_preferred_account,
253 Snackbar.LENGTH_INDEFINITE)
256 MLDB.queryInBackground(broaderSql, new String[]{description},
257 new MLDB.CallbackHelper() {
259 public void onStart() {
260 model.incrementBusyCounter();
263 public boolean onRow(@NonNull Cursor cursor) {
264 final String profileUUID = cursor.getString(0);
265 final int transactionId = cursor.getInt(1);
266 activity.runOnUiThread(
267 () -> loadTransactionIntoModel(profileUUID, transactionId));
271 public void onDone() {
272 model.decrementBusyCounter();
278 private void loadTransactionIntoModel(String profileUUID, int transactionId) {
279 LedgerTransaction tr;
280 MobileLedgerProfile profile = Data.getProfile(profileUUID);
282 throw new RuntimeException(String.format(
283 "Unable to find profile %s, which is supposed to contain transaction %d",
284 profileUUID, transactionId));
286 tr = profile.loadTransaction(transactionId);
287 List<LedgerTransactionAccount> accounts = tr.getAccounts();
288 NewTransactionModel.Item firstNegative = null;
289 NewTransactionModel.Item firstPositive = null;
290 int singleNegativeIndex = -1;
291 int singlePositiveIndex = -1;
292 int negativeCount = 0;
293 for (int i = 0; i < accounts.size(); i++) {
294 LedgerTransactionAccount acc = accounts.get(i);
295 NewTransactionModel.Item item;
296 if (model.getAccountCount() < i + 1) {
297 model.addAccount(acc);
298 notifyItemInserted(i + 1);
300 item = model.getItem(i + 1);
303 .setAccountName(acc.getAccountName());
304 item.setComment(acc.getComment());
305 if (acc.isAmountSet()) {
307 .setAmount(acc.getAmount());
308 if (acc.getAmount() < 0) {
309 if (firstNegative == null) {
310 firstNegative = item;
311 singleNegativeIndex = i;
314 singleNegativeIndex = -1;
317 if (firstPositive == null) {
318 firstPositive = item;
319 singlePositiveIndex = i;
322 singlePositiveIndex = -1;
328 notifyItemChanged(i + 1);
331 if (singleNegativeIndex != -1) {
332 firstNegative.getAccount()
334 model.moveItemLast(singleNegativeIndex);
336 else if (singlePositiveIndex != -1) {
337 firstPositive.getAccount()
339 model.moveItemLast(singlePositiveIndex);
342 checkTransactionSubmittable();
343 model.setFocusedItem(1);
345 public void toggleAllEditing(boolean editable) {
346 // item 0 is the header
347 for (int i = 0; i <= model.getAccountCount(); i++) {
349 .setEditable(editable);
350 notifyItemChanged(i);
351 // TODO perhaps do only one notification about the whole range (notifyDatasetChanged)?
355 int presentItemCount = model.getAccountCount();
357 notifyItemChanged(0); // header changed
358 notifyItemRangeChanged(1, 2); // the two empty rows
359 if (presentItemCount > 2)
360 notifyItemRangeRemoved(3, presentItemCount - 2); // all the rest are gone
362 void updateFocusedItem(int position) {
363 model.updateFocusedItem(position);
365 void noteFocusIsOnAccount(int position) {
366 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Account);
368 void noteFocusIsOnAmount(int position) {
369 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Amount);
371 void noteFocusIsOnComment(int position) {
372 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.Comment);
374 void noteFocusIsOnTransactionComment(int position) {
375 model.noteFocusChanged(position, NewTransactionModel.FocusedElement.TransactionComment);
377 public void noteFocusIsOnDescription(int pos) {
378 model.noteFocusChanged(pos, NewTransactionModel.FocusedElement.Description);
380 private void holdSubmittableChecks() {
383 private void releaseSubmittableChecks() {
384 if (checkHoldCounter == 0)
385 throw new RuntimeException("Asymmetrical call to releaseSubmittableChecks");
388 void setItemCurrency(NewTransactionModel.Item item, Currency newCurrency) {
389 Currency oldCurrency = item.getCurrency();
390 if (!Currency.equal(newCurrency, oldCurrency)) {
391 holdSubmittableChecks();
393 item.setCurrency(newCurrency);
394 // for (Item i : items) {
395 // if (Currency.equal(i.getCurrency(), oldCurrency))
396 // i.setCurrency(newCurrency);
400 releaseSubmittableChecks();
403 checkTransactionSubmittable();
407 A transaction is submittable if:
409 1) has at least two account names
410 2) each row with amount has account name
411 3) for each commodity:
412 3a) amounts must balance to 0, or
413 3b) there must be exactly one empty amount (with account)
414 4) empty accounts with empty amounts are ignored
416 5) a row with an empty account name or empty amount is guaranteed to exist for each
418 6) at least two rows need to be present in the ledger
421 @SuppressLint("DefaultLocale")
422 void checkTransactionSubmittable() {
423 if (checkHoldCounter > 0)
427 final BalanceForCurrency balance = new BalanceForCurrency();
428 final String descriptionText = model.getDescription();
429 boolean submittable = true;
430 final ItemsForCurrency itemsForCurrency = new ItemsForCurrency();
431 final ItemsForCurrency itemsWithEmptyAmountForCurrency = new ItemsForCurrency();
432 final ItemsForCurrency itemsWithAccountAndEmptyAmountForCurrency = new ItemsForCurrency();
433 final ItemsForCurrency itemsWithEmptyAccountForCurrency = new ItemsForCurrency();
434 final ItemsForCurrency itemsWithAmountForCurrency = new ItemsForCurrency();
435 final ItemsForCurrency itemsWithAccountForCurrency = new ItemsForCurrency();
436 final ItemsForCurrency emptyRowsForCurrency = new ItemsForCurrency();
437 final List<NewTransactionModel.Item> emptyRows = new ArrayList<>();
440 if ((descriptionText == null) || descriptionText.trim()
443 Logger.debug("submittable", "Transaction not submittable: missing description");
447 for (int i = 0; i < model.items.size(); i++) {
448 NewTransactionModel.Item item = model.items.get(i);
450 LedgerTransactionAccount acc = item.getAccount();
451 String acc_name = acc.getAccountName()
453 String currName = acc.getCurrency();
455 itemsForCurrency.add(currName, item);
457 if (acc_name.isEmpty()) {
458 itemsWithEmptyAccountForCurrency.add(currName, item);
460 if (acc.isAmountSet()) {
461 // 2) each amount has account name
462 Logger.debug("submittable", String.format(
463 "Transaction not submittable: row %d has no account name, but" +
464 " has" + " amount %1.2f", i + 1, acc.getAmount()));
468 emptyRowsForCurrency.add(currName, item);
473 itemsWithAccountForCurrency.add(currName, item);
476 if (!acc.isAmountValid()) {
477 Logger.debug("submittable",
478 String.format("Not submittable: row %d has an invalid amount", i + 1));
481 else if (acc.isAmountSet()) {
482 itemsWithAmountForCurrency.add(currName, item);
483 balance.add(currName, acc.getAmount());
486 itemsWithEmptyAmountForCurrency.add(currName, item);
488 if (!acc_name.isEmpty())
489 itemsWithAccountAndEmptyAmountForCurrency.add(currName, item);
493 // 1) has at least two account names
496 Logger.debug("submittable",
497 "Transaction not submittable: no account " + "names");
498 else if (accounts == 1)
499 Logger.debug("submittable",
500 "Transaction not submittable: only one account name");
502 Logger.debug("submittable",
503 String.format("Transaction not submittable: only %d account names",
508 // 3) for each commodity:
509 // 3a) amount must balance to 0, or
510 // 3b) there must be exactly one empty amount (with account)
511 for (String balCurrency : itemsForCurrency.currencies()) {
512 float currencyBalance = balance.get(balCurrency);
513 if (Misc.isZero(currencyBalance)) {
514 // remove hints from all amount inputs in that currency
515 for (NewTransactionModel.Item item : model.items) {
516 if (Currency.equal(item.getCurrency(), balCurrency))
517 item.setAmountHint(null);
521 List<NewTransactionModel.Item> list =
522 itemsWithAccountAndEmptyAmountForCurrency.getList(balCurrency);
523 int balanceReceiversCount = list.size();
524 if (balanceReceiversCount != 1) {
525 if (BuildConfig.DEBUG) {
526 if (balanceReceiversCount == 0)
527 Logger.debug("submittable", String.format(
528 "Transaction not submittable [%s]: non-zero balance " +
529 "with no empty amounts with accounts", balCurrency));
531 Logger.debug("submittable", String.format(
532 "Transaction not submittable [%s]: non-zero balance " +
533 "with multiple empty amounts with accounts", balCurrency));
538 List<NewTransactionModel.Item> emptyAmountList =
539 itemsWithEmptyAmountForCurrency.getList(balCurrency);
541 // suggest off-balance amount to a row and remove hints on other rows
542 NewTransactionModel.Item receiver = null;
544 receiver = list.get(0);
545 else if (!emptyAmountList.isEmpty())
546 receiver = emptyAmountList.get(0);
548 for (NewTransactionModel.Item item : model.items) {
549 if (!Currency.equal(item.getCurrency(), balCurrency))
552 if (item.equals(receiver)) {
553 if (BuildConfig.DEBUG)
554 Logger.debug("submittable",
555 String.format("Setting amount hint to %1.2f [%s]",
556 -currencyBalance, balCurrency));
557 item.setAmountHint(String.format("%1.2f", -currencyBalance));
560 if (BuildConfig.DEBUG)
561 Logger.debug("submittable",
562 String.format("Resetting hint of '%s' [%s]",
563 (item.getAccount() == null) ? "" : item.getAccount()
566 item.setAmountHint(null);
572 // 5) a row with an empty account name or empty amount is guaranteed to exist for
574 for (String balCurrency : balance.currencies()) {
575 int currEmptyRows = itemsWithEmptyAccountForCurrency.size(balCurrency);
576 int currRows = itemsForCurrency.size(balCurrency);
577 int currAccounts = itemsWithAccountForCurrency.size(balCurrency);
578 int currAmounts = itemsWithAmountForCurrency.size(balCurrency);
579 if ((currEmptyRows == 0) &&
580 ((currRows == currAccounts) || (currRows == currAmounts)))
582 // perhaps there already is an unused empty row for another currency that
584 // boolean foundIt = false;
585 // for (Item item : emptyRows) {
586 // Currency itemCurrency = item.getCurrency();
587 // String itemCurrencyName =
588 // (itemCurrency == null) ? "" : itemCurrency.getName();
589 // if (Misc.isZero(balance.get(itemCurrencyName))) {
590 // item.setCurrency(Currency.loadByName(balCurrency));
591 // item.setAmountHint(
592 // String.format("%1.2f", -balance.get(balCurrency)));
603 // drop extra empty rows, not needed
604 for (String currName : emptyRowsForCurrency.currencies()) {
605 List<NewTransactionModel.Item> emptyItems = emptyRowsForCurrency.getList(currName);
606 while ((model.items.size() > 2) && (emptyItems.size() > 1)) {
607 NewTransactionModel.Item item = emptyItems.get(1);
608 emptyItems.remove(1);
609 model.removeRow(item, this);
612 // unused currency, remove last item (which is also an empty one)
613 if ((model.items.size() > 2) && (emptyItems.size() == 1)) {
614 List<NewTransactionModel.Item> currItems = itemsForCurrency.getList(currName);
616 if (currItems.size() == 1) {
617 NewTransactionModel.Item item = emptyItems.get(0);
618 model.removeRow(item, this);
623 // 6) at least two rows need to be present in the ledger
624 while (model.items.size() < 2)
628 debug("submittable", submittable ? "YES" : "NO");
629 model.isSubmittable.setValue(submittable);
631 if (BuildConfig.DEBUG) {
632 debug("submittable", "== Dump of all items");
633 for (int i = 0; i < model.items.size(); i++) {
634 NewTransactionModel.Item item = model.items.get(i);
635 LedgerTransactionAccount acc = item.getAccount();
636 debug("submittable", String.format("Item %2d: [%4.2f(%s) %s] %s ; %s", i,
637 acc.isAmountSet() ? acc.getAmount() : 0,
638 item.isAmountHintSet() ? item.getAmountHint() : "ø", acc.getCurrency(),
639 acc.getAccountName(), acc.getComment()));
643 catch (NumberFormatException e) {
644 debug("submittable", "NO (because of NumberFormatException)");
645 model.isSubmittable.setValue(false);
647 catch (Exception e) {
649 debug("submittable", "NO (because of an Exception)");
650 model.isSubmittable.setValue(false);
654 private static class BalanceForCurrency {
655 private final HashMap<String, Float> hashMap = new HashMap<>();
656 float get(String currencyName) {
657 Float f = hashMap.get(currencyName);
660 hashMap.put(currencyName, f);
664 void add(String currencyName, float amount) {
665 hashMap.put(currencyName, get(currencyName) + amount);
667 Set<String> currencies() {
668 return hashMap.keySet();
670 boolean containsCurrency(String currencyName) {
671 return hashMap.containsKey(currencyName);
675 private static class ItemsForCurrency {
676 private final HashMap<String, List<NewTransactionModel.Item>> hashMap = new HashMap<>();
678 List<NewTransactionModel.Item> getList(@Nullable String currencyName) {
679 List<NewTransactionModel.Item> list = hashMap.get(currencyName);
681 list = new ArrayList<>();
682 hashMap.put(currencyName, list);
686 void add(@Nullable String currencyName, @NonNull NewTransactionModel.Item item) {
687 getList(currencyName).add(item);
689 int size(@Nullable String currencyName) {
690 return this.getList(currencyName)
693 Set<String> currencies() {
694 return hashMap.keySet();