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