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.Log;
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.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.DatePickerFragment;
57 import net.ktnx.mobileledger.ui.OnSwipeTouchListener;
58 import net.ktnx.mobileledger.utils.Globals;
59 import net.ktnx.mobileledger.utils.LockHolder;
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;
72 * TODO: nicer progress while transaction is submitted
74 * TODO: get rid of the custom session/cookie and auth code?
75 * (the last problem with the POST was the missing content-length header)
78 public class NewTransactionActivity extends ProfileThemedActivity
79 implements TaskCallback, DescriptionSelectedCallback {
80 private static SendTransactionTask saver;
81 private TableLayout table;
82 private ProgressBar progress;
83 private FloatingActionButton fab;
84 private TextView tvDate;
85 private AutoCompleteTextView tvDescription;
86 private static boolean isZero(float f) {
87 return (f < 0.005) && (f > -0.005);
90 protected void onCreate(Bundle savedInstanceState) {
91 super.onCreate(savedInstanceState);
93 setContentView(R.layout.activity_new_transaction);
94 Toolbar toolbar = findViewById(R.id.toolbar);
95 setSupportActionBar(toolbar);
96 toolbar.setSubtitle(Data.profile.get().getName());
98 tvDate = findViewById(R.id.new_transaction_date);
99 tvDate.setOnFocusChangeListener((v, hasFocus) -> {
100 if (hasFocus) pickTransactionDate(v);
102 tvDescription = findViewById(R.id.new_transaction_description);
103 MLDB.hookAutocompletionAdapter(this, tvDescription, MLDB.DESCRIPTION_HISTORY_TABLE,
104 "description", false, findViewById(R.id.new_transaction_acc_1), this);
105 hookTextChangeListener(tvDescription);
107 progress = findViewById(R.id.save_transaction_progress);
108 fab = findViewById(R.id.fab);
109 fab.setOnClickListener(v -> saveTransaction());
111 Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
112 table = findViewById(R.id.new_transaction_accounts_table);
113 for (int i = 0; i < table.getChildCount(); i++) {
114 TableRow row = (TableRow) table.getChildAt(i);
115 AutoCompleteTextView tvAccountName = (AutoCompleteTextView) row.getChildAt(0);
116 TextView tvAmount = (TextView) row.getChildAt(1);
117 hookSwipeListener(row);
118 MLDB.hookAutocompletionAdapter(this, tvAccountName, MLDB.ACCOUNTS_TABLE, "name", true,
120 hookTextChangeListener(tvAccountName);
121 hookTextChangeListener(tvAmount);
122 // Log.d("swipe", "hooked to row "+i);
127 public void finish() {
129 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
133 public boolean onOptionsItemSelected(MenuItem item) {
134 switch (item.getItemId()) {
135 case android.R.id.home:
139 return super.onOptionsItemSelected(item);
142 protected void onStart() {
144 if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
146 public void saveTransaction() {
147 if (fab != null) fab.setEnabled(false);
148 toggleAllEditing(false);
149 progress.setVisibility(View.VISIBLE);
152 saver = new SendTransactionTask(this);
154 String dateString = tvDate.getText().toString();
156 if (dateString.isEmpty()) date = new Date();
157 else date = Globals.parseLedgerDate(dateString);
158 LedgerTransaction tr = new LedgerTransaction(date, tvDescription.getText().toString());
160 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
161 LedgerTransactionAccount emptyAmountAccount = null;
162 float emptyAmountAccountBalance = 0;
163 for (int i = 0; i < table.getChildCount(); i++) {
164 TableRow row = (TableRow) table.getChildAt(i);
165 String acc = ((TextView) row.getChildAt(0)).getText().toString();
166 if (acc.isEmpty()) continue;
168 String amt = ((TextView) row.getChildAt(1)).getText().toString();
169 LedgerTransactionAccount item;
170 if (amt.length() > 0) {
171 final float amount = Float.parseFloat(amt);
172 item = new LedgerTransactionAccount(acc, amount);
173 emptyAmountAccountBalance += amount;
176 item = new LedgerTransactionAccount(acc);
177 emptyAmountAccount = item;
183 if (emptyAmountAccount != null) emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
186 catch (ParseException e) {
187 Log.d("new-transaction", "Parse error", e);
188 Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
189 Toast.LENGTH_LONG).show();
190 tvDate.requestFocus();
192 progress.setVisibility(View.GONE);
193 toggleAllEditing(true);
194 if (fab != null) fab.setEnabled(true);
196 catch (Exception e) {
197 Log.d("new-transaction", "Unknown error", e);
199 progress.setVisibility(View.GONE);
200 toggleAllEditing(true);
201 if (fab != null) fab.setEnabled(true);
204 private void toggleAllEditing(boolean enabled) {
205 tvDate.setEnabled(enabled);
206 tvDescription.setEnabled(enabled);
207 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
208 for (int i = 0; i < table.getChildCount(); i++) {
209 TableRow row = (TableRow) table.getChildAt(i);
210 for (int j = 0; j < row.getChildCount(); j++) {
211 row.getChildAt(j).setEnabled(enabled);
215 private void hookSwipeListener(final TableRow row) {
216 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
217 private void onSwipeAside() {
218 if (table.getChildCount() > 2) {
219 TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
220 TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
222 (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
224 (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
226 if (next_acc == null) {
227 prev_amt.setNextFocusRightId(R.id.none);
228 prev_amt.setNextFocusForwardId(R.id.none);
229 prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
232 prev_amt.setNextFocusRightId(next_acc.getId());
233 prev_amt.setNextFocusForwardId(next_acc.getId());
234 prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
237 if (row.hasFocus()) {
238 if (next_acc != null) next_acc.requestFocus();
239 else prev_amt.requestFocus();
242 table.removeView(row);
243 check_transaction_submittable();
244 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
247 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
248 Snackbar.LENGTH_LONG).setAction("Action", null).show();
251 public void onSwipeLeft() {
254 public void onSwipeRight() {
258 // public boolean performClick(View view, MotionEvent m) {
261 public boolean onTouch(View view, MotionEvent m) {
262 return gestureDetector.onTouchEvent(m);
267 public boolean simulateCrash(MenuItem item) {
268 Log.d("crash", "Will crash intentionally");
269 new AsyncCrasher().execute();
272 public boolean onCreateOptionsMenu(Menu menu) {
273 // Inflate the menu; this adds items to the action bar if it is present.
274 getMenuInflater().inflate(R.menu.new_transaction, menu);
276 if (BuildConfig.DEBUG) {
277 menu.findItem(R.id.action_simulate_crash).setVisible(true);
279 check_transaction_submittable();
284 public void pickTransactionDate(View view) {
285 DialogFragment picker = new DatePickerFragment();
286 picker.show(getSupportFragmentManager(), "datePicker");
289 public int dp2px(float dp) {
290 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
291 getResources().getDisplayMetrics()));
293 private void hookTextChangeListener(final TextView view) {
294 view.addTextChangedListener(new TextWatcher() {
296 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
301 public void onTextChanged(CharSequence s, int start, int before, int count) {
306 public void afterTextChanged(Editable s) {
307 // Log.d("input", "text changed");
308 check_transaction_submittable();
313 private TableRow doAddAccountRow(boolean focus) {
314 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
315 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
316 TableRow.LayoutParams.WRAP_CONTENT, 9f));
317 acc.setHint(R.string.new_transaction_account_hint);
319 acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
320 EditorInfo.IME_FLAG_NAVIGATE_NEXT);
321 acc.setSingleLine(true);
323 final EditText amt = new EditText(this);
324 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
325 TableRow.LayoutParams.MATCH_PARENT, 1f));
326 amt.setHint(R.string.new_transaction_amount_hint);
328 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
329 InputType.TYPE_NUMBER_FLAG_DECIMAL);
330 amt.setMinWidth(dp2px(40));
331 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
332 amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
333 amt.setSelectAllOnFocus(true);
335 // forward navigation support
336 final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
337 final TextView last_amt = (TextView) last_row.getChildAt(1);
338 last_amt.setNextFocusForwardId(acc.getId());
339 last_amt.setNextFocusRightId(acc.getId());
340 last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
341 acc.setNextFocusForwardId(amt.getId());
342 acc.setNextFocusRightId(amt.getId());
344 final TableRow row = new TableRow(this);
345 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
346 TableRow.LayoutParams.MATCH_PARENT));
347 row.setGravity(Gravity.BOTTOM);
352 if (focus) acc.requestFocus();
354 hookSwipeListener(row);
355 MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null);
356 hookTextChangeListener(acc);
357 hookTextChangeListener(amt);
361 public void addTransactionAccountFromMenu(MenuItem item) {
362 doAddAccountRow(true);
364 public void resetTransactionFromMenu(MenuItem item) {
367 public void saveTransactionFromMenu(MenuItem item) {
371 // 1) at least two account names
372 // 2) each amount must have account name
373 // 3) amounts must balance to 0, or
374 // 3a) there must be exactly one empty amount
375 // 4) empty accounts with empty amounts are ignored
376 // 5) a row with an empty account name or empty amount is guaranteed to exist
377 @SuppressLint("DefaultLocale")
378 private void check_transaction_submittable() {
379 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
381 int accounts_with_values = 0;
383 int amounts_with_accounts = 0;
385 TextView empty_amount = null;
386 boolean single_empty_amount = false;
387 boolean single_empty_amount_has_account = false;
388 float running_total = 0f;
389 boolean have_description =
390 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
394 for (int i = 0; i < table.getChildCount(); i++) {
395 TableRow row = (TableRow) table.getChildAt(i);
397 TextView acc_name_v = (TextView) row.getChildAt(0);
398 TextView amount_v = (TextView) row.getChildAt(1);
399 String amt = String.valueOf(amount_v.getText());
400 String acc_name = String.valueOf(acc_name_v.getText());
401 acc_name = acc_name.trim();
403 if (!acc_name.isEmpty()) {
406 if (!amt.isEmpty()) {
407 accounts_with_values++;
413 amount_v.setHint(String.format("%1.2f", 0f));
414 if (empty_amount == null) {
415 empty_amount = amount_v;
416 single_empty_amount = true;
417 single_empty_amount_has_account = !acc_name.isEmpty();
419 else if (!acc_name.isEmpty()) single_empty_amount = false;
423 if (!acc_name.isEmpty()) amounts_with_accounts++;
424 running_total += Float.valueOf(amt);
428 if ((empty_rows == 0) &&
429 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
431 doAddAccountRow(false);
434 Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
435 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
436 "single_empty_with_acc=%s", accounts,
437 accounts_with_values, amounts_with_accounts, amounts, running_total,
438 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
440 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
441 (amounts_with_accounts == amounts) &&
442 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
446 fab.setEnabled(true);
450 if (fab != null) fab.hide();
453 if (single_empty_amount) {
454 empty_amount.setHint(String.format("%1.2f",
455 (Math.abs(running_total) > 0.005) ? -running_total : 0f));
459 catch (NumberFormatException e) {
460 if (fab != null) fab.hide();
462 catch (Exception e) {
464 if (fab != null) fab.hide();
469 public void done(String error) {
470 progress.setVisibility(View.INVISIBLE);
471 Log.d("visuals", "hiding progress");
473 if (error == null) resetForm();
474 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
475 BaseTransientBottomBar.LENGTH_LONG).show();
477 toggleAllEditing(true);
478 check_transaction_submittable();
481 private void resetForm() {
483 tvDescription.setText("");
485 tvDescription.requestFocus();
487 while (table.getChildCount() > 2) {
488 table.removeViewAt(2);
490 for (int i = 0; i < 2; i++) {
491 TableRow tr = (TableRow) table.getChildAt(i);
492 if (tr == null) break;
494 ((TextView) tr.getChildAt(0)).setText("");
495 ((TextView) tr.getChildAt(1)).setText("");
499 public void descriptionSelected(String description) {
500 Log.d("descr selected", description);
501 if (!inputStateIsInitial()) return;
503 MobileLedgerProfile currentProfile = Data.profile.get();
504 String accFilter = currentProfile.getPreferredAccountsFilter();
506 ArrayList<String> params = new ArrayList<>();
507 StringBuilder sb = new StringBuilder(
508 "select t.profile, t.id from transactions t where t.description=?");
509 params.add(description);
511 if (accFilter != null) {
512 sb.append(" AND EXISTS (").append("SELECT 1 FROM transaction_accounts ta ")
513 .append("WHERE ta.profile = t.profile").append(" AND ta.transaction_id = t.id")
514 .append(" AND UPPER(ta.account_name) LIKE '%'||?||'%')");
515 params.add(accFilter.toUpperCase());
518 sb.append(" ORDER BY date desc limit 1");
520 final String sql = sb.toString();
522 Log.d("descr", params.toString());
524 try (Cursor c = MLDB.getDatabase().rawQuery(sql, params.toArray(new String[]{}))) {
525 if (!c.moveToNext()) return;
527 String profileUUID = c.getString(0);
528 int transactionId = c.getInt(1);
529 LedgerTransaction tr;
530 try (LockHolder lh = Data.profiles.lockForReading()) {
531 MobileLedgerProfile profile = null;
532 for (int i = 0; i < Data.profiles.size(); i++) {
533 MobileLedgerProfile p = Data.profiles.get(i);
534 if (p.getUuid().equals(profileUUID)) {
539 if (profile == null) throw new RuntimeException(String.format(
540 "Unable to find profile %s, which is supposed to contain " +
541 "transaction %d with description %s", profileUUID, transactionId,
544 tr = profile.loadTransaction(transactionId);
547 table = findViewById(R.id.new_transaction_accounts_table);
548 ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
549 TableRow firstNegative = null;
550 int negativeCount = 0;
551 for (i = 0; i < accounts.size(); i++) {
552 LedgerTransactionAccount acc = accounts.get(i);
553 TableRow row = (TableRow) table.getChildAt(i);
554 if (row == null) row = doAddAccountRow(false);
556 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
557 ((TextView) row.getChildAt(1))
558 .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
560 if (acc.getAmount() < 0.005) {
561 if (firstNegative == null) firstNegative = row;
566 if (negativeCount == 1) {
567 ((TextView) firstNegative.getChildAt(1)).setText(null);
570 check_transaction_submittable();
572 EditText firstAmount = (EditText) ((TableRow) table.getChildAt(0)).getChildAt(1);
573 String amtString = String.valueOf(firstAmount.getText());
574 firstAmount.requestFocus();
575 firstAmount.setSelection(0, amtString.length());
579 private boolean inputStateIsInitial() {
580 table = findViewById(R.id.new_transaction_accounts_table);
582 if (table.getChildCount() != 2) return false;
584 for (int i = 0; i < 2; i++) {
585 TableRow row = (TableRow) table.getChildAt(i);
586 if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
587 if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;
592 private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
594 protected Void doInBackground(Void... voids) {
595 throw new RuntimeException("Simulated crash");