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