]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/NewTransactionActivity.java
automatic addition of empty account rows
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / NewTransactionActivity.java
1 package net.ktnx.mobileledger;
2
3 import android.annotation.TargetApi;
4 import android.database.Cursor;
5 import android.database.MatrixCursor;
6 import android.database.sqlite.SQLiteDatabase;
7 import android.os.Build;
8 import android.os.Bundle;
9 import android.os.Handler;
10 import android.preference.PreferenceManager;
11 import android.provider.FontsContract;
12 import android.support.design.widget.FloatingActionButton;
13 import android.support.design.widget.Snackbar;
14 import android.support.v4.app.DialogFragment;
15 import android.support.v7.app.AppCompatActivity;
16 import android.support.v7.widget.Toolbar;
17 import android.text.Editable;
18 import android.text.InputType;
19 import android.text.TextWatcher;
20 import android.util.Log;
21 import android.util.TypedValue;
22 import android.view.Menu;
23 import android.view.MenuItem;
24 import android.view.MotionEvent;
25 import android.view.View;
26 import android.widget.AutoCompleteTextView;
27 import android.widget.EditText;
28 import android.widget.FilterQueryProvider;
29 import android.widget.ProgressBar;
30 import android.widget.SimpleCursorAdapter;
31 import android.widget.TableLayout;
32 import android.widget.TableRow;
33 import android.widget.TextView;
34
35 import java.util.Objects;
36
37 /*
38  * TODO: auto-fill of transaction description
39  *       if Android O's implementation won't work, add a custom one
40  * TODO: nicer progress while transaction is submitted
41  * TODO: periodic and manual refresh of available accounts
42  *         (now done forcibly each time the main activity is started)
43  * TODO: latest transactions, maybe with browsing further in the past?
44  * TODO: reports
45  * TODO: get rid of the custom session/cookie and auth code?
46  *         (the last problem with the POST was the missing content-length header)
47  * TODO: app icon
48  * TODO: nicer swiping removal with visual feedback
49  * TODO: activity with current balance
50  * TODO: setup wizard
51  * TODO: update accounts/check settings upon change of backend settings
52  *  */
53
54 public class NewTransactionActivity extends AppCompatActivity implements TaskCallback {
55     private TableLayout table;
56     private FloatingActionButton fab;
57     boolean fab_should_be_visible;
58     private ProgressBar progress;
59     private TextView text_date;
60     private TextView text_descr;
61     private static SaveTransactionTask saver;
62     FloatingActionButton.OnVisibilityChangedListener fab_visibility_changed_listener = new FloatingActionButton.OnVisibilityChangedListener() {
63         @Override
64         public void onShown(FloatingActionButton fab) {
65             Log.d("visuals", "FAB shown");
66             super.onShown(fab);
67             if (!fab_should_be_visible) fab.hide();
68         }
69
70         @Override
71         public void onHidden(FloatingActionButton fab) {
72             Log.d("visuals", "FAB hidden");
73             fab.setImageResource(R.drawable.ic_save_white_24dp);
74             fab.setEnabled(true);
75 //            super.onHidden(fab);
76             if (fab_should_be_visible) fab.show();
77         }
78     };
79
80     private void hide_fab() {
81         hide_fab(false);
82     }
83
84     private void hide_fab(boolean force) {
85         if (!fab_should_be_visible && !force) return;
86
87         fab_should_be_visible = false;
88         fab.hide(fab_visibility_changed_listener);
89     }
90
91     private void show_fab() {
92         show_fab(false);
93     }
94
95     private void show_fab(boolean force) {
96         if (fab_should_be_visible && !force) return;
97
98         fab_should_be_visible = true;
99         fab.show(fab_visibility_changed_listener);
100     }
101
102     @Override
103     protected void onCreate(Bundle savedInstanceState) {
104         super.onCreate(savedInstanceState);
105         setContentView(R.layout.activity_new_transaction);
106         Toolbar toolbar = findViewById(R.id.toolbar);
107         setSupportActionBar(toolbar);
108
109         text_date = findViewById(R.id.new_transaction_date);
110         text_descr = findViewById(R.id.new_transaction_description);
111
112         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
113             text_descr.setAutofillHints("");
114         }
115
116         fab = findViewById(R.id.fab);
117         fab.setOnClickListener(new View.OnClickListener() {
118             @Override
119             public void onClick(View view) {
120                 new_transaction_save_clicked(view);
121             }
122         });
123         progress = findViewById(R.id.save_transaction_progress);
124
125         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
126         table = findViewById(R.id.new_transaction_accounts_table);
127         for (int i = 0; i < table.getChildCount(); i++) {
128             TableRow row = (TableRow) table.getChildAt(i);
129             TextView acc_name_view = (TextView) row.getChildAt(0);
130             TextView amount_view = (TextView) row.getChildAt(1);
131             hook_swipe_listener(row);
132             hook_autocompletion_adapter(row);
133             hook_text_change_listener(acc_name_view);
134             hook_text_change_listener(amount_view);
135 //            Log.d("swipe", "hooked to row "+i);
136         }
137     }
138
139     public void new_transaction_save_clicked(View view) {
140         fab.setEnabled(false);
141         progress.setVisibility(View.VISIBLE);
142
143         saver = new SaveTransactionTask(this);
144
145         saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
146         LedgerTransaction tr = new LedgerTransaction(text_date.getText().toString(), text_descr.getText().toString());
147
148         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
149         for ( int i = 0; i < table.getChildCount(); i++ ) {
150             TableRow row = (TableRow) table.getChildAt(i);
151             String acc = ((TextView) row.getChildAt(0)).getText().toString();
152             String amt = ((TextView) row.getChildAt(1)).getText().toString();
153             LedgerTransactionItem item =
154                     amt.length() > 0
155                     ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
156                     : new LedgerTransactionItem( acc );
157
158             tr.add_item(item);
159         }
160         saver.execute(tr);
161     }
162     private void hook_swipe_listener(final TableRow row) {
163         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
164             public void onSwipeLeft() {
165 //                Log.d("swipe", "LEFT" + row.getId());
166                 if (table.getChildCount() > 2) {
167                     table.removeView(row);
168 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
169                 }
170                 else {
171                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
172                             .setAction("Action", null).show();
173                 }
174             }
175 //            @Override
176 //            public boolean performClick(View view, MotionEvent m) {
177 //                return true;
178 //            }
179             public boolean onTouch(View view, MotionEvent m) {
180                 return gestureDetector.onTouchEvent(m);
181             }
182         });
183     }
184
185     private void hook_text_change_listener(final TextView view) {
186         view.addTextChangedListener(new TextWatcher() {
187             @Override
188             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
189
190             }
191
192             @Override
193             public void onTextChanged(CharSequence s, int start, int before, int count) {
194
195             }
196
197             @Override
198             public void afterTextChanged(Editable s) {
199 //                Log.d("input", "text changed");
200                 check_transaction_submittable();
201             }
202         });
203
204     }
205
206     @TargetApi(Build.VERSION_CODES.N)
207     private void hook_autocompletion_adapter(final TableRow row) {
208         String[] from = {"name"};
209         int[] to = {android.R.id.text1};
210         SQLiteDatabase db = MobileLedgerDB.db;
211
212         AutoCompleteTextView acc = (AutoCompleteTextView) row.getChildAt(0);
213         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
214         adapter.setStringConversionColumn(1);
215
216         FilterQueryProvider provider = new FilterQueryProvider() {
217             @Override
218             public Cursor runQuery(CharSequence constraint) {
219                 if (constraint == null) return null;
220
221                 String str = constraint.toString().toUpperCase();
222                 Log.d("autocompletion", "Looking for "+str);
223                 String[] col_names = {FontsContract.Columns._ID, "name"};
224                 MatrixCursor c = new MatrixCursor(col_names);
225
226                 Cursor matches = db.rawQuery("SELECT name FROM accounts WHERE UPPER(name) LIKE '%'||?||'%' ORDER BY name;", new String[]{str});
227
228                 try {
229                     int i = 0;
230                     while (matches.moveToNext()) {
231                         String name = matches.getString(0);
232                         Log.d("autocompletion-match", name);
233                         c.newRow().add(i++).add(name);
234                     }
235                 }
236                 finally {
237                     matches.close();
238                 }
239
240                 return c;
241
242             }
243         };
244
245         adapter.setFilterQueryProvider(provider);
246
247         acc.setAdapter(adapter);
248     }
249
250     public boolean onCreateOptionsMenu(Menu menu) {
251         // Inflate the menu; this adds items to the action bar if it is present.
252         getMenuInflater().inflate(R.menu.new_transaction, menu);
253
254         return true;
255     }
256
257     public void pickTransactionDate(View view) {
258         DialogFragment picker = new DatePickerFragment();
259         picker.show(getSupportFragmentManager(), "datePicker");
260     }
261
262     public int dp2px(float dp) {
263         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
264     }
265
266     private void do_add_account_row(boolean focus) {
267         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
268         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
269         acc.setHint(R.string.new_transaction_account_hint);
270         acc.setWidth(0);
271
272         final EditText amt = new EditText(this);
273         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
274         amt.setHint(R.string.new_transaction_amount_hint);
275         amt.setWidth(0);
276         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
277         amt.setMinWidth(dp2px(40));
278         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
279
280         final TableRow row = new TableRow(this);
281         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
282         row.addView(acc);
283         row.addView(amt);
284         table.addView(row);
285
286         if (focus) acc.requestFocus();
287
288         hook_swipe_listener(row);
289         hook_autocompletion_adapter(row);
290         hook_text_change_listener(acc);
291         hook_text_change_listener(amt);
292     }
293
294     public void addTransactionAccountFromMenu(MenuItem item) {
295         do_add_account_row(true);
296     }
297
298     private void check_transaction_submittable() {
299         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
300         int accounts = 0;
301         int accounts_with_values = 0;
302         int empty_rows = 0;
303         for(int i = 0; i < table.getChildCount(); i++ ) {
304             TableRow row = (TableRow) table.getChildAt(i);
305
306             TextView acc_name_v = (TextView) row.getChildAt(0);
307
308             String acc_name = String.valueOf(acc_name_v.getText());
309             acc_name = acc_name.trim();
310             if (!acc_name.isEmpty()) {
311                 accounts++;
312
313                 TextView amount_v = (TextView) row.getChildAt(1);
314                 String amt = String.valueOf(amount_v.getText());
315
316                 if (!amt.isEmpty()) accounts_with_values++;
317             } else empty_rows++;
318         }
319
320         if (accounts_with_values == accounts && empty_rows == 0) {
321             do_add_account_row(false);
322         }
323
324         if ((accounts >= 2) && (accounts_with_values >= (accounts - 1))) {
325             show_fab();
326         } else hide_fab();
327     }
328
329     @Override
330     public void done() {
331         fab.setImageResource(R.drawable.ic_check_white_24dp);
332         progress.setVisibility(View.INVISIBLE);
333         Log.d("visuals", "hiding progress");
334
335         fab_should_be_visible = false;
336         final Handler fade_out = new Handler();
337         fade_out.postDelayed(new Runnable() {
338             @Override
339             public void run() {
340                 Log.d("visuals", "hiding FAB");
341
342                 hide_fab(true);
343             }
344         }, 1000);
345         reset_form();
346     }
347
348     private void reset_form() {
349         text_date.setText("");
350         text_descr.setText("");
351         while(table.getChildCount() > 2) {
352             table.removeViewAt(2);
353         }
354         for( int i = 0; i < 2; i++ ) {
355             TableRow tr = (TableRow) table.getChildAt(i);
356             if ( tr == null) break;
357
358             ((TextView)tr.getChildAt(0)).setText("");
359             ((TextView)tr.getChildAt(1)).setText("");
360         }
361
362         text_descr.requestFocus();
363     }
364 }