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