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)
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 private void onSwipeAside() {
206 if (table.getChildCount() > 2) {
207 TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
208 TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
210 (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
212 (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
214 if (next_acc == null) {
215 prev_amt.setNextFocusRightId(R.id.none);
216 prev_amt.setNextFocusForwardId(R.id.none);
217 prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
220 prev_amt.setNextFocusRightId(next_acc.getId());
221 prev_amt.setNextFocusForwardId(next_acc.getId());
222 prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
225 if (row.hasFocus()) {
226 if (next_acc != null) next_acc.requestFocus();
227 else prev_amt.requestFocus();
230 table.removeView(row);
231 check_transaction_submittable();
232 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
235 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
236 Snackbar.LENGTH_LONG).setAction("Action", null).show();
239 public void onSwipeLeft() {
242 public void onSwipeRight() {
246 // public boolean performClick(View view, MotionEvent m) {
249 public boolean onTouch(View view, MotionEvent m) {
250 return gestureDetector.onTouchEvent(m);
255 public boolean simulateCrash(MenuItem item) {
256 Log.d("crash", "Will crash intentionally");
257 new AsyncCrasher().execute();
260 public boolean onCreateOptionsMenu(Menu menu) {
261 // Inflate the menu; this adds items to the action bar if it is present.
262 getMenuInflater().inflate(R.menu.new_transaction, menu);
264 if (BuildConfig.DEBUG) {
265 menu.findItem(R.id.action_simulate_crash).setVisible(true);
267 check_transaction_submittable();
272 public void pickTransactionDate(View view) {
273 DialogFragment picker = new DatePickerFragment();
274 picker.show(getSupportFragmentManager(), "datePicker");
277 public int dp2px(float dp) {
278 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
279 getResources().getDisplayMetrics()));
281 private void hookTextChangeListener(final TextView view) {
282 view.addTextChangedListener(new TextWatcher() {
284 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
289 public void onTextChanged(CharSequence s, int start, int before, int count) {
294 public void afterTextChanged(Editable s) {
295 // Log.d("input", "text changed");
296 check_transaction_submittable();
301 private TableRow doAddAccountRow(boolean focus) {
302 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
303 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
304 TableRow.LayoutParams.WRAP_CONTENT, 9f));
305 acc.setHint(R.string.new_transaction_account_hint);
307 acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
308 EditorInfo.IME_FLAG_NAVIGATE_NEXT);
309 acc.setSingleLine(true);
311 final EditText amt = new EditText(this);
312 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
313 TableRow.LayoutParams.MATCH_PARENT, 1f));
314 amt.setHint(R.string.new_transaction_amount_hint);
316 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
317 InputType.TYPE_NUMBER_FLAG_DECIMAL);
318 amt.setMinWidth(dp2px(40));
319 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
320 amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
321 amt.setSelectAllOnFocus(true);
323 // forward navigation support
324 final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
325 final TextView last_amt = (TextView) last_row.getChildAt(1);
326 last_amt.setNextFocusForwardId(acc.getId());
327 last_amt.setNextFocusRightId(acc.getId());
328 last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
329 acc.setNextFocusForwardId(amt.getId());
330 acc.setNextFocusRightId(amt.getId());
332 final TableRow row = new TableRow(this);
333 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
334 TableRow.LayoutParams.MATCH_PARENT));
335 row.setGravity(Gravity.BOTTOM);
340 if (focus) acc.requestFocus();
342 hookSwipeListener(row);
343 MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null);
344 hookTextChangeListener(acc);
345 hookTextChangeListener(amt);
349 public void addTransactionAccountFromMenu(MenuItem item) {
350 doAddAccountRow(true);
352 public void resetTransactionFromMenu(MenuItem item) {
355 public void saveTransactionFromMenu(MenuItem item) {
359 // 1) at least two account names
360 // 2) each amount must have account name
361 // 3) amounts must balance to 0, or
362 // 3a) there must be exactly one empty amount
363 // 4) empty accounts with empty amounts are ignored
364 // 5) a row with an empty account name or empty amount is guaranteed to exist
365 @SuppressLint("DefaultLocale")
366 private void check_transaction_submittable() {
367 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
369 int accounts_with_values = 0;
371 int amounts_with_accounts = 0;
373 TextView empty_amount = null;
374 boolean single_empty_amount = false;
375 boolean single_empty_amount_has_account = false;
376 float running_total = 0f;
377 boolean have_description =
378 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
382 for (int i = 0; i < table.getChildCount(); i++) {
383 TableRow row = (TableRow) table.getChildAt(i);
385 TextView acc_name_v = (TextView) row.getChildAt(0);
386 TextView amount_v = (TextView) row.getChildAt(1);
387 String amt = String.valueOf(amount_v.getText());
388 String acc_name = String.valueOf(acc_name_v.getText());
389 acc_name = acc_name.trim();
391 if (!acc_name.isEmpty()) {
394 if (!amt.isEmpty()) {
395 accounts_with_values++;
401 amount_v.setHint(String.format("%1.2f", 0f));
402 if (empty_amount == null) {
403 empty_amount = amount_v;
404 single_empty_amount = true;
405 single_empty_amount_has_account = !acc_name.isEmpty();
407 else if (!acc_name.isEmpty()) single_empty_amount = false;
411 if (!acc_name.isEmpty()) amounts_with_accounts++;
412 running_total += Float.valueOf(amt);
416 if ((empty_rows == 0) &&
417 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
419 doAddAccountRow(false);
422 Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
423 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
424 "single_empty_with_acc=%s", accounts,
425 accounts_with_values, amounts_with_accounts, amounts, running_total,
426 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
428 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
429 (amounts_with_accounts == amounts) &&
430 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
434 fab.setEnabled(true);
438 if (fab != null) fab.hide();
441 if (single_empty_amount) {
442 empty_amount.setHint(String.format("%1.2f",
443 (Math.abs(running_total) > 0.005) ? -running_total : 0f));
447 catch (NumberFormatException e) {
448 if (fab != null) fab.hide();
450 catch (Exception e) {
452 if (fab != null) fab.hide();
457 public void done(String error) {
458 progress.setVisibility(View.INVISIBLE);
459 Log.d("visuals", "hiding progress");
461 if (error == null) resetForm();
462 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
463 BaseTransientBottomBar.LENGTH_LONG).show();
465 toggleAllEditing(true);
466 check_transaction_submittable();
469 private void resetForm() {
471 tvDescription.setText("");
473 tvDescription.requestFocus();
475 while (table.getChildCount() > 2) {
476 table.removeViewAt(2);
478 for (int i = 0; i < 2; i++) {
479 TableRow tr = (TableRow) table.getChildAt(i);
480 if (tr == null) break;
482 ((TextView) tr.getChildAt(0)).setText("");
483 ((TextView) tr.getChildAt(1)).setText("");
487 public void descriptionSelected(String description) {
488 Log.d("descr selected", description);
489 if (!inputStateIsInitial()) return;
491 try (Cursor c = MLDB.getDatabase().rawQuery(
492 "select profile, id from transactions where description=? order by date desc " +
493 "limit 1", new String[]{description}))
495 if (!c.moveToNext()) return;
497 String profileUUID = c.getString(0);
498 int transactionId = c.getInt(1);
499 LedgerTransaction tr;
500 try(LockHolder lh = Data.profiles.lockForReading()) {
501 MobileLedgerProfile profile = null;
502 for (int i = 0; i < Data.profiles.size(); i++) {
503 MobileLedgerProfile p = Data.profiles.get(i);
504 if (p.getUuid().equals(profileUUID)) {
509 if (profile == null) throw new RuntimeException(String.format(
510 "Unable to find profile %s, which is supposed to contain " +
511 "transaction %d with description %s", profileUUID, transactionId,
514 tr = profile.loadTransaction(transactionId);
517 table = findViewById(R.id.new_transaction_accounts_table);
518 ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
519 TableRow firstNegative = null;
520 int negativeCount = 0;
521 for (i = 0; i < accounts.size(); i++) {
522 LedgerTransactionAccount acc = accounts.get(i);
523 TableRow row = (TableRow) table.getChildAt(i);
524 if (row == null) row = doAddAccountRow(false);
526 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
527 ((TextView) row.getChildAt(1))
528 .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
530 if (acc.getAmount() < 0.005) {
531 if (firstNegative == null) firstNegative = row;
536 if (negativeCount == 1) {
537 ((TextView) firstNegative.getChildAt(1)).setText(null);
540 check_transaction_submittable();
542 EditText firstAmount = (EditText) ((TableRow) table.getChildAt(0)).getChildAt(1);
543 String amtString = String.valueOf(firstAmount.getText());
544 firstAmount.requestFocus();
545 firstAmount.setSelection(0, amtString.length());
549 private boolean inputStateIsInitial() {
550 table = findViewById(R.id.new_transaction_accounts_table);
552 if (table.getChildCount() != 2) return false;
554 for (int i = 0; i < 2; i++) {
555 TableRow row = (TableRow) table.getChildAt(i);
556 if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
557 if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;
562 private class AsyncCrasher extends AsyncTask<Void, Void, Void>{
564 protected Void doInBackground(Void... voids) {
565 throw new RuntimeException("Simulated crash");