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;
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.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.utils.MLDB;
53 import java.util.Date;
54 import java.util.Objects;
57 * TODO: nicer progress while transaction is submitted
58 * TODO: latest transactions, maybe with browsing further in the past?
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)
63 * TODO: nicer swiping removal with visual feedback
65 * TODO: update accounts/check settings upon change of backend settings
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;
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);
83 text_date = findViewById(R.id.new_transaction_date);
84 text_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
86 public void onFocusChange(View v, boolean hasFocus) {
87 if (hasFocus) pickTransactionDate(v);
90 text_descr = findViewById(R.id.new_transaction_description);
91 MLDB.hook_autocompletion_adapter(this, text_descr, MLDB.DESCRIPTION_HISTORY_TABLE,
93 hook_text_change_listener(text_descr);
95 progress = findViewById(R.id.save_transaction_progress);
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 acc_name_view = (AutoCompleteTextView) row.getChildAt(0);
102 TextView amount_view = (TextView) row.getChildAt(1);
103 hook_swipe_listener(row);
104 MLDB.hook_autocompletion_adapter(this, acc_name_view, MLDB.ACCOUNTS_TABLE, "name");
105 hook_text_change_listener(acc_name_view);
106 hook_text_change_listener(amount_view);
107 // Log.d("swipe", "hooked to row "+i);
112 protected void onStart() {
114 if (text_descr.getText().toString().isEmpty()) text_descr.requestFocus();
118 public void finish() {
120 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
124 public boolean onOptionsItemSelected(MenuItem item) {
125 switch (item.getItemId()) {
126 case android.R.id.home:
130 return super.onOptionsItemSelected(item);
133 public void save_transaction() {
134 if (mSave != null) mSave.setVisible(false);
135 toggle_all_editing(false);
136 progress.setVisibility(View.VISIBLE);
138 saver = new SaveTransactionTask(this);
140 saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
141 String date = text_date.getText().toString();
142 if (date.isEmpty()) date = String.valueOf(new Date().getDate());
143 LedgerTransaction tr = new LedgerTransaction(date, text_descr.getText().toString());
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);
159 private void toggle_all_editing(boolean enabled) {
160 text_date.setEnabled(enabled);
161 text_descr.setEnabled(enabled);
162 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
163 for (int i = 0; i < table.getChildCount(); i++) {
164 TableRow row = (TableRow) table.getChildAt(i);
165 for (int j = 0; j < row.getChildCount(); j++) {
166 row.getChildAt(j).setEnabled(enabled);
171 private void hook_swipe_listener(final TableRow row) {
172 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
173 public void onSwipeLeft() {
174 // Log.d("swipe", "LEFT" + row.getId());
175 if (table.getChildCount() > 2) {
176 TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
177 TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
179 (prev_row != null) ? (TextView) prev_row.getChildAt(1) : text_descr;
181 (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
183 if (next_acc == null) {
184 prev_amt.setNextFocusRightId(R.id.none);
185 prev_amt.setNextFocusForwardId(R.id.none);
186 prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
189 prev_amt.setNextFocusRightId(next_acc.getId());
190 prev_amt.setNextFocusForwardId(next_acc.getId());
191 prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
194 if (row.hasFocus()) {
195 if (next_acc != null) next_acc.requestFocus();
196 else prev_amt.requestFocus();
199 table.removeView(row);
200 check_transaction_submittable();
201 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
204 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required,
205 Snackbar.LENGTH_LONG).setAction("Action", null).show();
209 // public boolean performClick(View view, MotionEvent m) {
212 public boolean onTouch(View view, MotionEvent m) {
213 return gestureDetector.onTouchEvent(m);
218 private void hook_text_change_listener(final TextView view) {
219 view.addTextChangedListener(new TextWatcher() {
221 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
226 public void onTextChanged(CharSequence s, int start, int before, int count) {
231 public void afterTextChanged(Editable s) {
232 // Log.d("input", "text changed");
233 check_transaction_submittable();
239 public boolean onCreateOptionsMenu(Menu menu) {
240 // Inflate the menu; this adds items to the action bar if it is present.
241 getMenuInflater().inflate(R.menu.new_transaction, menu);
242 mSave = menu.findItem(R.id.action_submit_transaction);
243 if (mSave == null) throw new AssertionError();
245 check_transaction_submittable();
250 public void pickTransactionDate(View view) {
251 DialogFragment picker = new DatePickerFragment();
252 picker.show(getSupportFragmentManager(), "datePicker");
255 public int dp2px(float dp) {
256 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
257 getResources().getDisplayMetrics()));
260 private void do_add_account_row(boolean focus) {
261 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
262 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
263 TableRow.LayoutParams.WRAP_CONTENT, 9f));
264 acc.setHint(R.string.new_transaction_account_hint);
266 acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION |
267 EditorInfo.IME_FLAG_NAVIGATE_NEXT);
268 acc.setSingleLine(true);
270 final EditText amt = new EditText(this);
271 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
272 TableRow.LayoutParams.MATCH_PARENT, 1f));
273 amt.setHint(R.string.new_transaction_amount_hint);
275 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED |
276 InputType.TYPE_NUMBER_FLAG_DECIMAL);
277 amt.setMinWidth(dp2px(40));
278 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
279 amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
281 // forward navigation support
282 final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
283 final TextView last_amt = (TextView) last_row.getChildAt(1);
284 last_amt.setNextFocusForwardId(acc.getId());
285 last_amt.setNextFocusRightId(acc.getId());
286 last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
287 acc.setNextFocusForwardId(amt.getId());
288 acc.setNextFocusRightId(amt.getId());
290 final TableRow row = new TableRow(this);
291 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
292 TableRow.LayoutParams.MATCH_PARENT));
293 row.setGravity(Gravity.BOTTOM);
298 if (focus) acc.requestFocus();
300 hook_swipe_listener(row);
301 MLDB.hook_autocompletion_adapter(this, acc, MLDB.ACCOUNTS_TABLE, "name");
302 hook_text_change_listener(acc);
303 hook_text_change_listener(amt);
306 public void addTransactionAccountFromMenu(MenuItem item) {
307 do_add_account_row(true);
310 public void resetTransactionFromMenu(MenuItem item) {
314 public void saveTransactionFromMenu(MenuItem item) {
318 private boolean is_zero(float f) {
319 return (f < 0.005) && (f > -0.005);
323 // 1) at least two account names
324 // 2) each amount must have account name
325 // 3) amounts must balance to 0, or
326 // 3a) there must be exactly one empty amount
327 // 4) empty accounts with empty amounts are ignored
328 // 5) a row with an empty account name or empty amount is guaranteed to exist
329 @SuppressLint("DefaultLocale")
330 private void check_transaction_submittable() {
331 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
333 int accounts_with_values = 0;
335 int amounts_with_accounts = 0;
337 TextView empty_amount = null;
338 boolean single_empty_amount = false;
339 boolean single_empty_amount_has_account = false;
340 float running_total = 0f;
341 boolean have_description =
342 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
346 for (int i = 0; i < table.getChildCount(); i++) {
347 TableRow row = (TableRow) table.getChildAt(i);
349 TextView acc_name_v = (TextView) row.getChildAt(0);
350 TextView amount_v = (TextView) row.getChildAt(1);
351 String amt = String.valueOf(amount_v.getText());
352 String acc_name = String.valueOf(acc_name_v.getText());
353 acc_name = acc_name.trim();
355 if (!acc_name.isEmpty()) {
358 if (!amt.isEmpty()) {
359 accounts_with_values++;
365 amount_v.setHint(String.format("%1.2f", 0f));
366 if (empty_amount == null) {
367 empty_amount = amount_v;
368 single_empty_amount = true;
369 single_empty_amount_has_account = !acc_name.isEmpty();
371 else if (!acc_name.isEmpty()) single_empty_amount = false;
375 if (!acc_name.isEmpty()) amounts_with_accounts++;
376 running_total += Float.valueOf(amt);
380 if ((empty_rows == 0) &&
381 ((table.getChildCount() == accounts) || (table.getChildCount() == amounts)))
383 do_add_account_row(false);
386 Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, " +
387 "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, " +
388 "single_empty_with_acc=%s", accounts,
389 accounts_with_values, amounts_with_accounts, amounts, running_total,
390 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
392 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) &&
393 (amounts_with_accounts == amounts) &&
394 (single_empty_amount && single_empty_amount_has_account || is_zero(running_total)))
396 if (mSave != null) mSave.setVisible(true);
398 else if (mSave != null) mSave.setVisible(false);
400 if (single_empty_amount) {
402 .setHint(String.format("%1.2f", (running_total > 0) ? -running_total : 0f));
406 catch (NumberFormatException e) {
407 if (mSave != null) mSave.setVisible(false);
409 catch (Exception e) {
411 if (mSave != null) mSave.setVisible(false);
416 public void done(String error) {
417 progress.setVisibility(View.INVISIBLE);
418 Log.d("visuals", "hiding progress");
420 if (error == null) reset_form();
421 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
422 BaseTransientBottomBar.LENGTH_LONG).show();
424 toggle_all_editing(true);
425 check_transaction_submittable();
428 private void reset_form() {
429 text_date.setText("");
430 text_descr.setText("");
432 text_descr.requestFocus();
434 while (table.getChildCount() > 2) {
435 table.removeViewAt(2);
437 for (int i = 0; i < 2; i++) {
438 TableRow tr = (TableRow) table.getChildAt(i);
439 if (tr == null) break;
441 ((TextView) tr.getChildAt(0)).setText("");
442 ((TextView) tr.getChildAt(1)).setText("");