]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/NewTransactionActivity.java
new transaction: new menu item for resetting the activity
[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.widget.AutoCompleteTextView;
28 import android.widget.EditText;
29 import android.widget.FilterQueryProvider;
30 import android.widget.ProgressBar;
31 import android.widget.SimpleCursorAdapter;
32 import android.widget.TableLayout;
33 import android.widget.TableRow;
34 import android.widget.TextView;
35
36 import java.util.Objects;
37
38 /*
39  * TODO: auto-fill of transaction description
40  *       if Android O's implementation won't work, add a custom one
41  * TODO: nicer progress while transaction is submitted
42  * TODO: latest transactions, maybe with browsing further in the past?
43  * TODO: reports
44  * TODO: get rid of the custom session/cookie and auth code?
45  *         (the last problem with the POST was the missing content-length header)
46  * TODO: app icon
47  * TODO: nicer swiping removal with visual feedback
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_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
69             @Override
70             public
71             void onFocusChange(View v, boolean hasFocus) {
72                 if (hasFocus) pickTransactionDate(v);
73             }
74         });
75         text_descr = findViewById(R.id.new_transaction_description);
76         hook_autocompletion_adapter(text_descr, MobileLedgerDB.DESCRIPTION_HISTORY_TABLE, "description");
77
78         progress = findViewById(R.id.save_transaction_progress);
79
80         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
81         table = findViewById(R.id.new_transaction_accounts_table);
82         table.removeAllViews();
83         do_add_account_row(false);
84         do_add_account_row(false);
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(
202                         "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 " +
203                                 "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 " +
204                                 "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end " +
205                                 "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' " +
206                                 "ORDER BY 2, 1;", field, field, field, field, table, field),
207                         new String[]{str, str, str, str});
208
209                 try {
210                     int i = 0;
211                     while (matches.moveToNext()) {
212                         String match = matches.getString(0);
213                         int order = matches.getInt(1);
214                         Log.d("autocompletion", String.format("match: %s |%d", match, order));
215                         c.newRow().add(i++).add(match);
216                     }
217                 }
218                 finally {
219                     matches.close();
220                 }
221
222                 return c;
223
224             }
225         };
226
227         adapter.setFilterQueryProvider(provider);
228
229         view.setAdapter(adapter);
230     }
231
232     public boolean onCreateOptionsMenu(Menu menu) {
233         // Inflate the menu; this adds items to the action bar if it is present.
234         getMenuInflater().inflate(R.menu.new_transaction, menu);
235         mSave = menu.findItem(R.id.action_submit_transaction);
236         if (mSave == null) throw new AssertionError();
237
238         check_transaction_submittable();
239
240         return true;
241     }
242
243     public void pickTransactionDate(View view) {
244         DialogFragment picker = new DatePickerFragment();
245         picker.show(getSupportFragmentManager(), "datePicker");
246     }
247
248     public int dp2px(float dp) {
249         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
250     }
251
252     private void do_add_account_row(boolean focus) {
253         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
254         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
255         acc.setHint(R.string.new_transaction_account_hint);
256         acc.setWidth(0);
257
258         final EditText amt = new EditText(this);
259         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
260                 TableRow.LayoutParams.MATCH_PARENT, 1f));
261         amt.setHint(R.string.new_transaction_amount_hint);
262         amt.setWidth(0);
263         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
264         amt.setMinWidth(dp2px(40));
265         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
266
267         final TableRow row = new TableRow(this);
268         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
269         row.setGravity(Gravity.BOTTOM);
270         row.addView(acc);
271         row.addView(amt);
272         table.addView(row);
273
274         if (focus) acc.requestFocus();
275
276         hook_swipe_listener(row);
277         hook_autocompletion_adapter(acc, MobileLedgerDB.ACCOUNTS_TABLE, "name");
278         hook_text_change_listener(acc);
279         hook_text_change_listener(amt);
280     }
281
282     public void addTransactionAccountFromMenu(MenuItem item) {
283         do_add_account_row(true);
284     }
285
286     public
287     void resetTransactionFromMenu(MenuItem item) {
288         reset_form();
289     }
290
291     public void saveTransactionFromMenu(MenuItem item) {
292         save_transaction();
293     }
294
295     // rules:
296     // 1) at least two account names
297     // 2) each amount must have account name
298     // 3) amounts must balance to 0, or
299     // 3a) there must be exactly one empty amount
300     // 4) empty accounts with empty amounts are ignored
301     // 5) a row with an empty account name or empty amount is guaranteed to exist
302     @SuppressLint("DefaultLocale")
303     private void check_transaction_submittable() {
304         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
305         int accounts = 0;
306         int accounts_with_values = 0;
307         int amounts = 0;
308         int amounts_with_accounts = 0;
309         int empty_rows = 0;
310         TextView empty_amount = null;
311         boolean single_empty_amount = false;
312         float running_total = 0f;
313         boolean have_description =
314                 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
315                         .isEmpty();
316
317         try {
318             for (int i = 0; i < table.getChildCount(); i++) {
319                 TableRow row = (TableRow) table.getChildAt(i);
320
321                 TextView acc_name_v = (TextView) row.getChildAt(0);
322                 TextView amount_v = (TextView) row.getChildAt(1);
323                 String amt = String.valueOf(amount_v.getText());
324                 String acc_name = String.valueOf(acc_name_v.getText());
325                 acc_name = acc_name.trim();
326
327                 if (!acc_name.isEmpty()) {
328                     accounts++;
329
330                     if (!amt.isEmpty()) {
331                         accounts_with_values++;
332                     }
333                 }
334                 else empty_rows++;
335
336                 if (amt.isEmpty()) {
337                     amount_v.setHint(String.format("%1.2f", 0f));
338                     if (empty_amount == null) {
339                         empty_amount = amount_v;
340                         single_empty_amount = true;
341                     }
342                     else if (!acc_name.isEmpty()) single_empty_amount = false;
343                 }
344                 else {
345                     amounts++;
346                     if (!acc_name.isEmpty()) amounts_with_accounts++;
347                     running_total += Float.valueOf(amt);
348                 }
349             }
350
351             if ((empty_rows == 0) && ((table.getChildCount() == accounts) || (table.getChildCount()
352                     == amounts)))
353             {
354                 do_add_account_row(false);
355             }
356
357             if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) && (
358                     amounts_with_accounts == amounts))
359             {
360                 if (mSave != null) mSave.setVisible(true);
361             }
362             else if (mSave != null) mSave.setVisible(false);
363
364             if (single_empty_amount) {
365                 empty_amount
366                         .setHint(String.format("%1.2f", (running_total > 0) ? -running_total : 0f));
367             }
368         }
369         catch (NumberFormatException e) {
370             if (mSave != null) mSave.setVisible(false);
371         }
372         catch (Exception e) {
373             e.printStackTrace();
374             if (mSave != null) mSave.setVisible(false);
375         }
376     }
377
378     @Override
379     public
380     void done(String error) {
381         progress.setVisibility(View.INVISIBLE);
382         Log.d("visuals", "hiding progress");
383
384         if (error == null) reset_form();
385         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
386                 BaseTransientBottomBar.LENGTH_LONG).show();
387
388         toggle_all_editing(true);
389         check_transaction_submittable();
390     }
391
392     private void reset_form() {
393         text_date.setText("");
394         text_descr.setText("");
395         while(table.getChildCount() > 2) {
396             table.removeViewAt(2);
397         }
398         for( int i = 0; i < 2; i++ ) {
399             TableRow tr = (TableRow) table.getChildAt(i);
400             if ( tr == null) break;
401
402             ((TextView)tr.getChildAt(0)).setText("");
403             ((TextView)tr.getChildAt(1)).setText("");
404         }
405
406         text_descr.requestFocus();
407     }
408 }