fill transaction details when a previous transaction description is selected
[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.Bundle;
23 import android.support.design.widget.BaseTransientBottomBar;
24 import android.support.design.widget.FloatingActionButton;
25 import android.support.design.widget.Snackbar;
26 import android.support.v4.app.DialogFragment;
27 import android.support.v7.app.AppCompatActivity;
28 import android.support.v7.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.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.MLDB;
60
61 import java.text.ParseException;
62 import java.util.ArrayList;
63 import java.util.Date;
64 import java.util.List;
65 import java.util.Locale;
66 import java.util.Objects;
67
68 /*
69  * TODO: nicer progress while transaction is submitted
70  * TODO: reports
71  * TODO: get rid of the custom session/cookie and auth code?
72  *         (the last problem with the POST was the missing content-length header)
73  * TODO: nicer swiping removal with visual feedback
74  * TODO: setup wizard
75  * TODO: update accounts/check settings upon change of backend settings
76  *  */
77
78 public class NewTransactionActivity extends AppCompatActivity
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         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 onCreateOptionsMenu(Menu menu) {
249         // Inflate the menu; this adds items to the action bar if it is present.
250         getMenuInflater().inflate(R.menu.new_transaction, menu);
251
252         check_transaction_submittable();
253
254         return true;
255     }
256
257     public void pickTransactionDate(View view) {
258         DialogFragment picker = new DatePickerFragment();
259         picker.show(getSupportFragmentManager(), "datePicker");
260     }
261
262     public int dp2px(float dp) {
263         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
264                 getResources().getDisplayMetrics()));
265     }
266     private void hookTextChangeListener(final TextView view) {
267         view.addTextChangedListener(new TextWatcher() {
268             @Override
269             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
270
271             }
272
273             @Override
274             public void onTextChanged(CharSequence s, int start, int before, int count) {
275
276             }
277
278             @Override
279             public void afterTextChanged(Editable s) {
280 //                Log.d("input", "text changed");
281                 check_transaction_submittable();
282             }
283         });
284
285     }
286     private TableRow doAddAccountRow(boolean focus) {
287         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
288         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
289                 TableRow.LayoutParams.WRAP_CONTENT, 9f));
290         acc.setHint(R.string.new_transaction_account_hint);
291         acc.setWidth(0);
292         acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
293                           EditorInfo.IME_FLAG_NAVIGATE_NEXT);
294         acc.setSingleLine(true);
295
296         final EditText amt = new EditText(this);
297         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
298                 TableRow.LayoutParams.MATCH_PARENT, 1f));
299         amt.setHint(R.string.new_transaction_amount_hint);
300         amt.setWidth(0);
301         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
302                          InputType.TYPE_NUMBER_FLAG_DECIMAL);
303         amt.setMinWidth(dp2px(40));
304         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
305         amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
306
307         // forward navigation support
308         final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
309         final TextView last_amt = (TextView) last_row.getChildAt(1);
310         last_amt.setNextFocusForwardId(acc.getId());
311         last_amt.setNextFocusRightId(acc.getId());
312         last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
313         acc.setNextFocusForwardId(amt.getId());
314         acc.setNextFocusRightId(amt.getId());
315
316         final TableRow row = new TableRow(this);
317         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
318                 TableRow.LayoutParams.MATCH_PARENT));
319         row.setGravity(Gravity.BOTTOM);
320         row.addView(acc);
321         row.addView(amt);
322         table.addView(row);
323
324         if (focus) acc.requestFocus();
325
326         hookSwipeListener(row);
327         MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null);
328         hookTextChangeListener(acc);
329         hookTextChangeListener(amt);
330
331         return row;
332     }
333     public void addTransactionAccountFromMenu(MenuItem item) {
334         doAddAccountRow(true);
335     }
336     public void resetTransactionFromMenu(MenuItem item) {
337         resetForm();
338     }
339     public void saveTransactionFromMenu(MenuItem item) {
340         saveTransaction();
341     }
342     // rules:
343     // 1) at least two account names
344     // 2) each amount must have account name
345     // 3) amounts must balance to 0, or
346     // 3a) there must be exactly one empty amount
347     // 4) empty accounts with empty amounts are ignored
348     // 5) a row with an empty account name or empty amount is guaranteed to exist
349     @SuppressLint("DefaultLocale")
350     private void check_transaction_submittable() {
351         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
352         int accounts = 0;
353         int accounts_with_values = 0;
354         int amounts = 0;
355         int amounts_with_accounts = 0;
356         int empty_rows = 0;
357         TextView empty_amount = null;
358         boolean single_empty_amount = false;
359         boolean single_empty_amount_has_account = false;
360         float running_total = 0f;
361         boolean have_description =
362                 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
363                         .isEmpty();
364
365         try {
366             for (int i = 0; i < table.getChildCount(); i++) {
367                 TableRow row = (TableRow) table.getChildAt(i);
368
369                 TextView acc_name_v = (TextView) row.getChildAt(0);
370                 TextView amount_v = (TextView) row.getChildAt(1);
371                 String amt = String.valueOf(amount_v.getText());
372                 String acc_name = String.valueOf(acc_name_v.getText());
373                 acc_name = acc_name.trim();
374
375                 if (!acc_name.isEmpty()) {
376                     accounts++;
377
378                     if (!amt.isEmpty()) {
379                         accounts_with_values++;
380                     }
381                 }
382                 else empty_rows++;
383
384                 if (amt.isEmpty()) {
385                     amount_v.setHint(String.format("%1.2f", 0f));
386                     if (empty_amount == null) {
387                         empty_amount = amount_v;
388                         single_empty_amount = true;
389                         single_empty_amount_has_account = !acc_name.isEmpty();
390                     }
391                     else if (!acc_name.isEmpty()) single_empty_amount = false;
392                 }
393                 else {
394                     amounts++;
395                     if (!acc_name.isEmpty()) amounts_with_accounts++;
396                     running_total += Float.valueOf(amt);
397                 }
398             }
399
400             if ((empty_rows == 0) &&
401                 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
402             {
403                 doAddAccountRow(false);
404             }
405
406             Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
407                                                "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
408                                                "single_empty_with_acc=%s", accounts,
409                     accounts_with_values, amounts_with_accounts, amounts, running_total,
410                     (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
411
412             if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
413                 (amounts_with_accounts == amounts) &&
414                 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
415             {
416                 if (fab != null) {
417                     fab.show();
418                     fab.setEnabled(true);
419                 }
420             }
421             else {
422                 if (fab != null) fab.hide();
423             }
424
425             if (single_empty_amount) {
426                 empty_amount.setHint(String.format("%1.2f",
427                         (Math.abs(running_total) > 0.005) ? -running_total : 0f));
428             }
429
430         }
431         catch (NumberFormatException e) {
432             if (fab != null) fab.hide();
433         }
434         catch (Exception e) {
435             e.printStackTrace();
436             if (fab != null) fab.hide();
437         }
438     }
439
440     @Override
441     public void done(String error) {
442         progress.setVisibility(View.INVISIBLE);
443         Log.d("visuals", "hiding progress");
444
445         if (error == null) resetForm();
446         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
447                 BaseTransientBottomBar.LENGTH_LONG).show();
448
449         toggleAllEditing(true);
450         check_transaction_submittable();
451     }
452
453     private void resetForm() {
454         tvDate.setText("");
455         tvDescription.setText("");
456
457         tvDescription.requestFocus();
458
459         while (table.getChildCount() > 2) {
460             table.removeViewAt(2);
461         }
462         for (int i = 0; i < 2; i++) {
463             TableRow tr = (TableRow) table.getChildAt(i);
464             if (tr == null) break;
465
466             ((TextView) tr.getChildAt(0)).setText("");
467             ((TextView) tr.getChildAt(1)).setText("");
468         }
469     }
470     @Override
471     public void descriptionSelected(String description) {
472         Log.d("descr selected", description);
473         if (!inputStateIsInitial()) return;
474
475         try (Cursor c = MLDB.getReadableDatabase().rawQuery(
476                 "select profile, id from transactions where description=? order by date desc " +
477                 "limit 1", new String[]{description}))
478         {
479             if (!c.moveToNext()) return;
480
481             String profileUUID = c.getString(0);
482             int transactionId = c.getInt(1);
483             List<MobileLedgerProfile> profiles = Data.profiles.getList();
484             MobileLedgerProfile profile = null;
485             for (int i = 0; i < profiles.size(); i++) {
486                 MobileLedgerProfile p = profiles.get(i);
487                 if (p.getUuid().equals(profileUUID)) {
488                     profile = p;
489                     break;
490                 }
491             }
492             if (profile == null) throw new RuntimeException(String.format(
493                     "Unable to find profile %s, which is supposed to contain " +
494                     "transaction %d with description %s", profileUUID, transactionId, description));
495
496             LedgerTransaction tr = profile.loadTransaction(transactionId);
497             int i = 0;
498             table = findViewById(R.id.new_transaction_accounts_table);
499             ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
500             for (i = 0; i < accounts.size(); i++) {
501                 LedgerTransactionAccount acc = accounts.get(i);
502                 TableRow row = (TableRow) table.getChildAt(i);
503                 if (row == null) row = doAddAccountRow(false);
504
505                 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
506                 ((TextView) row.getChildAt(1))
507                         .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
508             }
509
510             check_transaction_submittable();
511
512             ((TableRow) table.getChildAt(table.getChildCount() - 1)).getChildAt(0).requestFocus();
513         }
514
515     }
516     private boolean inputStateIsInitial() {
517         table = findViewById(R.id.new_transaction_accounts_table);
518
519         if (table.getChildCount() != 2) return false;
520
521         for (int i = 0; i < 2; i++) {
522             TableRow row = (TableRow) table.getChildAt(i);
523             if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
524             if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;
525         }
526
527         return true;
528     }
529 }