drop two TODO items, done
[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  *  */
75
76 public class NewTransactionActivity extends AppCompatActivity
77         implements TaskCallback, DescriptionSelectedCallback {
78     private static SaveTransactionTask saver;
79     private TableLayout table;
80     private ProgressBar progress;
81     private FloatingActionButton fab;
82     private TextView tvDate;
83     private AutoCompleteTextView tvDescription;
84     private static boolean isZero(float f) {
85         return (f < 0.005) && (f > -0.005);
86     }
87     @Override
88     protected void onCreate(Bundle savedInstanceState) {
89         super.onCreate(savedInstanceState);
90         setContentView(R.layout.activity_new_transaction);
91         Toolbar toolbar = findViewById(R.id.toolbar);
92         setSupportActionBar(toolbar);
93         toolbar.setSubtitle(Data.profile.get().getName());
94
95         tvDate = findViewById(R.id.new_transaction_date);
96         tvDate.setOnFocusChangeListener((v, hasFocus) -> {
97             if (hasFocus) pickTransactionDate(v);
98         });
99         tvDescription = findViewById(R.id.new_transaction_description);
100         MLDB.hookAutocompletionAdapter(this, tvDescription, MLDB.DESCRIPTION_HISTORY_TABLE,
101                 "description", false, findViewById(R.id.new_transaction_acc_1), this);
102         hookTextChangeListener(tvDescription);
103
104         progress = findViewById(R.id.save_transaction_progress);
105         fab = findViewById(R.id.fab);
106         fab.setOnClickListener(v -> saveTransaction());
107
108         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
109         table = findViewById(R.id.new_transaction_accounts_table);
110         for (int i = 0; i < table.getChildCount(); i++) {
111             TableRow row = (TableRow) table.getChildAt(i);
112             AutoCompleteTextView tvAccountName = (AutoCompleteTextView) row.getChildAt(0);
113             TextView tvAmount = (TextView) row.getChildAt(1);
114             hookSwipeListener(row);
115             MLDB.hookAutocompletionAdapter(this, tvAccountName, MLDB.ACCOUNTS_TABLE, "name", true,
116                     tvAmount, null);
117             hookTextChangeListener(tvAccountName);
118             hookTextChangeListener(tvAmount);
119 //            Log.d("swipe", "hooked to row "+i);
120         }
121     }
122
123     @Override
124     public void finish() {
125         super.finish();
126         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
127     }
128
129     @Override
130     public boolean onOptionsItemSelected(MenuItem item) {
131         switch (item.getItemId()) {
132             case android.R.id.home:
133                 finish();
134                 return true;
135         }
136         return super.onOptionsItemSelected(item);
137     }
138     @Override
139     protected void onStart() {
140         super.onStart();
141         if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
142     }
143     public void saveTransaction() {
144         if (fab != null) fab.setEnabled(false);
145         toggleAllEditing(false);
146         progress.setVisibility(View.VISIBLE);
147         try {
148
149             saver = new SaveTransactionTask(this);
150
151             String dateString = tvDate.getText().toString();
152             Date date;
153             if (dateString.isEmpty()) date = new Date();
154             else date = Globals.parseLedgerDate(dateString);
155             LedgerTransaction tr = new LedgerTransaction(date, tvDescription.getText().toString());
156
157             TableLayout table = findViewById(R.id.new_transaction_accounts_table);
158             for (int i = 0; i < table.getChildCount(); i++) {
159                 TableRow row = (TableRow) table.getChildAt(i);
160                 String acc = ((TextView) row.getChildAt(0)).getText().toString();
161                 String amt = ((TextView) row.getChildAt(1)).getText().toString();
162                 LedgerTransactionAccount item =
163                         amt.length() > 0 ? new LedgerTransactionAccount(acc, Float.parseFloat(amt))
164                                          : new LedgerTransactionAccount(acc);
165
166                 tr.addAccount(item);
167             }
168             saver.execute(tr);
169         }
170         catch (ParseException e) {
171             Log.d("new-transaction", "Parse error", e);
172             Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
173                     Toast.LENGTH_LONG).show();
174             tvDate.requestFocus();
175
176             progress.setVisibility(View.GONE);
177             toggleAllEditing(true);
178             if (fab != null) fab.setEnabled(true);
179         }
180         catch (Exception e) {
181             Log.d("new-transaction", "Unknown error", e);
182
183             progress.setVisibility(View.GONE);
184             toggleAllEditing(true);
185             if (fab != null) fab.setEnabled(true);
186         }
187     }
188     private void toggleAllEditing(boolean enabled) {
189         tvDate.setEnabled(enabled);
190         tvDescription.setEnabled(enabled);
191         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
192         for (int i = 0; i < table.getChildCount(); i++) {
193             TableRow row = (TableRow) table.getChildAt(i);
194             for (int j = 0; j < row.getChildCount(); j++) {
195                 row.getChildAt(j).setEnabled(enabled);
196             }
197         }
198     }
199     private void hookSwipeListener(final TableRow row) {
200         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
201             public void onSwipeLeft() {
202 //                Log.d("swipe", "LEFT" + row.getId());
203                 if (table.getChildCount() > 2) {
204                     TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
205                     TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
206                     TextView prev_amt =
207                             (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
208                     TextView next_acc =
209                             (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
210
211                     if (next_acc == null) {
212                         prev_amt.setNextFocusRightId(R.id.none);
213                         prev_amt.setNextFocusForwardId(R.id.none);
214                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
215                     }
216                     else {
217                         prev_amt.setNextFocusRightId(next_acc.getId());
218                         prev_amt.setNextFocusForwardId(next_acc.getId());
219                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
220                     }
221
222                     if (row.hasFocus()) {
223                         if (next_acc != null) next_acc.requestFocus();
224                         else prev_amt.requestFocus();
225                     }
226
227                     table.removeView(row);
228                     check_transaction_submittable();
229 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
230                 }
231                 else {
232                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
233                             Snackbar.LENGTH_LONG).setAction("Action", null).show();
234                 }
235             }
236             //            @Override
237 //            public boolean performClick(View view, MotionEvent m) {
238 //                return true;
239 //            }
240             public boolean onTouch(View view, MotionEvent m) {
241                 return gestureDetector.onTouchEvent(m);
242             }
243         });
244     }
245
246     public boolean onCreateOptionsMenu(Menu menu) {
247         // Inflate the menu; this adds items to the action bar if it is present.
248         getMenuInflater().inflate(R.menu.new_transaction, menu);
249
250         check_transaction_submittable();
251
252         return true;
253     }
254
255     public void pickTransactionDate(View view) {
256         DialogFragment picker = new DatePickerFragment();
257         picker.show(getSupportFragmentManager(), "datePicker");
258     }
259
260     public int dp2px(float dp) {
261         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
262                 getResources().getDisplayMetrics()));
263     }
264     private void hookTextChangeListener(final TextView view) {
265         view.addTextChangedListener(new TextWatcher() {
266             @Override
267             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
268
269             }
270
271             @Override
272             public void onTextChanged(CharSequence s, int start, int before, int count) {
273
274             }
275
276             @Override
277             public void afterTextChanged(Editable s) {
278 //                Log.d("input", "text changed");
279                 check_transaction_submittable();
280             }
281         });
282
283     }
284     private TableRow doAddAccountRow(boolean focus) {
285         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
286         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
287                 TableRow.LayoutParams.WRAP_CONTENT, 9f));
288         acc.setHint(R.string.new_transaction_account_hint);
289         acc.setWidth(0);
290         acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
291                           EditorInfo.IME_FLAG_NAVIGATE_NEXT);
292         acc.setSingleLine(true);
293
294         final EditText amt = new EditText(this);
295         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
296                 TableRow.LayoutParams.MATCH_PARENT, 1f));
297         amt.setHint(R.string.new_transaction_amount_hint);
298         amt.setWidth(0);
299         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
300                          InputType.TYPE_NUMBER_FLAG_DECIMAL);
301         amt.setMinWidth(dp2px(40));
302         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
303         amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
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             for (i = 0; i < accounts.size(); i++) {
499                 LedgerTransactionAccount acc = accounts.get(i);
500                 TableRow row = (TableRow) table.getChildAt(i);
501                 if (row == null) row = doAddAccountRow(false);
502
503                 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
504                 ((TextView) row.getChildAt(1))
505                         .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
506             }
507
508             check_transaction_submittable();
509
510             ((TableRow) table.getChildAt(table.getChildCount() - 1)).getChildAt(0).requestFocus();
511         }
512
513     }
514     private boolean inputStateIsInitial() {
515         table = findViewById(R.id.new_transaction_accounts_table);
516
517         if (table.getChildCount() != 2) return false;
518
519         for (int i = 0; i < 2; i++) {
520             TableRow row = (TableRow) table.getChildAt(i);
521             if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
522             if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;
523         }
524
525         return true;
526     }
527 }