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