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