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