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