2 * Copyright © 2018 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.
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.
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/>.
18 package net.ktnx.mobileledger.ui.activity;
20 import android.annotation.SuppressLint;
21 import android.os.Bundle;
22 import android.preference.PreferenceManager;
23 import android.support.design.widget.BaseTransientBottomBar;
24 import android.support.design.widget.Snackbar;
25 import android.support.v4.app.DialogFragment;
26 import android.support.v7.app.AppCompatActivity;
27 import android.support.v7.widget.Toolbar;
28 import android.text.Editable;
29 import android.text.InputType;
30 import android.text.TextWatcher;
31 import android.util.Log;
32 import android.util.TypedValue;
33 import android.view.Gravity;
34 import android.view.Menu;
35 import android.view.MenuItem;
36 import android.view.MotionEvent;
37 import android.view.View;
38 import android.view.inputmethod.EditorInfo;
39 import android.widget.AutoCompleteTextView;
40 import android.widget.EditText;
41 import android.widget.ProgressBar;
42 import android.widget.TableLayout;
43 import android.widget.TableRow;
44 import android.widget.TextView;
46 import net.ktnx.mobileledger.ui.OnSwipeTouchListener;
47 import net.ktnx.mobileledger.R;
48 import net.ktnx.mobileledger.async.SaveTransactionTask;
49 import net.ktnx.mobileledger.async.TaskCallback;
50 import net.ktnx.mobileledger.model.LedgerTransaction;
51 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
52 import net.ktnx.mobileledger.ui.DatePickerFragment;
53 import net.ktnx.mobileledger.utils.MLDB;
55 import java.util.Date;
56 import java.util.Objects;
59 * TODO: nicer progress while transaction is submitted
60 * TODO: latest transactions, maybe with browsing further in the past?
62 * TODO: get rid of the custom session/cookie and auth code?
63 * (the last problem with the POST was the missing content-length header)
65 * TODO: nicer swiping removal with visual feedback
67 * TODO: update accounts/check settings upon change of backend settings
70 public class NewTransactionActivity extends AppCompatActivity implements TaskCallback {
71 private static SaveTransactionTask saver;
72 private TableLayout table;
73 private ProgressBar progress;
74 private TextView text_date;
75 private AutoCompleteTextView text_descr;
76 private MenuItem mSave;
79 protected void onCreate(Bundle savedInstanceState) {
80 super.onCreate(savedInstanceState);
81 setContentView(R.layout.activity_new_transaction);
82 Toolbar toolbar = findViewById(R.id.toolbar);
83 setSupportActionBar(toolbar);
85 text_date = findViewById(R.id.new_transaction_date);
86 text_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
88 public void onFocusChange(View v, boolean hasFocus) {
89 if (hasFocus) pickTransactionDate(v);
92 text_descr = findViewById(R.id.new_transaction_description);
93 MLDB.hook_autocompletion_adapter(this, text_descr, MLDB.DESCRIPTION_HISTORY_TABLE,
95 hook_text_change_listener(text_descr);
97 progress = findViewById(R.id.save_transaction_progress);
99 Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
100 table = findViewById(R.id.new_transaction_accounts_table);
101 for (int i = 0; i < table.getChildCount(); i++) {
102 TableRow row = (TableRow) table.getChildAt(i);
103 AutoCompleteTextView acc_name_view = (AutoCompleteTextView) row.getChildAt(0);
104 TextView amount_view = (TextView) row.getChildAt(1);
105 hook_swipe_listener(row);
106 MLDB.hook_autocompletion_adapter(this, acc_name_view, MLDB.ACCOUNTS_TABLE, "name");
107 hook_text_change_listener(acc_name_view);
108 hook_text_change_listener(amount_view);
109 // Log.d("swipe", "hooked to row "+i);
114 protected void onStart() {
116 if (text_descr.getText().toString().isEmpty()) text_descr.requestFocus();
120 public void finish() {
122 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
126 public boolean onOptionsItemSelected(MenuItem item) {
127 switch (item.getItemId()) {
128 case android.R.id.home:
132 return super.onOptionsItemSelected(item);
135 public void save_transaction() {
136 if (mSave != null) mSave.setVisible(false);
137 toggle_all_editing(false);
138 progress.setVisibility(View.VISIBLE);
140 saver = new SaveTransactionTask(this);
142 saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
143 String date = text_date.getText().toString();
144 if (date.isEmpty()) date = String.valueOf(new Date().getDate());
145 LedgerTransaction tr = new LedgerTransaction(date, text_descr.getText().toString());
147 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
148 for (int i = 0; i < table.getChildCount(); i++) {
149 TableRow row = (TableRow) table.getChildAt(i);
150 String acc = ((TextView) row.getChildAt(0)).getText().toString();
151 String amt = ((TextView) row.getChildAt(1)).getText().toString();
152 LedgerTransactionAccount item =
153 amt.length() > 0 ? new LedgerTransactionAccount(acc, Float.parseFloat(amt))
154 : new LedgerTransactionAccount(acc);
161 private void toggle_all_editing(boolean enabled) {
162 text_date.setEnabled(enabled);
163 text_descr.setEnabled(enabled);
164 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
165 for (int i = 0; i < table.getChildCount(); i++) {
166 TableRow row = (TableRow) table.getChildAt(i);
167 for (int j = 0; j < row.getChildCount(); j++) {
168 row.getChildAt(j).setEnabled(enabled);
173 private void hook_swipe_listener(final TableRow row) {
174 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
175 public void onSwipeLeft() {
176 // Log.d("swipe", "LEFT" + row.getId());
177 if (table.getChildCount() > 2) {
178 TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
179 TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
181 (prev_row != null) ? (TextView) prev_row.getChildAt(1) : text_descr;
183 (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
185 if (next_acc == null) {
186 prev_amt.setNextFocusRightId(R.id.none);
187 prev_amt.setNextFocusForwardId(R.id.none);
188 prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
191 prev_amt.setNextFocusRightId(next_acc.getId());
192 prev_amt.setNextFocusForwardId(next_acc.getId());
193 prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
196 if (row.hasFocus()) {
197 if (next_acc != null) next_acc.requestFocus();
198 else prev_amt.requestFocus();
201 table.removeView(row);
202 check_transaction_submittable();
203 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
206 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
207 Snackbar.LENGTH_LONG).setAction("Action", null).show();
211 // public boolean performClick(View view, MotionEvent m) {
214 public boolean onTouch(View view, MotionEvent m) {
215 return gestureDetector.onTouchEvent(m);
220 private void hook_text_change_listener(final TextView view) {
221 view.addTextChangedListener(new TextWatcher() {
223 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
228 public void onTextChanged(CharSequence s, int start, int before, int count) {
233 public void afterTextChanged(Editable s) {
234 // Log.d("input", "text changed");
235 check_transaction_submittable();
241 public boolean onCreateOptionsMenu(Menu menu) {
242 // Inflate the menu; this adds items to the action bar if it is present.
243 getMenuInflater().inflate(R.menu.new_transaction, menu);
244 mSave = menu.findItem(R.id.action_submit_transaction);
245 if (mSave == null) throw new AssertionError();
247 check_transaction_submittable();
252 public void pickTransactionDate(View view) {
253 DialogFragment picker = new DatePickerFragment();
254 picker.show(getSupportFragmentManager(), "datePicker");
257 public int dp2px(float dp) {
258 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
259 getResources().getDisplayMetrics()));
262 private void do_add_account_row(boolean focus) {
263 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
264 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
265 TableRow.LayoutParams.WRAP_CONTENT, 9f));
266 acc.setHint(R.string.new_transaction_account_hint);
268 acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
269 EditorInfo.IME_FLAG_NAVIGATE_NEXT);
270 acc.setSingleLine(true);
272 final EditText amt = new EditText(this);
273 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
274 TableRow.LayoutParams.MATCH_PARENT, 1f));
275 amt.setHint(R.string.new_transaction_amount_hint);
277 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
278 InputType.TYPE_NUMBER_FLAG_DECIMAL);
279 amt.setMinWidth(dp2px(40));
280 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
281 amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
283 // forward navigation support
284 final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
285 final TextView last_amt = (TextView) last_row.getChildAt(1);
286 last_amt.setNextFocusForwardId(acc.getId());
287 last_amt.setNextFocusRightId(acc.getId());
288 last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
289 acc.setNextFocusForwardId(amt.getId());
290 acc.setNextFocusRightId(amt.getId());
292 final TableRow row = new TableRow(this);
293 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
294 TableRow.LayoutParams.MATCH_PARENT));
295 row.setGravity(Gravity.BOTTOM);
300 if (focus) acc.requestFocus();
302 hook_swipe_listener(row);
303 MLDB.hook_autocompletion_adapter(this, acc, MLDB.ACCOUNTS_TABLE, "name");
304 hook_text_change_listener(acc);
305 hook_text_change_listener(amt);
308 public void addTransactionAccountFromMenu(MenuItem item) {
309 do_add_account_row(true);
312 public void resetTransactionFromMenu(MenuItem item) {
316 public void saveTransactionFromMenu(MenuItem item) {
320 private boolean is_zero(float f) {
321 return (f < 0.005) && (f > -0.005);
325 // 1) at least two account names
326 // 2) each amount must have account name
327 // 3) amounts must balance to 0, or
328 // 3a) there must be exactly one empty amount
329 // 4) empty accounts with empty amounts are ignored
330 // 5) a row with an empty account name or empty amount is guaranteed to exist
331 @SuppressLint("DefaultLocale")
332 private void check_transaction_submittable() {
333 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
335 int accounts_with_values = 0;
337 int amounts_with_accounts = 0;
339 TextView empty_amount = null;
340 boolean single_empty_amount = false;
341 boolean single_empty_amount_has_account = false;
342 float running_total = 0f;
343 boolean have_description =
344 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
348 for (int i = 0; i < table.getChildCount(); i++) {
349 TableRow row = (TableRow) table.getChildAt(i);
351 TextView acc_name_v = (TextView) row.getChildAt(0);
352 TextView amount_v = (TextView) row.getChildAt(1);
353 String amt = String.valueOf(amount_v.getText());
354 String acc_name = String.valueOf(acc_name_v.getText());
355 acc_name = acc_name.trim();
357 if (!acc_name.isEmpty()) {
360 if (!amt.isEmpty()) {
361 accounts_with_values++;
367 amount_v.setHint(String.format("%1.2f", 0f));
368 if (empty_amount == null) {
369 empty_amount = amount_v;
370 single_empty_amount = true;
371 single_empty_amount_has_account = !acc_name.isEmpty();
373 else if (!acc_name.isEmpty()) single_empty_amount = false;
377 if (!acc_name.isEmpty()) amounts_with_accounts++;
378 running_total += Float.valueOf(amt);
382 if ((empty_rows == 0) &&
383 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
385 do_add_account_row(false);
388 Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
389 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
390 "single_empty_with_acc=%s", accounts,
391 accounts_with_values, amounts_with_accounts, amounts, running_total,
392 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
394 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
395 (amounts_with_accounts == amounts) &&
396 (single_empty_amount && single_empty_amount_has_account || is_zero(running_total)))
398 if (mSave != null) mSave.setVisible(true);
400 else if (mSave != null) mSave.setVisible(false);
402 if (single_empty_amount) {
403 empty_amount.setHint(String.format("%1.2f",
404 (Math.abs(running_total) > 0.005) ? -running_total : 0f));
408 catch (NumberFormatException e) {
409 if (mSave != null) mSave.setVisible(false);
411 catch (Exception e) {
413 if (mSave != null) mSave.setVisible(false);
418 public void done(String error) {
419 progress.setVisibility(View.INVISIBLE);
420 Log.d("visuals", "hiding progress");
422 if (error == null) reset_form();
423 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
424 BaseTransientBottomBar.LENGTH_LONG).show();
426 toggle_all_editing(true);
427 check_transaction_submittable();
430 private void reset_form() {
431 text_date.setText("");
432 text_descr.setText("");
434 text_descr.requestFocus();
436 while (table.getChildCount() > 2) {
437 table.removeViewAt(2);
439 for (int i = 0; i < 2; i++) {
440 TableRow tr = (TableRow) table.getChildAt(i);
441 if (tr == null) break;
443 ((TextView) tr.getChildAt(0)).setText("");
444 ((TextView) tr.getChildAt(1)).setText("");