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.app.AppCompatActivity;
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.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;
69 * TODO: nicer progress while transaction is submitted
71 * TODO: get rid of the custom session/cookie and auth code?
72 * (the last problem with the POST was the missing content-length header)
73 * TODO: nicer swiping removal with visual feedback
76 public class NewTransactionActivity extends AppCompatActivity
77 implements TaskCallback, DescriptionSelectedCallback {
78 private static SaveTransactionTask saver;
79 private TableLayout table;
80 private ProgressBar progress;
81 private FloatingActionButton fab;
82 private TextView tvDate;
83 private AutoCompleteTextView tvDescription;
84 private static boolean isZero(float f) {
85 return (f < 0.005) && (f > -0.005);
88 protected void onCreate(Bundle savedInstanceState) {
89 super.onCreate(savedInstanceState);
90 setContentView(R.layout.activity_new_transaction);
91 Toolbar toolbar = findViewById(R.id.toolbar);
92 setSupportActionBar(toolbar);
93 toolbar.setSubtitle(Data.profile.get().getName());
95 tvDate = findViewById(R.id.new_transaction_date);
96 tvDate.setOnFocusChangeListener((v, hasFocus) -> {
97 if (hasFocus) pickTransactionDate(v);
99 tvDescription = findViewById(R.id.new_transaction_description);
100 MLDB.hookAutocompletionAdapter(this, tvDescription, MLDB.DESCRIPTION_HISTORY_TABLE,
101 "description", false, findViewById(R.id.new_transaction_acc_1), this);
102 hookTextChangeListener(tvDescription);
104 progress = findViewById(R.id.save_transaction_progress);
105 fab = findViewById(R.id.fab);
106 fab.setOnClickListener(v -> saveTransaction());
108 Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
109 table = findViewById(R.id.new_transaction_accounts_table);
110 for (int i = 0; i < table.getChildCount(); i++) {
111 TableRow row = (TableRow) table.getChildAt(i);
112 AutoCompleteTextView tvAccountName = (AutoCompleteTextView) row.getChildAt(0);
113 TextView tvAmount = (TextView) row.getChildAt(1);
114 hookSwipeListener(row);
115 MLDB.hookAutocompletionAdapter(this, tvAccountName, MLDB.ACCOUNTS_TABLE, "name", true,
117 hookTextChangeListener(tvAccountName);
118 hookTextChangeListener(tvAmount);
119 // Log.d("swipe", "hooked to row "+i);
124 public void finish() {
126 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
130 public boolean onOptionsItemSelected(MenuItem item) {
131 switch (item.getItemId()) {
132 case android.R.id.home:
136 return super.onOptionsItemSelected(item);
139 protected void onStart() {
141 if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
143 public void saveTransaction() {
144 if (fab != null) fab.setEnabled(false);
145 toggleAllEditing(false);
146 progress.setVisibility(View.VISIBLE);
149 saver = new SaveTransactionTask(this);
151 String dateString = tvDate.getText().toString();
153 if (dateString.isEmpty()) date = new Date();
154 else date = Globals.parseLedgerDate(dateString);
155 LedgerTransaction tr = new LedgerTransaction(date, tvDescription.getText().toString());
157 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
158 for (int i = 0; i < table.getChildCount(); i++) {
159 TableRow row = (TableRow) table.getChildAt(i);
160 String acc = ((TextView) row.getChildAt(0)).getText().toString();
161 String amt = ((TextView) row.getChildAt(1)).getText().toString();
162 LedgerTransactionAccount item =
163 amt.length() > 0 ? new LedgerTransactionAccount(acc, Float.parseFloat(amt))
164 : new LedgerTransactionAccount(acc);
170 catch (ParseException e) {
171 Log.d("new-transaction", "Parse error", e);
172 Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
173 Toast.LENGTH_LONG).show();
174 tvDate.requestFocus();
176 progress.setVisibility(View.GONE);
177 toggleAllEditing(true);
178 if (fab != null) fab.setEnabled(true);
180 catch (Exception e) {
181 Log.d("new-transaction", "Unknown error", e);
183 progress.setVisibility(View.GONE);
184 toggleAllEditing(true);
185 if (fab != null) fab.setEnabled(true);
188 private void toggleAllEditing(boolean enabled) {
189 tvDate.setEnabled(enabled);
190 tvDescription.setEnabled(enabled);
191 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
192 for (int i = 0; i < table.getChildCount(); i++) {
193 TableRow row = (TableRow) table.getChildAt(i);
194 for (int j = 0; j < row.getChildCount(); j++) {
195 row.getChildAt(j).setEnabled(enabled);
199 private void hookSwipeListener(final TableRow row) {
200 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
201 public void onSwipeLeft() {
202 // Log.d("swipe", "LEFT" + row.getId());
203 if (table.getChildCount() > 2) {
204 TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
205 TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
207 (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
209 (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
211 if (next_acc == null) {
212 prev_amt.setNextFocusRightId(R.id.none);
213 prev_amt.setNextFocusForwardId(R.id.none);
214 prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
217 prev_amt.setNextFocusRightId(next_acc.getId());
218 prev_amt.setNextFocusForwardId(next_acc.getId());
219 prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
222 if (row.hasFocus()) {
223 if (next_acc != null) next_acc.requestFocus();
224 else prev_amt.requestFocus();
227 table.removeView(row);
228 check_transaction_submittable();
229 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
232 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
233 Snackbar.LENGTH_LONG).setAction("Action", null).show();
237 // public boolean performClick(View view, MotionEvent m) {
240 public boolean onTouch(View view, MotionEvent m) {
241 return gestureDetector.onTouchEvent(m);
246 public boolean onCreateOptionsMenu(Menu menu) {
247 // Inflate the menu; this adds items to the action bar if it is present.
248 getMenuInflater().inflate(R.menu.new_transaction, menu);
250 check_transaction_submittable();
255 public void pickTransactionDate(View view) {
256 DialogFragment picker = new DatePickerFragment();
257 picker.show(getSupportFragmentManager(), "datePicker");
260 public int dp2px(float dp) {
261 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
262 getResources().getDisplayMetrics()));
264 private void hookTextChangeListener(final TextView view) {
265 view.addTextChangedListener(new TextWatcher() {
267 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
272 public void onTextChanged(CharSequence s, int start, int before, int count) {
277 public void afterTextChanged(Editable s) {
278 // Log.d("input", "text changed");
279 check_transaction_submittable();
284 private TableRow doAddAccountRow(boolean focus) {
285 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
286 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
287 TableRow.LayoutParams.WRAP_CONTENT, 9f));
288 acc.setHint(R.string.new_transaction_account_hint);
290 acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
291 EditorInfo.IME_FLAG_NAVIGATE_NEXT);
292 acc.setSingleLine(true);
294 final EditText amt = new EditText(this);
295 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
296 TableRow.LayoutParams.MATCH_PARENT, 1f));
297 amt.setHint(R.string.new_transaction_amount_hint);
299 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
300 InputType.TYPE_NUMBER_FLAG_DECIMAL);
301 amt.setMinWidth(dp2px(40));
302 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
303 amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
304 amt.setSelectAllOnFocus(true);
306 // forward navigation support
307 final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
308 final TextView last_amt = (TextView) last_row.getChildAt(1);
309 last_amt.setNextFocusForwardId(acc.getId());
310 last_amt.setNextFocusRightId(acc.getId());
311 last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
312 acc.setNextFocusForwardId(amt.getId());
313 acc.setNextFocusRightId(amt.getId());
315 final TableRow row = new TableRow(this);
316 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
317 TableRow.LayoutParams.MATCH_PARENT));
318 row.setGravity(Gravity.BOTTOM);
323 if (focus) acc.requestFocus();
325 hookSwipeListener(row);
326 MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null);
327 hookTextChangeListener(acc);
328 hookTextChangeListener(amt);
332 public void addTransactionAccountFromMenu(MenuItem item) {
333 doAddAccountRow(true);
335 public void resetTransactionFromMenu(MenuItem item) {
338 public void saveTransactionFromMenu(MenuItem item) {
342 // 1) at least two account names
343 // 2) each amount must have account name
344 // 3) amounts must balance to 0, or
345 // 3a) there must be exactly one empty amount
346 // 4) empty accounts with empty amounts are ignored
347 // 5) a row with an empty account name or empty amount is guaranteed to exist
348 @SuppressLint("DefaultLocale")
349 private void check_transaction_submittable() {
350 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
352 int accounts_with_values = 0;
354 int amounts_with_accounts = 0;
356 TextView empty_amount = null;
357 boolean single_empty_amount = false;
358 boolean single_empty_amount_has_account = false;
359 float running_total = 0f;
360 boolean have_description =
361 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
365 for (int i = 0; i < table.getChildCount(); i++) {
366 TableRow row = (TableRow) table.getChildAt(i);
368 TextView acc_name_v = (TextView) row.getChildAt(0);
369 TextView amount_v = (TextView) row.getChildAt(1);
370 String amt = String.valueOf(amount_v.getText());
371 String acc_name = String.valueOf(acc_name_v.getText());
372 acc_name = acc_name.trim();
374 if (!acc_name.isEmpty()) {
377 if (!amt.isEmpty()) {
378 accounts_with_values++;
384 amount_v.setHint(String.format("%1.2f", 0f));
385 if (empty_amount == null) {
386 empty_amount = amount_v;
387 single_empty_amount = true;
388 single_empty_amount_has_account = !acc_name.isEmpty();
390 else if (!acc_name.isEmpty()) single_empty_amount = false;
394 if (!acc_name.isEmpty()) amounts_with_accounts++;
395 running_total += Float.valueOf(amt);
399 if ((empty_rows == 0) &&
400 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
402 doAddAccountRow(false);
405 Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
406 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
407 "single_empty_with_acc=%s", accounts,
408 accounts_with_values, amounts_with_accounts, amounts, running_total,
409 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
411 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
412 (amounts_with_accounts == amounts) &&
413 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
417 fab.setEnabled(true);
421 if (fab != null) fab.hide();
424 if (single_empty_amount) {
425 empty_amount.setHint(String.format("%1.2f",
426 (Math.abs(running_total) > 0.005) ? -running_total : 0f));
430 catch (NumberFormatException e) {
431 if (fab != null) fab.hide();
433 catch (Exception e) {
435 if (fab != null) fab.hide();
440 public void done(String error) {
441 progress.setVisibility(View.INVISIBLE);
442 Log.d("visuals", "hiding progress");
444 if (error == null) resetForm();
445 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
446 BaseTransientBottomBar.LENGTH_LONG).show();
448 toggleAllEditing(true);
449 check_transaction_submittable();
452 private void resetForm() {
454 tvDescription.setText("");
456 tvDescription.requestFocus();
458 while (table.getChildCount() > 2) {
459 table.removeViewAt(2);
461 for (int i = 0; i < 2; i++) {
462 TableRow tr = (TableRow) table.getChildAt(i);
463 if (tr == null) break;
465 ((TextView) tr.getChildAt(0)).setText("");
466 ((TextView) tr.getChildAt(1)).setText("");
470 public void descriptionSelected(String description) {
471 Log.d("descr selected", description);
472 if (!inputStateIsInitial()) return;
474 try (Cursor c = MLDB.getReadableDatabase().rawQuery(
475 "select profile, id from transactions where description=? order by date desc " +
476 "limit 1", new String[]{description}))
478 if (!c.moveToNext()) return;
480 String profileUUID = c.getString(0);
481 int transactionId = c.getInt(1);
482 List<MobileLedgerProfile> profiles = Data.profiles.getList();
483 MobileLedgerProfile profile = null;
484 for (int i = 0; i < profiles.size(); i++) {
485 MobileLedgerProfile p = profiles.get(i);
486 if (p.getUuid().equals(profileUUID)) {
491 if (profile == null) throw new RuntimeException(String.format(
492 "Unable to find profile %s, which is supposed to contain " +
493 "transaction %d with description %s", profileUUID, transactionId, description));
495 LedgerTransaction tr = profile.loadTransaction(transactionId);
497 table = findViewById(R.id.new_transaction_accounts_table);
498 ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
499 TableRow firstNegative = null;
500 int negativeCount = 0;
501 for (i = 0; i < accounts.size(); i++) {
502 LedgerTransactionAccount acc = accounts.get(i);
503 TableRow row = (TableRow) table.getChildAt(i);
504 if (row == null) row = doAddAccountRow(false);
506 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
507 ((TextView) row.getChildAt(1))
508 .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
510 if (acc.getAmount() < 0.005) {
511 if (firstNegative == null) firstNegative = row;
516 if (negativeCount == 1) {
517 ((TextView) firstNegative.getChildAt(1)).setText(null);
520 check_transaction_submittable();
522 EditText firstAmount = (EditText) ((TableRow) table.getChildAt(0)).getChildAt(1);
523 String amtString = String.valueOf(firstAmount.getText());
524 firstAmount.requestFocus();
525 firstAmount.setSelection(0, amtString.length());
529 private boolean inputStateIsInitial() {
530 table = findViewById(R.id.new_transaction_accounts_table);
532 if (table.getChildCount() != 2) return false;
534 for (int i = 0; i < 2; i++) {
535 TableRow row = (TableRow) table.getChildAt(i);
536 if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
537 if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;