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.annotation.SuppressLint;
21 import android.database.Cursor;
22 import android.graphics.drawable.Drawable;
23 import android.os.AsyncTask;
24 import android.os.Bundle;
25 import android.text.Editable;
26 import android.text.InputType;
27 import android.text.TextWatcher;
28 import android.util.TypedValue;
29 import android.view.Gravity;
30 import android.view.Menu;
31 import android.view.MenuItem;
32 import android.view.MotionEvent;
33 import android.view.View;
34 import android.view.inputmethod.EditorInfo;
35 import android.widget.AutoCompleteTextView;
36 import android.widget.EditText;
37 import android.widget.ProgressBar;
38 import android.widget.TableLayout;
39 import android.widget.TableRow;
40 import android.widget.TextView;
41 import android.widget.Toast;
43 import com.google.android.material.floatingactionbutton.FloatingActionButton;
44 import com.google.android.material.snackbar.BaseTransientBottomBar;
45 import com.google.android.material.snackbar.Snackbar;
47 import net.ktnx.mobileledger.App;
48 import net.ktnx.mobileledger.BuildConfig;
49 import net.ktnx.mobileledger.R;
50 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
51 import net.ktnx.mobileledger.async.SendTransactionTask;
52 import net.ktnx.mobileledger.async.TaskCallback;
53 import net.ktnx.mobileledger.model.Data;
54 import net.ktnx.mobileledger.model.LedgerTransaction;
55 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
56 import net.ktnx.mobileledger.model.MobileLedgerProfile;
57 import net.ktnx.mobileledger.ui.DatePickerFragment;
58 import net.ktnx.mobileledger.ui.OnSwipeTouchListener;
59 import net.ktnx.mobileledger.utils.Globals;
60 import net.ktnx.mobileledger.utils.MLDB;
62 import java.text.ParseException;
63 import java.util.ArrayList;
64 import java.util.Date;
65 import java.util.Locale;
66 import java.util.Objects;
68 import androidx.appcompat.widget.Toolbar;
69 import androidx.fragment.app.DialogFragment;
71 import static net.ktnx.mobileledger.utils.Logger.debug;
74 * TODO: nicer progress while transaction is submitted
76 * TODO: get rid of the custom session/cookie and auth code?
77 * (the last problem with the POST was the missing content-length header)
80 public class NewTransactionActivity extends ProfileThemedActivity
81 implements TaskCallback, DescriptionSelectedCallback {
82 private static SendTransactionTask saver;
83 private TableLayout table;
84 private ProgressBar progress;
85 private FloatingActionButton fab;
86 private TextView tvDate;
87 private AutoCompleteTextView tvDescription;
88 private static boolean isZero(float f) {
89 return (f < 0.005) && (f > -0.005);
92 protected void onCreate(Bundle savedInstanceState) {
93 super.onCreate(savedInstanceState);
95 setContentView(R.layout.activity_new_transaction);
96 Toolbar toolbar = findViewById(R.id.toolbar);
97 setSupportActionBar(toolbar);
98 toolbar.setSubtitle(mProfile.getName());
100 tvDate = findViewById(R.id.new_transaction_date);
101 tvDate.setOnFocusChangeListener((v, hasFocus) -> {
102 if (hasFocus) pickTransactionDate(v);
104 tvDescription = findViewById(R.id.new_transaction_description);
105 MLDB.hookAutocompletionAdapter(this, tvDescription, MLDB.DESCRIPTION_HISTORY_TABLE,
106 "description", false, findViewById(R.id.new_transaction_acc_1), this, mProfile);
107 hookTextChangeListener(tvDescription);
108 hookClearClickListener(tvDescription);
110 progress = findViewById(R.id.save_transaction_progress);
111 fab = findViewById(R.id.fab);
112 fab.setOnClickListener(v -> saveTransaction());
114 Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
115 table = findViewById(R.id.new_transaction_accounts_table);
117 while (table.getChildCount() < 2) {
118 doAddAccountRow(false);
121 check_transaction_submittable();
123 private void hookClearClickListener(AutoCompleteTextView v) {
124 final TextWatcher w = new TextWatcher() {
125 private boolean hasText;
126 private boolean hadText;
128 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
129 hadText = s.length() > 0;
132 public void onTextChanged(CharSequence s, int start, int before, int count) {
136 public void afterTextChanged(Editable s) {
137 hasText = s.length() > 0;
139 if (hadText && !hasText) {
140 v.setCompoundDrawablesRelative(null, null, null, null);
142 if (!hadText && hasText) {
143 v.setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0,
144 R.drawable.ic_clear_black_24dp, 0);
148 View.OnFocusChangeListener prevFocusListener = v.getOnFocusChangeListener();
149 v.setOnFocusChangeListener((v12, hasFocus) -> {
151 if (((TextView) v12).getText().length() > 0) {
152 ((TextView) v12).setCompoundDrawablesRelativeWithIntrinsicBounds(0, 0,
153 R.drawable.ic_clear_black_24dp, 0);
155 ((TextView) v12).addTextChangedListener(w);
158 ((TextView) v12).removeTextChangedListener(w);
159 ((TextView) v12).setCompoundDrawables(null, null, null, null);
162 if (prevFocusListener != null) prevFocusListener.onFocusChange(v12, hasFocus);
165 v.setOnTouchListener((v1, event) -> {
166 if (event.getAction() == MotionEvent.ACTION_UP)
167 if (((TextView) v1).getText().length() > 0) {
168 boolean clearClicked = false;
169 final float x = event.getX();
170 final int vw = v1.getWidth();
171 // start, top, end, bottom (end == 2)
172 Drawable dwb = ((TextView) v1).getCompoundDrawablesRelative()[2];
174 final int dw = dwb.getBounds().width();
175 if (v1.getLayoutDirection() == View.LAYOUT_DIRECTION_LTR) {
176 if ((x > vw - dw)) clearClicked = true;
179 if (x < vw - dw) clearClicked = true;
182 ((TextView) v1).setText("");
193 protected void initProfile() {
194 String profileUUID = getIntent().getStringExtra("profile_uuid");
196 if (profileUUID != null) {
197 mProfile = Data.getProfile(profileUUID);
198 if (mProfile == null) finish();
200 else super.initProfile();
203 public void finish() {
205 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
209 public boolean onOptionsItemSelected(MenuItem item) {
210 switch (item.getItemId()) {
211 case android.R.id.home:
215 return super.onOptionsItemSelected(item);
218 protected void onStart() {
220 if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
222 public void saveTransaction() {
223 if (fab != null) fab.setEnabled(false);
224 toggleAllEditing(false);
225 progress.setVisibility(View.VISIBLE);
228 saver = new SendTransactionTask(this, mProfile);
230 String dateString = tvDate.getText().toString();
232 if (dateString.isEmpty()) date = new Date();
233 else date = Globals.parseLedgerDate(dateString);
234 LedgerTransaction tr = new LedgerTransaction(null, date, tvDescription.getText().toString(), mProfile);
236 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
237 LedgerTransactionAccount emptyAmountAccount = null;
238 float emptyAmountAccountBalance = 0;
239 for (int i = 0; i < table.getChildCount(); i++) {
240 TableRow row = (TableRow) table.getChildAt(i);
241 String acc = ((TextView) row.getChildAt(0)).getText().toString();
242 if (acc.isEmpty()) continue;
244 String amt = ((TextView) row.getChildAt(1)).getText().toString();
245 LedgerTransactionAccount item;
246 if (amt.length() > 0) {
247 final float amount = Float.parseFloat(amt);
248 item = new LedgerTransactionAccount(acc, amount);
249 emptyAmountAccountBalance += amount;
252 item = new LedgerTransactionAccount(acc);
253 emptyAmountAccount = item;
259 if (emptyAmountAccount != null)
260 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
263 catch (ParseException e) {
264 debug("new-transaction", "Parse error", e);
265 Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
266 Toast.LENGTH_LONG).show();
267 tvDate.requestFocus();
269 progress.setVisibility(View.GONE);
270 toggleAllEditing(true);
271 if (fab != null) fab.setEnabled(true);
273 catch (Exception e) {
274 debug("new-transaction", "Unknown error", e);
276 progress.setVisibility(View.GONE);
277 toggleAllEditing(true);
278 if (fab != null) fab.setEnabled(true);
281 private void toggleAllEditing(boolean enabled) {
282 tvDate.setEnabled(enabled);
283 tvDescription.setEnabled(enabled);
284 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
285 for (int i = 0; i < table.getChildCount(); i++) {
286 TableRow row = (TableRow) table.getChildAt(i);
287 for (int j = 0; j < row.getChildCount(); j++) {
288 row.getChildAt(j).setEnabled(enabled);
292 private void hookSwipeListener(final TableRow row) {
293 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
294 private void onSwipeAside() {
295 if (table.getChildCount() > 2) {
296 TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
297 TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
299 (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
301 (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
303 if (next_acc == null) {
304 prev_amt.setNextFocusRightId(R.id.none);
305 prev_amt.setNextFocusForwardId(R.id.none);
306 prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
309 prev_amt.setNextFocusRightId(next_acc.getId());
310 prev_amt.setNextFocusForwardId(next_acc.getId());
311 prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
314 if (row.hasFocus()) {
315 if (next_acc != null) next_acc.requestFocus();
316 else prev_amt.requestFocus();
319 table.removeView(row);
320 check_transaction_submittable();
321 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
324 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
325 Snackbar.LENGTH_LONG).setAction("Action", null).show();
328 public void onSwipeLeft() {
331 public void onSwipeRight() {
335 // public boolean performClick(View view, MotionEvent m) {
338 public boolean onTouch(View view, MotionEvent m) {
339 return gestureDetector.onTouchEvent(m);
344 public void simulateCrash(MenuItem item) {
345 debug("crash", "Will crash intentionally");
346 new AsyncCrasher().execute();
348 public boolean onCreateOptionsMenu(Menu menu) {
349 // Inflate the menu; this adds items to the action bar if it is present.
350 getMenuInflater().inflate(R.menu.new_transaction, menu);
352 if (BuildConfig.DEBUG) {
353 menu.findItem(R.id.action_simulate_crash).setVisible(true);
355 check_transaction_submittable();
360 public void pickTransactionDate(View view) {
361 DialogFragment picker = new DatePickerFragment();
362 picker.show(getSupportFragmentManager(), "datePicker");
365 public int dp2px(float dp) {
366 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
367 getResources().getDisplayMetrics()));
369 private void hookTextChangeListener(final TextView view) {
370 view.addTextChangedListener(new TextWatcher() {
372 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
377 public void onTextChanged(CharSequence s, int start, int before, int count) {
382 public void afterTextChanged(Editable s) {
383 // debug("input", "text changed");
384 check_transaction_submittable();
389 private TableRow doAddAccountRow(boolean focus) {
390 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
391 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
392 TableRow.LayoutParams.WRAP_CONTENT, 9f));
393 acc.setHint(R.string.new_transaction_account_hint);
395 acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
396 EditorInfo.IME_FLAG_NAVIGATE_NEXT);
397 acc.setSingleLine(true);
399 final EditText amt = new EditText(this);
400 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
401 TableRow.LayoutParams.MATCH_PARENT, 1f));
402 amt.setHint(R.string.new_transaction_amount_hint);
404 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
405 InputType.TYPE_NUMBER_FLAG_DECIMAL);
406 amt.setMinWidth(dp2px(40));
407 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
408 amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
409 amt.setSelectAllOnFocus(true);
411 // forward navigation support
413 int rows = table.getChildCount();
415 final TableRow last_row = (TableRow) table.getChildAt(rows - 1);
416 last_amt = (TextView) last_row.getChildAt(1);
419 last_amt = tvDescription;
421 last_amt.setNextFocusForwardId(acc.getId());
422 last_amt.setNextFocusRightId(acc.getId());
423 last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
424 acc.setNextFocusForwardId(amt.getId());
425 acc.setNextFocusRightId(amt.getId());
427 final TableRow row = new TableRow(this);
428 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
429 TableRow.LayoutParams.MATCH_PARENT));
430 row.setGravity(Gravity.BOTTOM);
435 if (focus) acc.requestFocus();
437 hookSwipeListener(row);
438 MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null,
440 hookTextChangeListener(acc);
441 hookClearClickListener(acc);
442 hookTextChangeListener(amt);
446 public void addTransactionAccountFromMenu(MenuItem item) {
447 doAddAccountRow(true);
449 public void resetTransactionFromMenu(MenuItem item) {
452 public void saveTransactionFromMenu(MenuItem item) {
456 // 1) at least two account names
457 // 2) each amount must have account name
458 // 3) amounts must balance to 0, or
459 // 3a) there must be exactly one empty amount
460 // 4) empty accounts with empty amounts are ignored
461 // 5) a row with an empty account name or empty amount is guaranteed to exist
462 @SuppressLint("DefaultLocale")
463 private void check_transaction_submittable() {
464 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
466 int accounts_with_values = 0;
468 int amounts_with_accounts = 0;
470 TextView empty_amount = null;
471 boolean single_empty_amount = false;
472 boolean single_empty_amount_has_account = false;
473 float running_total = 0f;
474 boolean have_description =
475 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
479 for (int i = 0; i < table.getChildCount(); i++) {
480 TableRow row = (TableRow) table.getChildAt(i);
482 TextView acc_name_v = (TextView) row.getChildAt(0);
483 TextView amount_v = (TextView) row.getChildAt(1);
484 String amt = String.valueOf(amount_v.getText());
485 String acc_name = String.valueOf(acc_name_v.getText());
486 acc_name = acc_name.trim();
488 if (!acc_name.isEmpty()) {
491 if (!amt.isEmpty()) {
492 accounts_with_values++;
498 amount_v.setHint(String.format("%1.2f", 0f));
499 if (empty_amount == null) {
500 empty_amount = amount_v;
501 single_empty_amount = true;
502 single_empty_amount_has_account = !acc_name.isEmpty();
504 else if (!acc_name.isEmpty()) single_empty_amount = false;
508 if (!acc_name.isEmpty()) amounts_with_accounts++;
509 running_total += Float.valueOf(amt);
513 if ((empty_rows == 0) &&
514 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
516 doAddAccountRow(false);
519 debug("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
520 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
521 "single_empty_with_acc=%s", accounts,
522 accounts_with_values, amounts_with_accounts, amounts, running_total,
523 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
525 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
526 (amounts_with_accounts == amounts) &&
527 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
531 fab.setEnabled(true);
535 if (fab != null) fab.hide();
538 if (single_empty_amount) {
539 empty_amount.setHint(String.format("%1.2f",
540 (Math.abs(running_total) > 0.005) ? -running_total : 0f));
544 catch (NumberFormatException e) {
545 if (fab != null) fab.hide();
547 catch (Exception e) {
549 if (fab != null) fab.hide();
554 public void done(String error) {
555 progress.setVisibility(View.INVISIBLE);
556 debug("visuals", "hiding progress");
558 if (error == null) resetForm();
559 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
560 BaseTransientBottomBar.LENGTH_LONG).show();
562 toggleAllEditing(true);
563 check_transaction_submittable();
566 private void resetForm() {
568 tvDescription.setText("");
570 tvDescription.requestFocus();
572 while (table.getChildCount() > 2) {
573 table.removeViewAt(2);
575 for (int i = 0; i < 2; i++) {
576 TableRow tr = (TableRow) table.getChildAt(i);
577 if (tr == null) break;
579 ((TextView) tr.getChildAt(0)).setText("");
580 ((TextView) tr.getChildAt(1)).setText("");
584 public void descriptionSelected(String description) {
585 debug("descr selected", description);
586 if (!inputStateIsInitial()) return;
588 String accFilter = mProfile.getPreferredAccountsFilter();
590 ArrayList<String> params = new ArrayList<>();
591 StringBuilder sb = new StringBuilder(
592 "select t.profile, t.id from transactions t where t.description=?");
593 params.add(description);
595 if (accFilter != null) {
596 sb.append(" AND EXISTS (").append("SELECT 1 FROM transaction_accounts ta ")
597 .append("WHERE ta.profile = t.profile").append(" AND ta.transaction_id = t.id")
598 .append(" AND UPPER(ta.account_name) LIKE '%'||?||'%')");
599 params.add(accFilter.toUpperCase());
602 sb.append(" ORDER BY date desc limit 1");
604 final String sql = sb.toString();
606 debug("descr", params.toString());
608 try (Cursor c = App.getDatabase().rawQuery(sql, params.toArray(new String[]{}))) {
609 if (!c.moveToNext()) return;
611 String profileUUID = c.getString(0);
612 int transactionId = c.getInt(1);
613 LedgerTransaction tr;
614 MobileLedgerProfile profile = Data.getProfile(profileUUID);
615 if (profile == null) throw new RuntimeException(String.format(
616 "Unable to find profile %s, which is supposed to contain " +
617 "transaction %d with description %s", profileUUID, transactionId, description));
619 tr = profile.loadTransaction(transactionId);
620 ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
621 TableRow firstNegative = null;
622 int negativeCount = 0;
623 for (int i = 0; i < accounts.size(); i++) {
624 LedgerTransactionAccount acc = accounts.get(i);
625 TableRow row = (TableRow) table.getChildAt(i);
626 if (row == null) row = doAddAccountRow(false);
628 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
629 ((TextView) row.getChildAt(1))
630 .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
632 if (acc.getAmount() < 0.005) {
633 if (firstNegative == null) firstNegative = row;
638 if (negativeCount == 1) {
639 ((TextView) firstNegative.getChildAt(1)).setText(null);
642 check_transaction_submittable();
644 EditText firstAmount = (EditText) ((TableRow) table.getChildAt(0)).getChildAt(1);
645 String amtString = String.valueOf(firstAmount.getText());
646 firstAmount.requestFocus();
647 firstAmount.setSelection(0, amtString.length());
651 private boolean inputStateIsInitial() {
652 table = findViewById(R.id.new_transaction_accounts_table);
654 if (table.getChildCount() != 2) return false;
656 for (int i = 0; i < 2; i++) {
657 TableRow row = (TableRow) table.getChildAt(i);
658 if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
659 if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;
664 private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
666 protected Void doInBackground(Void... voids) {
667 throw new RuntimeException("Simulated crash");