]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionActivity.java
4e6ee19274a795d07100e6ead83c991579d87753
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionActivity.java
1 /*
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.
8  *
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.
13  *
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/>.
16  */
17
18 package net.ktnx.mobileledger.ui.activity;
19
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;
27
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;
35
36 import com.google.android.material.floatingactionbutton.FloatingActionButton;
37 import com.google.android.material.snackbar.BaseTransientBottomBar;
38 import com.google.android.material.snackbar.Snackbar;
39
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;
47
48 import java.util.Date;
49 import java.util.Objects;
50
51 import static net.ktnx.mobileledger.utils.Logger.debug;
52
53 /*
54  * TODO: nicer progress while transaction is submitted
55  * TODO: reports
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)
58  *  */
59
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;
67     @Override
68     protected void onCreate(Bundle savedInstanceState) {
69         super.onCreate(savedInstanceState);
70
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()));
76
77         progress = findViewById(R.id.save_transaction_progress);
78         fab = findViewById(R.id.fab);
79         fab.setOnClickListener(v -> saveTransaction());
80
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() {
90             @Override
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);
99                     }
100                 }
101
102                 return flags;
103             }
104             @Override
105             public boolean onMove(@NonNull RecyclerView recyclerView,
106                                   @NonNull RecyclerView.ViewHolder viewHolder,
107                                   @NonNull RecyclerView.ViewHolder target) {
108                 return false;
109             }
110             @Override
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();
115                 else {
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);
121                 }
122             }
123         }).attachToRecyclerView(list);
124
125         viewModel.isSubmittable().observe(this, new Observer<Boolean>() {
126             @Override
127             public void onChanged(Boolean isSubmittable) {
128                 if (isSubmittable) {
129                     if (fab != null) {
130                         fab.show();
131                         fab.setEnabled(true);
132                     }
133                 }
134                 else {
135                     if (fab != null) {
136                         fab.hide();
137                     }
138                 }
139             }
140         });
141         viewModel.checkTransactionSubmittable(listAdapter);
142     }
143     @Override
144     protected void initProfile() {
145         String profileUUID = getIntent().getStringExtra("profile_uuid");
146
147         if (profileUUID != null) {
148             mProfile = Data.getProfile(profileUUID);
149             if (mProfile == null) finish();
150             Data.setCurrentProfile(mProfile);
151         }
152         else super.initProfile();
153     }
154     @Override
155     public void finish() {
156         super.finish();
157         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
158     }
159     @Override
160     public boolean onOptionsItemSelected(MenuItem item) {
161         switch (item.getItemId()) {
162             case android.R.id.home:
163                 finish();
164                 return true;
165         }
166         return super.onOptionsItemSelected(item);
167     }
168     @Override
169     protected void onStart() {
170         super.onStart();
171         // FIXME if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
172     }
173     public void saveTransaction() {
174         if (fab != null) fab.setEnabled(false);
175         listAdapter.toggleAllEditing(false);
176         progress.setVisibility(View.VISIBLE);
177         try {
178
179             saver = new SendTransactionTask(this, mProfile);
180
181             Date date = viewModel.getDate();
182             LedgerTransaction tr =
183                     new LedgerTransaction(null, date, viewModel.getDescription(),
184                             mProfile);
185
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;
191
192                 if (acc.isAmountSet()) {
193                     emptyAmountAccountBalance += acc.getAmount();
194                 }
195                 else {
196                     emptyAmountAccount = acc;
197                 }
198
199                 tr.addAccount(acc);
200             }
201
202             if (emptyAmountAccount != null)
203                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
204             saver.execute(tr);
205         }
206         catch (Exception e) {
207             debug("new-transaction", "Unknown error", e);
208
209             progress.setVisibility(View.GONE);
210             listAdapter.toggleAllEditing(true);
211             if (fab != null) fab.setEnabled(true);
212         }
213     }
214     public void simulateCrash(MenuItem item) {
215         debug("crash", "Will crash intentionally");
216         new AsyncCrasher().execute();
217     }
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);
221
222         if (BuildConfig.DEBUG) {
223             menu.findItem(R.id.action_simulate_crash).setVisible(true);
224         }
225
226         return true;
227     }
228
229
230     public int dp2px(float dp) {
231         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
232                 getResources().getDisplayMetrics()));
233     }
234     public void resetTransactionFromMenu(MenuItem item) {
235         resetForm();
236     }
237     @Override
238     public void done(String error) {
239         progress.setVisibility(View.INVISIBLE);
240         debug("visuals", "hiding progress");
241
242         if (error == null) resetForm();
243         else Snackbar.make(list, error, BaseTransientBottomBar.LENGTH_LONG).show();
244
245         listAdapter.toggleAllEditing(true);
246         viewModel.checkTransactionSubmittable(listAdapter);
247     }
248
249     private void resetForm() {
250         listAdapter.reset();
251     }
252     private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
253         @Override
254         protected Void doInBackground(Void... voids) {
255             throw new RuntimeException("Simulated crash");
256         }
257     }
258
259 }