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.SaveTransactionTask;
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 SaveTransactionTask 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 SaveTransactionTask(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 for (int i = 0; i < table.getChildCount(); i++) {
162 TableRow row = (TableRow) table.getChildAt(i);
163 String acc = ((TextView) row.getChildAt(0)).getText().toString();
164 String amt = ((TextView) row.getChildAt(1)).getText().toString();
165 LedgerTransactionAccount item =
166 amt.length() > 0 ? new LedgerTransactionAccount(acc, Float.parseFloat(amt))
167 : new LedgerTransactionAccount(acc);
173 catch (ParseException e) {
174 Log.d("new-transaction", "Parse error", e);
175 Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
176 Toast.LENGTH_LONG).show();
177 tvDate.requestFocus();
179 progress.setVisibility(View.GONE);
180 toggleAllEditing(true);
181 if (fab != null) fab.setEnabled(true);
183 catch (Exception e) {
184 Log.d("new-transaction", "Unknown error", e);
186 progress.setVisibility(View.GONE);
187 toggleAllEditing(true);
188 if (fab != null) fab.setEnabled(true);
191 private void toggleAllEditing(boolean enabled) {
192 tvDate.setEnabled(enabled);
193 tvDescription.setEnabled(enabled);
194 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
195 for (int i = 0; i < table.getChildCount(); i++) {
196 TableRow row = (TableRow) table.getChildAt(i);
197 for (int j = 0; j < row.getChildCount(); j++) {
198 row.getChildAt(j).setEnabled(enabled);
202 private void hookSwipeListener(final TableRow row) {
203 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
204 private void onSwipeAside() {
205 if (table.getChildCount() > 2) {
206 TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
207 TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
209 (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
211 (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
213 if (next_acc == null) {
214 prev_amt.setNextFocusRightId(R.id.none);
215 prev_amt.setNextFocusForwardId(R.id.none);
216 prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
219 prev_amt.setNextFocusRightId(next_acc.getId());
220 prev_amt.setNextFocusForwardId(next_acc.getId());
221 prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
224 if (row.hasFocus()) {
225 if (next_acc != null) next_acc.requestFocus();
226 else prev_amt.requestFocus();
229 table.removeView(row);
230 check_transaction_submittable();
231 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
234 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
235 Snackbar.LENGTH_LONG).setAction("Action", null).show();
238 public void onSwipeLeft() {
241 public void onSwipeRight() {
245 // public boolean performClick(View view, MotionEvent m) {
248 public boolean onTouch(View view, MotionEvent m) {
249 return gestureDetector.onTouchEvent(m);
254 public boolean simulateCrash(MenuItem item) {
255 Log.d("crash", "Will crash intentionally");
256 new AsyncCrasher().execute();
259 public boolean onCreateOptionsMenu(Menu menu) {
260 // Inflate the menu; this adds items to the action bar if it is present.
261 getMenuInflater().inflate(R.menu.new_transaction, menu);
263 if (BuildConfig.DEBUG) {
264 menu.findItem(R.id.action_simulate_crash).setVisible(true);
266 check_transaction_submittable();
271 public void pickTransactionDate(View view) {
272 DialogFragment picker = new DatePickerFragment();
273 picker.show(getSupportFragmentManager(), "datePicker");
276 public int dp2px(float dp) {
277 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
278 getResources().getDisplayMetrics()));
280 private void hookTextChangeListener(final TextView view) {
281 view.addTextChangedListener(new TextWatcher() {
283 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
288 public void onTextChanged(CharSequence s, int start, int before, int count) {
293 public void afterTextChanged(Editable s) {
294 // Log.d("input", "text changed");
295 check_transaction_submittable();
300 private TableRow doAddAccountRow(boolean focus) {
301 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
302 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
303 TableRow.LayoutParams.WRAP_CONTENT, 9f));
304 acc.setHint(R.string.new_transaction_account_hint);
306 acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
307 EditorInfo.IME_FLAG_NAVIGATE_NEXT);
308 acc.setSingleLine(true);
310 final EditText amt = new EditText(this);
311 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
312 TableRow.LayoutParams.MATCH_PARENT, 1f));
313 amt.setHint(R.string.new_transaction_amount_hint);
315 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
316 InputType.TYPE_NUMBER_FLAG_DECIMAL);
317 amt.setMinWidth(dp2px(40));
318 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
319 amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
320 amt.setSelectAllOnFocus(true);
322 // forward navigation support
323 final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
324 final TextView last_amt = (TextView) last_row.getChildAt(1);
325 last_amt.setNextFocusForwardId(acc.getId());
326 last_amt.setNextFocusRightId(acc.getId());
327 last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
328 acc.setNextFocusForwardId(amt.getId());
329 acc.setNextFocusRightId(amt.getId());
331 final TableRow row = new TableRow(this);
332 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
333 TableRow.LayoutParams.MATCH_PARENT));
334 row.setGravity(Gravity.BOTTOM);
339 if (focus) acc.requestFocus();
341 hookSwipeListener(row);
342 MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null);
343 hookTextChangeListener(acc);
344 hookTextChangeListener(amt);
348 public void addTransactionAccountFromMenu(MenuItem item) {
349 doAddAccountRow(true);
351 public void resetTransactionFromMenu(MenuItem item) {
354 public void saveTransactionFromMenu(MenuItem item) {
358 // 1) at least two account names
359 // 2) each amount must have account name
360 // 3) amounts must balance to 0, or
361 // 3a) there must be exactly one empty amount
362 // 4) empty accounts with empty amounts are ignored
363 // 5) a row with an empty account name or empty amount is guaranteed to exist
364 @SuppressLint("DefaultLocale")
365 private void check_transaction_submittable() {
366 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
368 int accounts_with_values = 0;
370 int amounts_with_accounts = 0;
372 TextView empty_amount = null;
373 boolean single_empty_amount = false;
374 boolean single_empty_amount_has_account = false;
375 float running_total = 0f;
376 boolean have_description =
377 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
381 for (int i = 0; i < table.getChildCount(); i++) {
382 TableRow row = (TableRow) table.getChildAt(i);
384 TextView acc_name_v = (TextView) row.getChildAt(0);
385 TextView amount_v = (TextView) row.getChildAt(1);
386 String amt = String.valueOf(amount_v.getText());
387 String acc_name = String.valueOf(acc_name_v.getText());
388 acc_name = acc_name.trim();
390 if (!acc_name.isEmpty()) {
393 if (!amt.isEmpty()) {
394 accounts_with_values++;
400 amount_v.setHint(String.format("%1.2f", 0f));
401 if (empty_amount == null) {
402 empty_amount = amount_v;
403 single_empty_amount = true;
404 single_empty_amount_has_account = !acc_name.isEmpty();
406 else if (!acc_name.isEmpty()) single_empty_amount = false;
410 if (!acc_name.isEmpty()) amounts_with_accounts++;
411 running_total += Float.valueOf(amt);
415 if ((empty_rows == 0) &&
416 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
418 doAddAccountRow(false);
421 Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
422 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
423 "single_empty_with_acc=%s", accounts,
424 accounts_with_values, amounts_with_accounts, amounts, running_total,
425 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
427 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
428 (amounts_with_accounts == amounts) &&
429 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
433 fab.setEnabled(true);
437 if (fab != null) fab.hide();
440 if (single_empty_amount) {
441 empty_amount.setHint(String.format("%1.2f",
442 (Math.abs(running_total) > 0.005) ? -running_total : 0f));
446 catch (NumberFormatException e) {
447 if (fab != null) fab.hide();
449 catch (Exception e) {
451 if (fab != null) fab.hide();
456 public void done(String error) {
457 progress.setVisibility(View.INVISIBLE);
458 Log.d("visuals", "hiding progress");
460 if (error == null) resetForm();
461 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
462 BaseTransientBottomBar.LENGTH_LONG).show();
464 toggleAllEditing(true);
465 check_transaction_submittable();
468 private void resetForm() {
470 tvDescription.setText("");
472 tvDescription.requestFocus();
474 while (table.getChildCount() > 2) {
475 table.removeViewAt(2);
477 for (int i = 0; i < 2; i++) {
478 TableRow tr = (TableRow) table.getChildAt(i);
479 if (tr == null) break;
481 ((TextView) tr.getChildAt(0)).setText("");
482 ((TextView) tr.getChildAt(1)).setText("");
486 public void descriptionSelected(String description) {
487 Log.d("descr selected", description);
488 if (!inputStateIsInitial()) return;
490 MobileLedgerProfile currentProfile = Data.profile.get();
491 String accFilter = currentProfile.getPreferredAccountsFilter();
493 ArrayList<String> params = new ArrayList<>();
494 StringBuilder sb = new StringBuilder(
495 "select t.profile, t.id from transactions t where t.description=?");
496 params.add(description);
498 if (accFilter != null) {
499 sb.append(" AND EXISTS (").append("SELECT 1 FROM transaction_accounts ta ")
500 .append("WHERE ta.profile = t.profile").append(" AND ta.transaction_id = t.id")
501 .append(" AND UPPER(ta.account_name) LIKE '%'||?||'%')");
502 params.add(accFilter.toUpperCase());
505 sb.append(" ORDER BY date desc limit 1");
507 final String sql = sb.toString();
509 Log.d("descr", params.toString());
511 try (Cursor c = MLDB.getDatabase().rawQuery(sql, params.toArray(new String[]{}))) {
512 if (!c.moveToNext()) return;
514 String profileUUID = c.getString(0);
515 int transactionId = c.getInt(1);
516 LedgerTransaction tr;
517 try (LockHolder lh = Data.profiles.lockForReading()) {
518 MobileLedgerProfile profile = null;
519 for (int i = 0; i < Data.profiles.size(); i++) {
520 MobileLedgerProfile p = Data.profiles.get(i);
521 if (p.getUuid().equals(profileUUID)) {
526 if (profile == null) throw new RuntimeException(String.format(
527 "Unable to find profile %s, which is supposed to contain " +
528 "transaction %d with description %s", profileUUID, transactionId,
531 tr = profile.loadTransaction(transactionId);
534 table = findViewById(R.id.new_transaction_accounts_table);
535 ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
536 TableRow firstNegative = null;
537 int negativeCount = 0;
538 for (i = 0; i < accounts.size(); i++) {
539 LedgerTransactionAccount acc = accounts.get(i);
540 TableRow row = (TableRow) table.getChildAt(i);
541 if (row == null) row = doAddAccountRow(false);
543 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
544 ((TextView) row.getChildAt(1))
545 .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
547 if (acc.getAmount() < 0.005) {
548 if (firstNegative == null) firstNegative = row;
553 if (negativeCount == 1) {
554 ((TextView) firstNegative.getChildAt(1)).setText(null);
557 check_transaction_submittable();
559 EditText firstAmount = (EditText) ((TableRow) table.getChildAt(0)).getChildAt(1);
560 String amtString = String.valueOf(firstAmount.getText());
561 firstAmount.requestFocus();
562 firstAmount.setSelection(0, amtString.length());
566 private boolean inputStateIsInitial() {
567 table = findViewById(R.id.new_transaction_accounts_table);
569 if (table.getChildCount() != 2) return false;
571 for (int i = 0; i < 2; i++) {
572 TableRow row = (TableRow) table.getChildAt(i);
573 if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
574 if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;
579 private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
581 protected Void doInBackground(Void... voids) {
582 throw new RuntimeException("Simulated crash");