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