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.os.AsyncTask;
23 import android.os.Bundle;
24 import android.text.Editable;
25 import android.text.InputType;
26 import android.text.TextWatcher;
27 import android.util.TypedValue;
28 import android.view.Gravity;
29 import android.view.Menu;
30 import android.view.MenuItem;
31 import android.view.MotionEvent;
32 import android.view.View;
33 import android.view.inputmethod.EditorInfo;
34 import android.widget.AutoCompleteTextView;
35 import android.widget.EditText;
36 import android.widget.ProgressBar;
37 import android.widget.TableLayout;
38 import android.widget.TableRow;
39 import android.widget.TextView;
40 import android.widget.Toast;
42 import com.google.android.material.floatingactionbutton.FloatingActionButton;
43 import com.google.android.material.snackbar.BaseTransientBottomBar;
44 import com.google.android.material.snackbar.Snackbar;
46 import net.ktnx.mobileledger.App;
47 import net.ktnx.mobileledger.BuildConfig;
48 import net.ktnx.mobileledger.R;
49 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
50 import net.ktnx.mobileledger.async.SendTransactionTask;
51 import net.ktnx.mobileledger.async.TaskCallback;
52 import net.ktnx.mobileledger.model.Data;
53 import net.ktnx.mobileledger.model.LedgerTransaction;
54 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
55 import net.ktnx.mobileledger.model.MobileLedgerProfile;
56 import net.ktnx.mobileledger.ui.AutoCompleteTextViewWithClear;
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, this, mProfile);
107 hookTextChangeListener(tvDescription);
109 progress = findViewById(R.id.save_transaction_progress);
110 fab = findViewById(R.id.fab);
111 fab.setOnClickListener(v -> saveTransaction());
113 Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
114 table = findViewById(R.id.new_transaction_accounts_table);
116 while (table.getChildCount() < 2) {
117 doAddAccountRow(false);
120 check_transaction_submittable();
123 protected void initProfile() {
124 String profileUUID = getIntent().getStringExtra("profile_uuid");
126 if (profileUUID != null) {
127 mProfile = Data.getProfile(profileUUID);
128 if (mProfile == null) finish();
130 else super.initProfile();
133 public void finish() {
135 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
139 public boolean onOptionsItemSelected(MenuItem item) {
140 switch (item.getItemId()) {
141 case android.R.id.home:
145 return super.onOptionsItemSelected(item);
148 protected void onStart() {
150 if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
152 public void saveTransaction() {
153 if (fab != null) fab.setEnabled(false);
154 toggleAllEditing(false);
155 progress.setVisibility(View.VISIBLE);
158 saver = new SendTransactionTask(this, mProfile);
160 String dateString = tvDate.getText().toString();
162 if (dateString.isEmpty()) date = new Date();
163 else date = Globals.parseLedgerDate(dateString);
164 LedgerTransaction tr =
165 new LedgerTransaction(null, date, tvDescription.getText().toString(), mProfile);
167 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
168 LedgerTransactionAccount emptyAmountAccount = null;
169 float emptyAmountAccountBalance = 0;
170 for (int i = 0; i < table.getChildCount(); i++) {
171 TableRow row = (TableRow) table.getChildAt(i);
172 String acc = ((TextView) row.getChildAt(0)).getText().toString();
173 if (acc.isEmpty()) continue;
175 String amt = ((TextView) row.getChildAt(1)).getText().toString();
176 LedgerTransactionAccount item;
177 if (amt.length() > 0) {
178 final float amount = Float.parseFloat(amt);
179 item = new LedgerTransactionAccount(acc, amount);
180 emptyAmountAccountBalance += amount;
183 item = new LedgerTransactionAccount(acc);
184 emptyAmountAccount = item;
190 if (emptyAmountAccount != null)
191 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
194 catch (ParseException e) {
195 debug("new-transaction", "Parse error", e);
196 Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
197 Toast.LENGTH_LONG).show();
198 tvDate.requestFocus();
200 progress.setVisibility(View.GONE);
201 toggleAllEditing(true);
202 if (fab != null) fab.setEnabled(true);
204 catch (Exception e) {
205 debug("new-transaction", "Unknown error", e);
207 progress.setVisibility(View.GONE);
208 toggleAllEditing(true);
209 if (fab != null) fab.setEnabled(true);
212 private void toggleAllEditing(boolean enabled) {
213 tvDate.setEnabled(enabled);
214 tvDescription.setEnabled(enabled);
215 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
216 for (int i = 0; i < table.getChildCount(); i++) {
217 TableRow row = (TableRow) table.getChildAt(i);
218 for (int j = 0; j < row.getChildCount(); j++) {
219 row.getChildAt(j).setEnabled(enabled);
223 private void hookSwipeListener(final TableRow row) {
224 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
225 private void onSwipeAside() {
226 if (table.getChildCount() > 2) {
227 TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
228 TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
230 (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
232 (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
234 if (next_acc == null) {
235 prev_amt.setNextFocusRightId(R.id.none);
236 prev_amt.setNextFocusForwardId(R.id.none);
237 prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
240 prev_amt.setNextFocusRightId(next_acc.getId());
241 prev_amt.setNextFocusForwardId(next_acc.getId());
242 prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
245 if (row.hasFocus()) {
246 if (next_acc != null) next_acc.requestFocus();
247 else prev_amt.requestFocus();
250 table.removeView(row);
251 check_transaction_submittable();
252 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
255 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
256 Snackbar.LENGTH_LONG).setAction("Action", null).show();
259 public void onSwipeLeft() {
262 public void onSwipeRight() {
266 // public boolean performClick(View view, MotionEvent m) {
269 public boolean onTouch(View view, MotionEvent m) {
270 return gestureDetector.onTouchEvent(m);
275 public void simulateCrash(MenuItem item) {
276 debug("crash", "Will crash intentionally");
277 new AsyncCrasher().execute();
279 public boolean onCreateOptionsMenu(Menu menu) {
280 // Inflate the menu; this adds items to the action bar if it is present.
281 getMenuInflater().inflate(R.menu.new_transaction, menu);
283 if (BuildConfig.DEBUG) {
284 menu.findItem(R.id.action_simulate_crash).setVisible(true);
286 check_transaction_submittable();
291 public void pickTransactionDate(View view) {
292 DialogFragment picker = new DatePickerFragment();
293 picker.show(getSupportFragmentManager(), "datePicker");
296 public int dp2px(float dp) {
297 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
298 getResources().getDisplayMetrics()));
300 private void hookTextChangeListener(final TextView view) {
301 view.addTextChangedListener(new TextWatcher() {
303 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
308 public void onTextChanged(CharSequence s, int start, int before, int count) {
313 public void afterTextChanged(Editable s) {
314 // debug("input", "text changed");
315 check_transaction_submittable();
320 private TableRow doAddAccountRow(boolean focus) {
321 final AutoCompleteTextView acc = new AutoCompleteTextViewWithClear(this);
322 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
323 TableRow.LayoutParams.WRAP_CONTENT, 9f));
324 acc.setHint(R.string.new_transaction_account_hint);
326 acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
327 EditorInfo.IME_FLAG_NAVIGATE_NEXT);
328 acc.setSingleLine(true);
330 final EditText amt = new EditText(this);
331 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
332 TableRow.LayoutParams.MATCH_PARENT, 1f));
333 amt.setHint(R.string.new_transaction_amount_hint);
335 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
336 InputType.TYPE_NUMBER_FLAG_DECIMAL);
337 amt.setMinWidth(dp2px(40));
338 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
339 amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
340 amt.setSelectAllOnFocus(true);
342 // forward navigation support
344 int rows = table.getChildCount();
346 final TableRow last_row = (TableRow) table.getChildAt(rows - 1);
347 last_amt = (TextView) last_row.getChildAt(1);
350 last_amt = tvDescription;
352 last_amt.setNextFocusForwardId(acc.getId());
353 last_amt.setNextFocusRightId(acc.getId());
354 last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
355 acc.setNextFocusForwardId(amt.getId());
356 acc.setNextFocusRightId(amt.getId());
358 final TableRow row = new TableRow(this);
359 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
360 TableRow.LayoutParams.MATCH_PARENT));
361 row.setGravity(Gravity.BOTTOM);
366 if (focus) acc.requestFocus();
368 hookSwipeListener(row);
369 MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true,
370 description -> amt.requestFocus(), mProfile);
371 hookTextChangeListener(acc);
372 hookTextChangeListener(amt);
376 public void addTransactionAccountFromMenu(MenuItem item) {
377 doAddAccountRow(true);
379 public void resetTransactionFromMenu(MenuItem item) {
382 public void saveTransactionFromMenu(MenuItem item) {
386 // 1) at least two account names
387 // 2) each amount must have account name
388 // 3) amounts must balance to 0, or
389 // 3a) there must be exactly one empty amount
390 // 4) empty accounts with empty amounts are ignored
391 // 5) a row with an empty account name or empty amount is guaranteed to exist
392 @SuppressLint("DefaultLocale")
393 private void check_transaction_submittable() {
394 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
396 int accounts_with_values = 0;
398 int amounts_with_accounts = 0;
400 TextView empty_amount = null;
401 boolean single_empty_amount = false;
402 boolean single_empty_amount_has_account = false;
403 float running_total = 0f;
404 boolean have_description =
405 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
409 for (int i = 0; i < table.getChildCount(); i++) {
410 TableRow row = (TableRow) table.getChildAt(i);
412 TextView acc_name_v = (TextView) row.getChildAt(0);
413 TextView amount_v = (TextView) row.getChildAt(1);
414 String amt = String.valueOf(amount_v.getText());
415 String acc_name = String.valueOf(acc_name_v.getText());
416 acc_name = acc_name.trim();
418 if (!acc_name.isEmpty()) {
421 if (!amt.isEmpty()) {
422 accounts_with_values++;
428 amount_v.setHint(String.format("%1.2f", 0f));
429 if (empty_amount == null) {
430 empty_amount = amount_v;
431 single_empty_amount = true;
432 single_empty_amount_has_account = !acc_name.isEmpty();
434 else if (!acc_name.isEmpty()) single_empty_amount = false;
438 if (!acc_name.isEmpty()) amounts_with_accounts++;
439 running_total += Float.valueOf(amt);
443 if ((empty_rows == 0) &&
444 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
446 doAddAccountRow(false);
449 debug("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
450 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
451 "single_empty_with_acc=%s", accounts,
452 accounts_with_values, amounts_with_accounts, amounts, running_total,
453 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
455 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
456 (amounts_with_accounts == amounts) &&
457 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
461 fab.setEnabled(true);
465 if (fab != null) fab.hide();
468 if (single_empty_amount) {
469 empty_amount.setHint(String.format("%1.2f",
470 (Math.abs(running_total) > 0.005) ? -running_total : 0f));
474 catch (NumberFormatException e) {
475 if (fab != null) fab.hide();
477 catch (Exception e) {
479 if (fab != null) fab.hide();
484 public void done(String error) {
485 progress.setVisibility(View.INVISIBLE);
486 debug("visuals", "hiding progress");
488 if (error == null) resetForm();
489 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
490 BaseTransientBottomBar.LENGTH_LONG).show();
492 toggleAllEditing(true);
493 check_transaction_submittable();
496 private void resetForm() {
498 tvDescription.setText("");
500 tvDescription.requestFocus();
502 while (table.getChildCount() > 2) {
503 table.removeViewAt(2);
505 for (int i = 0; i < 2; i++) {
506 TableRow tr = (TableRow) table.getChildAt(i);
507 if (tr == null) break;
509 ((TextView) tr.getChildAt(0)).setText("");
510 ((TextView) tr.getChildAt(1)).setText("");
514 public void descriptionSelected(String description) {
515 debug("descr selected", description);
516 if (!inputStateIsInitial()) return;
518 String accFilter = mProfile.getPreferredAccountsFilter();
520 ArrayList<String> params = new ArrayList<>();
521 StringBuilder sb = new StringBuilder(
522 "select t.profile, t.id from transactions t where t.description=?");
523 params.add(description);
525 if (accFilter != null) {
526 sb.append(" AND EXISTS (").append("SELECT 1 FROM transaction_accounts ta ")
527 .append("WHERE ta.profile = t.profile").append(" AND ta.transaction_id = t.id")
528 .append(" AND UPPER(ta.account_name) LIKE '%'||?||'%')");
529 params.add(accFilter.toUpperCase());
532 sb.append(" ORDER BY date desc limit 1");
534 final String sql = sb.toString();
536 debug("descr", params.toString());
538 try (Cursor c = App.getDatabase().rawQuery(sql, params.toArray(new String[]{}))) {
539 if (!c.moveToNext()) return;
541 String profileUUID = c.getString(0);
542 int transactionId = c.getInt(1);
543 LedgerTransaction tr;
544 MobileLedgerProfile profile = Data.getProfile(profileUUID);
545 if (profile == null) throw new RuntimeException(String.format(
546 "Unable to find profile %s, which is supposed to contain " +
547 "transaction %d with description %s", profileUUID, transactionId, description));
549 tr = profile.loadTransaction(transactionId);
550 ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
551 TableRow firstNegative = null;
552 int negativeCount = 0;
553 for (int i = 0; i < accounts.size(); i++) {
554 LedgerTransactionAccount acc = accounts.get(i);
555 TableRow row = (TableRow) table.getChildAt(i);
556 if (row == null) row = doAddAccountRow(false);
558 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
559 ((TextView) row.getChildAt(1))
560 .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
562 if (acc.getAmount() < 0.005) {
563 if (firstNegative == null) firstNegative = row;
568 if (negativeCount == 1) {
569 ((TextView) firstNegative.getChildAt(1)).setText(null);
572 check_transaction_submittable();
574 EditText firstAmount = (EditText) ((TableRow) table.getChildAt(0)).getChildAt(1);
575 String amtString = String.valueOf(firstAmount.getText());
576 firstAmount.requestFocus();
577 firstAmount.setSelection(0, amtString.length());
581 private boolean inputStateIsInitial() {
582 table = findViewById(R.id.new_transaction_accounts_table);
584 if (table.getChildCount() != 2) return false;
586 for (int i = 0; i < 2; i++) {
587 TableRow row = (TableRow) table.getChildAt(i);
588 if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
589 if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;
594 private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
596 protected Void doInBackground(Void... voids) {
597 throw new RuntimeException("Simulated crash");