]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/NewTransactionActivity.java
remove two done TODO items
[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.Menu;
22 import android.view.MenuItem;
23 import android.view.MotionEvent;
24 import android.view.View;
25 import android.widget.AutoCompleteTextView;
26 import android.widget.EditText;
27 import android.widget.FilterQueryProvider;
28 import android.widget.ProgressBar;
29 import android.widget.SimpleCursorAdapter;
30 import android.widget.TableLayout;
31 import android.widget.TableRow;
32 import android.widget.TextView;
33
34 import java.util.Objects;
35
36 /*
37  * TODO: auto-fill of transaction description
38  *       if Android O's implementation won't work, add a custom one
39  * TODO: nicer progress while transaction is submitted
40  * TODO: latest transactions, maybe with browsing further in the past?
41  * TODO: reports
42  * TODO: get rid of the custom session/cookie and auth code?
43  *         (the last problem with the POST was the missing content-length header)
44  * TODO: app icon
45  * TODO: nicer swiping removal with visual feedback
46  * TODO: setup wizard
47  * TODO: update accounts/check settings upon change of backend settings
48  *  */
49
50 public class NewTransactionActivity extends AppCompatActivity implements TaskCallback {
51     private TableLayout table;
52     private ProgressBar progress;
53     private TextView text_date;
54     private AutoCompleteTextView text_descr;
55     private static SaveTransactionTask saver;
56     private MenuItem mSave;
57
58     @Override
59     protected void onCreate(Bundle savedInstanceState) {
60         super.onCreate(savedInstanceState);
61         setContentView(R.layout.activity_new_transaction);
62         Toolbar toolbar = findViewById(R.id.toolbar);
63         setSupportActionBar(toolbar);
64
65         text_date = findViewById(R.id.new_transaction_date);
66         text_descr = findViewById(R.id.new_transaction_description);
67         hook_autocompletion_adapter(text_descr, MobileLedgerDB.DESCRIPTION_HISTORY_TABLE, "description");
68
69         progress = findViewById(R.id.save_transaction_progress);
70
71         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
72         table = findViewById(R.id.new_transaction_accounts_table);
73         for (int i = 0; i < table.getChildCount(); i++) {
74             TableRow row = (TableRow) table.getChildAt(i);
75             AutoCompleteTextView acc_name_view = (AutoCompleteTextView) row.getChildAt(0);
76             TextView amount_view = (TextView) row.getChildAt(1);
77             hook_swipe_listener(row);
78             hook_autocompletion_adapter(acc_name_view, MobileLedgerDB.ACCOUNTS_TABLE, "name");
79             hook_text_change_listener(acc_name_view);
80             hook_text_change_listener(amount_view);
81 //            Log.d("swipe", "hooked to row "+i);
82         }
83     }
84
85     @Override
86     public void finish() {
87         super.finish();
88         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
89     }
90
91     @Override
92     public boolean onOptionsItemSelected(MenuItem item) {
93         switch (item.getItemId()) {
94             case android.R.id.home:
95                 finish();
96                 return true;
97         }
98         return super.onOptionsItemSelected(item);
99     }
100
101     public void save_transaction() {
102         if (mSave != null) mSave.setVisible(false);
103         toggle_all_editing(false);
104         progress.setVisibility(View.VISIBLE);
105
106         saver = new SaveTransactionTask(this);
107
108         saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
109         LedgerTransaction tr = new LedgerTransaction(text_date.getText().toString(), text_descr.getText().toString());
110
111         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
112         for ( int i = 0; i < table.getChildCount(); i++ ) {
113             TableRow row = (TableRow) table.getChildAt(i);
114             String acc = ((TextView) row.getChildAt(0)).getText().toString();
115             String amt = ((TextView) row.getChildAt(1)).getText().toString();
116             LedgerTransactionItem item =
117                     amt.length() > 0
118                     ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
119                     : new LedgerTransactionItem( acc );
120
121             tr.add_item(item);
122         }
123         saver.execute(tr);
124     }
125
126     private void toggle_all_editing(boolean enabled) {
127         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
128         for (int i = 0; i < table.getChildCount(); i++) {
129             TableRow row = (TableRow) table.getChildAt(i);
130             for (int j = 0; j < row.getChildCount(); j++) {
131                 row.getChildAt(j).setEnabled(enabled);
132             }
133         }
134     }
135
136     private void hook_swipe_listener(final TableRow row) {
137         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
138             public void onSwipeLeft() {
139 //                Log.d("swipe", "LEFT" + row.getId());
140                 if (table.getChildCount() > 2) {
141                     table.removeView(row);
142 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
143                 }
144                 else {
145                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
146                             .setAction("Action", null).show();
147                 }
148             }
149 //            @Override
150 //            public boolean performClick(View view, MotionEvent m) {
151 //                return true;
152 //            }
153             public boolean onTouch(View view, MotionEvent m) {
154                 return gestureDetector.onTouchEvent(m);
155             }
156         });
157     }
158
159     private void hook_text_change_listener(final TextView view) {
160         view.addTextChangedListener(new TextWatcher() {
161             @Override
162             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
163
164             }
165
166             @Override
167             public void onTextChanged(CharSequence s, int start, int before, int count) {
168
169             }
170
171             @Override
172             public void afterTextChanged(Editable s) {
173 //                Log.d("input", "text changed");
174                 check_transaction_submittable();
175             }
176         });
177
178     }
179
180     @TargetApi(Build.VERSION_CODES.N)
181     private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table, final String field) {
182         String[] from = {field};
183         int[] to = {android.R.id.text1};
184         SQLiteDatabase db = MobileLedgerDB.db;
185
186         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
187         adapter.setStringConversionColumn(1);
188
189         FilterQueryProvider provider = new FilterQueryProvider() {
190             @Override
191             public Cursor runQuery(CharSequence constraint) {
192                 if (constraint == null) return null;
193
194                 String str = constraint.toString().toUpperCase();
195                 Log.d("autocompletion", "Looking for "+str);
196                 String[] col_names = {FontsContract.Columns._ID, field};
197                 MatrixCursor c = new MatrixCursor(col_names);
198
199                 Cursor matches = db.rawQuery(String.format(
200                         "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
201                                 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
202                                 "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
203                                 "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " +
204                                 "ORDER BY 2, 1;", field, field, field, field, table, field),
205                         new String[]{str, str, str, str});
206
207                 try {
208                     int i = 0;
209                     while (matches.moveToNext()) {
210                         String match = matches.getString(0);
211                         int order = matches.getInt(1);
212                         Log.d("autocompletion", String.format("match: %s |%d", match, order));
213                         c.newRow().add(i++).add(match);
214                     }
215                 }
216                 finally {
217                     matches.close();
218                 }
219
220                 return c;
221
222             }
223         };
224
225         adapter.setFilterQueryProvider(provider);
226
227         view.setAdapter(adapter);
228     }
229
230     public boolean onCreateOptionsMenu(Menu menu) {
231         // Inflate the menu; this adds items to the action bar if it is present.
232         getMenuInflater().inflate(R.menu.new_transaction, menu);
233         mSave = menu.findItem(R.id.action_submit_transaction);
234         if (mSave == null) throw new AssertionError();
235
236         return true;
237     }
238
239     public void pickTransactionDate(View view) {
240         DialogFragment picker = new DatePickerFragment();
241         picker.show(getSupportFragmentManager(), "datePicker");
242     }
243
244     public int dp2px(float dp) {
245         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
246     }
247
248     private void do_add_account_row(boolean focus) {
249         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
250         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
251         acc.setHint(R.string.new_transaction_account_hint);
252         acc.setWidth(0);
253
254         final EditText amt = new EditText(this);
255         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 1f));
256         amt.setHint(R.string.new_transaction_amount_hint);
257         amt.setWidth(0);
258         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
259         amt.setMinWidth(dp2px(40));
260         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
261
262         final TableRow row = new TableRow(this);
263         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
264         row.addView(acc);
265         row.addView(amt);
266         table.addView(row);
267
268         if (focus) acc.requestFocus();
269
270         hook_swipe_listener(row);
271         hook_autocompletion_adapter(acc, MobileLedgerDB.ACCOUNTS_TABLE, "name");
272         hook_text_change_listener(acc);
273         hook_text_change_listener(amt);
274     }
275
276     public void addTransactionAccountFromMenu(MenuItem item) {
277         do_add_account_row(true);
278     }
279
280     public void saveTransactionFromMenu(MenuItem item) {
281         save_transaction();
282     }
283
284     private void check_transaction_submittable() {
285         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
286         int accounts = 0;
287         int accounts_with_values = 0;
288         int empty_rows = 0;
289         for(int i = 0; i < table.getChildCount(); i++ ) {
290             TableRow row = (TableRow) table.getChildAt(i);
291
292             TextView acc_name_v = (TextView) row.getChildAt(0);
293
294             String acc_name = String.valueOf(acc_name_v.getText());
295             acc_name = acc_name.trim();
296             if (!acc_name.isEmpty()) {
297                 accounts++;
298
299                 TextView amount_v = (TextView) row.getChildAt(1);
300                 String amt = String.valueOf(amount_v.getText());
301
302                 if (!amt.isEmpty()) accounts_with_values++;
303             } else empty_rows++;
304         }
305
306         if (accounts_with_values == accounts && empty_rows == 0) {
307             do_add_account_row(false);
308         }
309
310         if ((accounts >= 2) && (accounts_with_values >= (accounts - 1))) {
311             if (mSave != null) mSave.setVisible(true);
312         } else {
313             if (mSave != null) mSave.setVisible(false);
314         }
315     }
316
317     @Override
318     public
319     void done(String error) {
320         progress.setVisibility(View.INVISIBLE);
321         Log.d("visuals", "hiding progress");
322
323         if (error == null) reset_form();
324         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
325                 BaseTransientBottomBar.LENGTH_LONG).show();
326
327         toggle_all_editing(true);
328         check_transaction_submittable();
329     }
330
331     private void reset_form() {
332         text_date.setText("");
333         text_descr.setText("");
334         while(table.getChildCount() > 2) {
335             table.removeViewAt(2);
336         }
337         for( int i = 0; i < 2; i++ ) {
338             TableRow tr = (TableRow) table.getChildAt(i);
339             if ( tr == null) break;
340
341             ((TextView)tr.getChildAt(0)).setText("");
342             ((TextView)tr.getChildAt(1)).setText("");
343         }
344
345         text_descr.requestFocus();
346     }
347 }