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