]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/NewTransactionActivity.java
add license boilerplates for authored content
[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 java.util.Date;
55 import java.util.Objects;
56
57 /*
58  * TODO: auto-fill of transaction description
59  *       if Android O's implementation won't work, add a custom one
60  * TODO: nicer progress while transaction is submitted
61  * TODO: latest transactions, maybe with browsing further in the past?
62  * TODO: reports
63  * TODO: get rid of the custom session/cookie and auth code?
64  *         (the last problem with the POST was the missing content-length header)
65  * TODO: app icon
66  * TODO: nicer swiping removal with visual feedback
67  * TODO: setup wizard
68  * TODO: update accounts/check settings upon change of backend settings
69  *  */
70
71 public class NewTransactionActivity extends AppCompatActivity implements TaskCallback {
72     private TableLayout table;
73     private ProgressBar progress;
74     private TextView text_date;
75     private AutoCompleteTextView text_descr;
76     private static SaveTransactionTask saver;
77     private MenuItem mSave;
78     private MobileLedgerDatabase dbh;
79
80     @Override
81     protected void onCreate(Bundle savedInstanceState) {
82         super.onCreate(savedInstanceState);
83         setContentView(R.layout.activity_new_transaction);
84         Toolbar toolbar = findViewById(R.id.toolbar);
85         setSupportActionBar(toolbar);
86
87         dbh = new MobileLedgerDatabase(this);
88
89         text_date = findViewById(R.id.new_transaction_date);
90         text_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
91             @Override
92             public
93             void onFocusChange(View v, boolean hasFocus) {
94                 if (hasFocus) pickTransactionDate(v);
95             }
96         });
97         text_descr = findViewById(R.id.new_transaction_description);
98         hook_autocompletion_adapter(text_descr, MobileLedgerDatabase
99                 .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, MobileLedgerDatabase.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
120     void onStart() {
121         super.onStart();
122         if (text_descr.getText().toString().isEmpty()) text_descr.requestFocus();
123     }
124
125     @Override
126     public void finish() {
127         super.finish();
128         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
129     }
130
131     @Override
132     public boolean onOptionsItemSelected(MenuItem item) {
133         switch (item.getItemId()) {
134             case android.R.id.home:
135                 finish();
136                 return true;
137         }
138         return super.onOptionsItemSelected(item);
139     }
140
141     public void save_transaction() {
142         if (mSave != null) mSave.setVisible(false);
143         toggle_all_editing(false);
144         progress.setVisibility(View.VISIBLE);
145
146         saver = new SaveTransactionTask(this);
147
148         saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
149         String date = text_date.getText().toString();
150         if (date.isEmpty()) date = String.valueOf(new Date().getDate());
151         LedgerTransaction tr = new LedgerTransaction(date, text_descr.getText().toString());
152
153         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
154         for ( int i = 0; i < table.getChildCount(); i++ ) {
155             TableRow row = (TableRow) table.getChildAt(i);
156             String acc = ((TextView) row.getChildAt(0)).getText().toString();
157             String amt = ((TextView) row.getChildAt(1)).getText().toString();
158             LedgerTransactionItem item =
159                     amt.length() > 0
160                     ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
161                     : new LedgerTransactionItem( acc );
162
163             tr.add_item(item);
164         }
165         saver.execute(tr);
166     }
167
168     private void toggle_all_editing(boolean enabled) {
169         text_date.setEnabled(enabled);
170         text_descr.setEnabled(enabled);
171         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
172         for (int i = 0; i < table.getChildCount(); i++) {
173             TableRow row = (TableRow) table.getChildAt(i);
174             for (int j = 0; j < row.getChildCount(); j++) {
175                 row.getChildAt(j).setEnabled(enabled);
176             }
177         }
178     }
179
180     private void hook_swipe_listener(final TableRow row) {
181         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
182             public void onSwipeLeft() {
183 //                Log.d("swipe", "LEFT" + row.getId());
184                 if (table.getChildCount() > 2) {
185                     TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
186                     TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
187                     TextView prev_amt =
188                             (prev_row != null) ? (TextView) prev_row.getChildAt(1) : text_descr;
189                     TextView next_acc =
190                             (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
191
192                     if (next_acc == null) {
193                         prev_amt.setNextFocusRightId(R.id.none);
194                         prev_amt.setNextFocusForwardId(R.id.none);
195                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
196                     }
197                     else {
198                         prev_amt.setNextFocusRightId(next_acc.getId());
199                         prev_amt.setNextFocusForwardId(next_acc.getId());
200                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
201                     }
202
203                     if (row.hasFocus()) {
204                         if (next_acc != null) next_acc.requestFocus();
205                         else prev_amt.requestFocus();
206                     }
207
208                     table.removeView(row);
209                     check_transaction_submittable();
210 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
211                 }
212                 else {
213                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
214                             .setAction("Action", null).show();
215                 }
216             }
217 //            @Override
218 //            public boolean performClick(View view, MotionEvent m) {
219 //                return true;
220 //            }
221             public boolean onTouch(View view, MotionEvent m) {
222                 return gestureDetector.onTouchEvent(m);
223             }
224         });
225     }
226
227     private void hook_text_change_listener(final TextView view) {
228         view.addTextChangedListener(new TextWatcher() {
229             @Override
230             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
231
232             }
233
234             @Override
235             public void onTextChanged(CharSequence s, int start, int before, int count) {
236
237             }
238
239             @Override
240             public void afterTextChanged(Editable s) {
241 //                Log.d("input", "text changed");
242                 check_transaction_submittable();
243             }
244         });
245
246     }
247
248     @TargetApi(Build.VERSION_CODES.N)
249     private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table, final String field) {
250         String[] from = {field};
251         int[] to = {android.R.id.text1};
252         SimpleCursorAdapter adapter =
253                 new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null,
254                         from, to, 0);
255         adapter.setStringConversionColumn(1);
256
257         FilterQueryProvider provider = new FilterQueryProvider() {
258             @Override
259             public
260             Cursor runQuery(CharSequence constraint) {
261                 if (constraint == null) return null;
262
263                 String str = constraint.toString().toUpperCase();
264                 Log.d("autocompletion", "Looking for " + str);
265                 String[] col_names = {FontsContract.Columns._ID, field};
266                 MatrixCursor c = new MatrixCursor(col_names);
267
268                 try (SQLiteDatabase db = dbh.getReadableDatabase()) {
269
270                     try (Cursor matches = db.rawQuery(String.format(
271                             "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 "
272                                     + "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 "
273                                     + "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end "
274                                     + "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' "
275                                     + "ORDER BY 2, 1;", field, field, field, field, table, field),
276                             new String[]{str, str, str, str}))
277                     {
278                         int i = 0;
279                         while (matches.moveToNext()) {
280                             String match = matches.getString(0);
281                             int order = matches.getInt(1);
282                             Log.d("autocompletion", String.format("match: %s |%d", match, order));
283                             c.newRow().add(i++).add(match);
284                         }
285                     }
286
287                     return c;
288                 }
289
290             }
291         };
292
293         adapter.setFilterQueryProvider(provider);
294
295         view.setAdapter(adapter);
296     }
297
298     public boolean onCreateOptionsMenu(Menu menu) {
299         // Inflate the menu; this adds items to the action bar if it is present.
300         getMenuInflater().inflate(R.menu.new_transaction, menu);
301         mSave = menu.findItem(R.id.action_submit_transaction);
302         if (mSave == null) throw new AssertionError();
303
304         check_transaction_submittable();
305
306         return true;
307     }
308
309     public void pickTransactionDate(View view) {
310         DialogFragment picker = new DatePickerFragment();
311         picker.show(getSupportFragmentManager(), "datePicker");
312     }
313
314     public int dp2px(float dp) {
315         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
316     }
317
318     private void do_add_account_row(boolean focus) {
319         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
320         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, 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 | InputType.TYPE_NUMBER_FLAG_DECIMAL );
333         amt.setMinWidth(dp2px(40));
334         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
335         amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
336
337         // forward navigation support
338         final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
339         final TextView last_amt = (TextView) last_row.getChildAt(1);
340         last_amt.setNextFocusForwardId(acc.getId());
341         last_amt.setNextFocusRightId(acc.getId());
342         last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
343         acc.setNextFocusForwardId(amt.getId());
344         acc.setNextFocusRightId(amt.getId());
345
346         final TableRow row = new TableRow(this);
347         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
348         row.setGravity(Gravity.BOTTOM);
349         row.addView(acc);
350         row.addView(amt);
351         table.addView(row);
352
353         if (focus) acc.requestFocus();
354
355         hook_swipe_listener(row);
356         hook_autocompletion_adapter(acc, MobileLedgerDatabase.ACCOUNTS_TABLE, "name");
357         hook_text_change_listener(acc);
358         hook_text_change_listener(amt);
359     }
360
361     public void addTransactionAccountFromMenu(MenuItem item) {
362         do_add_account_row(true);
363     }
364
365     public
366     void resetTransactionFromMenu(MenuItem item) {
367         reset_form();
368     }
369
370     public void saveTransactionFromMenu(MenuItem item) {
371         save_transaction();
372     }
373
374     private
375     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) && ((table.getChildCount() == accounts) || (table.getChildCount()
438                     == 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, accounts_with_values,
446                     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(
452                             running_total)))
453             {
454                 if (mSave != null) mSave.setVisible(true);
455             }
456             else if (mSave != null) mSave.setVisible(false);
457
458             if (single_empty_amount) {
459                 empty_amount
460                         .setHint(String.format("%1.2f", (running_total > 0) ? -running_total : 0f));
461             }
462
463         }
464         catch (NumberFormatException e) {
465             if (mSave != null) mSave.setVisible(false);
466         }
467         catch (Exception e) {
468             e.printStackTrace();
469             if (mSave != null) mSave.setVisible(false);
470         }
471     }
472
473     @Override
474     public
475     void done(String error) {
476         progress.setVisibility(View.INVISIBLE);
477         Log.d("visuals", "hiding progress");
478
479         if (error == null) reset_form();
480         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
481                 BaseTransientBottomBar.LENGTH_LONG).show();
482
483         toggle_all_editing(true);
484         check_transaction_submittable();
485     }
486
487     private void reset_form() {
488         text_date.setText("");
489         text_descr.setText("");
490
491         text_descr.requestFocus();
492
493         while(table.getChildCount() > 2) {
494             table.removeViewAt(2);
495         }
496         for( int i = 0; i < 2; i++ ) {
497             TableRow tr = (TableRow) table.getChildAt(i);
498             if ( tr == null) break;
499
500             ((TextView)tr.getChildAt(0)).setText("");
501             ((TextView)tr.getChildAt(1)).setText("");
502         }
503     }
504 }