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.MLDB;
61 import java.text.ParseException;
62 import java.util.ArrayList;
63 import java.util.Date;
64 import java.util.List;
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)
76 * TODO: nicer swiping removal with visual feedback
79 public class NewTransactionActivity extends ProfileThemedActivity
80 implements TaskCallback, DescriptionSelectedCallback {
81 private static SaveTransactionTask saver;
82 private TableLayout table;
83 private ProgressBar progress;
84 private FloatingActionButton fab;
85 private TextView tvDate;
86 private AutoCompleteTextView tvDescription;
87 private static boolean isZero(float f) {
88 return (f < 0.005) && (f > -0.005);
91 protected void onCreate(Bundle savedInstanceState) {
92 super.onCreate(savedInstanceState);
94 setContentView(R.layout.activity_new_transaction);
95 Toolbar toolbar = findViewById(R.id.toolbar);
96 setSupportActionBar(toolbar);
97 toolbar.setSubtitle(Data.profile.get().getName());
99 tvDate = findViewById(R.id.new_transaction_date);
100 tvDate.setOnFocusChangeListener((v, hasFocus) -> {
101 if (hasFocus) pickTransactionDate(v);
103 tvDescription = findViewById(R.id.new_transaction_description);
104 MLDB.hookAutocompletionAdapter(this, tvDescription, MLDB.DESCRIPTION_HISTORY_TABLE,
105 "description", false, findViewById(R.id.new_transaction_acc_1), this);
106 hookTextChangeListener(tvDescription);
108 progress = findViewById(R.id.save_transaction_progress);
109 fab = findViewById(R.id.fab);
110 fab.setOnClickListener(v -> saveTransaction());
112 Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
113 table = findViewById(R.id.new_transaction_accounts_table);
114 for (int i = 0; i < table.getChildCount(); i++) {
115 TableRow row = (TableRow) table.getChildAt(i);
116 AutoCompleteTextView tvAccountName = (AutoCompleteTextView) row.getChildAt(0);
117 TextView tvAmount = (TextView) row.getChildAt(1);
118 hookSwipeListener(row);
119 MLDB.hookAutocompletionAdapter(this, tvAccountName, MLDB.ACCOUNTS_TABLE, "name", true,
121 hookTextChangeListener(tvAccountName);
122 hookTextChangeListener(tvAmount);
123 // Log.d("swipe", "hooked to row "+i);
128 public void finish() {
130 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
134 public boolean onOptionsItemSelected(MenuItem item) {
135 switch (item.getItemId()) {
136 case android.R.id.home:
140 return super.onOptionsItemSelected(item);
143 protected void onStart() {
145 if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
147 public void saveTransaction() {
148 if (fab != null) fab.setEnabled(false);
149 toggleAllEditing(false);
150 progress.setVisibility(View.VISIBLE);
153 saver = new SaveTransactionTask(this);
155 String dateString = tvDate.getText().toString();
157 if (dateString.isEmpty()) date = new Date();
158 else date = Globals.parseLedgerDate(dateString);
159 LedgerTransaction tr = new LedgerTransaction(date, tvDescription.getText().toString());
161 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
162 for (int i = 0; i < table.getChildCount(); i++) {
163 TableRow row = (TableRow) table.getChildAt(i);
164 String acc = ((TextView) row.getChildAt(0)).getText().toString();
165 String amt = ((TextView) row.getChildAt(1)).getText().toString();
166 LedgerTransactionAccount item =
167 amt.length() > 0 ? new LedgerTransactionAccount(acc, Float.parseFloat(amt))
168 : new LedgerTransactionAccount(acc);
174 catch (ParseException e) {
175 Log.d("new-transaction", "Parse error", e);
176 Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
177 Toast.LENGTH_LONG).show();
178 tvDate.requestFocus();
180 progress.setVisibility(View.GONE);
181 toggleAllEditing(true);
182 if (fab != null) fab.setEnabled(true);
184 catch (Exception e) {
185 Log.d("new-transaction", "Unknown error", e);
187 progress.setVisibility(View.GONE);
188 toggleAllEditing(true);
189 if (fab != null) fab.setEnabled(true);
192 private void toggleAllEditing(boolean enabled) {
193 tvDate.setEnabled(enabled);
194 tvDescription.setEnabled(enabled);
195 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
196 for (int i = 0; i < table.getChildCount(); i++) {
197 TableRow row = (TableRow) table.getChildAt(i);
198 for (int j = 0; j < row.getChildCount(); j++) {
199 row.getChildAt(j).setEnabled(enabled);
203 private void hookSwipeListener(final TableRow row) {
204 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
205 public void onSwipeLeft() {
206 // Log.d("swipe", "LEFT" + row.getId());
207 if (table.getChildCount() > 2) {
208 TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
209 TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
211 (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
213 (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
215 if (next_acc == null) {
216 prev_amt.setNextFocusRightId(R.id.none);
217 prev_amt.setNextFocusForwardId(R.id.none);
218 prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
221 prev_amt.setNextFocusRightId(next_acc.getId());
222 prev_amt.setNextFocusForwardId(next_acc.getId());
223 prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
226 if (row.hasFocus()) {
227 if (next_acc != null) next_acc.requestFocus();
228 else prev_amt.requestFocus();
231 table.removeView(row);
232 check_transaction_submittable();
233 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
236 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
237 Snackbar.LENGTH_LONG).setAction("Action", null).show();
241 // public boolean performClick(View view, MotionEvent m) {
244 public boolean onTouch(View view, MotionEvent m) {
245 return gestureDetector.onTouchEvent(m);
250 public boolean simulateCrash(MenuItem item) {
251 Log.d("crash", "Will crash intentionally");
252 new AsyncCrasher().execute();
255 public boolean onCreateOptionsMenu(Menu menu) {
256 // Inflate the menu; this adds items to the action bar if it is present.
257 getMenuInflater().inflate(R.menu.new_transaction, menu);
259 if (BuildConfig.DEBUG) {
260 menu.findItem(R.id.action_simulate_crash).setVisible(true);
262 check_transaction_submittable();
267 public void pickTransactionDate(View view) {
268 DialogFragment picker = new DatePickerFragment();
269 picker.show(getSupportFragmentManager(), "datePicker");
272 public int dp2px(float dp) {
273 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
274 getResources().getDisplayMetrics()));
276 private void hookTextChangeListener(final TextView view) {
277 view.addTextChangedListener(new TextWatcher() {
279 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
284 public void onTextChanged(CharSequence s, int start, int before, int count) {
289 public void afterTextChanged(Editable s) {
290 // Log.d("input", "text changed");
291 check_transaction_submittable();
296 private TableRow doAddAccountRow(boolean focus) {
297 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
298 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
299 TableRow.LayoutParams.WRAP_CONTENT, 9f));
300 acc.setHint(R.string.new_transaction_account_hint);
302 acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
303 EditorInfo.IME_FLAG_NAVIGATE_NEXT);
304 acc.setSingleLine(true);
306 final EditText amt = new EditText(this);
307 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
308 TableRow.LayoutParams.MATCH_PARENT, 1f));
309 amt.setHint(R.string.new_transaction_amount_hint);
311 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
312 InputType.TYPE_NUMBER_FLAG_DECIMAL);
313 amt.setMinWidth(dp2px(40));
314 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
315 amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
316 amt.setSelectAllOnFocus(true);
318 // forward navigation support
319 final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
320 final TextView last_amt = (TextView) last_row.getChildAt(1);
321 last_amt.setNextFocusForwardId(acc.getId());
322 last_amt.setNextFocusRightId(acc.getId());
323 last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
324 acc.setNextFocusForwardId(amt.getId());
325 acc.setNextFocusRightId(amt.getId());
327 final TableRow row = new TableRow(this);
328 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
329 TableRow.LayoutParams.MATCH_PARENT));
330 row.setGravity(Gravity.BOTTOM);
335 if (focus) acc.requestFocus();
337 hookSwipeListener(row);
338 MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null);
339 hookTextChangeListener(acc);
340 hookTextChangeListener(amt);
344 public void addTransactionAccountFromMenu(MenuItem item) {
345 doAddAccountRow(true);
347 public void resetTransactionFromMenu(MenuItem item) {
350 public void saveTransactionFromMenu(MenuItem item) {
354 // 1) at least two account names
355 // 2) each amount must have account name
356 // 3) amounts must balance to 0, or
357 // 3a) there must be exactly one empty amount
358 // 4) empty accounts with empty amounts are ignored
359 // 5) a row with an empty account name or empty amount is guaranteed to exist
360 @SuppressLint("DefaultLocale")
361 private void check_transaction_submittable() {
362 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
364 int accounts_with_values = 0;
366 int amounts_with_accounts = 0;
368 TextView empty_amount = null;
369 boolean single_empty_amount = false;
370 boolean single_empty_amount_has_account = false;
371 float running_total = 0f;
372 boolean have_description =
373 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
377 for (int i = 0; i < table.getChildCount(); i++) {
378 TableRow row = (TableRow) table.getChildAt(i);
380 TextView acc_name_v = (TextView) row.getChildAt(0);
381 TextView amount_v = (TextView) row.getChildAt(1);
382 String amt = String.valueOf(amount_v.getText());
383 String acc_name = String.valueOf(acc_name_v.getText());
384 acc_name = acc_name.trim();
386 if (!acc_name.isEmpty()) {
389 if (!amt.isEmpty()) {
390 accounts_with_values++;
396 amount_v.setHint(String.format("%1.2f", 0f));
397 if (empty_amount == null) {
398 empty_amount = amount_v;
399 single_empty_amount = true;
400 single_empty_amount_has_account = !acc_name.isEmpty();
402 else if (!acc_name.isEmpty()) single_empty_amount = false;
406 if (!acc_name.isEmpty()) amounts_with_accounts++;
407 running_total += Float.valueOf(amt);
411 if ((empty_rows == 0) &&
412 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
414 doAddAccountRow(false);
417 Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
418 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
419 "single_empty_with_acc=%s", accounts,
420 accounts_with_values, amounts_with_accounts, amounts, running_total,
421 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
423 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
424 (amounts_with_accounts == amounts) &&
425 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
429 fab.setEnabled(true);
433 if (fab != null) fab.hide();
436 if (single_empty_amount) {
437 empty_amount.setHint(String.format("%1.2f",
438 (Math.abs(running_total) > 0.005) ? -running_total : 0f));
442 catch (NumberFormatException e) {
443 if (fab != null) fab.hide();
445 catch (Exception e) {
447 if (fab != null) fab.hide();
452 public void done(String error) {
453 progress.setVisibility(View.INVISIBLE);
454 Log.d("visuals", "hiding progress");
456 if (error == null) resetForm();
457 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
458 BaseTransientBottomBar.LENGTH_LONG).show();
460 toggleAllEditing(true);
461 check_transaction_submittable();
464 private void resetForm() {
466 tvDescription.setText("");
468 tvDescription.requestFocus();
470 while (table.getChildCount() > 2) {
471 table.removeViewAt(2);
473 for (int i = 0; i < 2; i++) {
474 TableRow tr = (TableRow) table.getChildAt(i);
475 if (tr == null) break;
477 ((TextView) tr.getChildAt(0)).setText("");
478 ((TextView) tr.getChildAt(1)).setText("");
482 public void descriptionSelected(String description) {
483 Log.d("descr selected", description);
484 if (!inputStateIsInitial()) return;
486 try (Cursor c = MLDB.getReadableDatabase().rawQuery(
487 "select profile, id from transactions where description=? order by date desc " +
488 "limit 1", new String[]{description}))
490 if (!c.moveToNext()) return;
492 String profileUUID = c.getString(0);
493 int transactionId = c.getInt(1);
494 List<MobileLedgerProfile> profiles = Data.profiles.getList();
495 MobileLedgerProfile profile = null;
496 for (int i = 0; i < profiles.size(); i++) {
497 MobileLedgerProfile p = profiles.get(i);
498 if (p.getUuid().equals(profileUUID)) {
503 if (profile == null) throw new RuntimeException(String.format(
504 "Unable to find profile %s, which is supposed to contain " +
505 "transaction %d with description %s", profileUUID, transactionId, description));
507 LedgerTransaction tr = profile.loadTransaction(transactionId);
509 table = findViewById(R.id.new_transaction_accounts_table);
510 ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
511 TableRow firstNegative = null;
512 int negativeCount = 0;
513 for (i = 0; i < accounts.size(); i++) {
514 LedgerTransactionAccount acc = accounts.get(i);
515 TableRow row = (TableRow) table.getChildAt(i);
516 if (row == null) row = doAddAccountRow(false);
518 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
519 ((TextView) row.getChildAt(1))
520 .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
522 if (acc.getAmount() < 0.005) {
523 if (firstNegative == null) firstNegative = row;
528 if (negativeCount == 1) {
529 ((TextView) firstNegative.getChildAt(1)).setText(null);
532 check_transaction_submittable();
534 EditText firstAmount = (EditText) ((TableRow) table.getChildAt(0)).getChildAt(1);
535 String amtString = String.valueOf(firstAmount.getText());
536 firstAmount.requestFocus();
537 firstAmount.setSelection(0, amtString.length());
541 private boolean inputStateIsInitial() {
542 table = findViewById(R.id.new_transaction_accounts_table);
544 if (table.getChildCount() != 2) return false;
546 for (int i = 0; i < 2; i++) {
547 TableRow row = (TableRow) table.getChildAt(i);
548 if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
549 if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;
554 private class AsyncCrasher extends AsyncTask<Void, Void, Void>{
556 protected Void doInBackground(Void... voids) {
557 throw new RuntimeException("Simulated crash");