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