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