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.Bundle;
23 import android.support.design.widget.BaseTransientBottomBar;
24 import android.support.design.widget.FloatingActionButton;
25 import android.support.design.widget.Snackbar;
26 import android.support.v4.app.DialogFragment;
27 import android.support.v7.widget.Toolbar;
28 import android.text.Editable;
29 import android.text.InputType;
30 import android.text.TextWatcher;
31 import android.util.Log;
32 import android.util.TypedValue;
33 import android.view.Gravity;
34 import android.view.Menu;
35 import android.view.MenuItem;
36 import android.view.MotionEvent;
37 import android.view.View;
38 import android.view.inputmethod.EditorInfo;
39 import android.widget.AutoCompleteTextView;
40 import android.widget.EditText;
41 import android.widget.ProgressBar;
42 import android.widget.TableLayout;
43 import android.widget.TableRow;
44 import android.widget.TextView;
45 import android.widget.Toast;
47 import net.ktnx.mobileledger.R;
48 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
49 import net.ktnx.mobileledger.async.SaveTransactionTask;
50 import net.ktnx.mobileledger.async.TaskCallback;
51 import net.ktnx.mobileledger.model.Data;
52 import net.ktnx.mobileledger.model.LedgerTransaction;
53 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
54 import net.ktnx.mobileledger.model.MobileLedgerProfile;
55 import net.ktnx.mobileledger.ui.DatePickerFragment;
56 import net.ktnx.mobileledger.ui.OnSwipeTouchListener;
57 import net.ktnx.mobileledger.utils.Globals;
58 import net.ktnx.mobileledger.utils.MLDB;
60 import java.text.ParseException;
61 import java.util.ArrayList;
62 import java.util.Date;
63 import java.util.List;
64 import java.util.Locale;
65 import java.util.Objects;
68 * TODO: nicer progress while transaction is submitted
70 * TODO: get rid of the custom session/cookie and auth code?
71 * (the last problem with the POST was the missing content-length header)
72 * TODO: nicer swiping removal with visual feedback
75 public class NewTransactionActivity extends CrashReportingActivity
76 implements TaskCallback, DescriptionSelectedCallback {
77 private static SaveTransactionTask saver;
78 private TableLayout table;
79 private ProgressBar progress;
80 private FloatingActionButton fab;
81 private TextView tvDate;
82 private AutoCompleteTextView tvDescription;
83 private static boolean isZero(float f) {
84 return (f < 0.005) && (f > -0.005);
87 protected void onCreate(Bundle savedInstanceState) {
88 super.onCreate(savedInstanceState);
89 setContentView(R.layout.activity_new_transaction);
90 Toolbar toolbar = findViewById(R.id.toolbar);
91 setSupportActionBar(toolbar);
92 toolbar.setSubtitle(Data.profile.get().getName());
94 tvDate = findViewById(R.id.new_transaction_date);
95 tvDate.setOnFocusChangeListener((v, hasFocus) -> {
96 if (hasFocus) pickTransactionDate(v);
98 tvDescription = findViewById(R.id.new_transaction_description);
99 MLDB.hookAutocompletionAdapter(this, tvDescription, MLDB.DESCRIPTION_HISTORY_TABLE,
100 "description", false, findViewById(R.id.new_transaction_acc_1), this);
101 hookTextChangeListener(tvDescription);
103 progress = findViewById(R.id.save_transaction_progress);
104 fab = findViewById(R.id.fab);
105 fab.setOnClickListener(v -> saveTransaction());
107 Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
108 table = findViewById(R.id.new_transaction_accounts_table);
109 for (int i = 0; i < table.getChildCount(); i++) {
110 TableRow row = (TableRow) table.getChildAt(i);
111 AutoCompleteTextView tvAccountName = (AutoCompleteTextView) row.getChildAt(0);
112 TextView tvAmount = (TextView) row.getChildAt(1);
113 hookSwipeListener(row);
114 MLDB.hookAutocompletionAdapter(this, tvAccountName, MLDB.ACCOUNTS_TABLE, "name", true,
116 hookTextChangeListener(tvAccountName);
117 hookTextChangeListener(tvAmount);
118 // Log.d("swipe", "hooked to row "+i);
123 public void finish() {
125 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
129 public boolean onOptionsItemSelected(MenuItem item) {
130 switch (item.getItemId()) {
131 case android.R.id.home:
135 return super.onOptionsItemSelected(item);
138 protected void onStart() {
140 if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
142 public void saveTransaction() {
143 if (fab != null) fab.setEnabled(false);
144 toggleAllEditing(false);
145 progress.setVisibility(View.VISIBLE);
148 saver = new SaveTransactionTask(this);
150 String dateString = tvDate.getText().toString();
152 if (dateString.isEmpty()) date = new Date();
153 else date = Globals.parseLedgerDate(dateString);
154 LedgerTransaction tr = new LedgerTransaction(date, tvDescription.getText().toString());
156 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
157 for (int i = 0; i < table.getChildCount(); i++) {
158 TableRow row = (TableRow) table.getChildAt(i);
159 String acc = ((TextView) row.getChildAt(0)).getText().toString();
160 String amt = ((TextView) row.getChildAt(1)).getText().toString();
161 LedgerTransactionAccount item =
162 amt.length() > 0 ? new LedgerTransactionAccount(acc, Float.parseFloat(amt))
163 : new LedgerTransactionAccount(acc);
169 catch (ParseException e) {
170 Log.d("new-transaction", "Parse error", e);
171 Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
172 Toast.LENGTH_LONG).show();
173 tvDate.requestFocus();
175 progress.setVisibility(View.GONE);
176 toggleAllEditing(true);
177 if (fab != null) fab.setEnabled(true);
179 catch (Exception e) {
180 Log.d("new-transaction", "Unknown error", e);
182 progress.setVisibility(View.GONE);
183 toggleAllEditing(true);
184 if (fab != null) fab.setEnabled(true);
187 private void toggleAllEditing(boolean enabled) {
188 tvDate.setEnabled(enabled);
189 tvDescription.setEnabled(enabled);
190 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
191 for (int i = 0; i < table.getChildCount(); i++) {
192 TableRow row = (TableRow) table.getChildAt(i);
193 for (int j = 0; j < row.getChildCount(); j++) {
194 row.getChildAt(j).setEnabled(enabled);
198 private void hookSwipeListener(final TableRow row) {
199 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
200 public void onSwipeLeft() {
201 // Log.d("swipe", "LEFT" + row.getId());
202 if (table.getChildCount() > 2) {
203 TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
204 TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
206 (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
208 (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
210 if (next_acc == null) {
211 prev_amt.setNextFocusRightId(R.id.none);
212 prev_amt.setNextFocusForwardId(R.id.none);
213 prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
216 prev_amt.setNextFocusRightId(next_acc.getId());
217 prev_amt.setNextFocusForwardId(next_acc.getId());
218 prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
221 if (row.hasFocus()) {
222 if (next_acc != null) next_acc.requestFocus();
223 else prev_amt.requestFocus();
226 table.removeView(row);
227 check_transaction_submittable();
228 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
231 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
232 Snackbar.LENGTH_LONG).setAction("Action", null).show();
236 // public boolean performClick(View view, MotionEvent m) {
239 public boolean onTouch(View view, MotionEvent m) {
240 return gestureDetector.onTouchEvent(m);
245 public boolean onCreateOptionsMenu(Menu menu) {
246 // Inflate the menu; this adds items to the action bar if it is present.
247 getMenuInflater().inflate(R.menu.new_transaction, menu);
249 check_transaction_submittable();
254 public void pickTransactionDate(View view) {
255 DialogFragment picker = new DatePickerFragment();
256 picker.show(getSupportFragmentManager(), "datePicker");
259 public int dp2px(float dp) {
260 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
261 getResources().getDisplayMetrics()));
263 private void hookTextChangeListener(final TextView view) {
264 view.addTextChangedListener(new TextWatcher() {
266 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
271 public void onTextChanged(CharSequence s, int start, int before, int count) {
276 public void afterTextChanged(Editable s) {
277 // Log.d("input", "text changed");
278 check_transaction_submittable();
283 private TableRow doAddAccountRow(boolean focus) {
284 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
285 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
286 TableRow.LayoutParams.WRAP_CONTENT, 9f));
287 acc.setHint(R.string.new_transaction_account_hint);
289 acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
290 EditorInfo.IME_FLAG_NAVIGATE_NEXT);
291 acc.setSingleLine(true);
293 final EditText amt = new EditText(this);
294 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
295 TableRow.LayoutParams.MATCH_PARENT, 1f));
296 amt.setHint(R.string.new_transaction_amount_hint);
298 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
299 InputType.TYPE_NUMBER_FLAG_DECIMAL);
300 amt.setMinWidth(dp2px(40));
301 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
302 amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
303 amt.setSelectAllOnFocus(true);
305 // forward navigation support
306 final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
307 final TextView last_amt = (TextView) last_row.getChildAt(1);
308 last_amt.setNextFocusForwardId(acc.getId());
309 last_amt.setNextFocusRightId(acc.getId());
310 last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
311 acc.setNextFocusForwardId(amt.getId());
312 acc.setNextFocusRightId(amt.getId());
314 final TableRow row = new TableRow(this);
315 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
316 TableRow.LayoutParams.MATCH_PARENT));
317 row.setGravity(Gravity.BOTTOM);
322 if (focus) acc.requestFocus();
324 hookSwipeListener(row);
325 MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null);
326 hookTextChangeListener(acc);
327 hookTextChangeListener(amt);
331 public void addTransactionAccountFromMenu(MenuItem item) {
332 doAddAccountRow(true);
334 public void resetTransactionFromMenu(MenuItem item) {
337 public void saveTransactionFromMenu(MenuItem item) {
341 // 1) at least two account names
342 // 2) each amount must have account name
343 // 3) amounts must balance to 0, or
344 // 3a) there must be exactly one empty amount
345 // 4) empty accounts with empty amounts are ignored
346 // 5) a row with an empty account name or empty amount is guaranteed to exist
347 @SuppressLint("DefaultLocale")
348 private void check_transaction_submittable() {
349 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
351 int accounts_with_values = 0;
353 int amounts_with_accounts = 0;
355 TextView empty_amount = null;
356 boolean single_empty_amount = false;
357 boolean single_empty_amount_has_account = false;
358 float running_total = 0f;
359 boolean have_description =
360 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
364 for (int i = 0; i < table.getChildCount(); i++) {
365 TableRow row = (TableRow) table.getChildAt(i);
367 TextView acc_name_v = (TextView) row.getChildAt(0);
368 TextView amount_v = (TextView) row.getChildAt(1);
369 String amt = String.valueOf(amount_v.getText());
370 String acc_name = String.valueOf(acc_name_v.getText());
371 acc_name = acc_name.trim();
373 if (!acc_name.isEmpty()) {
376 if (!amt.isEmpty()) {
377 accounts_with_values++;
383 amount_v.setHint(String.format("%1.2f", 0f));
384 if (empty_amount == null) {
385 empty_amount = amount_v;
386 single_empty_amount = true;
387 single_empty_amount_has_account = !acc_name.isEmpty();
389 else if (!acc_name.isEmpty()) single_empty_amount = false;
393 if (!acc_name.isEmpty()) amounts_with_accounts++;
394 running_total += Float.valueOf(amt);
398 if ((empty_rows == 0) &&
399 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
401 doAddAccountRow(false);
404 Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
405 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
406 "single_empty_with_acc=%s", accounts,
407 accounts_with_values, amounts_with_accounts, amounts, running_total,
408 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
410 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
411 (amounts_with_accounts == amounts) &&
412 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
416 fab.setEnabled(true);
420 if (fab != null) fab.hide();
423 if (single_empty_amount) {
424 empty_amount.setHint(String.format("%1.2f",
425 (Math.abs(running_total) > 0.005) ? -running_total : 0f));
429 catch (NumberFormatException e) {
430 if (fab != null) fab.hide();
432 catch (Exception e) {
434 if (fab != null) fab.hide();
439 public void done(String error) {
440 progress.setVisibility(View.INVISIBLE);
441 Log.d("visuals", "hiding progress");
443 if (error == null) resetForm();
444 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
445 BaseTransientBottomBar.LENGTH_LONG).show();
447 toggleAllEditing(true);
448 check_transaction_submittable();
451 private void resetForm() {
453 tvDescription.setText("");
455 tvDescription.requestFocus();
457 while (table.getChildCount() > 2) {
458 table.removeViewAt(2);
460 for (int i = 0; i < 2; i++) {
461 TableRow tr = (TableRow) table.getChildAt(i);
462 if (tr == null) break;
464 ((TextView) tr.getChildAt(0)).setText("");
465 ((TextView) tr.getChildAt(1)).setText("");
469 public void descriptionSelected(String description) {
470 Log.d("descr selected", description);
471 if (!inputStateIsInitial()) return;
473 try (Cursor c = MLDB.getReadableDatabase().rawQuery(
474 "select profile, id from transactions where description=? order by date desc " +
475 "limit 1", new String[]{description}))
477 if (!c.moveToNext()) return;
479 String profileUUID = c.getString(0);
480 int transactionId = c.getInt(1);
481 List<MobileLedgerProfile> profiles = Data.profiles.getList();
482 MobileLedgerProfile profile = null;
483 for (int i = 0; i < profiles.size(); i++) {
484 MobileLedgerProfile p = profiles.get(i);
485 if (p.getUuid().equals(profileUUID)) {
490 if (profile == null) throw new RuntimeException(String.format(
491 "Unable to find profile %s, which is supposed to contain " +
492 "transaction %d with description %s", profileUUID, transactionId, description));
494 LedgerTransaction tr = profile.loadTransaction(transactionId);
496 table = findViewById(R.id.new_transaction_accounts_table);
497 ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
498 TableRow firstNegative = null;
499 int negativeCount = 0;
500 for (i = 0; i < accounts.size(); i++) {
501 LedgerTransactionAccount acc = accounts.get(i);
502 TableRow row = (TableRow) table.getChildAt(i);
503 if (row == null) row = doAddAccountRow(false);
505 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
506 ((TextView) row.getChildAt(1))
507 .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
509 if (acc.getAmount() < 0.005) {
510 if (firstNegative == null) firstNegative = row;
515 if (negativeCount == 1) {
516 ((TextView) firstNegative.getChildAt(1)).setText(null);
519 check_transaction_submittable();
521 EditText firstAmount = (EditText) ((TableRow) table.getChildAt(0)).getChildAt(1);
522 String amtString = String.valueOf(firstAmount.getText());
523 firstAmount.requestFocus();
524 firstAmount.setSelection(0, amtString.length());
528 private boolean inputStateIsInitial() {
529 table = findViewById(R.id.new_transaction_accounts_table);
531 if (table.getChildCount() != 2) return false;
533 for (int i = 0; i < 2; i++) {
534 TableRow row = (TableRow) table.getChildAt(i);
535 if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
536 if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;