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