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, findViewById(R.id.new_transaction_acc_1), 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 = new LedgerTransaction(null, date, tvDescription.getText().toString(), mProfile);
166 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
167 LedgerTransactionAccount emptyAmountAccount = null;
168 float emptyAmountAccountBalance = 0;
169 for (int i = 0; i < table.getChildCount(); i++) {
170 TableRow row = (TableRow) table.getChildAt(i);
171 String acc = ((TextView) row.getChildAt(0)).getText().toString();
172 if (acc.isEmpty()) continue;
174 String amt = ((TextView) row.getChildAt(1)).getText().toString();
175 LedgerTransactionAccount item;
176 if (amt.length() > 0) {
177 final float amount = Float.parseFloat(amt);
178 item = new LedgerTransactionAccount(acc, amount);
179 emptyAmountAccountBalance += amount;
182 item = new LedgerTransactionAccount(acc);
183 emptyAmountAccount = item;
189 if (emptyAmountAccount != null)
190 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
193 catch (ParseException e) {
194 debug("new-transaction", "Parse error", e);
195 Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
196 Toast.LENGTH_LONG).show();
197 tvDate.requestFocus();
199 progress.setVisibility(View.GONE);
200 toggleAllEditing(true);
201 if (fab != null) fab.setEnabled(true);
203 catch (Exception e) {
204 debug("new-transaction", "Unknown error", e);
206 progress.setVisibility(View.GONE);
207 toggleAllEditing(true);
208 if (fab != null) fab.setEnabled(true);
211 private void toggleAllEditing(boolean enabled) {
212 tvDate.setEnabled(enabled);
213 tvDescription.setEnabled(enabled);
214 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
215 for (int i = 0; i < table.getChildCount(); i++) {
216 TableRow row = (TableRow) table.getChildAt(i);
217 for (int j = 0; j < row.getChildCount(); j++) {
218 row.getChildAt(j).setEnabled(enabled);
222 private void hookSwipeListener(final TableRow row) {
223 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
224 private void onSwipeAside() {
225 if (table.getChildCount() > 2) {
226 TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
227 TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
229 (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
231 (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
233 if (next_acc == null) {
234 prev_amt.setNextFocusRightId(R.id.none);
235 prev_amt.setNextFocusForwardId(R.id.none);
236 prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
239 prev_amt.setNextFocusRightId(next_acc.getId());
240 prev_amt.setNextFocusForwardId(next_acc.getId());
241 prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
244 if (row.hasFocus()) {
245 if (next_acc != null) next_acc.requestFocus();
246 else prev_amt.requestFocus();
249 table.removeView(row);
250 check_transaction_submittable();
251 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
254 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
255 Snackbar.LENGTH_LONG).setAction("Action", null).show();
258 public void onSwipeLeft() {
261 public void onSwipeRight() {
265 // public boolean performClick(View view, MotionEvent m) {
268 public boolean onTouch(View view, MotionEvent m) {
269 return gestureDetector.onTouchEvent(m);
274 public void simulateCrash(MenuItem item) {
275 debug("crash", "Will crash intentionally");
276 new AsyncCrasher().execute();
278 public boolean onCreateOptionsMenu(Menu menu) {
279 // Inflate the menu; this adds items to the action bar if it is present.
280 getMenuInflater().inflate(R.menu.new_transaction, menu);
282 if (BuildConfig.DEBUG) {
283 menu.findItem(R.id.action_simulate_crash).setVisible(true);
285 check_transaction_submittable();
290 public void pickTransactionDate(View view) {
291 DialogFragment picker = new DatePickerFragment();
292 picker.show(getSupportFragmentManager(), "datePicker");
295 public int dp2px(float dp) {
296 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
297 getResources().getDisplayMetrics()));
299 private void hookTextChangeListener(final TextView view) {
300 view.addTextChangedListener(new TextWatcher() {
302 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
307 public void onTextChanged(CharSequence s, int start, int before, int count) {
312 public void afterTextChanged(Editable s) {
313 // debug("input", "text changed");
314 check_transaction_submittable();
319 private TableRow doAddAccountRow(boolean focus) {
320 final AutoCompleteTextView acc = new AutoCompleteTextViewWithClear(this);
321 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
322 TableRow.LayoutParams.WRAP_CONTENT, 9f));
323 acc.setHint(R.string.new_transaction_account_hint);
325 acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
326 EditorInfo.IME_FLAG_NAVIGATE_NEXT);
327 acc.setSingleLine(true);
329 final EditText amt = new EditText(this);
330 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
331 TableRow.LayoutParams.MATCH_PARENT, 1f));
332 amt.setHint(R.string.new_transaction_amount_hint);
334 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
335 InputType.TYPE_NUMBER_FLAG_DECIMAL);
336 amt.setMinWidth(dp2px(40));
337 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
338 amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
339 amt.setSelectAllOnFocus(true);
341 // forward navigation support
343 int rows = table.getChildCount();
345 final TableRow last_row = (TableRow) table.getChildAt(rows - 1);
346 last_amt = (TextView) last_row.getChildAt(1);
349 last_amt = tvDescription;
351 last_amt.setNextFocusForwardId(acc.getId());
352 last_amt.setNextFocusRightId(acc.getId());
353 last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
354 acc.setNextFocusForwardId(amt.getId());
355 acc.setNextFocusRightId(amt.getId());
357 final TableRow row = new TableRow(this);
358 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
359 TableRow.LayoutParams.MATCH_PARENT));
360 row.setGravity(Gravity.BOTTOM);
365 if (focus) acc.requestFocus();
367 hookSwipeListener(row);
368 MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null,
370 hookTextChangeListener(acc);
371 hookTextChangeListener(amt);
375 public void addTransactionAccountFromMenu(MenuItem item) {
376 doAddAccountRow(true);
378 public void resetTransactionFromMenu(MenuItem item) {
381 public void saveTransactionFromMenu(MenuItem item) {
385 // 1) at least two account names
386 // 2) each amount must have account name
387 // 3) amounts must balance to 0, or
388 // 3a) there must be exactly one empty amount
389 // 4) empty accounts with empty amounts are ignored
390 // 5) a row with an empty account name or empty amount is guaranteed to exist
391 @SuppressLint("DefaultLocale")
392 private void check_transaction_submittable() {
393 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
395 int accounts_with_values = 0;
397 int amounts_with_accounts = 0;
399 TextView empty_amount = null;
400 boolean single_empty_amount = false;
401 boolean single_empty_amount_has_account = false;
402 float running_total = 0f;
403 boolean have_description =
404 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
408 for (int i = 0; i < table.getChildCount(); i++) {
409 TableRow row = (TableRow) table.getChildAt(i);
411 TextView acc_name_v = (TextView) row.getChildAt(0);
412 TextView amount_v = (TextView) row.getChildAt(1);
413 String amt = String.valueOf(amount_v.getText());
414 String acc_name = String.valueOf(acc_name_v.getText());
415 acc_name = acc_name.trim();
417 if (!acc_name.isEmpty()) {
420 if (!amt.isEmpty()) {
421 accounts_with_values++;
427 amount_v.setHint(String.format("%1.2f", 0f));
428 if (empty_amount == null) {
429 empty_amount = amount_v;
430 single_empty_amount = true;
431 single_empty_amount_has_account = !acc_name.isEmpty();
433 else if (!acc_name.isEmpty()) single_empty_amount = false;
437 if (!acc_name.isEmpty()) amounts_with_accounts++;
438 running_total += Float.valueOf(amt);
442 if ((empty_rows == 0) &&
443 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
445 doAddAccountRow(false);
448 debug("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
449 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
450 "single_empty_with_acc=%s", accounts,
451 accounts_with_values, amounts_with_accounts, amounts, running_total,
452 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
454 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
455 (amounts_with_accounts == amounts) &&
456 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
460 fab.setEnabled(true);
464 if (fab != null) fab.hide();
467 if (single_empty_amount) {
468 empty_amount.setHint(String.format("%1.2f",
469 (Math.abs(running_total) > 0.005) ? -running_total : 0f));
473 catch (NumberFormatException e) {
474 if (fab != null) fab.hide();
476 catch (Exception e) {
478 if (fab != null) fab.hide();
483 public void done(String error) {
484 progress.setVisibility(View.INVISIBLE);
485 debug("visuals", "hiding progress");
487 if (error == null) resetForm();
488 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
489 BaseTransientBottomBar.LENGTH_LONG).show();
491 toggleAllEditing(true);
492 check_transaction_submittable();
495 private void resetForm() {
497 tvDescription.setText("");
499 tvDescription.requestFocus();
501 while (table.getChildCount() > 2) {
502 table.removeViewAt(2);
504 for (int i = 0; i < 2; i++) {
505 TableRow tr = (TableRow) table.getChildAt(i);
506 if (tr == null) break;
508 ((TextView) tr.getChildAt(0)).setText("");
509 ((TextView) tr.getChildAt(1)).setText("");
513 public void descriptionSelected(String description) {
514 debug("descr selected", description);
515 if (!inputStateIsInitial()) return;
517 String accFilter = mProfile.getPreferredAccountsFilter();
519 ArrayList<String> params = new ArrayList<>();
520 StringBuilder sb = new StringBuilder(
521 "select t.profile, t.id from transactions t where t.description=?");
522 params.add(description);
524 if (accFilter != null) {
525 sb.append(" AND EXISTS (").append("SELECT 1 FROM transaction_accounts ta ")
526 .append("WHERE ta.profile = t.profile").append(" AND ta.transaction_id = t.id")
527 .append(" AND UPPER(ta.account_name) LIKE '%'||?||'%')");
528 params.add(accFilter.toUpperCase());
531 sb.append(" ORDER BY date desc limit 1");
533 final String sql = sb.toString();
535 debug("descr", params.toString());
537 try (Cursor c = App.getDatabase().rawQuery(sql, params.toArray(new String[]{}))) {
538 if (!c.moveToNext()) return;
540 String profileUUID = c.getString(0);
541 int transactionId = c.getInt(1);
542 LedgerTransaction tr;
543 MobileLedgerProfile profile = Data.getProfile(profileUUID);
544 if (profile == null) throw new RuntimeException(String.format(
545 "Unable to find profile %s, which is supposed to contain " +
546 "transaction %d with description %s", profileUUID, transactionId, description));
548 tr = profile.loadTransaction(transactionId);
549 ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
550 TableRow firstNegative = null;
551 int negativeCount = 0;
552 for (int i = 0; i < accounts.size(); i++) {
553 LedgerTransactionAccount acc = accounts.get(i);
554 TableRow row = (TableRow) table.getChildAt(i);
555 if (row == null) row = doAddAccountRow(false);
557 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
558 ((TextView) row.getChildAt(1))
559 .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
561 if (acc.getAmount() < 0.005) {
562 if (firstNegative == null) firstNegative = row;
567 if (negativeCount == 1) {
568 ((TextView) firstNegative.getChildAt(1)).setText(null);
571 check_transaction_submittable();
573 EditText firstAmount = (EditText) ((TableRow) table.getChildAt(0)).getChildAt(1);
574 String amtString = String.valueOf(firstAmount.getText());
575 firstAmount.requestFocus();
576 firstAmount.setSelection(0, amtString.length());
580 private boolean inputStateIsInitial() {
581 table = findViewById(R.id.new_transaction_accounts_table);
583 if (table.getChildCount() != 2) return false;
585 for (int i = 0; i < 2; i++) {
586 TableRow row = (TableRow) table.getChildAt(i);
587 if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
588 if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;
593 private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
595 protected Void doInBackground(Void... voids) {
596 throw new RuntimeException("Simulated crash");