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