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.support.design.widget.BaseTransientBottomBar;
25 import android.support.design.widget.FloatingActionButton;
26 import android.support.design.widget.Snackbar;
27 import android.support.v4.app.DialogFragment;
28 import android.support.v7.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);
91 setContentView(R.layout.activity_new_transaction);
92 Toolbar toolbar = findViewById(R.id.toolbar);
93 setSupportActionBar(toolbar);
94 toolbar.setSubtitle(Data.profile.get().getName());
96 tvDate = findViewById(R.id.new_transaction_date);
97 tvDate.setOnFocusChangeListener((v, hasFocus) -> {
98 if (hasFocus) pickTransactionDate(v);
100 tvDescription = findViewById(R.id.new_transaction_description);
101 MLDB.hookAutocompletionAdapter(this, tvDescription, MLDB.DESCRIPTION_HISTORY_TABLE,
102 "description", false, findViewById(R.id.new_transaction_acc_1), this);
103 hookTextChangeListener(tvDescription);
105 progress = findViewById(R.id.save_transaction_progress);
106 fab = findViewById(R.id.fab);
107 fab.setOnClickListener(v -> saveTransaction());
109 Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
110 table = findViewById(R.id.new_transaction_accounts_table);
111 for (int i = 0; i < table.getChildCount(); i++) {
112 TableRow row = (TableRow) table.getChildAt(i);
113 AutoCompleteTextView tvAccountName = (AutoCompleteTextView) row.getChildAt(0);
114 TextView tvAmount = (TextView) row.getChildAt(1);
115 hookSwipeListener(row);
116 MLDB.hookAutocompletionAdapter(this, tvAccountName, MLDB.ACCOUNTS_TABLE, "name", true,
118 hookTextChangeListener(tvAccountName);
119 hookTextChangeListener(tvAmount);
120 // Log.d("swipe", "hooked to row "+i);
125 public void finish() {
127 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
131 public boolean onOptionsItemSelected(MenuItem item) {
132 switch (item.getItemId()) {
133 case android.R.id.home:
137 return super.onOptionsItemSelected(item);
140 protected void onStart() {
142 if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
144 public void saveTransaction() {
145 if (fab != null) fab.setEnabled(false);
146 toggleAllEditing(false);
147 progress.setVisibility(View.VISIBLE);
150 saver = new SaveTransactionTask(this);
152 String dateString = tvDate.getText().toString();
154 if (dateString.isEmpty()) date = new Date();
155 else date = Globals.parseLedgerDate(dateString);
156 LedgerTransaction tr = new LedgerTransaction(date, tvDescription.getText().toString());
158 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
159 for (int i = 0; i < table.getChildCount(); i++) {
160 TableRow row = (TableRow) table.getChildAt(i);
161 String acc = ((TextView) row.getChildAt(0)).getText().toString();
162 String amt = ((TextView) row.getChildAt(1)).getText().toString();
163 LedgerTransactionAccount item =
164 amt.length() > 0 ? new LedgerTransactionAccount(acc, Float.parseFloat(amt))
165 : new LedgerTransactionAccount(acc);
171 catch (ParseException e) {
172 Log.d("new-transaction", "Parse error", e);
173 Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
174 Toast.LENGTH_LONG).show();
175 tvDate.requestFocus();
177 progress.setVisibility(View.GONE);
178 toggleAllEditing(true);
179 if (fab != null) fab.setEnabled(true);
181 catch (Exception e) {
182 Log.d("new-transaction", "Unknown error", e);
184 progress.setVisibility(View.GONE);
185 toggleAllEditing(true);
186 if (fab != null) fab.setEnabled(true);
189 private void toggleAllEditing(boolean enabled) {
190 tvDate.setEnabled(enabled);
191 tvDescription.setEnabled(enabled);
192 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
193 for (int i = 0; i < table.getChildCount(); i++) {
194 TableRow row = (TableRow) table.getChildAt(i);
195 for (int j = 0; j < row.getChildCount(); j++) {
196 row.getChildAt(j).setEnabled(enabled);
200 private void hookSwipeListener(final TableRow row) {
201 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
202 public void onSwipeLeft() {
203 // Log.d("swipe", "LEFT" + row.getId());
204 if (table.getChildCount() > 2) {
205 TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
206 TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
208 (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
210 (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
212 if (next_acc == null) {
213 prev_amt.setNextFocusRightId(R.id.none);
214 prev_amt.setNextFocusForwardId(R.id.none);
215 prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
218 prev_amt.setNextFocusRightId(next_acc.getId());
219 prev_amt.setNextFocusForwardId(next_acc.getId());
220 prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
223 if (row.hasFocus()) {
224 if (next_acc != null) next_acc.requestFocus();
225 else prev_amt.requestFocus();
228 table.removeView(row);
229 check_transaction_submittable();
230 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
233 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
234 Snackbar.LENGTH_LONG).setAction("Action", null).show();
238 // public boolean performClick(View view, MotionEvent m) {
241 public boolean onTouch(View view, MotionEvent m) {
242 return gestureDetector.onTouchEvent(m);
247 public boolean simulateCrash(MenuItem item) {
248 Log.d("crash", "Will crash intentionally");
249 new AsyncCrasher().execute();
252 public boolean onCreateOptionsMenu(Menu menu) {
253 // Inflate the menu; this adds items to the action bar if it is present.
254 getMenuInflater().inflate(R.menu.new_transaction, menu);
256 if (BuildConfig.DEBUG) {
257 menu.findItem(R.id.action_simulate_crash).setVisible(true);
259 check_transaction_submittable();
264 public void pickTransactionDate(View view) {
265 DialogFragment picker = new DatePickerFragment();
266 picker.show(getSupportFragmentManager(), "datePicker");
269 public int dp2px(float dp) {
270 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
271 getResources().getDisplayMetrics()));
273 private void hookTextChangeListener(final TextView view) {
274 view.addTextChangedListener(new TextWatcher() {
276 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
281 public void onTextChanged(CharSequence s, int start, int before, int count) {
286 public void afterTextChanged(Editable s) {
287 // Log.d("input", "text changed");
288 check_transaction_submittable();
293 private TableRow doAddAccountRow(boolean focus) {
294 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
295 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
296 TableRow.LayoutParams.WRAP_CONTENT, 9f));
297 acc.setHint(R.string.new_transaction_account_hint);
299 acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
300 EditorInfo.IME_FLAG_NAVIGATE_NEXT);
301 acc.setSingleLine(true);
303 final EditText amt = new EditText(this);
304 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
305 TableRow.LayoutParams.MATCH_PARENT, 1f));
306 amt.setHint(R.string.new_transaction_amount_hint);
308 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
309 InputType.TYPE_NUMBER_FLAG_DECIMAL);
310 amt.setMinWidth(dp2px(40));
311 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
312 amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
313 amt.setSelectAllOnFocus(true);
315 // forward navigation support
316 final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
317 final TextView last_amt = (TextView) last_row.getChildAt(1);
318 last_amt.setNextFocusForwardId(acc.getId());
319 last_amt.setNextFocusRightId(acc.getId());
320 last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
321 acc.setNextFocusForwardId(amt.getId());
322 acc.setNextFocusRightId(amt.getId());
324 final TableRow row = new TableRow(this);
325 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
326 TableRow.LayoutParams.MATCH_PARENT));
327 row.setGravity(Gravity.BOTTOM);
332 if (focus) acc.requestFocus();
334 hookSwipeListener(row);
335 MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null);
336 hookTextChangeListener(acc);
337 hookTextChangeListener(amt);
341 public void addTransactionAccountFromMenu(MenuItem item) {
342 doAddAccountRow(true);
344 public void resetTransactionFromMenu(MenuItem item) {
347 public void saveTransactionFromMenu(MenuItem item) {
351 // 1) at least two account names
352 // 2) each amount must have account name
353 // 3) amounts must balance to 0, or
354 // 3a) there must be exactly one empty amount
355 // 4) empty accounts with empty amounts are ignored
356 // 5) a row with an empty account name or empty amount is guaranteed to exist
357 @SuppressLint("DefaultLocale")
358 private void check_transaction_submittable() {
359 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
361 int accounts_with_values = 0;
363 int amounts_with_accounts = 0;
365 TextView empty_amount = null;
366 boolean single_empty_amount = false;
367 boolean single_empty_amount_has_account = false;
368 float running_total = 0f;
369 boolean have_description =
370 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
374 for (int i = 0; i < table.getChildCount(); i++) {
375 TableRow row = (TableRow) table.getChildAt(i);
377 TextView acc_name_v = (TextView) row.getChildAt(0);
378 TextView amount_v = (TextView) row.getChildAt(1);
379 String amt = String.valueOf(amount_v.getText());
380 String acc_name = String.valueOf(acc_name_v.getText());
381 acc_name = acc_name.trim();
383 if (!acc_name.isEmpty()) {
386 if (!amt.isEmpty()) {
387 accounts_with_values++;
393 amount_v.setHint(String.format("%1.2f", 0f));
394 if (empty_amount == null) {
395 empty_amount = amount_v;
396 single_empty_amount = true;
397 single_empty_amount_has_account = !acc_name.isEmpty();
399 else if (!acc_name.isEmpty()) single_empty_amount = false;
403 if (!acc_name.isEmpty()) amounts_with_accounts++;
404 running_total += Float.valueOf(amt);
408 if ((empty_rows == 0) &&
409 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
411 doAddAccountRow(false);
414 Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
415 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
416 "single_empty_with_acc=%s", accounts,
417 accounts_with_values, amounts_with_accounts, amounts, running_total,
418 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
420 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
421 (amounts_with_accounts == amounts) &&
422 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
426 fab.setEnabled(true);
430 if (fab != null) fab.hide();
433 if (single_empty_amount) {
434 empty_amount.setHint(String.format("%1.2f",
435 (Math.abs(running_total) > 0.005) ? -running_total : 0f));
439 catch (NumberFormatException e) {
440 if (fab != null) fab.hide();
442 catch (Exception e) {
444 if (fab != null) fab.hide();
449 public void done(String error) {
450 progress.setVisibility(View.INVISIBLE);
451 Log.d("visuals", "hiding progress");
453 if (error == null) resetForm();
454 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
455 BaseTransientBottomBar.LENGTH_LONG).show();
457 toggleAllEditing(true);
458 check_transaction_submittable();
461 private void resetForm() {
463 tvDescription.setText("");
465 tvDescription.requestFocus();
467 while (table.getChildCount() > 2) {
468 table.removeViewAt(2);
470 for (int i = 0; i < 2; i++) {
471 TableRow tr = (TableRow) table.getChildAt(i);
472 if (tr == null) break;
474 ((TextView) tr.getChildAt(0)).setText("");
475 ((TextView) tr.getChildAt(1)).setText("");
479 public void descriptionSelected(String description) {
480 Log.d("descr selected", description);
481 if (!inputStateIsInitial()) return;
483 try (Cursor c = MLDB.getReadableDatabase().rawQuery(
484 "select profile, id from transactions where description=? order by date desc " +
485 "limit 1", new String[]{description}))
487 if (!c.moveToNext()) return;
489 String profileUUID = c.getString(0);
490 int transactionId = c.getInt(1);
491 List<MobileLedgerProfile> profiles = Data.profiles.getList();
492 MobileLedgerProfile profile = null;
493 for (int i = 0; i < profiles.size(); i++) {
494 MobileLedgerProfile p = profiles.get(i);
495 if (p.getUuid().equals(profileUUID)) {
500 if (profile == null) throw new RuntimeException(String.format(
501 "Unable to find profile %s, which is supposed to contain " +
502 "transaction %d with description %s", profileUUID, transactionId, description));
504 LedgerTransaction tr = profile.loadTransaction(transactionId);
506 table = findViewById(R.id.new_transaction_accounts_table);
507 ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
508 TableRow firstNegative = null;
509 int negativeCount = 0;
510 for (i = 0; i < accounts.size(); i++) {
511 LedgerTransactionAccount acc = accounts.get(i);
512 TableRow row = (TableRow) table.getChildAt(i);
513 if (row == null) row = doAddAccountRow(false);
515 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
516 ((TextView) row.getChildAt(1))
517 .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
519 if (acc.getAmount() < 0.005) {
520 if (firstNegative == null) firstNegative = row;
525 if (negativeCount == 1) {
526 ((TextView) firstNegative.getChildAt(1)).setText(null);
529 check_transaction_submittable();
531 EditText firstAmount = (EditText) ((TableRow) table.getChildAt(0)).getChildAt(1);
532 String amtString = String.valueOf(firstAmount.getText());
533 firstAmount.requestFocus();
534 firstAmount.setSelection(0, amtString.length());
538 private boolean inputStateIsInitial() {
539 table = findViewById(R.id.new_transaction_accounts_table);
541 if (table.getChildCount() != 2) return false;
543 for (int i = 0; i < 2; i++) {
544 TableRow row = (TableRow) table.getChildAt(i);
545 if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
546 if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;
551 private class AsyncCrasher extends AsyncTask<Void, Void, Void>{
553 protected Void doInBackground(Void... voids) {
554 throw new RuntimeException("Simulated crash");