]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionActivity.java
6a6fb4194c5139e0e0187abee725e8fc3d09469d
[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())
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() {
92             @Override
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);
101                     }
102                 }
103
104                 return flags;
105             }
106             @Override
107             public boolean onMove(@NonNull RecyclerView recyclerView,
108                                   @NonNull RecyclerView.ViewHolder viewHolder,
109                                   @NonNull RecyclerView.ViewHolder target) {
110                 return false;
111             }
112             @Override
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)
118                             .show();
119                 else {
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);
125                 }
126             }
127         }).attachToRecyclerView(list);
128
129         viewModel.isSubmittable()
130                  .observe(this, new Observer<Boolean>() {
131                      @Override
132                      public void onChanged(Boolean isSubmittable) {
133                          if (isSubmittable) {
134                              if (fab != null) {
135                                  fab.show();
136                                  fab.setEnabled(true);
137                              }
138                          }
139                          else {
140                              if (fab != null) {
141                                  fab.hide();
142                              }
143                          }
144                      }
145                  });
146         viewModel.checkTransactionSubmittable(listAdapter);
147     }
148     @Override
149     protected void initProfile() {
150         String profileUUID = getIntent().getStringExtra("profile_uuid");
151
152         if (profileUUID != null) {
153             mProfile = Data.getProfile(profileUUID);
154             if (mProfile == null) finish();
155             Data.setCurrentProfile(mProfile);
156         }
157         else super.initProfile();
158     }
159     @Override
160     public void finish() {
161         super.finish();
162         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
163     }
164     @Override
165     public boolean onOptionsItemSelected(MenuItem item) {
166         switch (item.getItemId()) {
167             case android.R.id.home:
168                 finish();
169                 return true;
170         }
171         return super.onOptionsItemSelected(item);
172     }
173     @Override
174     protected void onStart() {
175         super.onStart();
176         // FIXME if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
177     }
178     public void saveTransaction() {
179         if (fab != null) fab.setEnabled(false);
180         listAdapter.toggleAllEditing(false);
181         progress.setVisibility(View.VISIBLE);
182         try {
183
184             saver = new SendTransactionTask(this, mProfile);
185
186             Date date = viewModel.getDate();
187             LedgerTransaction tr =
188                     new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
189
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()
195                        .trim()
196                        .isEmpty()) 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) fab.setEnabled(true);
218         }
219     }
220     public void simulateCrash(MenuItem item) {
221         debug("crash", "Will crash intentionally");
222         new AsyncCrasher().execute();
223     }
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);
227
228         if (BuildConfig.DEBUG) {
229             menu.findItem(R.id.action_simulate_crash)
230                 .setVisible(true);
231         }
232
233         return true;
234     }
235
236
237     public int dp2px(float dp) {
238         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
239                 getResources().getDisplayMetrics()));
240     }
241     public void resetTransactionFromMenu(MenuItem item) {
242         resetForm();
243     }
244     @Override
245     public void done(String error) {
246         progress.setVisibility(View.INVISIBLE);
247         debug("visuals", "hiding progress");
248
249         if (error == null) resetForm();
250         else Snackbar.make(list, error, BaseTransientBottomBar.LENGTH_LONG)
251                      .show();
252
253         listAdapter.toggleAllEditing(true);
254         viewModel.checkTransactionSubmittable(listAdapter);
255     }
256
257     private void resetForm() {
258         listAdapter.reset();
259     }
260     private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
261         @Override
262         protected Void doInBackground(Void... voids) {
263             throw new RuntimeException("Simulated crash");
264         }
265     }
266
267 }