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