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