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 com.google.android.material.snackbar.BaseTransientBottomBar;
25 import com.google.android.material.floatingactionbutton.FloatingActionButton;
26 import com.google.android.material.snackbar.Snackbar;
27 import androidx.fragment.app.DialogFragment;
28 import androidx.appcompat.widget.Toolbar;
29 import android.text.Editable;
30 import android.text.InputType;
31 import android.text.TextWatcher;
32 import android.util.Log;
33 import android.util.TypedValue;
34 import android.view.Gravity;
35 import android.view.Menu;
36 import android.view.MenuItem;
37 import android.view.MotionEvent;
38 import android.view.View;
39 import android.view.inputmethod.EditorInfo;
40 import android.widget.AutoCompleteTextView;
41 import android.widget.EditText;
42 import android.widget.ProgressBar;
43 import android.widget.TableLayout;
44 import android.widget.TableRow;
45 import android.widget.TextView;
46 import android.widget.Toast;
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.SaveTransactionTask;
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.List;
66 import java.util.Locale;
67 import java.util.Objects;
70 * TODO: nicer progress while transaction is submitted
72 * TODO: get rid of the custom session/cookie and auth code?
73 * (the last problem with the POST was the missing content-length header)
74 * TODO: nicer swiping removal with visual feedback
77 public class NewTransactionActivity extends CrashReportingActivity
78 implements TaskCallback, DescriptionSelectedCallback {
79 private static SaveTransactionTask saver;
80 private TableLayout table;
81 private ProgressBar progress;
82 private FloatingActionButton fab;
83 private TextView tvDate;
84 private AutoCompleteTextView tvDescription;
85 private static boolean isZero(float f) {
86 return (f < 0.005) && (f > -0.005);
89 protected void onCreate(Bundle savedInstanceState) {
90 super.onCreate(savedInstanceState);
92 setContentView(R.layout.activity_new_transaction);
93 Toolbar toolbar = findViewById(R.id.toolbar);
94 setSupportActionBar(toolbar);
95 toolbar.setSubtitle(Data.profile.get().getName());
97 tvDate = findViewById(R.id.new_transaction_date);
98 tvDate.setOnFocusChangeListener((v, hasFocus) -> {
99 if (hasFocus) pickTransactionDate(v);
101 tvDescription = findViewById(R.id.new_transaction_description);
102 MLDB.hookAutocompletionAdapter(this, tvDescription, MLDB.DESCRIPTION_HISTORY_TABLE,
103 "description", false, findViewById(R.id.new_transaction_acc_1), this);
104 hookTextChangeListener(tvDescription);
106 progress = findViewById(R.id.save_transaction_progress);
107 fab = findViewById(R.id.fab);
108 fab.setOnClickListener(v -> saveTransaction());
110 Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
111 table = findViewById(R.id.new_transaction_accounts_table);
112 for (int i = 0; i < table.getChildCount(); i++) {
113 TableRow row = (TableRow) table.getChildAt(i);
114 AutoCompleteTextView tvAccountName = (AutoCompleteTextView) row.getChildAt(0);
115 TextView tvAmount = (TextView) row.getChildAt(1);
116 hookSwipeListener(row);
117 MLDB.hookAutocompletionAdapter(this, tvAccountName, MLDB.ACCOUNTS_TABLE, "name", true,
119 hookTextChangeListener(tvAccountName);
120 hookTextChangeListener(tvAmount);
121 // Log.d("swipe", "hooked to row "+i);
126 public void finish() {
128 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
132 public boolean onOptionsItemSelected(MenuItem item) {
133 switch (item.getItemId()) {
134 case android.R.id.home:
138 return super.onOptionsItemSelected(item);
141 protected void onStart() {
143 if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
145 public void saveTransaction() {
146 if (fab != null) fab.setEnabled(false);
147 toggleAllEditing(false);
148 progress.setVisibility(View.VISIBLE);
151 saver = new SaveTransactionTask(this);
153 String dateString = tvDate.getText().toString();
155 if (dateString.isEmpty()) date = new Date();
156 else date = Globals.parseLedgerDate(dateString);
157 LedgerTransaction tr = new LedgerTransaction(date, tvDescription.getText().toString());
159 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
160 for (int i = 0; i < table.getChildCount(); i++) {
161 TableRow row = (TableRow) table.getChildAt(i);
162 String acc = ((TextView) row.getChildAt(0)).getText().toString();
163 String amt = ((TextView) row.getChildAt(1)).getText().toString();
164 LedgerTransactionAccount item =
165 amt.length() > 0 ? new LedgerTransactionAccount(acc, Float.parseFloat(amt))
166 : new LedgerTransactionAccount(acc);
172 catch (ParseException e) {
173 Log.d("new-transaction", "Parse error", e);
174 Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
175 Toast.LENGTH_LONG).show();
176 tvDate.requestFocus();
178 progress.setVisibility(View.GONE);
179 toggleAllEditing(true);
180 if (fab != null) fab.setEnabled(true);
182 catch (Exception e) {
183 Log.d("new-transaction", "Unknown error", e);
185 progress.setVisibility(View.GONE);
186 toggleAllEditing(true);
187 if (fab != null) fab.setEnabled(true);
190 private void toggleAllEditing(boolean enabled) {
191 tvDate.setEnabled(enabled);
192 tvDescription.setEnabled(enabled);
193 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
194 for (int i = 0; i < table.getChildCount(); i++) {
195 TableRow row = (TableRow) table.getChildAt(i);
196 for (int j = 0; j < row.getChildCount(); j++) {
197 row.getChildAt(j).setEnabled(enabled);
201 private void hookSwipeListener(final TableRow row) {
202 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
203 public void onSwipeLeft() {
204 // Log.d("swipe", "LEFT" + row.getId());
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();
239 // public boolean performClick(View view, MotionEvent m) {
242 public boolean onTouch(View view, MotionEvent m) {
243 return gestureDetector.onTouchEvent(m);
248 public boolean simulateCrash(MenuItem item) {
249 Log.d("crash", "Will crash intentionally");
250 new AsyncCrasher().execute();
253 public boolean onCreateOptionsMenu(Menu menu) {
254 // Inflate the menu; this adds items to the action bar if it is present.
255 getMenuInflater().inflate(R.menu.new_transaction, menu);
257 if (BuildConfig.DEBUG) {
258 menu.findItem(R.id.action_simulate_crash).setVisible(true);
260 check_transaction_submittable();
265 public void pickTransactionDate(View view) {
266 DialogFragment picker = new DatePickerFragment();
267 picker.show(getSupportFragmentManager(), "datePicker");
270 public int dp2px(float dp) {
271 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
272 getResources().getDisplayMetrics()));
274 private void hookTextChangeListener(final TextView view) {
275 view.addTextChangedListener(new TextWatcher() {
277 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
282 public void onTextChanged(CharSequence s, int start, int before, int count) {
287 public void afterTextChanged(Editable s) {
288 // Log.d("input", "text changed");
289 check_transaction_submittable();
294 private TableRow doAddAccountRow(boolean focus) {
295 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
296 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
297 TableRow.LayoutParams.WRAP_CONTENT, 9f));
298 acc.setHint(R.string.new_transaction_account_hint);
300 acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
301 EditorInfo.IME_FLAG_NAVIGATE_NEXT);
302 acc.setSingleLine(true);
304 final EditText amt = new EditText(this);
305 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
306 TableRow.LayoutParams.MATCH_PARENT, 1f));
307 amt.setHint(R.string.new_transaction_amount_hint);
309 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
310 InputType.TYPE_NUMBER_FLAG_DECIMAL);
311 amt.setMinWidth(dp2px(40));
312 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
313 amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
314 amt.setSelectAllOnFocus(true);
316 // forward navigation support
317 final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
318 final TextView last_amt = (TextView) last_row.getChildAt(1);
319 last_amt.setNextFocusForwardId(acc.getId());
320 last_amt.setNextFocusRightId(acc.getId());
321 last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
322 acc.setNextFocusForwardId(amt.getId());
323 acc.setNextFocusRightId(amt.getId());
325 final TableRow row = new TableRow(this);
326 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
327 TableRow.LayoutParams.MATCH_PARENT));
328 row.setGravity(Gravity.BOTTOM);
333 if (focus) acc.requestFocus();
335 hookSwipeListener(row);
336 MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null);
337 hookTextChangeListener(acc);
338 hookTextChangeListener(amt);
342 public void addTransactionAccountFromMenu(MenuItem item) {
343 doAddAccountRow(true);
345 public void resetTransactionFromMenu(MenuItem item) {
348 public void saveTransactionFromMenu(MenuItem item) {
352 // 1) at least two account names
353 // 2) each amount must have account name
354 // 3) amounts must balance to 0, or
355 // 3a) there must be exactly one empty amount
356 // 4) empty accounts with empty amounts are ignored
357 // 5) a row with an empty account name or empty amount is guaranteed to exist
358 @SuppressLint("DefaultLocale")
359 private void check_transaction_submittable() {
360 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
362 int accounts_with_values = 0;
364 int amounts_with_accounts = 0;
366 TextView empty_amount = null;
367 boolean single_empty_amount = false;
368 boolean single_empty_amount_has_account = false;
369 float running_total = 0f;
370 boolean have_description =
371 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
375 for (int i = 0; i < table.getChildCount(); i++) {
376 TableRow row = (TableRow) table.getChildAt(i);
378 TextView acc_name_v = (TextView) row.getChildAt(0);
379 TextView amount_v = (TextView) row.getChildAt(1);
380 String amt = String.valueOf(amount_v.getText());
381 String acc_name = String.valueOf(acc_name_v.getText());
382 acc_name = acc_name.trim();
384 if (!acc_name.isEmpty()) {
387 if (!amt.isEmpty()) {
388 accounts_with_values++;
394 amount_v.setHint(String.format("%1.2f", 0f));
395 if (empty_amount == null) {
396 empty_amount = amount_v;
397 single_empty_amount = true;
398 single_empty_amount_has_account = !acc_name.isEmpty();
400 else if (!acc_name.isEmpty()) single_empty_amount = false;
404 if (!acc_name.isEmpty()) amounts_with_accounts++;
405 running_total += Float.valueOf(amt);
409 if ((empty_rows == 0) &&
410 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
412 doAddAccountRow(false);
415 Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
416 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
417 "single_empty_with_acc=%s", accounts,
418 accounts_with_values, amounts_with_accounts, amounts, running_total,
419 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
421 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
422 (amounts_with_accounts == amounts) &&
423 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
427 fab.setEnabled(true);
431 if (fab != null) fab.hide();
434 if (single_empty_amount) {
435 empty_amount.setHint(String.format("%1.2f",
436 (Math.abs(running_total) > 0.005) ? -running_total : 0f));
440 catch (NumberFormatException e) {
441 if (fab != null) fab.hide();
443 catch (Exception e) {
445 if (fab != null) fab.hide();
450 public void done(String error) {
451 progress.setVisibility(View.INVISIBLE);
452 Log.d("visuals", "hiding progress");
454 if (error == null) resetForm();
455 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
456 BaseTransientBottomBar.LENGTH_LONG).show();
458 toggleAllEditing(true);
459 check_transaction_submittable();
462 private void resetForm() {
464 tvDescription.setText("");
466 tvDescription.requestFocus();
468 while (table.getChildCount() > 2) {
469 table.removeViewAt(2);
471 for (int i = 0; i < 2; i++) {
472 TableRow tr = (TableRow) table.getChildAt(i);
473 if (tr == null) break;
475 ((TextView) tr.getChildAt(0)).setText("");
476 ((TextView) tr.getChildAt(1)).setText("");
480 public void descriptionSelected(String description) {
481 Log.d("descr selected", description);
482 if (!inputStateIsInitial()) return;
484 try (Cursor c = MLDB.getReadableDatabase().rawQuery(
485 "select profile, id from transactions where description=? order by date desc " +
486 "limit 1", new String[]{description}))
488 if (!c.moveToNext()) return;
490 String profileUUID = c.getString(0);
491 int transactionId = c.getInt(1);
492 List<MobileLedgerProfile> profiles = Data.profiles.getList();
493 MobileLedgerProfile profile = null;
494 for (int i = 0; i < profiles.size(); i++) {
495 MobileLedgerProfile p = profiles.get(i);
496 if (p.getUuid().equals(profileUUID)) {
501 if (profile == null) throw new RuntimeException(String.format(
502 "Unable to find profile %s, which is supposed to contain " +
503 "transaction %d with description %s", profileUUID, transactionId, description));
505 LedgerTransaction tr = profile.loadTransaction(transactionId);
507 table = findViewById(R.id.new_transaction_accounts_table);
508 ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
509 TableRow firstNegative = null;
510 int negativeCount = 0;
511 for (i = 0; i < accounts.size(); i++) {
512 LedgerTransactionAccount acc = accounts.get(i);
513 TableRow row = (TableRow) table.getChildAt(i);
514 if (row == null) row = doAddAccountRow(false);
516 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
517 ((TextView) row.getChildAt(1))
518 .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
520 if (acc.getAmount() < 0.005) {
521 if (firstNegative == null) firstNegative = row;
526 if (negativeCount == 1) {
527 ((TextView) firstNegative.getChildAt(1)).setText(null);
530 check_transaction_submittable();
532 EditText firstAmount = (EditText) ((TableRow) table.getChildAt(0)).getChildAt(1);
533 String amtString = String.valueOf(firstAmount.getText());
534 firstAmount.requestFocus();
535 firstAmount.setSelection(0, amtString.length());
539 private boolean inputStateIsInitial() {
540 table = findViewById(R.id.new_transaction_accounts_table);
542 if (table.getChildCount() != 2) return false;
544 for (int i = 0; i < 2; i++) {
545 TableRow row = (TableRow) table.getChildAt(i);
546 if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
547 if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;
552 private class AsyncCrasher extends AsyncTask<Void, Void, Void>{
554 protected Void doInBackground(Void... voids) {
555 throw new RuntimeException("Simulated crash");