]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/NewTransactionActivity.java
pop-up the date picked dialog as soon as the date field receives focus
[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.BaseTransientBottomBar;
12 import android.support.design.widget.Snackbar;
13 import android.support.v4.app.DialogFragment;
14 import android.support.v7.app.AppCompatActivity;
15 import android.support.v7.widget.Toolbar;
16 import android.text.Editable;
17 import android.text.InputType;
18 import android.text.TextWatcher;
19 import android.util.Log;
20 import android.util.TypedValue;
21 import android.view.Gravity;
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: 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: setup wizard
48  * TODO: update accounts/check settings upon change of backend settings
49  *  */
50
51 public class NewTransactionActivity extends AppCompatActivity implements TaskCallback {
52     private TableLayout table;
53     private ProgressBar progress;
54     private TextView text_date;
55     private AutoCompleteTextView text_descr;
56     private static SaveTransactionTask saver;
57     private MenuItem mSave;
58
59     @Override
60     protected void onCreate(Bundle savedInstanceState) {
61         super.onCreate(savedInstanceState);
62         setContentView(R.layout.activity_new_transaction);
63         Toolbar toolbar = findViewById(R.id.toolbar);
64         setSupportActionBar(toolbar);
65
66         text_date = findViewById(R.id.new_transaction_date);
67         text_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
68             @Override
69             public
70             void onFocusChange(View v, boolean hasFocus) {
71                 if (hasFocus) pickTransactionDate(v);
72             }
73         });
74         text_descr = findViewById(R.id.new_transaction_description);
75         hook_autocompletion_adapter(text_descr, MobileLedgerDB.DESCRIPTION_HISTORY_TABLE, "description");
76
77         progress = findViewById(R.id.save_transaction_progress);
78
79         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
80         table = findViewById(R.id.new_transaction_accounts_table);
81         for (int i = 0; i < table.getChildCount(); i++) {
82             TableRow row = (TableRow) table.getChildAt(i);
83             AutoCompleteTextView acc_name_view = (AutoCompleteTextView) row.getChildAt(0);
84             TextView amount_view = (TextView) row.getChildAt(1);
85             hook_swipe_listener(row);
86             hook_autocompletion_adapter(acc_name_view, MobileLedgerDB.ACCOUNTS_TABLE, "name");
87             hook_text_change_listener(acc_name_view);
88             hook_text_change_listener(amount_view);
89 //            Log.d("swipe", "hooked to row "+i);
90         }
91     }
92
93     @Override
94     public void finish() {
95         super.finish();
96         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
97     }
98
99     @Override
100     public boolean onOptionsItemSelected(MenuItem item) {
101         switch (item.getItemId()) {
102             case android.R.id.home:
103                 finish();
104                 return true;
105         }
106         return super.onOptionsItemSelected(item);
107     }
108
109     public void save_transaction() {
110         if (mSave != null) mSave.setVisible(false);
111         toggle_all_editing(false);
112         progress.setVisibility(View.VISIBLE);
113
114         saver = new SaveTransactionTask(this);
115
116         saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
117         LedgerTransaction tr = new LedgerTransaction(text_date.getText().toString(), text_descr.getText().toString());
118
119         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
120         for ( int i = 0; i < table.getChildCount(); i++ ) {
121             TableRow row = (TableRow) table.getChildAt(i);
122             String acc = ((TextView) row.getChildAt(0)).getText().toString();
123             String amt = ((TextView) row.getChildAt(1)).getText().toString();
124             LedgerTransactionItem item =
125                     amt.length() > 0
126                     ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
127                     : new LedgerTransactionItem( acc );
128
129             tr.add_item(item);
130         }
131         saver.execute(tr);
132     }
133
134     private void toggle_all_editing(boolean enabled) {
135         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
136         for (int i = 0; i < table.getChildCount(); i++) {
137             TableRow row = (TableRow) table.getChildAt(i);
138             for (int j = 0; j < row.getChildCount(); j++) {
139                 row.getChildAt(j).setEnabled(enabled);
140             }
141         }
142     }
143
144     private void hook_swipe_listener(final TableRow row) {
145         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
146             public void onSwipeLeft() {
147 //                Log.d("swipe", "LEFT" + row.getId());
148                 if (table.getChildCount() > 2) {
149                     table.removeView(row);
150 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
151                 }
152                 else {
153                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
154                             .setAction("Action", null).show();
155                 }
156             }
157 //            @Override
158 //            public boolean performClick(View view, MotionEvent m) {
159 //                return true;
160 //            }
161             public boolean onTouch(View view, MotionEvent m) {
162                 return gestureDetector.onTouchEvent(m);
163             }
164         });
165     }
166
167     private void hook_text_change_listener(final TextView view) {
168         view.addTextChangedListener(new TextWatcher() {
169             @Override
170             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
171
172             }
173
174             @Override
175             public void onTextChanged(CharSequence s, int start, int before, int count) {
176
177             }
178
179             @Override
180             public void afterTextChanged(Editable s) {
181 //                Log.d("input", "text changed");
182                 check_transaction_submittable();
183             }
184         });
185
186     }
187
188     @TargetApi(Build.VERSION_CODES.N)
189     private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table, final String field) {
190         String[] from = {field};
191         int[] to = {android.R.id.text1};
192         SQLiteDatabase db = MobileLedgerDB.db;
193
194         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
195         adapter.setStringConversionColumn(1);
196
197         FilterQueryProvider provider = new FilterQueryProvider() {
198             @Override
199             public Cursor runQuery(CharSequence constraint) {
200                 if (constraint == null) return null;
201
202                 String str = constraint.toString().toUpperCase();
203                 Log.d("autocompletion", "Looking for "+str);
204                 String[] col_names = {FontsContract.Columns._ID, field};
205                 MatrixCursor c = new MatrixCursor(col_names);
206
207                 Cursor matches = db.rawQuery(String.format(
208                         "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
209                                 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
210                                 "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
211                                 "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " +
212                                 "ORDER BY 2, 1;", field, field, field, field, table, field),
213                         new String[]{str, str, str, str});
214
215                 try {
216                     int i = 0;
217                     while (matches.moveToNext()) {
218                         String match = matches.getString(0);
219                         int order = matches.getInt(1);
220                         Log.d("autocompletion", String.format("match: %s |%d", match, order));
221                         c.newRow().add(i++).add(match);
222                     }
223                 }
224                 finally {
225                     matches.close();
226                 }
227
228                 return c;
229
230             }
231         };
232
233         adapter.setFilterQueryProvider(provider);
234
235         view.setAdapter(adapter);
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, getResources().getDisplayMetrics()));
256     }
257
258     private void do_add_account_row(boolean focus) {
259         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
260         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
261         acc.setHint(R.string.new_transaction_account_hint);
262         acc.setWidth(0);
263
264         final EditText amt = new EditText(this);
265         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
266                 TableRow.LayoutParams.MATCH_PARENT, 1f));
267         amt.setHint(R.string.new_transaction_amount_hint);
268         amt.setWidth(0);
269         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
270         amt.setMinWidth(dp2px(40));
271         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
272
273         final TableRow row = new TableRow(this);
274         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
275         row.setGravity(Gravity.BOTTOM);
276         row.addView(acc);
277         row.addView(amt);
278         table.addView(row);
279
280         if (focus) acc.requestFocus();
281
282         hook_swipe_listener(row);
283         hook_autocompletion_adapter(acc, MobileLedgerDB.ACCOUNTS_TABLE, "name");
284         hook_text_change_listener(acc);
285         hook_text_change_listener(amt);
286     }
287
288     public void addTransactionAccountFromMenu(MenuItem item) {
289         do_add_account_row(true);
290     }
291
292     public void saveTransactionFromMenu(MenuItem item) {
293         save_transaction();
294     }
295
296     private void check_transaction_submittable() {
297         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
298         int accounts = 0;
299         int accounts_with_values = 0;
300         int empty_rows = 0;
301         for(int i = 0; i < table.getChildCount(); i++ ) {
302             TableRow row = (TableRow) table.getChildAt(i);
303
304             TextView acc_name_v = (TextView) row.getChildAt(0);
305
306             String acc_name = String.valueOf(acc_name_v.getText());
307             acc_name = acc_name.trim();
308             if (!acc_name.isEmpty()) {
309                 accounts++;
310
311                 TextView amount_v = (TextView) row.getChildAt(1);
312                 String amt = String.valueOf(amount_v.getText());
313
314                 if (!amt.isEmpty()) accounts_with_values++;
315             } else empty_rows++;
316         }
317
318         if (accounts_with_values == accounts && empty_rows == 0) {
319             do_add_account_row(false);
320         }
321
322         if ((accounts >= 2) && (accounts_with_values >= (accounts - 1))) {
323             if (mSave != null) mSave.setVisible(true);
324         } else {
325             if (mSave != null) mSave.setVisible(false);
326         }
327     }
328
329     @Override
330     public
331     void done(String error) {
332         progress.setVisibility(View.INVISIBLE);
333         Log.d("visuals", "hiding progress");
334
335         if (error == null) reset_form();
336         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
337                 BaseTransientBottomBar.LENGTH_LONG).show();
338
339         toggle_all_editing(true);
340         check_transaction_submittable();
341     }
342
343     private void reset_form() {
344         text_date.setText("");
345         text_descr.setText("");
346         while(table.getChildCount() > 2) {
347             table.removeViewAt(2);
348         }
349         for( int i = 0; i < 2; i++ ) {
350             TableRow tr = (TableRow) table.getChildAt(i);
351             if ( tr == null) break;
352
353             ((TextView)tr.getChildAt(0)).setText("");
354             ((TextView)tr.getChildAt(1)).setText("");
355         }
356
357         text_descr.requestFocus();
358     }
359 }