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