]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionActivity.java
a08f88c1ddcdb0b67792d3a5a41b4fecc277a6f4
[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 Mobile-Ledger.
4  * Mobile-Ledger is free software: you can distribute it and/or modify it
5  * under the term of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your opinion), any later version.
8  *
9  * Mobile-Ledger is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License terms for details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with Mobile-Ledger. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.ui.activity;
19
20 import android.annotation.SuppressLint;
21 import android.os.Bundle;
22 import android.support.design.widget.BaseTransientBottomBar;
23 import android.support.design.widget.Snackbar;
24 import android.support.v4.app.DialogFragment;
25 import android.support.v7.app.AppCompatActivity;
26 import android.support.v7.widget.Toolbar;
27 import android.text.Editable;
28 import android.text.InputType;
29 import android.text.TextWatcher;
30 import android.util.Log;
31 import android.util.TypedValue;
32 import android.view.Gravity;
33 import android.view.Menu;
34 import android.view.MenuItem;
35 import android.view.MotionEvent;
36 import android.view.View;
37 import android.view.inputmethod.EditorInfo;
38 import android.widget.AutoCompleteTextView;
39 import android.widget.EditText;
40 import android.widget.ProgressBar;
41 import android.widget.TableLayout;
42 import android.widget.TableRow;
43 import android.widget.TextView;
44
45 import net.ktnx.mobileledger.R;
46 import net.ktnx.mobileledger.async.SaveTransactionTask;
47 import net.ktnx.mobileledger.async.TaskCallback;
48 import net.ktnx.mobileledger.model.LedgerTransaction;
49 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
50 import net.ktnx.mobileledger.ui.DatePickerFragment;
51 import net.ktnx.mobileledger.ui.OnSwipeTouchListener;
52 import net.ktnx.mobileledger.utils.Globals;
53 import net.ktnx.mobileledger.utils.MLDB;
54
55 import java.util.Date;
56 import java.util.Objects;
57
58 /*
59  * TODO: nicer progress while transaction is submitted
60  * TODO: reports
61  * TODO: get rid of the custom session/cookie and auth code?
62  *         (the last problem with the POST was the missing content-length header)
63  * TODO: app icon
64  * TODO: nicer swiping removal with visual feedback
65  * TODO: setup wizard
66  * TODO: update accounts/check settings upon change of backend settings
67  *  */
68
69 public class NewTransactionActivity extends AppCompatActivity implements TaskCallback {
70     private static SaveTransactionTask saver;
71     private TableLayout table;
72     private ProgressBar progress;
73     private TextView tvDate;
74     private AutoCompleteTextView tvDescription;
75     private MenuItem mSave;
76     private static boolean isZero(float f) {
77         return (f < 0.005) && (f > -0.005);
78     }
79     @Override
80     protected void onCreate(Bundle savedInstanceState) {
81         super.onCreate(savedInstanceState);
82         setContentView(R.layout.activity_new_transaction);
83         Toolbar toolbar = findViewById(R.id.toolbar);
84         setSupportActionBar(toolbar);
85
86         tvDate = findViewById(R.id.new_transaction_date);
87         tvDate.setOnFocusChangeListener((v, hasFocus) -> {
88             if (hasFocus) pickTransactionDate(v);
89         });
90         tvDescription = findViewById(R.id.new_transaction_description);
91         MLDB.hookAutocompletionAdapter(this, tvDescription, MLDB.DESCRIPTION_HISTORY_TABLE,
92                 "description", false, findViewById(R.id.new_transaction_acc_1));
93         hookTextChangeListener(tvDescription);
94
95         progress = findViewById(R.id.save_transaction_progress);
96
97         Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
98         table = findViewById(R.id.new_transaction_accounts_table);
99         for (int i = 0; i < table.getChildCount(); i++) {
100             TableRow row = (TableRow) table.getChildAt(i);
101             AutoCompleteTextView tvAccountName = (AutoCompleteTextView) row.getChildAt(0);
102             TextView tvAmount = (TextView) row.getChildAt(1);
103             hookSwipeListener(row);
104             MLDB.hookAutocompletionAdapter(this, tvAccountName, MLDB.ACCOUNTS_TABLE, "name", true,
105                     tvAmount);
106             hookTextChangeListener(tvAccountName);
107             hookTextChangeListener(tvAmount);
108 //            Log.d("swipe", "hooked to row "+i);
109         }
110     }
111
112     @Override
113     public void finish() {
114         super.finish();
115         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
116     }
117
118     @Override
119     public boolean onOptionsItemSelected(MenuItem item) {
120         switch (item.getItemId()) {
121             case android.R.id.home:
122                 finish();
123                 return true;
124         }
125         return super.onOptionsItemSelected(item);
126     }
127     @Override
128     protected void onStart() {
129         super.onStart();
130         if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
131     }
132     public void saveTransaction() {
133         if (mSave != null) mSave.setVisible(false);
134         toggleAllEditing(false);
135         progress.setVisibility(View.VISIBLE);
136
137         saver = new SaveTransactionTask(this);
138
139         String dateString = tvDate.getText().toString();
140         Date date;
141         if (dateString.isEmpty()) date = new Date();
142         else date = Globals.parseLedgerDate(dateString);
143         LedgerTransaction tr = new LedgerTransaction(date, tvDescription.getText().toString());
144
145         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
146         for (int i = 0; i < table.getChildCount(); i++) {
147             TableRow row = (TableRow) table.getChildAt(i);
148             String acc = ((TextView) row.getChildAt(0)).getText().toString();
149             String amt = ((TextView) row.getChildAt(1)).getText().toString();
150             LedgerTransactionAccount item =
151                     amt.length() > 0 ? new LedgerTransactionAccount(acc, Float.parseFloat(amt))
152                                      : new LedgerTransactionAccount(acc);
153
154             tr.addAccount(item);
155         }
156         saver.execute(tr);
157     }
158     private void toggleAllEditing(boolean enabled) {
159         tvDate.setEnabled(enabled);
160         tvDescription.setEnabled(enabled);
161         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
162         for (int i = 0; i < table.getChildCount(); i++) {
163             TableRow row = (TableRow) table.getChildAt(i);
164             for (int j = 0; j < row.getChildCount(); j++) {
165                 row.getChildAt(j).setEnabled(enabled);
166             }
167         }
168     }
169     private void hookSwipeListener(final TableRow row) {
170         row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
171             public void onSwipeLeft() {
172 //                Log.d("swipe", "LEFT" + row.getId());
173                 if (table.getChildCount() > 2) {
174                     TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
175                     TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
176                     TextView prev_amt =
177                             (prev_row != null) ? (TextView) prev_row.getChildAt(1) : tvDescription;
178                     TextView next_acc =
179                             (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
180
181                     if (next_acc == null) {
182                         prev_amt.setNextFocusRightId(R.id.none);
183                         prev_amt.setNextFocusForwardId(R.id.none);
184                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
185                     }
186                     else {
187                         prev_amt.setNextFocusRightId(next_acc.getId());
188                         prev_amt.setNextFocusForwardId(next_acc.getId());
189                         prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
190                     }
191
192                     if (row.hasFocus()) {
193                         if (next_acc != null) next_acc.requestFocus();
194                         else prev_amt.requestFocus();
195                     }
196
197                     table.removeView(row);
198                     check_transaction_submittable();
199 //                    Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
200                 }
201                 else {
202                     Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
203                             Snackbar.LENGTH_LONG).setAction("Action", null).show();
204                 }
205             }
206             //            @Override
207 //            public boolean performClick(View view, MotionEvent m) {
208 //                return true;
209 //            }
210             public boolean onTouch(View view, MotionEvent m) {
211                 return gestureDetector.onTouchEvent(m);
212             }
213         });
214     }
215
216     public boolean onCreateOptionsMenu(Menu menu) {
217         // Inflate the menu; this adds items to the action bar if it is present.
218         getMenuInflater().inflate(R.menu.new_transaction, menu);
219         mSave = menu.findItem(R.id.action_submit_transaction);
220         if (mSave == null) throw new AssertionError();
221
222         check_transaction_submittable();
223
224         return true;
225     }
226
227     public void pickTransactionDate(View view) {
228         DialogFragment picker = new DatePickerFragment();
229         picker.show(getSupportFragmentManager(), "datePicker");
230     }
231
232     public int dp2px(float dp) {
233         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
234                 getResources().getDisplayMetrics()));
235     }
236     private void hookTextChangeListener(final TextView view) {
237         view.addTextChangedListener(new TextWatcher() {
238             @Override
239             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
240
241             }
242
243             @Override
244             public void onTextChanged(CharSequence s, int start, int before, int count) {
245
246             }
247
248             @Override
249             public void afterTextChanged(Editable s) {
250 //                Log.d("input", "text changed");
251                 check_transaction_submittable();
252             }
253         });
254
255     }
256     private void doAddAccountRow(boolean focus) {
257         final AutoCompleteTextView acc = new AutoCompleteTextView(this);
258         acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
259                 TableRow.LayoutParams.WRAP_CONTENT, 9f));
260         acc.setHint(R.string.new_transaction_account_hint);
261         acc.setWidth(0);
262         acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
263                           EditorInfo.IME_FLAG_NAVIGATE_NEXT);
264         acc.setSingleLine(true);
265
266         final EditText amt = new EditText(this);
267         amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
268                 TableRow.LayoutParams.MATCH_PARENT, 1f));
269         amt.setHint(R.string.new_transaction_amount_hint);
270         amt.setWidth(0);
271         amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
272                          InputType.TYPE_NUMBER_FLAG_DECIMAL);
273         amt.setMinWidth(dp2px(40));
274         amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
275         amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
276
277         // forward navigation support
278         final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
279         final TextView last_amt = (TextView) last_row.getChildAt(1);
280         last_amt.setNextFocusForwardId(acc.getId());
281         last_amt.setNextFocusRightId(acc.getId());
282         last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
283         acc.setNextFocusForwardId(amt.getId());
284         acc.setNextFocusRightId(amt.getId());
285
286         final TableRow row = new TableRow(this);
287         row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
288                 TableRow.LayoutParams.MATCH_PARENT));
289         row.setGravity(Gravity.BOTTOM);
290         row.addView(acc);
291         row.addView(amt);
292         table.addView(row);
293
294         if (focus) acc.requestFocus();
295
296         hookSwipeListener(row);
297         MLDB.hookAutocompletionAdapter(this, acc, MLDB.ACCOUNTS_TABLE, "name", true, amt);
298         hookTextChangeListener(acc);
299         hookTextChangeListener(amt);
300     }
301     public void addTransactionAccountFromMenu(MenuItem item) {
302         doAddAccountRow(true);
303     }
304     public void resetTransactionFromMenu(MenuItem item) {
305         resetForm();
306     }
307     public void saveTransactionFromMenu(MenuItem item) {
308         saveTransaction();
309     }
310     // rules:
311     // 1) at least two account names
312     // 2) each amount must have account name
313     // 3) amounts must balance to 0, or
314     // 3a) there must be exactly one empty amount
315     // 4) empty accounts with empty amounts are ignored
316     // 5) a row with an empty account name or empty amount is guaranteed to exist
317     @SuppressLint("DefaultLocale")
318     private void check_transaction_submittable() {
319         TableLayout table = findViewById(R.id.new_transaction_accounts_table);
320         int accounts = 0;
321         int accounts_with_values = 0;
322         int amounts = 0;
323         int amounts_with_accounts = 0;
324         int empty_rows = 0;
325         TextView empty_amount = null;
326         boolean single_empty_amount = false;
327         boolean single_empty_amount_has_account = false;
328         float running_total = 0f;
329         boolean have_description =
330                 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
331                         .isEmpty();
332
333         try {
334             for (int i = 0; i < table.getChildCount(); i++) {
335                 TableRow row = (TableRow) table.getChildAt(i);
336
337                 TextView acc_name_v = (TextView) row.getChildAt(0);
338                 TextView amount_v = (TextView) row.getChildAt(1);
339                 String amt = String.valueOf(amount_v.getText());
340                 String acc_name = String.valueOf(acc_name_v.getText());
341                 acc_name = acc_name.trim();
342
343                 if (!acc_name.isEmpty()) {
344                     accounts++;
345
346                     if (!amt.isEmpty()) {
347                         accounts_with_values++;
348                     }
349                 }
350                 else empty_rows++;
351
352                 if (amt.isEmpty()) {
353                     amount_v.setHint(String.format("%1.2f", 0f));
354                     if (empty_amount == null) {
355                         empty_amount = amount_v;
356                         single_empty_amount = true;
357                         single_empty_amount_has_account = !acc_name.isEmpty();
358                     }
359                     else if (!acc_name.isEmpty()) single_empty_amount = false;
360                 }
361                 else {
362                     amounts++;
363                     if (!acc_name.isEmpty()) amounts_with_accounts++;
364                     running_total += Float.valueOf(amt);
365                 }
366             }
367
368             if ((empty_rows == 0) &&
369                 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
370             {
371                 doAddAccountRow(false);
372             }
373
374             Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
375                                                "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
376                                                "single_empty_with_acc=%s", accounts,
377                     accounts_with_values, amounts_with_accounts, amounts, running_total,
378                     (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
379
380             if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
381                 (amounts_with_accounts == amounts) &&
382                 (single_empty_amount && single_empty_amount_has_account || isZero(running_total)))
383             {
384                 if (mSave != null) mSave.setVisible(true);
385             }
386             else if (mSave != null) mSave.setVisible(false);
387
388             if (single_empty_amount) {
389                 empty_amount.setHint(String.format("%1.2f",
390                         (Math.abs(running_total) > 0.005) ? -running_total : 0f));
391             }
392
393         }
394         catch (NumberFormatException e) {
395             if (mSave != null) mSave.setVisible(false);
396         }
397         catch (Exception e) {
398             e.printStackTrace();
399             if (mSave != null) mSave.setVisible(false);
400         }
401     }
402
403     @Override
404     public void done(String error) {
405         progress.setVisibility(View.INVISIBLE);
406         Log.d("visuals", "hiding progress");
407
408         if (error == null) resetForm();
409         else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
410                 BaseTransientBottomBar.LENGTH_LONG).show();
411
412         toggleAllEditing(true);
413         check_transaction_submittable();
414     }
415
416     private void resetForm() {
417         tvDate.setText("");
418         tvDescription.setText("");
419
420         tvDescription.requestFocus();
421
422         while (table.getChildCount() > 2) {
423             table.removeViewAt(2);
424         }
425         for (int i = 0; i < 2; i++) {
426             TableRow tr = (TableRow) table.getChildAt(i);
427             if (tr == null) break;
428
429             ((TextView) tr.getChildAt(0)).setText("");
430             ((TextView) tr.getChildAt(1)).setText("");
431         }
432     }
433 }