]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/NewTransactionActivity.java
separate packages for the different aspects of the application
[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.MobileLedgerDatabase;
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     private MobileLedgerDatabase dbh;
84
85     @Override
86     protected void onCreate(Bundle savedInstanceState) {
87         super.onCreate(savedInstanceState);
88         setContentView(R.layout.activity_new_transaction);
89         Toolbar toolbar = findViewById(R.id.toolbar);
90         setSupportActionBar(toolbar);
91
92         dbh = new MobileLedgerDatabase(this);
93
94         text_date = findViewById(R.id.new_transaction_date);
95         text_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
96             @Override
97             public
98             void onFocusChange(View v, boolean hasFocus) {
99                 if (hasFocus) pickTransactionDate(v);
100             }
101         });
102         text_descr = findViewById(R.id.new_transaction_description);
103         hook_autocompletion_adapter(text_descr, MobileLedgerDatabase
104                 .DESCRIPTION_HISTORY_TABLE, "description");
105         hook_text_change_listener(text_descr);
106
107         progress = findViewById(R.id.save_transaction_progress);
108
109         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
110         table = findViewById(R.id.new_transaction_accounts_table);
111         for (int i = 0; i < table.getChildCount(); i++) {
112             TableRow row = (TableRow) table.getChildAt(i);
113             AutoCompleteTextView acc_name_view = (AutoCompleteTextView) row.getChildAt(0);
114             TextView amount_view = (TextView) row.getChildAt(1);
115             hook_swipe_listener(row);
116             hook_autocompletion_adapter(acc_name_view, MobileLedgerDatabase.ACCOUNTS_TABLE, "name");
117             hook_text_change_listener(acc_name_view);
118             hook_text_change_listener(amount_view);
119 //            Log.d("swipe", "hooked to row "+i);
120         }
121     }
122
123     @Override
124     protected
125     void onStart() {
126         super.onStart();
127         if (text_descr.getText().toString().isEmpty()) text_descr.requestFocus();
128     }
129
130     @Override
131     public void finish() {
132         super.finish();
133         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
134     }
135
136     @Override
137     public boolean onOptionsItemSelected(MenuItem item) {
138         switch (item.getItemId()) {
139             case android.R.id.home:
140                 finish();
141                 return true;
142         }
143         return super.onOptionsItemSelected(item);
144     }
145
146     public void save_transaction() {
147         if (mSave != null) mSave.setVisible(false);
148         toggle_all_editing(false);
149         progress.setVisibility(View.VISIBLE);
150
151         saver = new SaveTransactionTask(this);
152
153         saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
154         String date = text_date.getText().toString();
155         if (date.isEmpty()) date = String.valueOf(new Date().getDate());
156         LedgerTransaction tr = new LedgerTransaction(date, text_descr.getText().toString());
157
158         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
159         for ( int i = 0; i < table.getChildCount(); i++ ) {
160             TableRow row = (TableRow) table.getChildAt(i);
161             String acc = ((TextView) row.getChildAt(0)).getText().toString();
162             String amt = ((TextView) row.getChildAt(1)).getText().toString();
163             LedgerTransactionItem item =
164                     amt.length() > 0
165                     ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
166                     : new LedgerTransactionItem( acc );
167
168             tr.add_item(item);
169         }
170         saver.execute(tr);
171     }
172
173     private void toggle_all_editing(boolean enabled) {
174         text_date.setEnabled(enabled);
175         text_descr.setEnabled(enabled);
176         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
177         for (int i = 0; i < table.getChildCount(); i++) {
178             TableRow row = (TableRow) table.getChildAt(i);
179             for (int j = 0; j < row.getChildCount(); j++) {
180                 row.getChildAt(j).setEnabled(enabled);
181             }
182         }
183     }
184
185     private void hook_swipe_listener(final TableRow row) {
186         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
187             public void onSwipeLeft() {
188 //                Log.d("swipe", "LEFT" + row.getId());
189                 if (table.getChildCount() > 2) {
190                     TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
191                     TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
192                     TextView prev_amt =
193                             (prev_row != null) ? (TextView) prev_row.getChildAt(1) : text_descr;
194                     TextView next_acc =
195                             (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
196
197                     if (next_acc == null) {
198                         prev_amt.setNextFocusRightId(R.id.none);
199                         prev_amt.setNextFocusForwardId(R.id.none);
200                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
201                     }
202                     else {
203                         prev_amt.setNextFocusRightId(next_acc.getId());
204                         prev_amt.setNextFocusForwardId(next_acc.getId());
205                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
206                     }
207
208                     if (row.hasFocus()) {
209                         if (next_acc != null) next_acc.requestFocus();
210                         else prev_amt.requestFocus();
211                     }
212
213                     table.removeView(row);
214                     check_transaction_submittable();
215 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
216                 }
217                 else {
218                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
219                             .setAction("Action", null).show();
220                 }
221             }
222 //            @Override
223 //            public boolean performClick(View view, MotionEvent m) {
224 //                return true;
225 //            }
226             public boolean onTouch(View view, MotionEvent m) {
227                 return gestureDetector.onTouchEvent(m);
228             }
229         });
230     }
231
232     private void hook_text_change_listener(final TextView view) {
233         view.addTextChangedListener(new TextWatcher() {
234             @Override
235             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
236
237             }
238
239             @Override
240             public void onTextChanged(CharSequence s, int start, int before, int count) {
241
242             }
243
244             @Override
245             public void afterTextChanged(Editable s) {
246 //                Log.d("input", "text changed");
247                 check_transaction_submittable();
248             }
249         });
250
251     }
252
253     @TargetApi(Build.VERSION_CODES.N)
254     private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table, final String field) {
255         String[] from = {field};
256         int[] to = {android.R.id.text1};
257         SimpleCursorAdapter adapter =
258                 new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null,
259                         from, to, 0);
260         adapter.setStringConversionColumn(1);
261
262         FilterQueryProvider provider = new FilterQueryProvider() {
263             @Override
264             public
265             Cursor runQuery(CharSequence constraint) {
266                 if (constraint == null) return null;
267
268                 String str = constraint.toString().toUpperCase();
269                 Log.d("autocompletion", "Looking for " + str);
270                 String[] col_names = {FontsContract.Columns._ID, field};
271                 MatrixCursor c = new MatrixCursor(col_names);
272
273                 try (SQLiteDatabase db = dbh.getReadableDatabase()) {
274
275                     try (Cursor matches = db.rawQuery(String.format(
276                             "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 "
277                                     + "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 "
278                                     + "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end "
279                                     + "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' "
280                                     + "ORDER BY 2, 1;", field, field, field, field, table, field),
281                             new String[]{str, str, str, str}))
282                     {
283                         int i = 0;
284                         while (matches.moveToNext()) {
285                             String match = matches.getString(0);
286                             int order = matches.getInt(1);
287                             Log.d("autocompletion", String.format("match: %s |%d", match, order));
288                             c.newRow().add(i++).add(match);
289                         }
290                     }
291
292                     return c;
293                 }
294
295             }
296         };
297
298         adapter.setFilterQueryProvider(provider);
299
300         view.setAdapter(adapter);
301     }
302
303     public boolean onCreateOptionsMenu(Menu menu) {
304         // Inflate the menu; this adds items to the action bar if it is present.
305         getMenuInflater().inflate(R.menu.new_transaction, menu);
306         mSave = menu.findItem(R.id.action_submit_transaction);
307         if (mSave == null) throw new AssertionError();
308
309         check_transaction_submittable();
310
311         return true;
312     }
313
314     public void pickTransactionDate(View view) {
315         DialogFragment picker = new DatePickerFragment();
316         picker.show(getSupportFragmentManager(), "datePicker");
317     }
318
319     public int dp2px(float dp) {
320         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
321     }
322
323     private void do_add_account_row(boolean focus) {
324         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
325         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
326         acc.setHint(R.string.new_transaction_account_hint);
327         acc.setWidth(0);
328         acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION
329                 | EditorInfo.IME_FLAG_NAVIGATE_NEXT);
330         acc.setSingleLine(true);
331
332         final EditText amt = new EditText(this);
333         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
334                 TableRow.LayoutParams.MATCH_PARENT, 1f));
335         amt.setHint(R.string.new_transaction_amount_hint);
336         amt.setWidth(0);
337         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
338         amt.setMinWidth(dp2px(40));
339         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
340         amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
341
342         // forward navigation support
343         final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
344         final TextView last_amt = (TextView) last_row.getChildAt(1);
345         last_amt.setNextFocusForwardId(acc.getId());
346         last_amt.setNextFocusRightId(acc.getId());
347         last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
348         acc.setNextFocusForwardId(amt.getId());
349         acc.setNextFocusRightId(amt.getId());
350
351         final TableRow row = new TableRow(this);
352         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
353         row.setGravity(Gravity.BOTTOM);
354         row.addView(acc);
355         row.addView(amt);
356         table.addView(row);
357
358         if (focus) acc.requestFocus();
359
360         hook_swipe_listener(row);
361         hook_autocompletion_adapter(acc, MobileLedgerDatabase.ACCOUNTS_TABLE, "name");
362         hook_text_change_listener(acc);
363         hook_text_change_listener(amt);
364     }
365
366     public void addTransactionAccountFromMenu(MenuItem item) {
367         do_add_account_row(true);
368     }
369
370     public
371     void resetTransactionFromMenu(MenuItem item) {
372         reset_form();
373     }
374
375     public void saveTransactionFromMenu(MenuItem item) {
376         save_transaction();
377     }
378
379     private
380     boolean is_zero(float f) {
381         return (f < 0.005) && (f > -0.005);
382     }
383
384     // rules:
385     // 1) at least two account names
386     // 2) each amount must have account name
387     // 3) amounts must balance to 0, or
388     // 3a) there must be exactly one empty amount
389     // 4) empty accounts with empty amounts are ignored
390     // 5) a row with an empty account name or empty amount is guaranteed to exist
391     @SuppressLint("DefaultLocale")
392     private void check_transaction_submittable() {
393         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
394         int accounts = 0;
395         int accounts_with_values = 0;
396         int amounts = 0;
397         int amounts_with_accounts = 0;
398         int empty_rows = 0;
399         TextView empty_amount = null;
400         boolean single_empty_amount = false;
401         boolean single_empty_amount_has_account = false;
402         float running_total = 0f;
403         boolean have_description =
404                 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
405                         .isEmpty();
406
407         try {
408             for (int i = 0; i < table.getChildCount(); i++) {
409                 TableRow row = (TableRow) table.getChildAt(i);
410
411                 TextView acc_name_v = (TextView) row.getChildAt(0);
412                 TextView amount_v = (TextView) row.getChildAt(1);
413                 String amt = String.valueOf(amount_v.getText());
414                 String acc_name = String.valueOf(acc_name_v.getText());
415                 acc_name = acc_name.trim();
416
417                 if (!acc_name.isEmpty()) {
418                     accounts++;
419
420                     if (!amt.isEmpty()) {
421                         accounts_with_values++;
422                     }
423                 }
424                 else empty_rows++;
425
426                 if (amt.isEmpty()) {
427                     amount_v.setHint(String.format("%1.2f", 0f));
428                     if (empty_amount == null) {
429                         empty_amount = amount_v;
430                         single_empty_amount = true;
431                         single_empty_amount_has_account = !acc_name.isEmpty();
432                     }
433                     else if (!acc_name.isEmpty()) single_empty_amount = false;
434                 }
435                 else {
436                     amounts++;
437                     if (!acc_name.isEmpty()) amounts_with_accounts++;
438                     running_total += Float.valueOf(amt);
439                 }
440             }
441
442             if ((empty_rows == 0) && ((table.getChildCount() == accounts) || (table.getChildCount()
443                     == amounts)))
444             {
445                 do_add_account_row(false);
446             }
447
448             Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, "
449                             + "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, "
450                             + "single_empty_with_acc=%s", accounts, accounts_with_values,
451                     amounts_with_accounts, amounts, running_total,
452                     (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
453
454             if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) && (
455                     amounts_with_accounts == amounts) && (
456                     single_empty_amount && single_empty_amount_has_account || is_zero(
457                             running_total)))
458             {
459                 if (mSave != null) mSave.setVisible(true);
460             }
461             else if (mSave != null) mSave.setVisible(false);
462
463             if (single_empty_amount) {
464                 empty_amount
465                         .setHint(String.format("%1.2f", (running_total > 0) ? -running_total : 0f));
466             }
467
468         }
469         catch (NumberFormatException e) {
470             if (mSave != null) mSave.setVisible(false);
471         }
472         catch (Exception e) {
473             e.printStackTrace();
474             if (mSave != null) mSave.setVisible(false);
475         }
476     }
477
478     @Override
479     public
480     void done(String error) {
481         progress.setVisibility(View.INVISIBLE);
482         Log.d("visuals", "hiding progress");
483
484         if (error == null) reset_form();
485         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
486                 BaseTransientBottomBar.LENGTH_LONG).show();
487
488         toggle_all_editing(true);
489         check_transaction_submittable();
490     }
491
492     private void reset_form() {
493         text_date.setText("");
494         text_descr.setText("");
495
496         text_descr.requestFocus();
497
498         while(table.getChildCount() > 2) {
499             table.removeViewAt(2);
500         }
501         for( int i = 0; i < 2; i++ ) {
502             TableRow tr = (TableRow) table.getChildAt(i);
503             if ( tr == null) break;
504
505             ((TextView)tr.getChildAt(0)).setText("");
506             ((TextView)tr.getChildAt(1)).setText("");
507         }
508     }
509 }