]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/NewTransactionActivity.java
new transaction: remove the xml-driven rows and populate by hand
[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         table.removeAllViews();
82         do_add_account_row(false);
83         do_add_account_row(false);
84     }
85
86     @Override
87     public void finish() {
88         super.finish();
89         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
90     }
91
92     @Override
93     public boolean onOptionsItemSelected(MenuItem item) {
94         switch (item.getItemId()) {
95             case android.R.id.home:
96                 finish();
97                 return true;
98         }
99         return super.onOptionsItemSelected(item);
100     }
101
102     public void save_transaction() {
103         if (mSave != null) mSave.setVisible(false);
104         toggle_all_editing(false);
105         progress.setVisibility(View.VISIBLE);
106
107         saver = new SaveTransactionTask(this);
108
109         saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
110         LedgerTransaction tr = new LedgerTransaction(text_date.getText().toString(), text_descr.getText().toString());
111
112         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
113         for ( int i = 0; i < table.getChildCount(); i++ ) {
114             TableRow row = (TableRow) table.getChildAt(i);
115             String acc = ((TextView) row.getChildAt(0)).getText().toString();
116             String amt = ((TextView) row.getChildAt(1)).getText().toString();
117             LedgerTransactionItem item =
118                     amt.length() > 0
119                     ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
120                     : new LedgerTransactionItem( acc );
121
122             tr.add_item(item);
123         }
124         saver.execute(tr);
125     }
126
127     private void toggle_all_editing(boolean enabled) {
128         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
129         for (int i = 0; i < table.getChildCount(); i++) {
130             TableRow row = (TableRow) table.getChildAt(i);
131             for (int j = 0; j < row.getChildCount(); j++) {
132                 row.getChildAt(j).setEnabled(enabled);
133             }
134         }
135     }
136
137     private void hook_swipe_listener(final TableRow row) {
138         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
139             public void onSwipeLeft() {
140 //                Log.d("swipe", "LEFT" + row.getId());
141                 if (table.getChildCount() > 2) {
142                     table.removeView(row);
143 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
144                 }
145                 else {
146                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
147                             .setAction("Action", null).show();
148                 }
149             }
150 //            @Override
151 //            public boolean performClick(View view, MotionEvent m) {
152 //                return true;
153 //            }
154             public boolean onTouch(View view, MotionEvent m) {
155                 return gestureDetector.onTouchEvent(m);
156             }
157         });
158     }
159
160     private void hook_text_change_listener(final TextView view) {
161         view.addTextChangedListener(new TextWatcher() {
162             @Override
163             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
164
165             }
166
167             @Override
168             public void onTextChanged(CharSequence s, int start, int before, int count) {
169
170             }
171
172             @Override
173             public void afterTextChanged(Editable s) {
174 //                Log.d("input", "text changed");
175                 check_transaction_submittable();
176             }
177         });
178
179     }
180
181     @TargetApi(Build.VERSION_CODES.N)
182     private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table, final String field) {
183         String[] from = {field};
184         int[] to = {android.R.id.text1};
185         SQLiteDatabase db = MobileLedgerDB.db;
186
187         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
188         adapter.setStringConversionColumn(1);
189
190         FilterQueryProvider provider = new FilterQueryProvider() {
191             @Override
192             public Cursor runQuery(CharSequence constraint) {
193                 if (constraint == null) return null;
194
195                 String str = constraint.toString().toUpperCase();
196                 Log.d("autocompletion", "Looking for "+str);
197                 String[] col_names = {FontsContract.Columns._ID, field};
198                 MatrixCursor c = new MatrixCursor(col_names);
199
200                 Cursor matches = db.rawQuery(String.format(
201                         "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
202                                 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
203                                 "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
204                                 "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " +
205                                 "ORDER BY 2, 1;", field, field, field, field, table, field),
206                         new String[]{str, str, str, str});
207
208                 try {
209                     int i = 0;
210                     while (matches.moveToNext()) {
211                         String match = matches.getString(0);
212                         int order = matches.getInt(1);
213                         Log.d("autocompletion", String.format("match: %s |%d", match, order));
214                         c.newRow().add(i++).add(match);
215                     }
216                 }
217                 finally {
218                     matches.close();
219                 }
220
221                 return c;
222
223             }
224         };
225
226         adapter.setFilterQueryProvider(provider);
227
228         view.setAdapter(adapter);
229     }
230
231     public boolean onCreateOptionsMenu(Menu menu) {
232         // Inflate the menu; this adds items to the action bar if it is present.
233         getMenuInflater().inflate(R.menu.new_transaction, menu);
234         mSave = menu.findItem(R.id.action_submit_transaction);
235         if (mSave == null) throw new AssertionError();
236
237         check_transaction_submittable();
238
239         return true;
240     }
241
242     public void pickTransactionDate(View view) {
243         DialogFragment picker = new DatePickerFragment();
244         picker.show(getSupportFragmentManager(), "datePicker");
245     }
246
247     public int dp2px(float dp) {
248         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
249     }
250
251     private void do_add_account_row(boolean focus) {
252         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
253         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
254         acc.setHint(R.string.new_transaction_account_hint);
255         acc.setWidth(0);
256
257         final EditText amt = new EditText(this);
258         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
259                 TableRow.LayoutParams.MATCH_PARENT, 1f));
260         amt.setHint(R.string.new_transaction_amount_hint);
261         amt.setWidth(0);
262         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
263         amt.setMinWidth(dp2px(40));
264         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
265
266         final TableRow row = new TableRow(this);
267         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
268         row.setGravity(Gravity.BOTTOM);
269         row.addView(acc);
270         row.addView(amt);
271         table.addView(row);
272
273         if (focus) acc.requestFocus();
274
275         hook_swipe_listener(row);
276         hook_autocompletion_adapter(acc, MobileLedgerDB.ACCOUNTS_TABLE, "name");
277         hook_text_change_listener(acc);
278         hook_text_change_listener(amt);
279     }
280
281     public void addTransactionAccountFromMenu(MenuItem item) {
282         do_add_account_row(true);
283     }
284
285     public void saveTransactionFromMenu(MenuItem item) {
286         save_transaction();
287     }
288
289     private void check_transaction_submittable() {
290         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
291         int accounts = 0;
292         int accounts_with_values = 0;
293         int empty_rows = 0;
294         for(int i = 0; i < table.getChildCount(); i++ ) {
295             TableRow row = (TableRow) table.getChildAt(i);
296
297             TextView acc_name_v = (TextView) row.getChildAt(0);
298
299             String acc_name = String.valueOf(acc_name_v.getText());
300             acc_name = acc_name.trim();
301             if (!acc_name.isEmpty()) {
302                 accounts++;
303
304                 TextView amount_v = (TextView) row.getChildAt(1);
305                 String amt = String.valueOf(amount_v.getText());
306
307                 if (!amt.isEmpty()) accounts_with_values++;
308             } else empty_rows++;
309         }
310
311         if (accounts_with_values == accounts && empty_rows == 0) {
312             do_add_account_row(false);
313         }
314
315         if ((accounts >= 2) && (accounts_with_values >= (accounts - 1))) {
316             if (mSave != null) mSave.setVisible(true);
317         } else {
318             if (mSave != null) mSave.setVisible(false);
319         }
320     }
321
322     @Override
323     public
324     void done(String error) {
325         progress.setVisibility(View.INVISIBLE);
326         Log.d("visuals", "hiding progress");
327
328         if (error == null) reset_form();
329         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
330                 BaseTransientBottomBar.LENGTH_LONG).show();
331
332         toggle_all_editing(true);
333         check_transaction_submittable();
334     }
335
336     private void reset_form() {
337         text_date.setText("");
338         text_descr.setText("");
339         while(table.getChildCount() > 2) {
340             table.removeViewAt(2);
341         }
342         for( int i = 0; i < 2; i++ ) {
343             TableRow tr = (TableRow) table.getChildAt(i);
344             if ( tr == null) break;
345
346             ((TextView)tr.getChildAt(0)).setText("");
347             ((TextView)tr.getChildAt(1)).setText("");
348         }
349
350         text_descr.requestFocus();
351     }
352 }