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