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