]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionActivity.java
cef99101f8eae72776103b72c46d477cb0a31265
[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                 if (viewModel.getAccountCount() > 2) flags |=
95                         makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE,
96                                 ItemTouchHelper.START | ItemTouchHelper.END);
97                 return flags;
98             }
99             @Override
100             public boolean onMove(@NonNull RecyclerView recyclerView,
101                                   @NonNull RecyclerView.ViewHolder viewHolder,
102                                   @NonNull RecyclerView.ViewHolder target) {
103                 return false;
104             }
105             @Override
106             public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
107                 if (viewModel.getAccountCount() == 2)
108                     Snackbar.make(list, R.string.msg_at_least_two_accounts_are_required,
109                             Snackbar.LENGTH_LONG).setAction("Action", null).show();
110                 else {
111                     int pos = viewHolder.getAdapterPosition();
112                     listAdapter.removeItem(pos);
113                     // FIXME hook next/prev links somehow
114                     throw new RuntimeException("TODO");
115                 }
116             }
117         }).attachToRecyclerView(list);
118
119         viewModel.isSubmittable().observe(this, new Observer<Boolean>() {
120             @Override
121             public void onChanged(Boolean isSubmittable) {
122                 if (isSubmittable) {
123                     if (fab != null) {
124                         fab.show();
125                         fab.setEnabled(true);
126                     }
127                 }
128                 else {
129                     if (fab != null) {
130                         fab.hide();
131                     }
132                 }
133             }
134         });
135         viewModel.checkTransactionSubmittable(listAdapter);
136     }
137     @Override
138     protected void initProfile() {
139         String profileUUID = getIntent().getStringExtra("profile_uuid");
140
141         if (profileUUID != null) {
142             mProfile = Data.getProfile(profileUUID);
143             if (mProfile == null) finish();
144         }
145         else super.initProfile();
146     }
147     @Override
148     public void finish() {
149         super.finish();
150         overridePendingTransition(R.anim.dummy, R.anim.slide_out_right);
151     }
152     @Override
153     public boolean onOptionsItemSelected(MenuItem item) {
154         switch (item.getItemId()) {
155             case android.R.id.home:
156                 finish();
157                 return true;
158         }
159         return super.onOptionsItemSelected(item);
160     }
161     @Override
162     protected void onStart() {
163         super.onStart();
164         // FIXME if (tvDescription.getText().toString().isEmpty()) tvDescription.requestFocus();
165     }
166     public void saveTransaction() {
167         if (fab != null) fab.setEnabled(false);
168         listAdapter.toggleAllEditing(false);
169         progress.setVisibility(View.VISIBLE);
170         try {
171
172             saver = new SendTransactionTask(this, mProfile);
173
174             Date date = viewModel.getDate();
175             LedgerTransaction tr =
176                     new LedgerTransaction(null, date, viewModel.getDescription(),
177                             mProfile);
178
179             LedgerTransactionAccount emptyAmountAccount = null;
180             float emptyAmountAccountBalance = 0;
181             for (int i = 0; i < viewModel.getAccountCount(); i++) {
182                 LedgerTransactionAccount acc = viewModel.getAccount(i);
183                 if (acc.getAccountName().trim().isEmpty()) continue;
184
185                 if (acc.isAmountSet()) {
186                     emptyAmountAccountBalance += acc.getAmount();
187                 }
188                 else {
189                     emptyAmountAccount = acc;
190                 }
191
192                 tr.addAccount(acc);
193             }
194
195             if (emptyAmountAccount != null)
196                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
197             saver.execute(tr);
198         }
199         catch (Exception e) {
200             debug("new-transaction", "Unknown error", e);
201
202             progress.setVisibility(View.GONE);
203             listAdapter.toggleAllEditing(true);
204             if (fab != null) fab.setEnabled(true);
205         }
206     }
207     public void simulateCrash(MenuItem item) {
208         debug("crash", "Will crash intentionally");
209         new AsyncCrasher().execute();
210     }
211     public boolean onCreateOptionsMenu(Menu menu) {
212         // Inflate the menu; this adds items to the action bar if it is present.
213         getMenuInflater().inflate(R.menu.new_transaction, menu);
214
215         if (BuildConfig.DEBUG) {
216             menu.findItem(R.id.action_simulate_crash).setVisible(true);
217         }
218
219         return true;
220     }
221
222
223     public int dp2px(float dp) {
224         return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
225                 getResources().getDisplayMetrics()));
226     }
227     public void resetTransactionFromMenu(MenuItem item) {
228         resetForm();
229     }
230     @Override
231     public void done(String error) {
232         progress.setVisibility(View.INVISIBLE);
233         debug("visuals", "hiding progress");
234
235         if (error == null) resetForm();
236         else Snackbar.make(list, error, BaseTransientBottomBar.LENGTH_LONG).show();
237
238         listAdapter.toggleAllEditing(true);
239         viewModel.checkTransactionSubmittable(listAdapter);
240     }
241
242     private void resetForm() {
243         listAdapter.reset();
244     }
245     private class AsyncCrasher extends AsyncTask<Void, Void, Void> {
246         @Override
247         protected Void doInBackground(Void... voids) {
248             throw new RuntimeException("Simulated crash");
249         }
250     }
251
252 }