2 * Copyright © 2019 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe 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 * MoLe 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 MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.ui.activity;
20 import android.os.AsyncTask;
21 import android.os.Bundle;
22 import android.util.TypedValue;
23 import android.view.Menu;
24 import android.view.MenuItem;
25 import android.view.View;
26 import android.widget.ProgressBar;
28 import androidx.annotation.NonNull;
29 import androidx.appcompat.widget.Toolbar;
30 import androidx.lifecycle.Observer;
31 import androidx.lifecycle.ViewModelProviders;
32 import androidx.recyclerview.widget.ItemTouchHelper;
33 import androidx.recyclerview.widget.LinearLayoutManager;
34 import androidx.recyclerview.widget.RecyclerView;
36 import com.google.android.material.floatingactionbutton.FloatingActionButton;
37 import com.google.android.material.snackbar.BaseTransientBottomBar;
38 import com.google.android.material.snackbar.Snackbar;
40 import net.ktnx.mobileledger.BuildConfig;
41 import net.ktnx.mobileledger.R;
42 import net.ktnx.mobileledger.async.SendTransactionTask;
43 import net.ktnx.mobileledger.async.TaskCallback;
44 import net.ktnx.mobileledger.model.Data;
45 import net.ktnx.mobileledger.model.LedgerTransaction;
46 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
48 import java.util.Date;
49 import java.util.Objects;
51 import static net.ktnx.mobileledger.utils.Logger.debug;
54 * TODO: nicer progress while transaction is submitted
56 * TODO: get rid of the custom session/cookie and auth code?
57 * (the last problem with the POST was the missing content-length header)
60 public class NewTransactionActivity extends ProfileThemedActivity implements TaskCallback {
61 private static SendTransactionTask saver;
62 private ProgressBar progress;
63 private FloatingActionButton fab;
64 private NewTransactionItemsAdapter listAdapter;
65 private NewTransactionModel viewModel;
66 private RecyclerView list;
68 protected void onCreate(Bundle savedInstanceState) {
69 super.onCreate(savedInstanceState);
71 setContentView(R.layout.activity_new_transaction);
72 Toolbar toolbar = findViewById(R.id.toolbar);
73 setSupportActionBar(toolbar);
74 Data.profile.observe(this,
75 mobileLedgerProfile -> toolbar.setSubtitle(mobileLedgerProfile.getName()));
77 progress = findViewById(R.id.save_transaction_progress);
78 fab = findViewById(R.id.fab);
79 fab.setOnClickListener(v -> saveTransaction());
81 Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
82 list = findViewById(R.id.new_transaction_accounts);
83 viewModel = ViewModelProviders.of(this).get(NewTransactionModel.class);
84 listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
85 list.setAdapter(listAdapter);
86 list.setLayoutManager(new LinearLayoutManager(this));
87 Data.profile.observe(this, profile -> listAdapter.setProfile(profile));
88 listAdapter.notifyDataSetChanged();
89 new ItemTouchHelper(new ItemTouchHelper.Callback() {
91 public int getMovementFlags(@NonNull RecyclerView recyclerView,
92 @NonNull RecyclerView.ViewHolder viewHolder) {
93 int flags = makeFlag(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.END);
94 // the top item is always there (date and description)
95 if (viewHolder.getAdapterPosition() > 0) {
96 if (viewModel.getAccountCount() > 2) {
97 flags |= makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE,
98 ItemTouchHelper.START | ItemTouchHelper.END);
105 public boolean onMove(@NonNull RecyclerView recyclerView,
106 @NonNull RecyclerView.ViewHolder viewHolder,
107 @NonNull RecyclerView.ViewHolder target) {
111 public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
112 if (viewModel.getAccountCount() == 2)
113 Snackbar.make(list, R.string.msg_at_least_two_accounts_are_required,
114 Snackbar.LENGTH_LONG).setAction("Action", null).show();
116 int pos = viewHolder.getAdapterPosition();
117 viewModel.removeItem(pos - 1);
118 listAdapter.notifyItemRemoved(pos);
119 viewModel.sendCountNotifications(); // needed after items re-arrangement
120 viewModel.checkTransactionSubmittable(listAdapter);
123 }).attachToRecyclerView(list);
125 viewModel.isSubmittable().observe(this, new Observer<Boolean>() {
127 public void onChanged(Boolean isSubmittable) {
131 fab.setEnabled(true);
141 viewModel.checkTransactionSubmittable(listAdapter);
144 protected void initProfile() {
145 String profileUUID = getIntent().getStringExtra("profile_uuid");
147 if (profileUUID != null) {
148 mProfile = Data.getProfile(profileUUID);
149 if (mProfile == null) finish();
150 Data.setCurrentProfile(mProfile);
152 else super.initProfile();
155 public void finish() {
157 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
160 public boolean onOptionsItemSelected(MenuItem item) {
161 switch (item.getItemId()) {
162 case android.R.id.home:
166 return super.onOptionsItemSelected(item);
169 protected void onStart() {
171 // FIXME if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
173 public void saveTransaction() {
174 if (fab != null) fab.setEnabled(false);
175 listAdapter.toggleAllEditing(false);
176 progress.setVisibility(View.VISIBLE);
179 saver = new SendTransactionTask(this, mProfile);
181 Date date = viewModel.getDate();
182 LedgerTransaction tr =
183 new LedgerTransaction(null, date, viewModel.getDescription(),
186 LedgerTransactionAccount emptyAmountAccount = null;
187 float emptyAmountAccountBalance = 0;
188 for (int i = 0; i < viewModel.getAccountCount(); i++) {
189 LedgerTransactionAccount acc = viewModel.getAccount(i);
190 if (acc.getAccountName().trim().isEmpty()) continue;
192 if (acc.isAmountSet()) {
193 emptyAmountAccountBalance += acc.getAmount();
196 emptyAmountAccount = acc;
202 if (emptyAmountAccount != null)
203 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
206 catch (Exception e) {
207 debug("new-transaction", "Unknown error", e);
209 progress.setVisibility(View.GONE);
210 listAdapter.toggleAllEditing(true);
211 if (fab != null) fab.setEnabled(true);
214 public void simulateCrash(MenuItem item) {
215 debug("crash", "Will crash intentionally");
216 new AsyncCrasher().execute();
218 public boolean onCreateOptionsMenu(Menu menu) {
219 // Inflate the menu; this adds items to the action bar if it is present.
220 getMenuInflater().inflate(R.menu.new_transaction, menu);
222 if (BuildConfig.DEBUG) {
223 menu.findItem(R.id.action_simulate_crash).setVisible(true);
230 public int dp2px(float dp) {
231 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
232 getResources().getDisplayMetrics()));
234 public void resetTransactionFromMenu(MenuItem item) {
238 public void done(String error) {
239 progress.setVisibility(View.INVISIBLE);
240 debug("visuals", "hiding progress");
242 if (error == null) resetForm();
243 else Snackbar.make(list, error, BaseTransientBottomBar.LENGTH_LONG).show();
245 listAdapter.toggleAllEditing(true);
246 viewModel.checkTransactionSubmittable(listAdapter);
249 private void resetForm() {
252 private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
254 protected Void doInBackground(Void... voids) {
255 throw new RuntimeException("Simulated crash");