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