"Crash app" menu item in the new transaction menu. visible in debug builds only
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionActivity.java
1 /*
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.ui.activity;
19
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;
47
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;
61
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;
68
69 /*
70  * TODO: nicer progress while transaction is submitted
71  * TODO: reports
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
75  *  */
76
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);
87     }
88     @Override
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());
95
96         tvDate = findViewById(R.id.new_transaction_date);
97         tvDate.setOnFocusChangeListener((v, hasFocus) -> {
98             if (hasFocus) pickTransactionDate(v);
99         });
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);
104
105         progress = findViewById(R.id.save_transaction_progress);
106         fab = findViewById(R.id.fab);
107         fab.setOnClickListener(v -> saveTransaction());
108
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,
117                     tvAmount, null);
118             hookTextChangeListener(tvAccountName);
119             hookTextChangeListener(tvAmount);
120 //            Log.d("swipe", "hooked to row "+i);
121         }
122     }
123
124     @Override
125     public void finish() {
126         super.finish();
127         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
128     }
129
130     @Override
131     public boolean onOptionsItemSelected(MenuItem item) {
132         switch (item.getItemId()) {
133             case android.R.id.home:
134                 finish();
135                 return true;
136         }
137         return super.onOptionsItemSelected(item);
138     }
139     @Override
140     protected void onStart() {
141         super.onStart();
142         if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
143     }
144     public void saveTransaction() {
145         if (fab != null) fab.setEnabled(false);
146         toggleAllEditing(false);
147         progress.setVisibility(View.VISIBLE);
148         try {
149
150             saver = new SaveTransactionTask(this);
151
152             String dateString = tvDate.getText().toString();
153             Date date;
154             if (dateString.isEmpty()) date = new Date();
155             else date = Globals.parseLedgerDate(dateString);
156             LedgerTransaction tr = new LedgerTransaction(date, tvDescription.getText().toString());
157
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);
166
167                 tr.addAccount(item);
168             }
169             saver.execute(tr);
170         }
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();
176
177             progress.setVisibility(View.GONE);
178             toggleAllEditing(true);
179             if (fab != null) fab.setEnabled(true);
180         }
181         catch (Exception e) {
182             Log.d("new-transaction", "Unknown error", e);
183
184             progress.setVisibility(View.GONE);
185             toggleAllEditing(true);
186             if (fab != null) fab.setEnabled(true);
187         }
188     }
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);
197             }
198         }
199     }
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);
207                     TextView prev_amt =
208                             (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
209                     TextView next_acc =
210                             (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
211
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);
216                     }
217                     else {
218                         prev_amt.setNextFocusRightId(next_acc.getId());
219                         prev_amt.setNextFocusForwardId(next_acc.getId());
220                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
221                     }
222
223                     if (row.hasFocus()) {
224                         if (next_acc != null) next_acc.requestFocus();
225                         else prev_amt.requestFocus();
226                     }
227
228                     table.removeView(row);
229                     check_transaction_submittable();
230 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
231                 }
232                 else {
233                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
234                             Snackbar.LENGTH_LONG).setAction("Action", null).show();
235                 }
236             }
237             //            @Override
238 //            public boolean performClick(View view, MotionEvent m) {
239 //                return true;
240 //            }
241             public boolean onTouch(View view, MotionEvent m) {
242                 return gestureDetector.onTouchEvent(m);
243             }
244         });
245     }
246
247     public boolean simulateCrash(MenuItem item) {
248         Log.d("crash", "Will crash intentionally");
249         new AsyncCrasher().execute();
250         return true;
251     }
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);
255
256         if (BuildConfig.DEBUG) {
257             menu.findItem(R.id.action_simulate_crash).setVisible(true);
258         }
259         check_transaction_submittable();
260
261         return true;
262     }
263
264     public void pickTransactionDate(View view) {
265         DialogFragment picker = new DatePickerFragment();
266         picker.show(getSupportFragmentManager(), "datePicker");
267     }
268
269     public int dp2px(float dp) {
270         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
271                 getResources().getDisplayMetrics()));
272     }
273     private void hookTextChangeListener(final TextView view) {
274         view.addTextChangedListener(new TextWatcher() {
275             @Override
276             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
277
278             }
279
280             @Override
281             public void onTextChanged(CharSequence s, int start, int before, int count) {
282
283             }
284
285             @Override
286             public void afterTextChanged(Editable s) {
287 //                Log.d("input", "text changed");
288                 check_transaction_submittable();
289             }
290         });
291
292     }
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);
298         acc.setWidth(0);
299         acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
300                           EditorInfo.IME_FLAG_NAVIGATE_NEXT);
301         acc.setSingleLine(true);
302
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);
307         amt.setWidth(0);
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);
314
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());
323
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);
328         row.addView(acc);
329         row.addView(amt);
330         table.addView(row);
331
332         if (focus) acc.requestFocus();
333
334         hookSwipeListener(row);
335         MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null);
336         hookTextChangeListener(acc);
337         hookTextChangeListener(amt);
338
339         return row;
340     }
341     public void addTransactionAccountFromMenu(MenuItem item) {
342         doAddAccountRow(true);
343     }
344     public void resetTransactionFromMenu(MenuItem item) {
345         resetForm();
346     }
347     public void saveTransactionFromMenu(MenuItem item) {
348         saveTransaction();
349     }
350     // rules:
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);
360         int accounts = 0;
361         int accounts_with_values = 0;
362         int amounts = 0;
363         int amounts_with_accounts = 0;
364         int empty_rows = 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()
371                         .isEmpty();
372
373         try {
374             for (int i = 0; i < table.getChildCount(); i++) {
375                 TableRow row = (TableRow) table.getChildAt(i);
376
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();
382
383                 if (!acc_name.isEmpty()) {
384                     accounts++;
385
386                     if (!amt.isEmpty()) {
387                         accounts_with_values++;
388                     }
389                 }
390                 else empty_rows++;
391
392                 if (amt.isEmpty()) {
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();
398                     }
399                     else if (!acc_name.isEmpty()) single_empty_amount = false;
400                 }
401                 else {
402                     amounts++;
403                     if (!acc_name.isEmpty()) amounts_with_accounts++;
404                     running_total += Float.valueOf(amt);
405                 }
406             }
407
408             if ((empty_rows == 0) &&
409                 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
410             {
411                 doAddAccountRow(false);
412             }
413
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"));
419
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)))
423             {
424                 if (fab != null) {
425                     fab.show();
426                     fab.setEnabled(true);
427                 }
428             }
429             else {
430                 if (fab != null) fab.hide();
431             }
432
433             if (single_empty_amount) {
434                 empty_amount.setHint(String.format("%1.2f",
435                         (Math.abs(running_total) > 0.005) ? -running_total : 0f));
436             }
437
438         }
439         catch (NumberFormatException e) {
440             if (fab != null) fab.hide();
441         }
442         catch (Exception e) {
443             e.printStackTrace();
444             if (fab != null) fab.hide();
445         }
446     }
447
448     @Override
449     public void done(String error) {
450         progress.setVisibility(View.INVISIBLE);
451         Log.d("visuals", "hiding progress");
452
453         if (error == null) resetForm();
454         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
455                 BaseTransientBottomBar.LENGTH_LONG).show();
456
457         toggleAllEditing(true);
458         check_transaction_submittable();
459     }
460
461     private void resetForm() {
462         tvDate.setText("");
463         tvDescription.setText("");
464
465         tvDescription.requestFocus();
466
467         while (table.getChildCount() > 2) {
468             table.removeViewAt(2);
469         }
470         for (int i = 0; i < 2; i++) {
471             TableRow tr = (TableRow) table.getChildAt(i);
472             if (tr == null) break;
473
474             ((TextView) tr.getChildAt(0)).setText("");
475             ((TextView) tr.getChildAt(1)).setText("");
476         }
477     }
478     @Override
479     public void descriptionSelected(String description) {
480         Log.d("descr selected", description);
481         if (!inputStateIsInitial()) return;
482
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}))
486         {
487             if (!c.moveToNext()) return;
488
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)) {
496                     profile = p;
497                     break;
498                 }
499             }
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));
503
504             LedgerTransaction tr = profile.loadTransaction(transactionId);
505             int i = 0;
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);
514
515                 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
516                 ((TextView) row.getChildAt(1))
517                         .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
518
519                 if (acc.getAmount() < 0.005) {
520                     if (firstNegative == null) firstNegative = row;
521                     negativeCount++;
522                 }
523             }
524
525             if (negativeCount == 1) {
526                 ((TextView) firstNegative.getChildAt(1)).setText(null);
527             }
528
529             check_transaction_submittable();
530
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());
535         }
536
537     }
538     private boolean inputStateIsInitial() {
539         table = findViewById(R.id.new_transaction_accounts_table);
540
541         if (table.getChildCount() != 2) return false;
542
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;
547         }
548
549         return true;
550     }
551     private class AsyncCrasher extends AsyncTask<Void, Void, Void>{
552         @Override
553         protected Void doInBackground(Void... voids) {
554             throw new RuntimeException("Simulated crash");
555         }
556     }
557 }