use the activity's mProfile, not the global current profile in Data
[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.SendTransactionTask;
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;
60
61 import java.text.ParseException;
62 import java.util.ArrayList;
63 import java.util.Date;
64 import java.util.Locale;
65 import java.util.Objects;
66
67 import androidx.appcompat.widget.Toolbar;
68 import androidx.fragment.app.DialogFragment;
69
70 /*
71  * TODO: nicer progress while transaction is submitted
72  * TODO: reports
73  * TODO: get rid of the custom session/cookie and auth code?
74  *         (the last problem with the POST was the missing content-length header)
75  *  */
76
77 public class NewTransactionActivity extends ProfileThemedActivity
78         implements TaskCallback, DescriptionSelectedCallback {
79     private static SendTransactionTask 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
92         setContentView(R.layout.activity_new_transaction);
93         Toolbar toolbar = findViewById(R.id.toolbar);
94         setSupportActionBar(toolbar);
95         toolbar.setSubtitle(mProfile.getName());
96
97         tvDate = findViewById(R.id.new_transaction_date);
98         tvDate.setOnFocusChangeListener((v, hasFocus) -> {
99             if (hasFocus) pickTransactionDate(v);
100         });
101         tvDescription = findViewById(R.id.new_transaction_description);
102         MLDB.hookAutocompletionAdapter(this, tvDescription, MLDB.DESCRIPTION_HISTORY_TABLE,
103                 "description", false, findViewById(R.id.new_transaction_acc_1), this);
104         hookTextChangeListener(tvDescription);
105
106         progress = findViewById(R.id.save_transaction_progress);
107         fab = findViewById(R.id.fab);
108         fab.setOnClickListener(v -> saveTransaction());
109
110         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
111         table = findViewById(R.id.new_transaction_accounts_table);
112         for (int i = 0; i < table.getChildCount(); i++) {
113             TableRow row = (TableRow) table.getChildAt(i);
114             AutoCompleteTextView tvAccountName = (AutoCompleteTextView) row.getChildAt(0);
115             TextView tvAmount = (TextView) row.getChildAt(1);
116             hookSwipeListener(row);
117             MLDB.hookAutocompletionAdapter(this, tvAccountName, MLDB.ACCOUNTS_TABLE, "name", true,
118                     tvAmount, null);
119             hookTextChangeListener(tvAccountName);
120             hookTextChangeListener(tvAmount);
121 //            Log.d("swipe", "hooked to row "+i);
122         }
123     }
124     @Override
125     protected void initProfile() {
126         String profileUUID = getIntent().getStringExtra("profile_uuid");
127
128         if (profileUUID != null) {
129             mProfile = Data.getProfile(profileUUID);
130             if (mProfile == null) finish();
131         }
132         else super.initProfile();
133     }
134     @Override
135     public void finish() {
136         super.finish();
137         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
138     }
139
140     @Override
141     public boolean onOptionsItemSelected(MenuItem item) {
142         switch (item.getItemId()) {
143             case android.R.id.home:
144                 finish();
145                 return true;
146         }
147         return super.onOptionsItemSelected(item);
148     }
149     @Override
150     protected void onStart() {
151         super.onStart();
152         if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
153     }
154     public void saveTransaction() {
155         if (fab != null) fab.setEnabled(false);
156         toggleAllEditing(false);
157         progress.setVisibility(View.VISIBLE);
158         try {
159
160             saver = new SendTransactionTask(this, mProfile);
161
162             String dateString = tvDate.getText().toString();
163             Date date;
164             if (dateString.isEmpty()) date = new Date();
165             else date = Globals.parseLedgerDate(dateString);
166             LedgerTransaction tr = new LedgerTransaction(date, tvDescription.getText().toString());
167
168             TableLayout table = findViewById(R.id.new_transaction_accounts_table);
169             LedgerTransactionAccount emptyAmountAccount = null;
170             float emptyAmountAccountBalance = 0;
171             for (int i = 0; i < table.getChildCount(); i++) {
172                 TableRow row = (TableRow) table.getChildAt(i);
173                 String acc = ((TextView) row.getChildAt(0)).getText().toString();
174                 if (acc.isEmpty()) continue;
175
176                 String amt = ((TextView) row.getChildAt(1)).getText().toString();
177                 LedgerTransactionAccount item;
178                 if (amt.length() > 0) {
179                     final float amount = Float.parseFloat(amt);
180                     item = new LedgerTransactionAccount(acc, amount);
181                     emptyAmountAccountBalance += amount;
182                 }
183                 else {
184                     item = new LedgerTransactionAccount(acc);
185                     emptyAmountAccount = item;
186                 }
187
188                 tr.addAccount(item);
189             }
190
191             if (emptyAmountAccount != null)
192                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
193             saver.execute(tr);
194         }
195         catch (ParseException e) {
196             Log.d("new-transaction", "Parse error", e);
197             Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
198                     Toast.LENGTH_LONG).show();
199             tvDate.requestFocus();
200
201             progress.setVisibility(View.GONE);
202             toggleAllEditing(true);
203             if (fab != null) fab.setEnabled(true);
204         }
205         catch (Exception e) {
206             Log.d("new-transaction", "Unknown error", e);
207
208             progress.setVisibility(View.GONE);
209             toggleAllEditing(true);
210             if (fab != null) fab.setEnabled(true);
211         }
212     }
213     private void toggleAllEditing(boolean enabled) {
214         tvDate.setEnabled(enabled);
215         tvDescription.setEnabled(enabled);
216         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
217         for (int i = 0; i < table.getChildCount(); i++) {
218             TableRow row = (TableRow) table.getChildAt(i);
219             for (int j = 0; j < row.getChildCount(); j++) {
220                 row.getChildAt(j).setEnabled(enabled);
221             }
222         }
223     }
224     private void hookSwipeListener(final TableRow row) {
225         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
226             private void onSwipeAside() {
227                 if (table.getChildCount() > 2) {
228                     TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
229                     TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
230                     TextView prev_amt =
231                             (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
232                     TextView next_acc =
233                             (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
234
235                     if (next_acc == null) {
236                         prev_amt.setNextFocusRightId(R.id.none);
237                         prev_amt.setNextFocusForwardId(R.id.none);
238                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
239                     }
240                     else {
241                         prev_amt.setNextFocusRightId(next_acc.getId());
242                         prev_amt.setNextFocusForwardId(next_acc.getId());
243                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
244                     }
245
246                     if (row.hasFocus()) {
247                         if (next_acc != null) next_acc.requestFocus();
248                         else prev_amt.requestFocus();
249                     }
250
251                     table.removeView(row);
252                     check_transaction_submittable();
253 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
254                 }
255                 else {
256                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
257                             Snackbar.LENGTH_LONG).setAction("Action", null).show();
258                 }
259             }
260             public void onSwipeLeft() {
261                 onSwipeAside();
262             }
263             public void onSwipeRight() {
264                 onSwipeAside();
265             }
266             //            @Override
267 //            public boolean performClick(View view, MotionEvent m) {
268 //                return true;
269 //            }
270             public boolean onTouch(View view, MotionEvent m) {
271                 return gestureDetector.onTouchEvent(m);
272             }
273         });
274     }
275
276     public boolean simulateCrash(MenuItem item) {
277         Log.d("crash", "Will crash intentionally");
278         new AsyncCrasher().execute();
279         return true;
280     }
281     public boolean onCreateOptionsMenu(Menu menu) {
282         // Inflate the menu; this adds items to the action bar if it is present.
283         getMenuInflater().inflate(R.menu.new_transaction, menu);
284
285         if (BuildConfig.DEBUG) {
286             menu.findItem(R.id.action_simulate_crash).setVisible(true);
287         }
288         check_transaction_submittable();
289
290         return true;
291     }
292
293     public void pickTransactionDate(View view) {
294         DialogFragment picker = new DatePickerFragment();
295         picker.show(getSupportFragmentManager(), "datePicker");
296     }
297
298     public int dp2px(float dp) {
299         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
300                 getResources().getDisplayMetrics()));
301     }
302     private void hookTextChangeListener(final TextView view) {
303         view.addTextChangedListener(new TextWatcher() {
304             @Override
305             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
306
307             }
308
309             @Override
310             public void onTextChanged(CharSequence s, int start, int before, int count) {
311
312             }
313
314             @Override
315             public void afterTextChanged(Editable s) {
316 //                Log.d("input", "text changed");
317                 check_transaction_submittable();
318             }
319         });
320
321     }
322     private TableRow doAddAccountRow(boolean focus) {
323         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
324         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
325                 TableRow.LayoutParams.WRAP_CONTENT, 9f));
326         acc.setHint(R.string.new_transaction_account_hint);
327         acc.setWidth(0);
328         acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
329                           EditorInfo.IME_FLAG_NAVIGATE_NEXT);
330         acc.setSingleLine(true);
331
332         final EditText amt = new EditText(this);
333         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
334                 TableRow.LayoutParams.MATCH_PARENT, 1f));
335         amt.setHint(R.string.new_transaction_amount_hint);
336         amt.setWidth(0);
337         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
338                          InputType.TYPE_NUMBER_FLAG_DECIMAL);
339         amt.setMinWidth(dp2px(40));
340         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
341         amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
342         amt.setSelectAllOnFocus(true);
343
344         // forward navigation support
345         final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
346         final TextView last_amt = (TextView) last_row.getChildAt(1);
347         last_amt.setNextFocusForwardId(acc.getId());
348         last_amt.setNextFocusRightId(acc.getId());
349         last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
350         acc.setNextFocusForwardId(amt.getId());
351         acc.setNextFocusRightId(amt.getId());
352
353         final TableRow row = new TableRow(this);
354         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
355                 TableRow.LayoutParams.MATCH_PARENT));
356         row.setGravity(Gravity.BOTTOM);
357         row.addView(acc);
358         row.addView(amt);
359         table.addView(row);
360
361         if (focus) acc.requestFocus();
362
363         hookSwipeListener(row);
364         MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null);
365         hookTextChangeListener(acc);
366         hookTextChangeListener(amt);
367
368         return row;
369     }
370     public void addTransactionAccountFromMenu(MenuItem item) {
371         doAddAccountRow(true);
372     }
373     public void resetTransactionFromMenu(MenuItem item) {
374         resetForm();
375     }
376     public void saveTransactionFromMenu(MenuItem item) {
377         saveTransaction();
378     }
379     // rules:
380     // 1) at least two account names
381     // 2) each amount must have account name
382     // 3) amounts must balance to 0, or
383     // 3a) there must be exactly one empty amount
384     // 4) empty accounts with empty amounts are ignored
385     // 5) a row with an empty account name or empty amount is guaranteed to exist
386     @SuppressLint("DefaultLocale")
387     private void check_transaction_submittable() {
388         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
389         int accounts = 0;
390         int accounts_with_values = 0;
391         int amounts = 0;
392         int amounts_with_accounts = 0;
393         int empty_rows = 0;
394         TextView empty_amount = null;
395         boolean single_empty_amount = false;
396         boolean single_empty_amount_has_account = false;
397         float running_total = 0f;
398         boolean have_description =
399                 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
400                         .isEmpty();
401
402         try {
403             for (int i = 0; i < table.getChildCount(); i++) {
404                 TableRow row = (TableRow) table.getChildAt(i);
405
406                 TextView acc_name_v = (TextView) row.getChildAt(0);
407                 TextView amount_v = (TextView) row.getChildAt(1);
408                 String amt = String.valueOf(amount_v.getText());
409                 String acc_name = String.valueOf(acc_name_v.getText());
410                 acc_name = acc_name.trim();
411
412                 if (!acc_name.isEmpty()) {
413                     accounts++;
414
415                     if (!amt.isEmpty()) {
416                         accounts_with_values++;
417                     }
418                 }
419                 else empty_rows++;
420
421                 if (amt.isEmpty()) {
422                     amount_v.setHint(String.format("%1.2f", 0f));
423                     if (empty_amount == null) {
424                         empty_amount = amount_v;
425                         single_empty_amount = true;
426                         single_empty_amount_has_account = !acc_name.isEmpty();
427                     }
428                     else if (!acc_name.isEmpty()) single_empty_amount = false;
429                 }
430                 else {
431                     amounts++;
432                     if (!acc_name.isEmpty()) amounts_with_accounts++;
433                     running_total += Float.valueOf(amt);
434                 }
435             }
436
437             if ((empty_rows == 0) &&
438                 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
439             {
440                 doAddAccountRow(false);
441             }
442
443             Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
444                                                "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
445                                                "single_empty_with_acc=%s", accounts,
446                     accounts_with_values, amounts_with_accounts, amounts, running_total,
447                     (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
448
449             if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
450                 (amounts_with_accounts == amounts) &&
451                 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
452             {
453                 if (fab != null) {
454                     fab.show();
455                     fab.setEnabled(true);
456                 }
457             }
458             else {
459                 if (fab != null) fab.hide();
460             }
461
462             if (single_empty_amount) {
463                 empty_amount.setHint(String.format("%1.2f",
464                         (Math.abs(running_total) > 0.005) ? -running_total : 0f));
465             }
466
467         }
468         catch (NumberFormatException e) {
469             if (fab != null) fab.hide();
470         }
471         catch (Exception e) {
472             e.printStackTrace();
473             if (fab != null) fab.hide();
474         }
475     }
476
477     @Override
478     public void done(String error) {
479         progress.setVisibility(View.INVISIBLE);
480         Log.d("visuals", "hiding progress");
481
482         if (error == null) resetForm();
483         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
484                 BaseTransientBottomBar.LENGTH_LONG).show();
485
486         toggleAllEditing(true);
487         check_transaction_submittable();
488     }
489
490     private void resetForm() {
491         tvDate.setText("");
492         tvDescription.setText("");
493
494         tvDescription.requestFocus();
495
496         while (table.getChildCount() > 2) {
497             table.removeViewAt(2);
498         }
499         for (int i = 0; i < 2; i++) {
500             TableRow tr = (TableRow) table.getChildAt(i);
501             if (tr == null) break;
502
503             ((TextView) tr.getChildAt(0)).setText("");
504             ((TextView) tr.getChildAt(1)).setText("");
505         }
506     }
507     @Override
508     public void descriptionSelected(String description) {
509         Log.d("descr selected", description);
510         if (!inputStateIsInitial()) return;
511
512         String accFilter = mProfile.getPreferredAccountsFilter();
513
514         ArrayList<String> params = new ArrayList<>();
515         StringBuilder sb = new StringBuilder(
516                 "select t.profile, t.id from transactions t where t.description=?");
517         params.add(description);
518
519         if (accFilter != null) {
520             sb.append(" AND EXISTS (").append("SELECT 1 FROM transaction_accounts ta ")
521                     .append("WHERE ta.profile = t.profile").append(" AND ta.transaction_id = t.id")
522                     .append(" AND UPPER(ta.account_name) LIKE '%'||?||'%')");
523             params.add(accFilter.toUpperCase());
524         }
525
526         sb.append(" ORDER BY date desc limit 1");
527
528         final String sql = sb.toString();
529         Log.d("descr", sql);
530         Log.d("descr", params.toString());
531
532         try (Cursor c = MLDB.getDatabase().rawQuery(sql, params.toArray(new String[]{}))) {
533             if (!c.moveToNext()) return;
534
535             String profileUUID = c.getString(0);
536             int transactionId = c.getInt(1);
537             LedgerTransaction tr;
538             MobileLedgerProfile profile = Data.getProfile(profileUUID);
539             if (profile == null) throw new RuntimeException(String.format(
540                     "Unable to find profile %s, which is supposed to contain " +
541                     "transaction %d with description %s", profileUUID, transactionId, description));
542
543             tr = profile.loadTransaction(transactionId);
544             table = findViewById(R.id.new_transaction_accounts_table);
545             ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
546             TableRow firstNegative = null;
547             int negativeCount = 0;
548             for (int i = 0; i < accounts.size(); i++) {
549                 LedgerTransactionAccount acc = accounts.get(i);
550                 TableRow row = (TableRow) table.getChildAt(i);
551                 if (row == null) row = doAddAccountRow(false);
552
553                 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
554                 ((TextView) row.getChildAt(1))
555                         .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
556
557                 if (acc.getAmount() < 0.005) {
558                     if (firstNegative == null) firstNegative = row;
559                     negativeCount++;
560                 }
561             }
562
563             if (negativeCount == 1) {
564                 ((TextView) firstNegative.getChildAt(1)).setText(null);
565             }
566
567             check_transaction_submittable();
568
569             EditText firstAmount = (EditText) ((TableRow) table.getChildAt(0)).getChildAt(1);
570             String amtString = String.valueOf(firstAmount.getText());
571             firstAmount.requestFocus();
572             firstAmount.setSelection(0, amtString.length());
573         }
574
575     }
576     private boolean inputStateIsInitial() {
577         table = findViewById(R.id.new_transaction_accounts_table);
578
579         if (table.getChildCount() != 2) return false;
580
581         for (int i = 0; i < 2; i++) {
582             TableRow row = (TableRow) table.getChildAt(i);
583             if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
584             if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;
585         }
586
587         return true;
588     }
589     private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
590         @Override
591         protected Void doInBackground(Void... voids) {
592             throw new RuntimeException("Simulated crash");
593         }
594     }
595 }