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