]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionActivity.java
move DB access routines to the application class
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionActivity.java
1 /*
2  * Copyright © 2019 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe 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  * MoLe 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 MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.ui.activity;
19
20 import android.annotation.SuppressLint;
21 import android.database.Cursor;
22 import android.os.AsyncTask;
23 import android.os.Bundle;
24 import android.text.Editable;
25 import android.text.InputType;
26 import android.text.TextWatcher;
27 import android.util.TypedValue;
28 import android.view.Gravity;
29 import android.view.Menu;
30 import android.view.MenuItem;
31 import android.view.MotionEvent;
32 import android.view.View;
33 import android.view.inputmethod.EditorInfo;
34 import android.widget.AutoCompleteTextView;
35 import android.widget.EditText;
36 import android.widget.ProgressBar;
37 import android.widget.TableLayout;
38 import android.widget.TableRow;
39 import android.widget.TextView;
40 import android.widget.Toast;
41
42 import com.google.android.material.floatingactionbutton.FloatingActionButton;
43 import com.google.android.material.snackbar.BaseTransientBottomBar;
44 import com.google.android.material.snackbar.Snackbar;
45
46 import net.ktnx.mobileledger.App;
47 import net.ktnx.mobileledger.BuildConfig;
48 import net.ktnx.mobileledger.R;
49 import net.ktnx.mobileledger.async.DescriptionSelectedCallback;
50 import net.ktnx.mobileledger.async.SendTransactionTask;
51 import net.ktnx.mobileledger.async.TaskCallback;
52 import net.ktnx.mobileledger.model.Data;
53 import net.ktnx.mobileledger.model.LedgerTransaction;
54 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
55 import net.ktnx.mobileledger.model.MobileLedgerProfile;
56 import net.ktnx.mobileledger.ui.DatePickerFragment;
57 import net.ktnx.mobileledger.ui.OnSwipeTouchListener;
58 import net.ktnx.mobileledger.utils.Globals;
59 import net.ktnx.mobileledger.utils.MLDB;
60
61 import java.text.ParseException;
62 import java.util.ArrayList;
63 import java.util.Date;
64 import java.util.Locale;
65 import java.util.Objects;
66
67 import androidx.appcompat.widget.Toolbar;
68 import androidx.fragment.app.DialogFragment;
69
70 import static net.ktnx.mobileledger.utils.Logger.debug;
71
72 /*
73  * TODO: nicer progress while transaction is submitted
74  * TODO: reports
75  * TODO: get rid of the custom session/cookie and auth code?
76  *         (the last problem with the POST was the missing content-length header)
77  *  */
78
79 public class NewTransactionActivity extends ProfileThemedActivity
80         implements TaskCallback, DescriptionSelectedCallback {
81     private static SendTransactionTask saver;
82     private TableLayout table;
83     private ProgressBar progress;
84     private FloatingActionButton fab;
85     private TextView tvDate;
86     private AutoCompleteTextView tvDescription;
87     private static boolean isZero(float f) {
88         return (f < 0.005) && (f > -0.005);
89     }
90     @Override
91     protected void onCreate(Bundle savedInstanceState) {
92         super.onCreate(savedInstanceState);
93
94         setContentView(R.layout.activity_new_transaction);
95         Toolbar toolbar = findViewById(R.id.toolbar);
96         setSupportActionBar(toolbar);
97         toolbar.setSubtitle(mProfile.getName());
98
99         tvDate = findViewById(R.id.new_transaction_date);
100         tvDate.setOnFocusChangeListener((v, hasFocus) -> {
101             if (hasFocus) pickTransactionDate(v);
102         });
103         tvDescription = findViewById(R.id.new_transaction_description);
104         MLDB.hookAutocompletionAdapter(this, tvDescription, MLDB.DESCRIPTION_HISTORY_TABLE,
105                 "description", false, findViewById(R.id.new_transaction_acc_1), this, mProfile);
106         hookTextChangeListener(tvDescription);
107
108         progress = findViewById(R.id.save_transaction_progress);
109         fab = findViewById(R.id.fab);
110         fab.setOnClickListener(v -> saveTransaction());
111
112         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
113         table = findViewById(R.id.new_transaction_accounts_table);
114         for (int i = 0; i < table.getChildCount(); i++) {
115             TableRow row = (TableRow) table.getChildAt(i);
116             AutoCompleteTextView tvAccountName = (AutoCompleteTextView) row.getChildAt(0);
117             TextView tvAmount = (TextView) row.getChildAt(1);
118             hookSwipeListener(row);
119             MLDB.hookAutocompletionAdapter(this, tvAccountName, MLDB.ACCOUNTS_TABLE, "name", true,
120                     tvAmount, null, mProfile);
121             hookTextChangeListener(tvAccountName);
122             hookTextChangeListener(tvAmount);
123 //            debug("swipe", "hooked to row "+i);
124         }
125     }
126     @Override
127     protected void initProfile() {
128         String profileUUID = getIntent().getStringExtra("profile_uuid");
129
130         if (profileUUID != null) {
131             mProfile = Data.getProfile(profileUUID);
132             if (mProfile == null) finish();
133         }
134         else super.initProfile();
135     }
136     @Override
137     public void finish() {
138         super.finish();
139         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
140     }
141
142     @Override
143     public boolean onOptionsItemSelected(MenuItem item) {
144         switch (item.getItemId()) {
145             case android.R.id.home:
146                 finish();
147                 return true;
148         }
149         return super.onOptionsItemSelected(item);
150     }
151     @Override
152     protected void onStart() {
153         super.onStart();
154         if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
155     }
156     public void saveTransaction() {
157         if (fab != null) fab.setEnabled(false);
158         toggleAllEditing(false);
159         progress.setVisibility(View.VISIBLE);
160         try {
161
162             saver = new SendTransactionTask(this, mProfile);
163
164             String dateString = tvDate.getText().toString();
165             Date date;
166             if (dateString.isEmpty()) date = new Date();
167             else date = Globals.parseLedgerDate(dateString);
168             LedgerTransaction tr = new LedgerTransaction(null, date, tvDescription.getText().toString(), mProfile);
169
170             TableLayout table = findViewById(R.id.new_transaction_accounts_table);
171             LedgerTransactionAccount emptyAmountAccount = null;
172             float emptyAmountAccountBalance = 0;
173             for (int i = 0; i < table.getChildCount(); i++) {
174                 TableRow row = (TableRow) table.getChildAt(i);
175                 String acc = ((TextView) row.getChildAt(0)).getText().toString();
176                 if (acc.isEmpty()) continue;
177
178                 String amt = ((TextView) row.getChildAt(1)).getText().toString();
179                 LedgerTransactionAccount item;
180                 if (amt.length() > 0) {
181                     final float amount = Float.parseFloat(amt);
182                     item = new LedgerTransactionAccount(acc, amount);
183                     emptyAmountAccountBalance += amount;
184                 }
185                 else {
186                     item = new LedgerTransactionAccount(acc);
187                     emptyAmountAccount = item;
188                 }
189
190                 tr.addAccount(item);
191             }
192
193             if (emptyAmountAccount != null)
194                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
195             saver.execute(tr);
196         }
197         catch (ParseException e) {
198             debug("new-transaction", "Parse error", e);
199             Toast.makeText(this, getResources().getString(R.string.error_invalid_date),
200                     Toast.LENGTH_LONG).show();
201             tvDate.requestFocus();
202
203             progress.setVisibility(View.GONE);
204             toggleAllEditing(true);
205             if (fab != null) fab.setEnabled(true);
206         }
207         catch (Exception e) {
208             debug("new-transaction", "Unknown error", e);
209
210             progress.setVisibility(View.GONE);
211             toggleAllEditing(true);
212             if (fab != null) fab.setEnabled(true);
213         }
214     }
215     private void toggleAllEditing(boolean enabled) {
216         tvDate.setEnabled(enabled);
217         tvDescription.setEnabled(enabled);
218         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
219         for (int i = 0; i < table.getChildCount(); i++) {
220             TableRow row = (TableRow) table.getChildAt(i);
221             for (int j = 0; j < row.getChildCount(); j++) {
222                 row.getChildAt(j).setEnabled(enabled);
223             }
224         }
225     }
226     private void hookSwipeListener(final TableRow row) {
227         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
228             private void onSwipeAside() {
229                 if (table.getChildCount() > 2) {
230                     TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
231                     TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
232                     TextView prev_amt =
233                             (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
234                     TextView next_acc =
235                             (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
236
237                     if (next_acc == null) {
238                         prev_amt.setNextFocusRightId(R.id.none);
239                         prev_amt.setNextFocusForwardId(R.id.none);
240                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
241                     }
242                     else {
243                         prev_amt.setNextFocusRightId(next_acc.getId());
244                         prev_amt.setNextFocusForwardId(next_acc.getId());
245                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
246                     }
247
248                     if (row.hasFocus()) {
249                         if (next_acc != null) next_acc.requestFocus();
250                         else prev_amt.requestFocus();
251                     }
252
253                     table.removeView(row);
254                     check_transaction_submittable();
255 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
256                 }
257                 else {
258                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
259                             Snackbar.LENGTH_LONG).setAction("Action", null).show();
260                 }
261             }
262             public void onSwipeLeft() {
263                 onSwipeAside();
264             }
265             public void onSwipeRight() {
266                 onSwipeAside();
267             }
268             //            @Override
269 //            public boolean performClick(View view, MotionEvent m) {
270 //                return true;
271 //            }
272             public boolean onTouch(View view, MotionEvent m) {
273                 return gestureDetector.onTouchEvent(m);
274             }
275         });
276     }
277
278     public boolean simulateCrash(MenuItem item) {
279         debug("crash", "Will crash intentionally");
280         new AsyncCrasher().execute();
281         return true;
282     }
283     public boolean onCreateOptionsMenu(Menu menu) {
284         // Inflate the menu; this adds items to the action bar if it is present.
285         getMenuInflater().inflate(R.menu.new_transaction, menu);
286
287         if (BuildConfig.DEBUG) {
288             menu.findItem(R.id.action_simulate_crash).setVisible(true);
289         }
290         check_transaction_submittable();
291
292         return true;
293     }
294
295     public void pickTransactionDate(View view) {
296         DialogFragment picker = new DatePickerFragment();
297         picker.show(getSupportFragmentManager(), "datePicker");
298     }
299
300     public int dp2px(float dp) {
301         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
302                 getResources().getDisplayMetrics()));
303     }
304     private void hookTextChangeListener(final TextView view) {
305         view.addTextChangedListener(new TextWatcher() {
306             @Override
307             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
308
309             }
310
311             @Override
312             public void onTextChanged(CharSequence s, int start, int before, int count) {
313
314             }
315
316             @Override
317             public void afterTextChanged(Editable s) {
318 //                debug("input", "text changed");
319                 check_transaction_submittable();
320             }
321         });
322
323     }
324     private TableRow doAddAccountRow(boolean focus) {
325         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
326         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
327                 TableRow.LayoutParams.WRAP_CONTENT, 9f));
328         acc.setHint(R.string.new_transaction_account_hint);
329         acc.setWidth(0);
330         acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
331                           EditorInfo.IME_FLAG_NAVIGATE_NEXT);
332         acc.setSingleLine(true);
333
334         final EditText amt = new EditText(this);
335         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
336                 TableRow.LayoutParams.MATCH_PARENT, 1f));
337         amt.setHint(R.string.new_transaction_amount_hint);
338         amt.setWidth(0);
339         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
340                          InputType.TYPE_NUMBER_FLAG_DECIMAL);
341         amt.setMinWidth(dp2px(40));
342         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
343         amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
344         amt.setSelectAllOnFocus(true);
345
346         // forward navigation support
347         final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
348         final TextView last_amt = (TextView) last_row.getChildAt(1);
349         last_amt.setNextFocusForwardId(acc.getId());
350         last_amt.setNextFocusRightId(acc.getId());
351         last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
352         acc.setNextFocusForwardId(amt.getId());
353         acc.setNextFocusRightId(amt.getId());
354
355         final TableRow row = new TableRow(this);
356         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
357                 TableRow.LayoutParams.MATCH_PARENT));
358         row.setGravity(Gravity.BOTTOM);
359         row.addView(acc);
360         row.addView(amt);
361         table.addView(row);
362
363         if (focus) acc.requestFocus();
364
365         hookSwipeListener(row);
366         MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt, null,
367                 mProfile);
368         hookTextChangeListener(acc);
369         hookTextChangeListener(amt);
370
371         return row;
372     }
373     public void addTransactionAccountFromMenu(MenuItem item) {
374         doAddAccountRow(true);
375     }
376     public void resetTransactionFromMenu(MenuItem item) {
377         resetForm();
378     }
379     public void saveTransactionFromMenu(MenuItem item) {
380         saveTransaction();
381     }
382     // rules:
383     // 1) at least two account names
384     // 2) each amount must have account name
385     // 3) amounts must balance to 0, or
386     // 3a) there must be exactly one empty amount
387     // 4) empty accounts with empty amounts are ignored
388     // 5) a row with an empty account name or empty amount is guaranteed to exist
389     @SuppressLint("DefaultLocale")
390     private void check_transaction_submittable() {
391         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
392         int accounts = 0;
393         int accounts_with_values = 0;
394         int amounts = 0;
395         int amounts_with_accounts = 0;
396         int empty_rows = 0;
397         TextView empty_amount = null;
398         boolean single_empty_amount = false;
399         boolean single_empty_amount_has_account = false;
400         float running_total = 0f;
401         boolean have_description =
402                 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
403                         .isEmpty();
404
405         try {
406             for (int i = 0; i < table.getChildCount(); i++) {
407                 TableRow row = (TableRow) table.getChildAt(i);
408
409                 TextView acc_name_v = (TextView) row.getChildAt(0);
410                 TextView amount_v = (TextView) row.getChildAt(1);
411                 String amt = String.valueOf(amount_v.getText());
412                 String acc_name = String.valueOf(acc_name_v.getText());
413                 acc_name = acc_name.trim();
414
415                 if (!acc_name.isEmpty()) {
416                     accounts++;
417
418                     if (!amt.isEmpty()) {
419                         accounts_with_values++;
420                     }
421                 }
422                 else empty_rows++;
423
424                 if (amt.isEmpty()) {
425                     amount_v.setHint(String.format("%1.2f", 0f));
426                     if (empty_amount == null) {
427                         empty_amount = amount_v;
428                         single_empty_amount = true;
429                         single_empty_amount_has_account = !acc_name.isEmpty();
430                     }
431                     else if (!acc_name.isEmpty()) single_empty_amount = false;
432                 }
433                 else {
434                     amounts++;
435                     if (!acc_name.isEmpty()) amounts_with_accounts++;
436                     running_total += Float.valueOf(amt);
437                 }
438             }
439
440             if ((empty_rows == 0) &&
441                 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
442             {
443                 doAddAccountRow(false);
444             }
445
446             debug("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
447                                                "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
448                                                "single_empty_with_acc=%s", accounts,
449                     accounts_with_values, amounts_with_accounts, amounts, running_total,
450                     (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
451
452             if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
453                 (amounts_with_accounts == amounts) &&
454                 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
455             {
456                 if (fab != null) {
457                     fab.show();
458                     fab.setEnabled(true);
459                 }
460             }
461             else {
462                 if (fab != null) fab.hide();
463             }
464
465             if (single_empty_amount) {
466                 empty_amount.setHint(String.format("%1.2f",
467                         (Math.abs(running_total) > 0.005) ? -running_total : 0f));
468             }
469
470         }
471         catch (NumberFormatException e) {
472             if (fab != null) fab.hide();
473         }
474         catch (Exception e) {
475             e.printStackTrace();
476             if (fab != null) fab.hide();
477         }
478     }
479
480     @Override
481     public void done(String error) {
482         progress.setVisibility(View.INVISIBLE);
483         debug("visuals", "hiding progress");
484
485         if (error == null) resetForm();
486         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
487                 BaseTransientBottomBar.LENGTH_LONG).show();
488
489         toggleAllEditing(true);
490         check_transaction_submittable();
491     }
492
493     private void resetForm() {
494         tvDate.setText("");
495         tvDescription.setText("");
496
497         tvDescription.requestFocus();
498
499         while (table.getChildCount() > 2) {
500             table.removeViewAt(2);
501         }
502         for (int i = 0; i < 2; i++) {
503             TableRow tr = (TableRow) table.getChildAt(i);
504             if (tr == null) break;
505
506             ((TextView) tr.getChildAt(0)).setText("");
507             ((TextView) tr.getChildAt(1)).setText("");
508         }
509     }
510     @Override
511     public void descriptionSelected(String description) {
512         debug("descr selected", description);
513         if (!inputStateIsInitial()) return;
514
515         String accFilter = mProfile.getPreferredAccountsFilter();
516
517         ArrayList<String> params = new ArrayList<>();
518         StringBuilder sb = new StringBuilder(
519                 "select t.profile, t.id from transactions t where t.description=?");
520         params.add(description);
521
522         if (accFilter != null) {
523             sb.append(" AND EXISTS (").append("SELECT 1 FROM transaction_accounts ta ")
524                     .append("WHERE ta.profile = t.profile").append(" AND ta.transaction_id = t.id")
525                     .append(" AND UPPER(ta.account_name) LIKE '%'||?||'%')");
526             params.add(accFilter.toUpperCase());
527         }
528
529         sb.append(" ORDER BY date desc limit 1");
530
531         final String sql = sb.toString();
532         debug("descr", sql);
533         debug("descr", params.toString());
534
535         try (Cursor c = App.getDatabase().rawQuery(sql, params.toArray(new String[]{}))) {
536             if (!c.moveToNext()) return;
537
538             String profileUUID = c.getString(0);
539             int transactionId = c.getInt(1);
540             LedgerTransaction tr;
541             MobileLedgerProfile profile = Data.getProfile(profileUUID);
542             if (profile == null) throw new RuntimeException(String.format(
543                     "Unable to find profile %s, which is supposed to contain " +
544                     "transaction %d with description %s", profileUUID, transactionId, description));
545
546             tr = profile.loadTransaction(transactionId);
547             table = findViewById(R.id.new_transaction_accounts_table);
548             ArrayList<LedgerTransactionAccount> accounts = tr.getAccounts();
549             TableRow firstNegative = null;
550             int negativeCount = 0;
551             for (int i = 0; i < accounts.size(); i++) {
552                 LedgerTransactionAccount acc = accounts.get(i);
553                 TableRow row = (TableRow) table.getChildAt(i);
554                 if (row == null) row = doAddAccountRow(false);
555
556                 ((TextView) row.getChildAt(0)).setText(acc.getAccountName());
557                 ((TextView) row.getChildAt(1))
558                         .setText(String.format(Locale.US, "%1.2f", acc.getAmount()));
559
560                 if (acc.getAmount() < 0.005) {
561                     if (firstNegative == null) firstNegative = row;
562                     negativeCount++;
563                 }
564             }
565
566             if (negativeCount == 1) {
567                 ((TextView) firstNegative.getChildAt(1)).setText(null);
568             }
569
570             check_transaction_submittable();
571
572             EditText firstAmount = (EditText) ((TableRow) table.getChildAt(0)).getChildAt(1);
573             String amtString = String.valueOf(firstAmount.getText());
574             firstAmount.requestFocus();
575             firstAmount.setSelection(0, amtString.length());
576         }
577
578     }
579     private boolean inputStateIsInitial() {
580         table = findViewById(R.id.new_transaction_accounts_table);
581
582         if (table.getChildCount() != 2) return false;
583
584         for (int i = 0; i < 2; i++) {
585             TableRow row = (TableRow) table.getChildAt(i);
586             if (((TextView) row.getChildAt(0)).getText().length() > 0) return false;
587             if (((TextView) row.getChildAt(1)).getText().length() > 0) return false;
588         }
589
590         return true;
591     }
592     private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
593         @Override
594         protected Void doInBackground(Void... voids) {
595             throw new RuntimeException("Simulated crash");
596         }
597     }
598 }