new transaction: remove account on right swipe too
[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.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;
42
43 import com.google.android.material.floatingactionbutton.FloatingActionButton;
44 import com.google.android.material.snackbar.BaseTransientBottomBar;
45 import com.google.android.material.snackbar.Snackbar;
46
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;
61
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;
67
68 import androidx.appcompat.widget.Toolbar;
69 import androidx.fragment.app.DialogFragment;
70
71 /*
72  * TODO: nicer progress while transaction is submitted
73  * TODO: reports
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
77  *  */
78
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);
89     }
90     @Override
91     protected void onCreate(Bundle savedInstanceState) {
92         super.onCreate(savedInstanceState);
93
94         setContentView(R.layout.activity_new_transaction);
95         Toolbar toolbar = findViewById(R.id.toolbar);
96         setSupportActionBar(toolbar);
97         toolbar.setSubtitle(Data.profile.get().getName());
98
99         tvDate = findViewById(R.id.new_transaction_date);
100         tvDate.setOnFocusChangeListener((v, hasFocus) -> {
101             if (hasFocus) pickTransactionDate(v);
102         });
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);
107
108         progress = findViewById(R.id.save_transaction_progress);
109         fab = findViewById(R.id.fab);
110         fab.setOnClickListener(v -> saveTransaction());
111
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,
120                     tvAmount, null);
121             hookTextChangeListener(tvAccountName);
122             hookTextChangeListener(tvAmount);
123 //            Log.d("swipe", "hooked to row "+i);
124         }
125     }
126
127     @Override
128     public void finish() {
129         super.finish();
130         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
131     }
132
133     @Override
134     public boolean onOptionsItemSelected(MenuItem item) {
135         switch (item.getItemId()) {
136             case android.R.id.home:
137                 finish();
138                 return true;
139         }
140         return super.onOptionsItemSelected(item);
141     }
142     @Override
143     protected void onStart() {
144         super.onStart();
145         if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
146     }
147     public void saveTransaction() {
148         if (fab != null) fab.setEnabled(false);
149         toggleAllEditing(false);
150         progress.setVisibility(View.VISIBLE);
151         try {
152
153             saver = new SaveTransactionTask(this);
154
155             String dateString = tvDate.getText().toString();
156             Date date;
157             if (dateString.isEmpty()) date = new Date();
158             else date = Globals.parseLedgerDate(dateString);
159             LedgerTransaction tr = new LedgerTransaction(date, tvDescription.getText().toString());
160
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);
169
170                 tr.addAccount(item);
171             }
172             saver.execute(tr);
173         }
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();
179
180             progress.setVisibility(View.GONE);
181             toggleAllEditing(true);
182             if (fab != null) fab.setEnabled(true);
183         }
184         catch (Exception e) {
185             Log.d("new-transaction", "Unknown error", e);
186
187             progress.setVisibility(View.GONE);
188             toggleAllEditing(true);
189             if (fab != null) fab.setEnabled(true);
190         }
191     }
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);
200             }
201         }
202     }
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);
209                     TextView prev_amt =
210                             (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
211                     TextView next_acc =
212                             (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
213
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);
218                     }
219                     else {
220                         prev_amt.setNextFocusRightId(next_acc.getId());
221                         prev_amt.setNextFocusForwardId(next_acc.getId());
222                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
223                     }
224
225                     if (row.hasFocus()) {
226                         if (next_acc != null) next_acc.requestFocus();
227                         else prev_amt.requestFocus();
228                     }
229
230                     table.removeView(row);
231                     check_transaction_submittable();
232 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
233                 }
234                 else {
235                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
236                             Snackbar.LENGTH_LONG).setAction("Action", null).show();
237                 }
238             }
239             public void onSwipeLeft() {
240                 onSwipeAside();
241             }
242             public void onSwipeRight() {
243                 onSwipeAside();
244             }
245             //            @Override
246 //            public boolean performClick(View view, MotionEvent m) {
247 //                return true;
248 //            }
249             public boolean onTouch(View view, MotionEvent m) {
250                 return gestureDetector.onTouchEvent(m);
251             }
252         });
253     }
254
255     public boolean simulateCrash(MenuItem item) {
256         Log.d("crash", "Will crash intentionally");
257         new AsyncCrasher().execute();
258         return true;
259     }
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);
263
264         if (BuildConfig.DEBUG) {
265             menu.findItem(R.id.action_simulate_crash).setVisible(true);
266         }
267         check_transaction_submittable();
268
269         return true;
270     }
271
272     public void pickTransactionDate(View view) {
273         DialogFragment picker = new DatePickerFragment();
274         picker.show(getSupportFragmentManager(), "datePicker");
275     }
276
277     public int dp2px(float dp) {
278         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
279                 getResources().getDisplayMetrics()));
280     }
281     private void hookTextChangeListener(final TextView view) {
282         view.addTextChangedListener(new TextWatcher() {
283             @Override
284             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
285
286             }
287
288             @Override
289             public void onTextChanged(CharSequence s, int start, int before, int count) {
290
291             }
292
293             @Override
294             public void afterTextChanged(Editable s) {
295 //                Log.d("input", "text changed");
296                 check_transaction_submittable();
297             }
298         });
299
300     }
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);
306         acc.setWidth(0);
307         acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
308                           EditorInfo.IME_FLAG_NAVIGATE_NEXT);
309         acc.setSingleLine(true);
310
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);
315         amt.setWidth(0);
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);
322
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());
331
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);
336         row.addView(acc);
337         row.addView(amt);
338         table.addView(row);
339
340         if (focus) acc.requestFocus();
341
342         hookSwipeListener(row);
343         MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null);
344         hookTextChangeListener(acc);
345         hookTextChangeListener(amt);
346
347         return row;
348     }
349     public void addTransactionAccountFromMenu(MenuItem item) {
350         doAddAccountRow(true);
351     }
352     public void resetTransactionFromMenu(MenuItem item) {
353         resetForm();
354     }
355     public void saveTransactionFromMenu(MenuItem item) {
356         saveTransaction();
357     }
358     // rules:
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);
368         int accounts = 0;
369         int accounts_with_values = 0;
370         int amounts = 0;
371         int amounts_with_accounts = 0;
372         int empty_rows = 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()
379                         .isEmpty();
380
381         try {
382             for (int i = 0; i < table.getChildCount(); i++) {
383                 TableRow row = (TableRow) table.getChildAt(i);
384
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();
390
391                 if (!acc_name.isEmpty()) {
392                     accounts++;
393
394                     if (!amt.isEmpty()) {
395                         accounts_with_values++;
396                     }
397                 }
398                 else empty_rows++;
399
400                 if (amt.isEmpty()) {
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();
406                     }
407                     else if (!acc_name.isEmpty()) single_empty_amount = false;
408                 }
409                 else {
410                     amounts++;
411                     if (!acc_name.isEmpty()) amounts_with_accounts++;
412                     running_total += Float.valueOf(amt);
413                 }
414             }
415
416             if ((empty_rows == 0) &&
417                 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
418             {
419                 doAddAccountRow(false);
420             }
421
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"));
427
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)))
431             {
432                 if (fab != null) {
433                     fab.show();
434                     fab.setEnabled(true);
435                 }
436             }
437             else {
438                 if (fab != null) fab.hide();
439             }
440
441             if (single_empty_amount) {
442                 empty_amount.setHint(String.format("%1.2f",
443                         (Math.abs(running_total) > 0.005) ? -running_total : 0f));
444             }
445
446         }
447         catch (NumberFormatException e) {
448             if (fab != null) fab.hide();
449         }
450         catch (Exception e) {
451             e.printStackTrace();
452             if (fab != null) fab.hide();
453         }
454     }
455
456     @Override
457     public void done(String error) {
458         progress.setVisibility(View.INVISIBLE);
459         Log.d("visuals", "hiding progress");
460
461         if (error == null) resetForm();
462         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
463                 BaseTransientBottomBar.LENGTH_LONG).show();
464
465         toggleAllEditing(true);
466         check_transaction_submittable();
467     }
468
469     private void resetForm() {
470         tvDate.setText("");
471         tvDescription.setText("");
472
473         tvDescription.requestFocus();
474
475         while (table.getChildCount() > 2) {
476             table.removeViewAt(2);
477         }
478         for (int i = 0; i < 2; i++) {
479             TableRow tr = (TableRow) table.getChildAt(i);
480             if (tr == null) break;
481
482             ((TextView) tr.getChildAt(0)).setText("");
483             ((TextView) tr.getChildAt(1)).setText("");
484         }
485     }
486     @Override
487     public void descriptionSelected(String description) {
488         Log.d("descr selected", description);
489         if (!inputStateIsInitial()) return;
490
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}))
494         {
495             if (!c.moveToNext()) return;
496
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)) {
505                         profile = p;
506                         break;
507                     }
508                 }
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,
512                         description));
513
514                 tr = profile.loadTransaction(transactionId);
515             }
516             int i = 0;
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);
525
526                 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
527                 ((TextView) row.getChildAt(1))
528                         .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
529
530                 if (acc.getAmount() < 0.005) {
531                     if (firstNegative == null) firstNegative = row;
532                     negativeCount++;
533                 }
534             }
535
536             if (negativeCount == 1) {
537                 ((TextView) firstNegative.getChildAt(1)).setText(null);
538             }
539
540             check_transaction_submittable();
541
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());
546         }
547
548     }
549     private boolean inputStateIsInitial() {
550         table = findViewById(R.id.new_transaction_accounts_table);
551
552         if (table.getChildCount() != 2) return false;
553
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;
558         }
559
560         return true;
561     }
562     private class AsyncCrasher extends AsyncTask<Void, Void, Void>{
563         @Override
564         protected Void doInBackground(Void... voids) {
565             throw new RuntimeException("Simulated crash");
566         }
567     }
568 }