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