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())
82 .setDisplayHomeAsUpEnabled(true);
83 list = findViewById(R.id.new_transaction_accounts);
84 viewModel = ViewModelProviders.of(this)
85 .get(NewTransactionModel.class);
86 listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
87 list.setAdapter(listAdapter);
88 list.setLayoutManager(new LinearLayoutManager(this));
89 Data.profile.observe(this, profile -> listAdapter.setProfile(profile));
90 listAdapter.notifyDataSetChanged();
91 new ItemTouchHelper(new ItemTouchHelper.Callback() {
93 public int getMovementFlags(@NonNull RecyclerView recyclerView,
94 @NonNull RecyclerView.ViewHolder viewHolder) {
95 int flags = makeFlag(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.END);
96 // the top item is always there (date and description)
97 if (viewHolder.getAdapterPosition() > 0) {
98 if (viewModel.getAccountCount() > 2) {
99 flags |= makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE,
100 ItemTouchHelper.START | ItemTouchHelper.END);
107 public boolean onMove(@NonNull RecyclerView recyclerView,
108 @NonNull RecyclerView.ViewHolder viewHolder,
109 @NonNull RecyclerView.ViewHolder target) {
113 public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
114 if (viewModel.getAccountCount() == 2)
115 Snackbar.make(list, R.string.msg_at_least_two_accounts_are_required,
116 Snackbar.LENGTH_LONG)
117 .setAction("Action", null)
120 int pos = viewHolder.getAdapterPosition();
121 viewModel.removeItem(pos - 1);
122 listAdapter.notifyItemRemoved(pos);
123 viewModel.sendCountNotifications(); // needed after items re-arrangement
124 viewModel.checkTransactionSubmittable(listAdapter);
127 }).attachToRecyclerView(list);
129 viewModel.isSubmittable()
130 .observe(this, new Observer<Boolean>() {
132 public void onChanged(Boolean isSubmittable) {
136 fab.setEnabled(true);
146 viewModel.checkTransactionSubmittable(listAdapter);
149 protected void initProfile() {
150 String profileUUID = getIntent().getStringExtra("profile_uuid");
152 if (profileUUID != null) {
153 mProfile = Data.getProfile(profileUUID);
154 if (mProfile == null) finish();
155 Data.setCurrentProfile(mProfile);
157 else super.initProfile();
160 public void finish() {
162 overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
165 public boolean onOptionsItemSelected(MenuItem item) {
166 switch (item.getItemId()) {
167 case android.R.id.home:
171 return super.onOptionsItemSelected(item);
174 protected void onStart() {
176 // FIXME if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
178 public void saveTransaction() {
179 if (fab != null) fab.setEnabled(false);
180 listAdapter.toggleAllEditing(false);
181 progress.setVisibility(View.VISIBLE);
184 saver = new SendTransactionTask(this, mProfile);
186 Date date = viewModel.getDate();
187 LedgerTransaction tr =
188 new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
190 LedgerTransactionAccount emptyAmountAccount = null;
191 float emptyAmountAccountBalance = 0;
192 for (int i = 0; i < viewModel.getAccountCount(); i++) {
193 LedgerTransactionAccount acc = viewModel.getAccount(i);
194 if (acc.getAccountName()
196 .isEmpty()) continue;
198 if (acc.isAmountSet()) {
199 emptyAmountAccountBalance += acc.getAmount();
202 emptyAmountAccount = acc;
208 if (emptyAmountAccount != null)
209 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
212 catch (Exception e) {
213 debug("new-transaction", "Unknown error", e);
215 progress.setVisibility(View.GONE);
216 listAdapter.toggleAllEditing(true);
217 if (fab != null) fab.setEnabled(true);
220 public void simulateCrash(MenuItem item) {
221 debug("crash", "Will crash intentionally");
222 new AsyncCrasher().execute();
224 public boolean onCreateOptionsMenu(Menu menu) {
225 // Inflate the menu; this adds items to the action bar if it is present.
226 getMenuInflater().inflate(R.menu.new_transaction, menu);
228 if (BuildConfig.DEBUG) {
229 menu.findItem(R.id.action_simulate_crash)
237 public int dp2px(float dp) {
238 return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
239 getResources().getDisplayMetrics()));
241 public void resetTransactionFromMenu(MenuItem item) {
245 public void done(String error) {
246 progress.setVisibility(View.INVISIBLE);
247 debug("visuals", "hiding progress");
251 else Snackbar.make(list, error, BaseTransientBottomBar.LENGTH_LONG)
254 listAdapter.toggleAllEditing(true);
255 viewModel.checkTransactionSubmittable(listAdapter);
258 private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
260 protected Void doInBackground(Void... voids) {
261 throw new RuntimeException("Simulated crash");