]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/NewTransactionActivity.java
38289020715be1d118a1def9e034a83005ffb259
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / NewTransactionActivity.java
1 /*
2  * Copyright © 2018 Damyan Ivanov.
3  * This file is part of Mobile-Ledger.
4  * Mobile-Ledger is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * Mobile-Ledger is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with Mobile-Ledger. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger;
19
20 import android.annotation.SuppressLint;
21 import android.annotation.TargetApi;
22 import android.database.Cursor;
23 import android.database.MatrixCursor;
24 import android.database.sqlite.SQLiteDatabase;
25 import android.os.Build;
26 import android.os.Bundle;
27 import android.preference.PreferenceManager;
28 import android.provider.FontsContract;
29 import android.support.design.widget.BaseTransientBottomBar;
30 import android.support.design.widget.Snackbar;
31 import android.support.v4.app.DialogFragment;
32 import android.support.v7.app.AppCompatActivity;
33 import android.support.v7.widget.Toolbar;
34 import android.text.Editable;
35 import android.text.InputType;
36 import android.text.TextWatcher;
37 import android.util.Log;
38 import android.util.TypedValue;
39 import android.view.Gravity;
40 import android.view.Menu;
41 import android.view.MenuItem;
42 import android.view.MotionEvent;
43 import android.view.View;
44 import android.view.inputmethod.EditorInfo;
45 import android.widget.AutoCompleteTextView;
46 import android.widget.EditText;
47 import android.widget.FilterQueryProvider;
48 import android.widget.ProgressBar;
49 import android.widget.SimpleCursorAdapter;
50 import android.widget.TableLayout;
51 import android.widget.TableRow;
52 import android.widget.TextView;
53
54 import net.ktnx.mobileledger.async.SaveTransactionTask;
55 import net.ktnx.mobileledger.async.TaskCallback;
56 import net.ktnx.mobileledger.model.LedgerTransaction;
57 import net.ktnx.mobileledger.model.LedgerTransactionItem;
58 import net.ktnx.mobileledger.ui.DatePickerFragment;
59 import net.ktnx.mobileledger.utils.MLDB;
60
61 import java.util.Date;
62 import java.util.Objects;
63
64 /*
65  * TODO: nicer progress while transaction is submitted
66  * TODO: latest transactions, maybe with browsing further in the past?
67  * TODO: reports
68  * TODO: get rid of the custom session/cookie and auth code?
69  *         (the last problem with the POST was the missing content-length header)
70  * TODO: app icon
71  * TODO: nicer swiping removal with visual feedback
72  * TODO: setup wizard
73  * TODO: update accounts/check settings upon change of backend settings
74  *  */
75
76 public class NewTransactionActivity extends AppCompatActivity implements TaskCallback {
77     private TableLayout table;
78     private ProgressBar progress;
79     private TextView text_date;
80     private AutoCompleteTextView text_descr;
81     private static SaveTransactionTask saver;
82     private MenuItem mSave;
83
84     @Override
85     protected void onCreate(Bundle savedInstanceState) {
86         super.onCreate(savedInstanceState);
87         setContentView(R.layout.activity_new_transaction);
88         Toolbar toolbar = findViewById(R.id.toolbar);
89         setSupportActionBar(toolbar);
90
91         text_date = findViewById(R.id.new_transaction_date);
92         text_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
93             @Override
94             public
95             void onFocusChange(View v, boolean hasFocus) {
96                 if (hasFocus) pickTransactionDate(v);
97             }
98         });
99         text_descr = findViewById(R.id.new_transaction_description);
100         hook_autocompletion_adapter(text_descr, MLDB.DESCRIPTION_HISTORY_TABLE, "description");
101         hook_text_change_listener(text_descr);
102
103         progress = findViewById(R.id.save_transaction_progress);
104
105         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
106         table = findViewById(R.id.new_transaction_accounts_table);
107         for (int i = 0; i < table.getChildCount(); i++) {
108             TableRow row = (TableRow) table.getChildAt(i);
109             AutoCompleteTextView acc_name_view = (AutoCompleteTextView) row.getChildAt(0);
110             TextView amount_view = (TextView) row.getChildAt(1);
111             hook_swipe_listener(row);
112             hook_autocompletion_adapter(acc_name_view, MLDB.ACCOUNTS_TABLE, "name");
113             hook_text_change_listener(acc_name_view);
114             hook_text_change_listener(amount_view);
115 //            Log.d("swipe", "hooked to row "+i);
116         }
117     }
118
119     @Override
120     protected
121     void onStart() {
122         super.onStart();
123         if (text_descr.getText().toString().isEmpty()) text_descr.requestFocus();
124     }
125
126     @Override
127     public void finish() {
128         super.finish();
129         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
130     }
131
132     @Override
133     public boolean onOptionsItemSelected(MenuItem item) {
134         switch (item.getItemId()) {
135             case android.R.id.home:
136                 finish();
137                 return true;
138         }
139         return super.onOptionsItemSelected(item);
140     }
141
142     public void save_transaction() {
143         if (mSave != null) mSave.setVisible(false);
144         toggle_all_editing(false);
145         progress.setVisibility(View.VISIBLE);
146
147         saver = new SaveTransactionTask(this);
148
149         saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
150         String date = text_date.getText().toString();
151         if (date.isEmpty()) date = String.valueOf(new Date().getDate());
152         LedgerTransaction tr = new LedgerTransaction(date, text_descr.getText().toString());
153
154         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
155         for ( int i = 0; i < table.getChildCount(); i++ ) {
156             TableRow row = (TableRow) table.getChildAt(i);
157             String acc = ((TextView) row.getChildAt(0)).getText().toString();
158             String amt = ((TextView) row.getChildAt(1)).getText().toString();
159             LedgerTransactionItem item =
160                     amt.length() > 0
161                     ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
162                     : new LedgerTransactionItem( acc );
163
164             tr.add_item(item);
165         }
166         saver.execute(tr);
167     }
168
169     private void toggle_all_editing(boolean enabled) {
170         text_date.setEnabled(enabled);
171         text_descr.setEnabled(enabled);
172         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
173         for (int i = 0; i < table.getChildCount(); i++) {
174             TableRow row = (TableRow) table.getChildAt(i);
175             for (int j = 0; j < row.getChildCount(); j++) {
176                 row.getChildAt(j).setEnabled(enabled);
177             }
178         }
179     }
180
181     private void hook_swipe_listener(final TableRow row) {
182         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
183             public void onSwipeLeft() {
184 //                Log.d("swipe", "LEFT" + row.getId());
185                 if (table.getChildCount() > 2) {
186                     TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
187                     TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
188                     TextView prev_amt =
189                             (prev_row != null) ? (TextView) prev_row.getChildAt(1) : text_descr;
190                     TextView next_acc =
191                             (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
192
193                     if (next_acc == null) {
194                         prev_amt.setNextFocusRightId(R.id.none);
195                         prev_amt.setNextFocusForwardId(R.id.none);
196                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
197                     }
198                     else {
199                         prev_amt.setNextFocusRightId(next_acc.getId());
200                         prev_amt.setNextFocusForwardId(next_acc.getId());
201                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
202                     }
203
204                     if (row.hasFocus()) {
205                         if (next_acc != null) next_acc.requestFocus();
206                         else prev_amt.requestFocus();
207                     }
208
209                     table.removeView(row);
210                     check_transaction_submittable();
211 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
212                 }
213                 else {
214                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
215                             .setAction("Action", null).show();
216                 }
217             }
218 //            @Override
219 //            public boolean performClick(View view, MotionEvent m) {
220 //                return true;
221 //            }
222             public boolean onTouch(View view, MotionEvent m) {
223                 return gestureDetector.onTouchEvent(m);
224             }
225         });
226     }
227
228     private void hook_text_change_listener(final TextView view) {
229         view.addTextChangedListener(new TextWatcher() {
230             @Override
231             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
232
233             }
234
235             @Override
236             public void onTextChanged(CharSequence s, int start, int before, int count) {
237
238             }
239
240             @Override
241             public void afterTextChanged(Editable s) {
242 //                Log.d("input", "text changed");
243                 check_transaction_submittable();
244             }
245         });
246
247     }
248
249     @TargetApi(Build.VERSION_CODES.N)
250     private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table, final String field) {
251         String[] from = {field};
252         int[] to = {android.R.id.text1};
253         SimpleCursorAdapter adapter =
254                 new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null,
255                         from, to, 0);
256         adapter.setStringConversionColumn(1);
257
258         FilterQueryProvider provider = new FilterQueryProvider() {
259             @Override
260             public
261             Cursor runQuery(CharSequence constraint) {
262                 if (constraint == null) return null;
263
264                 String str = constraint.toString().toUpperCase();
265                 Log.d("autocompletion", "Looking for " + str);
266                 String[] col_names = {FontsContract.Columns._ID, field};
267                 MatrixCursor c = new MatrixCursor(col_names);
268
269                 try (SQLiteDatabase db = MLDB.getReadableDatabase(getApplicationContext())) {
270
271                     try (Cursor matches = db.rawQuery(String.format(
272                             "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 "
273                                     + "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 "
274                                     + "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end "
275                                     + "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' "
276                                     + "ORDER BY 2, 1;", field, field, field, field, table, field),
277                             new String[]{str, str, str, str}))
278                     {
279                         int i = 0;
280                         while (matches.moveToNext()) {
281                             String match = matches.getString(0);
282                             int order = matches.getInt(1);
283                             Log.d("autocompletion", String.format("match: %s |%d", match, order));
284                             c.newRow().add(i++).add(match);
285                         }
286                     }
287
288                     return c;
289                 }
290
291             }
292         };
293
294         adapter.setFilterQueryProvider(provider);
295
296         view.setAdapter(adapter);
297     }
298
299     public boolean onCreateOptionsMenu(Menu menu) {
300         // Inflate the menu; this adds items to the action bar if it is present.
301         getMenuInflater().inflate(R.menu.new_transaction, menu);
302         mSave = menu.findItem(R.id.action_submit_transaction);
303         if (mSave == null) throw new AssertionError();
304
305         check_transaction_submittable();
306
307         return true;
308     }
309
310     public void pickTransactionDate(View view) {
311         DialogFragment picker = new DatePickerFragment();
312         picker.show(getSupportFragmentManager(), "datePicker");
313     }
314
315     public int dp2px(float dp) {
316         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
317     }
318
319     private void do_add_account_row(boolean focus) {
320         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
321         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
322         acc.setHint(R.string.new_transaction_account_hint);
323         acc.setWidth(0);
324         acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION
325                 | EditorInfo.IME_FLAG_NAVIGATE_NEXT);
326         acc.setSingleLine(true);
327
328         final EditText amt = new EditText(this);
329         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
330                 TableRow.LayoutParams.MATCH_PARENT, 1f));
331         amt.setHint(R.string.new_transaction_amount_hint);
332         amt.setWidth(0);
333         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
334         amt.setMinWidth(dp2px(40));
335         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
336         amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
337
338         // forward navigation support
339         final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
340         final TextView last_amt = (TextView) last_row.getChildAt(1);
341         last_amt.setNextFocusForwardId(acc.getId());
342         last_amt.setNextFocusRightId(acc.getId());
343         last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
344         acc.setNextFocusForwardId(amt.getId());
345         acc.setNextFocusRightId(amt.getId());
346
347         final TableRow row = new TableRow(this);
348         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
349         row.setGravity(Gravity.BOTTOM);
350         row.addView(acc);
351         row.addView(amt);
352         table.addView(row);
353
354         if (focus) acc.requestFocus();
355
356         hook_swipe_listener(row);
357         hook_autocompletion_adapter(acc, MLDB.ACCOUNTS_TABLE, "name");
358         hook_text_change_listener(acc);
359         hook_text_change_listener(amt);
360     }
361
362     public void addTransactionAccountFromMenu(MenuItem item) {
363         do_add_account_row(true);
364     }
365
366     public
367     void resetTransactionFromMenu(MenuItem item) {
368         reset_form();
369     }
370
371     public void saveTransactionFromMenu(MenuItem item) {
372         save_transaction();
373     }
374
375     private
376     boolean is_zero(float f) {
377         return (f < 0.005) && (f > -0.005);
378     }
379
380     // rules:
381     // 1) at least two account names
382     // 2) each amount must have account name
383     // 3) amounts must balance to 0, or
384     // 3a) there must be exactly one empty amount
385     // 4) empty accounts with empty amounts are ignored
386     // 5) a row with an empty account name or empty amount is guaranteed to exist
387     @SuppressLint("DefaultLocale")
388     private void check_transaction_submittable() {
389         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
390         int accounts = 0;
391         int accounts_with_values = 0;
392         int amounts = 0;
393         int amounts_with_accounts = 0;
394         int empty_rows = 0;
395         TextView empty_amount = null;
396         boolean single_empty_amount = false;
397         boolean single_empty_amount_has_account = false;
398         float running_total = 0f;
399         boolean have_description =
400                 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
401                         .isEmpty();
402
403         try {
404             for (int i = 0; i < table.getChildCount(); i++) {
405                 TableRow row = (TableRow) table.getChildAt(i);
406
407                 TextView acc_name_v = (TextView) row.getChildAt(0);
408                 TextView amount_v = (TextView) row.getChildAt(1);
409                 String amt = String.valueOf(amount_v.getText());
410                 String acc_name = String.valueOf(acc_name_v.getText());
411                 acc_name = acc_name.trim();
412
413                 if (!acc_name.isEmpty()) {
414                     accounts++;
415
416                     if (!amt.isEmpty()) {
417                         accounts_with_values++;
418                     }
419                 }
420                 else empty_rows++;
421
422                 if (amt.isEmpty()) {
423                     amount_v.setHint(String.format("%1.2f", 0f));
424                     if (empty_amount == null) {
425                         empty_amount = amount_v;
426                         single_empty_amount = true;
427                         single_empty_amount_has_account = !acc_name.isEmpty();
428                     }
429                     else if (!acc_name.isEmpty()) single_empty_amount = false;
430                 }
431                 else {
432                     amounts++;
433                     if (!acc_name.isEmpty()) amounts_with_accounts++;
434                     running_total += Float.valueOf(amt);
435                 }
436             }
437
438             if ((empty_rows == 0) && ((table.getChildCount() == accounts) || (table.getChildCount()
439                     == amounts)))
440             {
441                 do_add_account_row(false);
442             }
443
444             Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, "
445                             + "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, "
446                             + "single_empty_with_acc=%s", accounts, accounts_with_values,
447                     amounts_with_accounts, amounts, running_total,
448                     (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
449
450             if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) && (
451                     amounts_with_accounts == amounts) && (
452                     single_empty_amount && single_empty_amount_has_account || is_zero(
453                             running_total)))
454             {
455                 if (mSave != null) mSave.setVisible(true);
456             }
457             else if (mSave != null) mSave.setVisible(false);
458
459             if (single_empty_amount) {
460                 empty_amount
461                         .setHint(String.format("%1.2f", (running_total > 0) ? -running_total : 0f));
462             }
463
464         }
465         catch (NumberFormatException e) {
466             if (mSave != null) mSave.setVisible(false);
467         }
468         catch (Exception e) {
469             e.printStackTrace();
470             if (mSave != null) mSave.setVisible(false);
471         }
472     }
473
474     @Override
475     public
476     void done(String error) {
477         progress.setVisibility(View.INVISIBLE);
478         Log.d("visuals", "hiding progress");
479
480         if (error == null) reset_form();
481         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
482                 BaseTransientBottomBar.LENGTH_LONG).show();
483
484         toggle_all_editing(true);
485         check_transaction_submittable();
486     }
487
488     private void reset_form() {
489         text_date.setText("");
490         text_descr.setText("");
491
492         text_descr.requestFocus();
493
494         while(table.getChildCount() > 2) {
495             table.removeViewAt(2);
496         }
497         for( int i = 0; i < 2; i++ ) {
498             TableRow tr = (TableRow) table.getChildAt(i);
499             if ( tr == null) break;
500
501             ((TextView)tr.getChildAt(0)).setText("");
502             ((TextView)tr.getChildAt(1)).setText("");
503         }
504     }
505 }