]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionActivity.java
90ce60b174bc6c10a2cf70e8d9ca6178c9fa60df
[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.ViewModelProviders;
31 import androidx.recyclerview.widget.ItemTouchHelper;
32 import androidx.recyclerview.widget.LinearLayoutManager;
33 import androidx.recyclerview.widget.RecyclerView;
34
35 import com.google.android.material.floatingactionbutton.FloatingActionButton;
36 import com.google.android.material.snackbar.BaseTransientBottomBar;
37 import com.google.android.material.snackbar.Snackbar;
38
39 import net.ktnx.mobileledger.BuildConfig;
40 import net.ktnx.mobileledger.R;
41 import net.ktnx.mobileledger.async.SendTransactionTask;
42 import net.ktnx.mobileledger.async.TaskCallback;
43 import net.ktnx.mobileledger.model.Data;
44 import net.ktnx.mobileledger.model.LedgerTransaction;
45 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
46
47 import java.util.Date;
48 import java.util.Objects;
49
50 import static net.ktnx.mobileledger.utils.Logger.debug;
51
52 /*
53  * TODO: nicer progress while transaction is submitted
54  * TODO: reports
55  * TODO: get rid of the custom session/cookie and auth code?
56  *         (the last problem with the POST was the missing content-length header)
57  *  */
58
59 public class NewTransactionActivity extends ProfileThemedActivity implements TaskCallback {
60     private static SendTransactionTask saver;
61     private ProgressBar progress;
62     private FloatingActionButton fab;
63     private NewTransactionItemsAdapter listAdapter;
64     private NewTransactionModel viewModel;
65     private RecyclerView list;
66     @Override
67     protected void onCreate(Bundle savedInstanceState) {
68         super.onCreate(savedInstanceState);
69
70         setContentView(R.layout.activity_new_transaction);
71         Toolbar toolbar = findViewById(R.id.toolbar);
72         setSupportActionBar(toolbar);
73         Data.profile.observe(this,
74                 mobileLedgerProfile -> toolbar.setSubtitle(mobileLedgerProfile.getName()));
75
76         progress = findViewById(R.id.save_transaction_progress);
77         fab = findViewById(R.id.fab);
78         fab.setOnClickListener(v -> saveTransaction());
79
80         Objects.requireNonNull(getSupportActionBar())
81                .setDisplayHomeAsUpEnabled(true);
82         list = findViewById(R.id.new_transaction_accounts);
83         viewModel = ViewModelProviders.of(this)
84                                       .get(NewTransactionModel.class);
85         listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
86         list.setAdapter(listAdapter);
87         list.setLayoutManager(new LinearLayoutManager(this));
88         Data.profile.observe(this, profile -> listAdapter.setProfile(profile));
89         listAdapter.notifyDataSetChanged();
90         new ItemTouchHelper(new ItemTouchHelper.Callback() {
91             @Override
92             public int getMovementFlags(@NonNull RecyclerView recyclerView,
93                                         @NonNull RecyclerView.ViewHolder viewHolder) {
94                 int flags = makeFlag(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.END);
95                 // the top item is always there (date and description)
96                 if (viewHolder.getAdapterPosition() > 0) {
97                     if (viewModel.getAccountCount() > 2) {
98                         flags |= makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE,
99                                 ItemTouchHelper.START | ItemTouchHelper.END);
100                     }
101                 }
102
103                 return flags;
104             }
105             @Override
106             public boolean onMove(@NonNull RecyclerView recyclerView,
107                                   @NonNull RecyclerView.ViewHolder viewHolder,
108                                   @NonNull RecyclerView.ViewHolder target) {
109                 return false;
110             }
111             @Override
112             public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
113                 if (viewModel.getAccountCount() == 2)
114                     Snackbar.make(list, R.string.msg_at_least_two_accounts_are_required,
115                             Snackbar.LENGTH_LONG)
116                             .setAction("Action", null)
117                             .show();
118                 else {
119                     int pos = viewHolder.getAdapterPosition();
120                     viewModel.removeItem(pos - 1);
121                     listAdapter.notifyItemRemoved(pos);
122                     viewModel.sendCountNotifications(); // needed after items re-arrangement
123                     viewModel.checkTransactionSubmittable(listAdapter);
124                 }
125             }
126         }).attachToRecyclerView(list);
127
128         viewModel.isSubmittable()
129                  .observe(this, isSubmittable -> {
130                      if (isSubmittable) {
131                          if (fab != null) {
132                              fab.show();
133                              fab.setEnabled(true);
134                          }
135                      }
136                      else {
137                          if (fab != null) {
138                              fab.hide();
139                          }
140                      }
141                  });
142         viewModel.checkTransactionSubmittable(listAdapter);
143     }
144     @Override
145     protected void initProfile() {
146         String profileUUID = getIntent().getStringExtra("profile_uuid");
147
148         if (profileUUID != null) {
149             mProfile = Data.getProfile(profileUUID);
150             if (mProfile == null)
151                 finish();
152             Data.setCurrentProfile(mProfile);
153         }
154         else
155             super.initProfile();
156     }
157     @Override
158     public void finish() {
159         super.finish();
160         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
161     }
162     @Override
163     public boolean onOptionsItemSelected(MenuItem item) {
164         switch (item.getItemId()) {
165             case android.R.id.home:
166                 finish();
167                 return true;
168         }
169         return super.onOptionsItemSelected(item);
170     }
171     @Override
172     protected void onStart() {
173         super.onStart();
174         // FIXME if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
175     }
176     public void saveTransaction() {
177         if (fab != null)
178             fab.setEnabled(false);
179         listAdapter.toggleAllEditing(false);
180         progress.setVisibility(View.VISIBLE);
181         try {
182
183             saver = new SendTransactionTask(this, mProfile);
184
185             Date date = viewModel.getDate();
186             LedgerTransaction tr =
187                     new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
188
189             LedgerTransactionAccount emptyAmountAccount = null;
190             float emptyAmountAccountBalance = 0;
191             for (int i = 0; i < viewModel.getAccountCount(); i++) {
192                 LedgerTransactionAccount acc = viewModel.getAccount(i);
193                 if (acc.getAccountName()
194                        .trim()
195                        .isEmpty())
196                     continue;
197
198                 if (acc.isAmountSet()) {
199                     emptyAmountAccountBalance += acc.getAmount();
200                 }
201                 else {
202                     emptyAmountAccount = acc;
203                 }
204
205                 tr.addAccount(acc);
206             }
207
208             if (emptyAmountAccount != null)
209                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
210             saver.execute(tr);
211         }
212         catch (Exception e) {
213             debug("new-transaction", "Unknown error", e);
214
215             progress.setVisibility(View.GONE);
216             listAdapter.toggleAllEditing(true);
217             if (fab != null)
218                 fab.setEnabled(true);
219         }
220     }
221     public void simulateCrash(MenuItem item) {
222         debug("crash", "Will crash intentionally");
223         new AsyncCrasher().execute();
224     }
225     public boolean onCreateOptionsMenu(Menu menu) {
226         // Inflate the menu; this adds items to the action bar if it is present.
227         getMenuInflater().inflate(R.menu.new_transaction, menu);
228
229         if (BuildConfig.DEBUG) {
230             menu.findItem(R.id.action_simulate_crash)
231                 .setVisible(true);
232         }
233
234         return true;
235     }
236
237
238     public int dp2px(float dp) {
239         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
240                 getResources().getDisplayMetrics()));
241     }
242     public void resetTransactionFromMenu(MenuItem item) {
243         listAdapter.reset();
244     }
245     @Override
246     public void done(String error) {
247         progress.setVisibility(View.INVISIBLE);
248         debug("visuals", "hiding progress");
249
250         if (error == null)
251             listAdapter.reset();
252         else
253             Snackbar.make(list, error, BaseTransientBottomBar.LENGTH_LONG)
254                     .show();
255
256         listAdapter.toggleAllEditing(true);
257
258         viewModel.checkTransactionSubmittable(listAdapter);
259     }
260
261     private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
262         @Override
263         protected Void doInBackground(Void... voids) {
264             throw new RuntimeException("Simulated crash");
265         }
266     }
267
268 }