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