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