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