]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/NewTransactionActivity.java
migrate to a proper db helper class, sub-classed from SQLiteOpenHelper
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / NewTransactionActivity.java
1 package net.ktnx.mobileledger;
2
3 import android.annotation.SuppressLint;
4 import android.annotation.TargetApi;
5 import android.database.Cursor;
6 import android.database.MatrixCursor;
7 import android.database.sqlite.SQLiteDatabase;
8 import android.os.Build;
9 import android.os.Bundle;
10 import android.preference.PreferenceManager;
11 import android.provider.FontsContract;
12 import android.support.design.widget.BaseTransientBottomBar;
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.Gravity;
23 import android.view.Menu;
24 import android.view.MenuItem;
25 import android.view.MotionEvent;
26 import android.view.View;
27 import android.view.inputmethod.EditorInfo;
28 import android.widget.AutoCompleteTextView;
29 import android.widget.EditText;
30 import android.widget.FilterQueryProvider;
31 import android.widget.ProgressBar;
32 import android.widget.SimpleCursorAdapter;
33 import android.widget.TableLayout;
34 import android.widget.TableRow;
35 import android.widget.TextView;
36
37 import java.util.Date;
38 import java.util.Objects;
39
40 /*
41  * TODO: auto-fill of transaction description
42  *       if Android O's implementation won't work, add a custom one
43  * TODO: nicer progress while transaction is submitted
44  * TODO: latest transactions, maybe with browsing further in the past?
45  * TODO: reports
46  * TODO: get rid of the custom session/cookie and auth code?
47  *         (the last problem with the POST was the missing content-length header)
48  * TODO: app icon
49  * TODO: nicer swiping removal with visual feedback
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 ProgressBar progress;
57     private TextView text_date;
58     private AutoCompleteTextView text_descr;
59     private static SaveTransactionTask saver;
60     private MenuItem mSave;
61     private MobileLedgerDatabase dbh;
62
63     @Override
64     protected void onCreate(Bundle savedInstanceState) {
65         super.onCreate(savedInstanceState);
66         setContentView(R.layout.activity_new_transaction);
67         Toolbar toolbar = findViewById(R.id.toolbar);
68         setSupportActionBar(toolbar);
69
70         dbh = new MobileLedgerDatabase(this);
71
72         text_date = findViewById(R.id.new_transaction_date);
73         text_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
74             @Override
75             public
76             void onFocusChange(View v, boolean hasFocus) {
77                 if (hasFocus) pickTransactionDate(v);
78             }
79         });
80         text_descr = findViewById(R.id.new_transaction_description);
81         hook_autocompletion_adapter(text_descr, MobileLedgerDatabase
82                 .DESCRIPTION_HISTORY_TABLE, "description");
83         hook_text_change_listener(text_descr);
84
85         progress = findViewById(R.id.save_transaction_progress);
86
87         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
88         table = findViewById(R.id.new_transaction_accounts_table);
89         for (int i = 0; i < table.getChildCount(); i++) {
90             TableRow row = (TableRow) table.getChildAt(i);
91             AutoCompleteTextView acc_name_view = (AutoCompleteTextView) row.getChildAt(0);
92             TextView amount_view = (TextView) row.getChildAt(1);
93             hook_swipe_listener(row);
94             hook_autocompletion_adapter(acc_name_view, MobileLedgerDatabase.ACCOUNTS_TABLE, "name");
95             hook_text_change_listener(acc_name_view);
96             hook_text_change_listener(amount_view);
97 //            Log.d("swipe", "hooked to row "+i);
98         }
99     }
100
101     @Override
102     protected
103     void onStart() {
104         super.onStart();
105         if (text_descr.getText().toString().isEmpty()) text_descr.requestFocus();
106     }
107
108     @Override
109     public void finish() {
110         super.finish();
111         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
112     }
113
114     @Override
115     public boolean onOptionsItemSelected(MenuItem item) {
116         switch (item.getItemId()) {
117             case android.R.id.home:
118                 finish();
119                 return true;
120         }
121         return super.onOptionsItemSelected(item);
122     }
123
124     public void save_transaction() {
125         if (mSave != null) mSave.setVisible(false);
126         toggle_all_editing(false);
127         progress.setVisibility(View.VISIBLE);
128
129         saver = new SaveTransactionTask(this);
130
131         saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
132         String date = text_date.getText().toString();
133         if (date.isEmpty()) date = String.valueOf(new Date().getDate());
134         LedgerTransaction tr = new LedgerTransaction(date, text_descr.getText().toString());
135
136         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
137         for ( int i = 0; i < table.getChildCount(); i++ ) {
138             TableRow row = (TableRow) table.getChildAt(i);
139             String acc = ((TextView) row.getChildAt(0)).getText().toString();
140             String amt = ((TextView) row.getChildAt(1)).getText().toString();
141             LedgerTransactionItem item =
142                     amt.length() > 0
143                     ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
144                     : new LedgerTransactionItem( acc );
145
146             tr.add_item(item);
147         }
148         saver.execute(tr);
149     }
150
151     private void toggle_all_editing(boolean enabled) {
152         text_date.setEnabled(enabled);
153         text_descr.setEnabled(enabled);
154         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
155         for (int i = 0; i < table.getChildCount(); i++) {
156             TableRow row = (TableRow) table.getChildAt(i);
157             for (int j = 0; j < row.getChildCount(); j++) {
158                 row.getChildAt(j).setEnabled(enabled);
159             }
160         }
161     }
162
163     private void hook_swipe_listener(final TableRow row) {
164         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
165             public void onSwipeLeft() {
166 //                Log.d("swipe", "LEFT" + row.getId());
167                 if (table.getChildCount() > 2) {
168                     TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
169                     TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
170                     TextView prev_amt =
171                             (prev_row != null) ? (TextView) prev_row.getChildAt(1) : text_descr;
172                     TextView next_acc =
173                             (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
174
175                     if (next_acc == null) {
176                         prev_amt.setNextFocusRightId(R.id.none);
177                         prev_amt.setNextFocusForwardId(R.id.none);
178                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
179                     }
180                     else {
181                         prev_amt.setNextFocusRightId(next_acc.getId());
182                         prev_amt.setNextFocusForwardId(next_acc.getId());
183                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
184                     }
185
186                     if (row.hasFocus()) {
187                         if (next_acc != null) next_acc.requestFocus();
188                         else prev_amt.requestFocus();
189                     }
190
191                     table.removeView(row);
192                     check_transaction_submittable();
193 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
194                 }
195                 else {
196                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
197                             .setAction("Action", null).show();
198                 }
199             }
200 //            @Override
201 //            public boolean performClick(View view, MotionEvent m) {
202 //                return true;
203 //            }
204             public boolean onTouch(View view, MotionEvent m) {
205                 return gestureDetector.onTouchEvent(m);
206             }
207         });
208     }
209
210     private void hook_text_change_listener(final TextView view) {
211         view.addTextChangedListener(new TextWatcher() {
212             @Override
213             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
214
215             }
216
217             @Override
218             public void onTextChanged(CharSequence s, int start, int before, int count) {
219
220             }
221
222             @Override
223             public void afterTextChanged(Editable s) {
224 //                Log.d("input", "text changed");
225                 check_transaction_submittable();
226             }
227         });
228
229     }
230
231     @TargetApi(Build.VERSION_CODES.N)
232     private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table, final String field) {
233         String[] from = {field};
234         int[] to = {android.R.id.text1};
235         SimpleCursorAdapter adapter =
236                 new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null,
237                         from, to, 0);
238         adapter.setStringConversionColumn(1);
239
240         FilterQueryProvider provider = new FilterQueryProvider() {
241             @Override
242             public
243             Cursor runQuery(CharSequence constraint) {
244                 if (constraint == null) return null;
245
246                 String str = constraint.toString().toUpperCase();
247                 Log.d("autocompletion", "Looking for " + str);
248                 String[] col_names = {FontsContract.Columns._ID, field};
249                 MatrixCursor c = new MatrixCursor(col_names);
250
251                 try (SQLiteDatabase db = dbh.getReadableDatabase()) {
252
253                     try (Cursor matches = db.rawQuery(String.format(
254                             "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 "
255                                     + "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 "
256                                     + "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end "
257                                     + "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' "
258                                     + "ORDER BY 2, 1;", field, field, field, field, table, field),
259                             new String[]{str, str, str, str}))
260                     {
261                         int i = 0;
262                         while (matches.moveToNext()) {
263                             String match = matches.getString(0);
264                             int order = matches.getInt(1);
265                             Log.d("autocompletion", String.format("match: %s |%d", match, order));
266                             c.newRow().add(i++).add(match);
267                         }
268                     }
269
270                     return c;
271                 }
272
273             }
274         };
275
276         adapter.setFilterQueryProvider(provider);
277
278         view.setAdapter(adapter);
279     }
280
281     public boolean onCreateOptionsMenu(Menu menu) {
282         // Inflate the menu; this adds items to the action bar if it is present.
283         getMenuInflater().inflate(R.menu.new_transaction, menu);
284         mSave = menu.findItem(R.id.action_submit_transaction);
285         if (mSave == null) throw new AssertionError();
286
287         check_transaction_submittable();
288
289         return true;
290     }
291
292     public void pickTransactionDate(View view) {
293         DialogFragment picker = new DatePickerFragment();
294         picker.show(getSupportFragmentManager(), "datePicker");
295     }
296
297     public int dp2px(float dp) {
298         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
299     }
300
301     private void do_add_account_row(boolean focus) {
302         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
303         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
304         acc.setHint(R.string.new_transaction_account_hint);
305         acc.setWidth(0);
306         acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION
307                 | EditorInfo.IME_FLAG_NAVIGATE_NEXT);
308         acc.setSingleLine(true);
309
310         final EditText amt = new EditText(this);
311         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
312                 TableRow.LayoutParams.MATCH_PARENT, 1f));
313         amt.setHint(R.string.new_transaction_amount_hint);
314         amt.setWidth(0);
315         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
316         amt.setMinWidth(dp2px(40));
317         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
318         amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
319
320         // forward navigation support
321         final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
322         final TextView last_amt = (TextView) last_row.getChildAt(1);
323         last_amt.setNextFocusForwardId(acc.getId());
324         last_amt.setNextFocusRightId(acc.getId());
325         last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
326         acc.setNextFocusForwardId(amt.getId());
327         acc.setNextFocusRightId(amt.getId());
328
329         final TableRow row = new TableRow(this);
330         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
331         row.setGravity(Gravity.BOTTOM);
332         row.addView(acc);
333         row.addView(amt);
334         table.addView(row);
335
336         if (focus) acc.requestFocus();
337
338         hook_swipe_listener(row);
339         hook_autocompletion_adapter(acc, MobileLedgerDatabase.ACCOUNTS_TABLE, "name");
340         hook_text_change_listener(acc);
341         hook_text_change_listener(amt);
342     }
343
344     public void addTransactionAccountFromMenu(MenuItem item) {
345         do_add_account_row(true);
346     }
347
348     public
349     void resetTransactionFromMenu(MenuItem item) {
350         reset_form();
351     }
352
353     public void saveTransactionFromMenu(MenuItem item) {
354         save_transaction();
355     }
356
357     private
358     boolean is_zero(float f) {
359         return (f < 0.005) && (f > -0.005);
360     }
361
362     // rules:
363     // 1) at least two account names
364     // 2) each amount must have account name
365     // 3) amounts must balance to 0, or
366     // 3a) there must be exactly one empty amount
367     // 4) empty accounts with empty amounts are ignored
368     // 5) a row with an empty account name or empty amount is guaranteed to exist
369     @SuppressLint("DefaultLocale")
370     private void check_transaction_submittable() {
371         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
372         int accounts = 0;
373         int accounts_with_values = 0;
374         int amounts = 0;
375         int amounts_with_accounts = 0;
376         int empty_rows = 0;
377         TextView empty_amount = null;
378         boolean single_empty_amount = false;
379         boolean single_empty_amount_has_account = false;
380         float running_total = 0f;
381         boolean have_description =
382                 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
383                         .isEmpty();
384
385         try {
386             for (int i = 0; i < table.getChildCount(); i++) {
387                 TableRow row = (TableRow) table.getChildAt(i);
388
389                 TextView acc_name_v = (TextView) row.getChildAt(0);
390                 TextView amount_v = (TextView) row.getChildAt(1);
391                 String amt = String.valueOf(amount_v.getText());
392                 String acc_name = String.valueOf(acc_name_v.getText());
393                 acc_name = acc_name.trim();
394
395                 if (!acc_name.isEmpty()) {
396                     accounts++;
397
398                     if (!amt.isEmpty()) {
399                         accounts_with_values++;
400                     }
401                 }
402                 else empty_rows++;
403
404                 if (amt.isEmpty()) {
405                     amount_v.setHint(String.format("%1.2f", 0f));
406                     if (empty_amount == null) {
407                         empty_amount = amount_v;
408                         single_empty_amount = true;
409                         single_empty_amount_has_account = !acc_name.isEmpty();
410                     }
411                     else if (!acc_name.isEmpty()) single_empty_amount = false;
412                 }
413                 else {
414                     amounts++;
415                     if (!acc_name.isEmpty()) amounts_with_accounts++;
416                     running_total += Float.valueOf(amt);
417                 }
418             }
419
420             if ((empty_rows == 0) && ((table.getChildCount() == accounts) || (table.getChildCount()
421                     == amounts)))
422             {
423                 do_add_account_row(false);
424             }
425
426             Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, "
427                             + "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, "
428                             + "single_empty_with_acc=%s", accounts, accounts_with_values,
429                     amounts_with_accounts, amounts, running_total,
430                     (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
431
432             if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) && (
433                     amounts_with_accounts == amounts) && (
434                     single_empty_amount && single_empty_amount_has_account || is_zero(
435                             running_total)))
436             {
437                 if (mSave != null) mSave.setVisible(true);
438             }
439             else if (mSave != null) mSave.setVisible(false);
440
441             if (single_empty_amount) {
442                 empty_amount
443                         .setHint(String.format("%1.2f", (running_total > 0) ? -running_total : 0f));
444             }
445
446         }
447         catch (NumberFormatException e) {
448             if (mSave != null) mSave.setVisible(false);
449         }
450         catch (Exception e) {
451             e.printStackTrace();
452             if (mSave != null) mSave.setVisible(false);
453         }
454     }
455
456     @Override
457     public
458     void done(String error) {
459         progress.setVisibility(View.INVISIBLE);
460         Log.d("visuals", "hiding progress");
461
462         if (error == null) reset_form();
463         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
464                 BaseTransientBottomBar.LENGTH_LONG).show();
465
466         toggle_all_editing(true);
467         check_transaction_submittable();
468     }
469
470     private void reset_form() {
471         text_date.setText("");
472         text_descr.setText("");
473
474         text_descr.requestFocus();
475
476         while(table.getChildCount() > 2) {
477             table.removeViewAt(2);
478         }
479         for( int i = 0; i < 2; i++ ) {
480             TableRow tr = (TableRow) table.getChildAt(i);
481             if ( tr == null) break;
482
483             ((TextView)tr.getChildAt(0)).setText("");
484             ((TextView)tr.getChildAt(1)).setText("");
485         }
486     }
487 }