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