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.annotation.TargetApi;
22 import android.database.Cursor;
23 import android.database.MatrixCursor;
24 import android.database.sqlite.SQLiteDatabase;
25 import android.os.Build;
26 import android.os.Bundle;
27 import android.preference.PreferenceManager;
28 import android.provider.FontsContract;
29 import android.support.design.widget.BaseTransientBottomBar;
30 import android.support.design.widget.Snackbar;
31 import android.support.v4.app.DialogFragment;
32 import android.support.v7.app.AppCompatActivity;
33 import android.support.v7.widget.Toolbar;
34 import android.text.Editable;
35 import android.text.InputType;
36 import android.text.TextWatcher;
37 import android.util.Log;
38 import android.util.TypedValue;
39 import android.view.Gravity;
40 import android.view.Menu;
41 import android.view.MenuItem;
42 import android.view.MotionEvent;
43 import android.view.View;
44 import android.view.inputmethod.EditorInfo;
45 import android.widget.AutoCompleteTextView;
46 import android.widget.EditText;
47 import android.widget.FilterQueryProvider;
48 import android.widget.ProgressBar;
49 import android.widget.SimpleCursorAdapter;
50 import android.widget.TableLayout;
51 import android.widget.TableRow;
52 import android.widget.TextView;
54 import net.ktnx.mobileledger.async.SaveTransactionTask;
55 import net.ktnx.mobileledger.async.TaskCallback;
56 import net.ktnx.mobileledger.model.LedgerTransaction;
57 import net.ktnx.mobileledger.model.LedgerTransactionItem;
58 import net.ktnx.mobileledger.ui.DatePickerFragment;
59 import net.ktnx.mobileledger.utils.MobileLedgerDatabase;
61 import java.util.Date;
62 import java.util.Objects;
65 * TODO: nicer progress while transaction is submitted
66 * TODO: latest transactions, maybe with browsing further in the past?
68 * TODO: get rid of the custom session/cookie and auth code?
69 * (the last problem with the POST was the missing content-length header)
71 * TODO: nicer swiping removal with visual feedback
73 * TODO: update accounts/check settings upon change of backend settings
76 public class NewTransactionActivity extends AppCompatActivity implements TaskCallback {
77 private TableLayout table;
78 private ProgressBar progress;
79 private TextView text_date;
80 private AutoCompleteTextView text_descr;
81 private static SaveTransactionTask saver;
82 private MenuItem mSave;
83 private MobileLedgerDatabase dbh;
86 protected void onCreate(Bundle savedInstanceState) {
87 super.onCreate(savedInstanceState);
88 setContentView(R.layout.activity_new_transaction);
89 Toolbar toolbar = findViewById(R.id.toolbar);
90 setSupportActionBar(toolbar);
92 dbh = new MobileLedgerDatabase(this);
94 text_date = findViewById(R.id.new_transaction_date);
95 text_date.setOnFocusChangeListener(new View.OnFocusChangeListener() {
98 void onFocusChange(View v, boolean hasFocus) {
99 if (hasFocus) pickTransactionDate(v);
102 text_descr = findViewById(R.id.new_transaction_description);
103 hook_autocompletion_adapter(text_descr, MobileLedgerDatabase
104 .DESCRIPTION_HISTORY_TABLE, "description");
105 hook_text_change_listener(text_descr);
107 progress = findViewById(R.id.save_transaction_progress);
109 Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
110 table = findViewById(R.id.new_transaction_accounts_table);
111 for (int i = 0; i < table.getChildCount(); i++) {
112 TableRow row = (TableRow) table.getChildAt(i);
113 AutoCompleteTextView acc_name_view = (AutoCompleteTextView) row.getChildAt(0);
114 TextView amount_view = (TextView) row.getChildAt(1);
115 hook_swipe_listener(row);
116 hook_autocompletion_adapter(acc_name_view, MobileLedgerDatabase.ACCOUNTS_TABLE, "name");
117 hook_text_change_listener(acc_name_view);
118 hook_text_change_listener(amount_view);
119 // Log.d("swipe", "hooked to row "+i);
127 if (text_descr.getText().toString().isEmpty()) text_descr.requestFocus();
131 public void finish() {
133 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
137 public boolean onOptionsItemSelected(MenuItem item) {
138 switch (item.getItemId()) {
139 case android.R.id.home:
143 return super.onOptionsItemSelected(item);
146 public void save_transaction() {
147 if (mSave != null) mSave.setVisible(false);
148 toggle_all_editing(false);
149 progress.setVisibility(View.VISIBLE);
151 saver = new SaveTransactionTask(this);
153 saver.setPref(PreferenceManager.getDefaultSharedPreferences(this));
154 String date = text_date.getText().toString();
155 if (date.isEmpty()) date = String.valueOf(new Date().getDate());
156 LedgerTransaction tr = new LedgerTransaction(date, text_descr.getText().toString());
158 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
159 for ( int i = 0; i < table.getChildCount(); i++ ) {
160 TableRow row = (TableRow) table.getChildAt(i);
161 String acc = ((TextView) row.getChildAt(0)).getText().toString();
162 String amt = ((TextView) row.getChildAt(1)).getText().toString();
163 LedgerTransactionItem item =
165 ? new LedgerTransactionItem( acc, Float.parseFloat(amt))
166 : new LedgerTransactionItem( acc );
173 private void toggle_all_editing(boolean enabled) {
174 text_date.setEnabled(enabled);
175 text_descr.setEnabled(enabled);
176 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
177 for (int i = 0; i < table.getChildCount(); i++) {
178 TableRow row = (TableRow) table.getChildAt(i);
179 for (int j = 0; j < row.getChildCount(); j++) {
180 row.getChildAt(j).setEnabled(enabled);
185 private void hook_swipe_listener(final TableRow row) {
186 row.getChildAt(0).setOnTouchListener(new OnSwipeTouchListener(this) {
187 public void onSwipeLeft() {
188 // Log.d("swipe", "LEFT" + row.getId());
189 if (table.getChildCount() > 2) {
190 TableRow prev_row = (TableRow) table.getChildAt(table.indexOfChild(row) - 1);
191 TableRow next_row = (TableRow) table.getChildAt(table.indexOfChild(row) + 1);
193 (prev_row != null) ? (TextView) prev_row.getChildAt(1) : text_descr;
195 (next_row != null) ? (TextView) next_row.getChildAt(0) : null;
197 if (next_acc == null) {
198 prev_amt.setNextFocusRightId(R.id.none);
199 prev_amt.setNextFocusForwardId(R.id.none);
200 prev_amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
203 prev_amt.setNextFocusRightId(next_acc.getId());
204 prev_amt.setNextFocusForwardId(next_acc.getId());
205 prev_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
208 if (row.hasFocus()) {
209 if (next_acc != null) next_acc.requestFocus();
210 else prev_amt.requestFocus();
213 table.removeView(row);
214 check_transaction_submittable();
215 // Toast.makeText(NewTransactionActivity.this, "LEFT", Toast.LENGTH_LONG).show();
218 Snackbar.make(table, R.string.msg_at_least_two_accounts_are_required, Snackbar.LENGTH_LONG)
219 .setAction("Action", null).show();
223 // public boolean performClick(View view, MotionEvent m) {
226 public boolean onTouch(View view, MotionEvent m) {
227 return gestureDetector.onTouchEvent(m);
232 private void hook_text_change_listener(final TextView view) {
233 view.addTextChangedListener(new TextWatcher() {
235 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
240 public void onTextChanged(CharSequence s, int start, int before, int count) {
245 public void afterTextChanged(Editable s) {
246 // Log.d("input", "text changed");
247 check_transaction_submittable();
253 @TargetApi(Build.VERSION_CODES.N)
254 private void hook_autocompletion_adapter(final AutoCompleteTextView view, final String table, final String field) {
255 String[] from = {field};
256 int[] to = {android.R.id.text1};
257 SimpleCursorAdapter adapter =
258 new SimpleCursorAdapter(this, android.R.layout.simple_dropdown_item_1line, null,
260 adapter.setStringConversionColumn(1);
262 FilterQueryProvider provider = new FilterQueryProvider() {
265 Cursor runQuery(CharSequence constraint) {
266 if (constraint == null) return null;
268 String str = constraint.toString().toUpperCase();
269 Log.d("autocompletion", "Looking for " + str);
270 String[] col_names = {FontsContract.Columns._ID, field};
271 MatrixCursor c = new MatrixCursor(col_names);
273 try (SQLiteDatabase db = dbh.getReadableDatabase()) {
275 try (Cursor matches = db.rawQuery(String.format(
276 "SELECT %s as a, case when %s_upper LIKE ?||'%%' then 1 "
277 + "WHEN %s_upper LIKE '%%:'||?||'%%' then 2 "
278 + "WHEN %s_upper LIKE '%% '||?||'%%' then 3 " + "else 9 end "
279 + "FROM %s " + "WHERE %s_upper LIKE '%%'||?||'%%' "
280 + "ORDER BY 2, 1;", field, field, field, field, table, field),
281 new String[]{str, str, str, str}))
284 while (matches.moveToNext()) {
285 String match = matches.getString(0);
286 int order = matches.getInt(1);
287 Log.d("autocompletion", String.format("match: %s |%d", match, order));
288 c.newRow().add(i++).add(match);
298 adapter.setFilterQueryProvider(provider);
300 view.setAdapter(adapter);
303 public boolean onCreateOptionsMenu(Menu menu) {
304 // Inflate the menu; this adds items to the action bar if it is present.
305 getMenuInflater().inflate(R.menu.new_transaction, menu);
306 mSave = menu.findItem(R.id.action_submit_transaction);
307 if (mSave == null) throw new AssertionError();
309 check_transaction_submittable();
314 public void pickTransactionDate(View view) {
315 DialogFragment picker = new DatePickerFragment();
316 picker.show(getSupportFragmentManager(), "datePicker");
319 public int dp2px(float dp) {
320 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()));
323 private void do_add_account_row(boolean focus) {
324 final AutoCompleteTextView acc = new AutoCompleteTextView(this);
325 acc.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 9f));
326 acc.setHint(R.string.new_transaction_account_hint);
328 acc.setImeOptions(EditorInfo.IME_ACTION_NEXT | EditorInfo.IME_FLAG_NO_ENTER_ACTION
329 | EditorInfo.IME_FLAG_NAVIGATE_NEXT);
330 acc.setSingleLine(true);
332 final EditText amt = new EditText(this);
333 amt.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
334 TableRow.LayoutParams.MATCH_PARENT, 1f));
335 amt.setHint(R.string.new_transaction_amount_hint);
337 amt.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED | InputType.TYPE_NUMBER_FLAG_DECIMAL );
338 amt.setMinWidth(dp2px(40));
339 amt.setTextAlignment(EditText.TEXT_ALIGNMENT_VIEW_END);
340 amt.setImeOptions(EditorInfo.IME_ACTION_DONE);
342 // forward navigation support
343 final TableRow last_row = (TableRow) table.getChildAt(table.getChildCount() - 1);
344 final TextView last_amt = (TextView) last_row.getChildAt(1);
345 last_amt.setNextFocusForwardId(acc.getId());
346 last_amt.setNextFocusRightId(acc.getId());
347 last_amt.setImeOptions(EditorInfo.IME_ACTION_NEXT);
348 acc.setNextFocusForwardId(amt.getId());
349 acc.setNextFocusRightId(amt.getId());
351 final TableRow row = new TableRow(this);
352 row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
353 row.setGravity(Gravity.BOTTOM);
358 if (focus) acc.requestFocus();
360 hook_swipe_listener(row);
361 hook_autocompletion_adapter(acc, MobileLedgerDatabase.ACCOUNTS_TABLE, "name");
362 hook_text_change_listener(acc);
363 hook_text_change_listener(amt);
366 public void addTransactionAccountFromMenu(MenuItem item) {
367 do_add_account_row(true);
371 void resetTransactionFromMenu(MenuItem item) {
375 public void saveTransactionFromMenu(MenuItem item) {
380 boolean is_zero(float f) {
381 return (f < 0.005) && (f > -0.005);
385 // 1) at least two account names
386 // 2) each amount must have account name
387 // 3) amounts must balance to 0, or
388 // 3a) there must be exactly one empty amount
389 // 4) empty accounts with empty amounts are ignored
390 // 5) a row with an empty account name or empty amount is guaranteed to exist
391 @SuppressLint("DefaultLocale")
392 private void check_transaction_submittable() {
393 TableLayout table = findViewById(R.id.new_transaction_accounts_table);
395 int accounts_with_values = 0;
397 int amounts_with_accounts = 0;
399 TextView empty_amount = null;
400 boolean single_empty_amount = false;
401 boolean single_empty_amount_has_account = false;
402 float running_total = 0f;
403 boolean have_description =
404 !((TextView) findViewById(R.id.new_transaction_description)).getText().toString()
408 for (int i = 0; i < table.getChildCount(); i++) {
409 TableRow row = (TableRow) table.getChildAt(i);
411 TextView acc_name_v = (TextView) row.getChildAt(0);
412 TextView amount_v = (TextView) row.getChildAt(1);
413 String amt = String.valueOf(amount_v.getText());
414 String acc_name = String.valueOf(acc_name_v.getText());
415 acc_name = acc_name.trim();
417 if (!acc_name.isEmpty()) {
420 if (!amt.isEmpty()) {
421 accounts_with_values++;
427 amount_v.setHint(String.format("%1.2f", 0f));
428 if (empty_amount == null) {
429 empty_amount = amount_v;
430 single_empty_amount = true;
431 single_empty_amount_has_account = !acc_name.isEmpty();
433 else if (!acc_name.isEmpty()) single_empty_amount = false;
437 if (!acc_name.isEmpty()) amounts_with_accounts++;
438 running_total += Float.valueOf(amt);
442 if ((empty_rows == 0) && ((table.getChildCount() == accounts) || (table.getChildCount()
445 do_add_account_row(false);
448 Log.d("submittable", String.format("accounts=%d, accounts_with_values=%s, "
449 + "amounts_with_accounts=%d, amounts=%d, running_total=%1.2f, "
450 + "single_empty_with_acc=%s", accounts, accounts_with_values,
451 amounts_with_accounts, amounts, running_total,
452 (single_empty_amount && single_empty_amount_has_account) ? "true" : "false"));
454 if (have_description && (accounts >= 2) && (accounts_with_values >= (accounts - 1)) && (
455 amounts_with_accounts == amounts) && (
456 single_empty_amount && single_empty_amount_has_account || is_zero(
459 if (mSave != null) mSave.setVisible(true);
461 else if (mSave != null) mSave.setVisible(false);
463 if (single_empty_amount) {
465 .setHint(String.format("%1.2f", (running_total > 0) ? -running_total : 0f));
469 catch (NumberFormatException e) {
470 if (mSave != null) mSave.setVisible(false);
472 catch (Exception e) {
474 if (mSave != null) mSave.setVisible(false);
480 void done(String error) {
481 progress.setVisibility(View.INVISIBLE);
482 Log.d("visuals", "hiding progress");
484 if (error == null) reset_form();
485 else Snackbar.make(findViewById(R.id.new_transaction_accounts_table), error,
486 BaseTransientBottomBar.LENGTH_LONG).show();
488 toggle_all_editing(true);
489 check_transaction_submittable();
492 private void reset_form() {
493 text_date.setText("");
494 text_descr.setText("");
496 text_descr.requestFocus();
498 while(table.getChildCount() > 2) {
499 table.removeViewAt(2);
501 for( int i = 0; i < 2; i++ ) {
502 TableRow tr = (TableRow) table.getChildAt(i);
503 if ( tr == null) break;
505 ((TextView)tr.getChildAt(0)).setText("");
506 ((TextView)tr.getChildAt(1)).setText("");