]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionActivity.java
whitespace
[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)
155                 finish();
156             Data.setCurrentProfile(mProfile);
157         }
158         else
159             super.initProfile();
160     }
161     @Override
162     public void finish() {
163         super.finish();
164         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
165     }
166     @Override
167     public boolean onOptionsItemSelected(MenuItem item) {
168         switch (item.getItemId()) {
169             case android.R.id.home:
170                 finish();
171                 return true;
172         }
173         return super.onOptionsItemSelected(item);
174     }
175     @Override
176     protected void onStart() {
177         super.onStart();
178         // FIXME if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
179     }
180     public void saveTransaction() {
181         if (fab != null)
182             fab.setEnabled(false);
183         listAdapter.toggleAllEditing(false);
184         progress.setVisibility(View.VISIBLE);
185         try {
186
187             saver = new SendTransactionTask(this, mProfile);
188
189             Date date = viewModel.getDate();
190             LedgerTransaction tr =
191                     new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
192
193             LedgerTransactionAccount emptyAmountAccount = null;
194             float emptyAmountAccountBalance = 0;
195             for (int i = 0; i < viewModel.getAccountCount(); i++) {
196                 LedgerTransactionAccount acc = viewModel.getAccount(i);
197                 if (acc.getAccountName()
198                        .trim()
199                        .isEmpty())
200                     continue;
201
202                 if (acc.isAmountSet()) {
203                     emptyAmountAccountBalance += acc.getAmount();
204                 }
205                 else {
206                     emptyAmountAccount = acc;
207                 }
208
209                 tr.addAccount(acc);
210             }
211
212             if (emptyAmountAccount != null)
213                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
214             saver.execute(tr);
215         }
216         catch (Exception e) {
217             debug("new-transaction", "Unknown error", e);
218
219             progress.setVisibility(View.GONE);
220             listAdapter.toggleAllEditing(true);
221             if (fab != null)
222                 fab.setEnabled(true);
223         }
224     }
225     public void simulateCrash(MenuItem item) {
226         debug("crash", "Will crash intentionally");
227         new AsyncCrasher().execute();
228     }
229     public boolean onCreateOptionsMenu(Menu menu) {
230         // Inflate the menu; this adds items to the action bar if it is present.
231         getMenuInflater().inflate(R.menu.new_transaction, menu);
232
233         if (BuildConfig.DEBUG) {
234             menu.findItem(R.id.action_simulate_crash)
235                 .setVisible(true);
236         }
237
238         return true;
239     }
240
241
242     public int dp2px(float dp) {
243         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
244                 getResources().getDisplayMetrics()));
245     }
246     public void resetTransactionFromMenu(MenuItem item) {
247         listAdapter.reset();
248     }
249     @Override
250     public void done(String error) {
251         progress.setVisibility(View.INVISIBLE);
252         debug("visuals", "hiding progress");
253
254         if (error == null)
255             listAdapter.reset();
256         else
257             Snackbar.make(list, error, BaseTransientBottomBar.LENGTH_LONG)
258                     .show();
259
260         listAdapter.toggleAllEditing(true);
261
262         viewModel.checkTransactionSubmittable(listAdapter);
263     }
264
265     private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
266         @Override
267         protected Void doInBackground(Void... voids) {
268             throw new RuntimeException("Simulated crash");
269         }
270     }
271
272 }