]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionFragment.java
new transaction: hide FAB on submit
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionFragment.java
1 /*
2  * Copyright © 2020 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.content.Context;
21 import android.os.Bundle;
22 import android.renderscript.RSInvalidStateException;
23 import android.view.LayoutInflater;
24 import android.view.Menu;
25 import android.view.MenuInflater;
26 import android.view.MenuItem;
27 import android.view.View;
28 import android.view.ViewGroup;
29 import android.widget.ProgressBar;
30
31 import androidx.annotation.NonNull;
32 import androidx.annotation.Nullable;
33 import androidx.fragment.app.Fragment;
34 import androidx.fragment.app.FragmentActivity;
35 import androidx.lifecycle.ViewModelProvider;
36 import androidx.recyclerview.widget.LinearLayoutManager;
37 import androidx.recyclerview.widget.RecyclerView;
38
39 import com.google.android.material.floatingactionbutton.FloatingActionButton;
40 import com.google.android.material.snackbar.Snackbar;
41
42 import net.ktnx.mobileledger.R;
43 import net.ktnx.mobileledger.model.Data;
44 import net.ktnx.mobileledger.model.LedgerTransaction;
45 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
46 import net.ktnx.mobileledger.model.MobileLedgerProfile;
47 import net.ktnx.mobileledger.utils.Logger;
48 import net.ktnx.mobileledger.utils.Misc;
49 import net.ktnx.mobileledger.utils.SimpleDate;
50
51 import org.jetbrains.annotations.NotNull;
52
53 /**
54  * A simple {@link Fragment} subclass.
55  * Activities that contain this fragment must implement the
56  * {@link OnNewTransactionFragmentInteractionListener} interface
57  * to handle interaction events.
58  */
59
60 // TODO: offer to undo account remove-on-swipe
61 // TODO: transaction-level comment
62
63 public class NewTransactionFragment extends Fragment {
64     private NewTransactionItemsAdapter listAdapter;
65     private NewTransactionModel viewModel;
66     private RecyclerView list;
67     private FloatingActionButton fab;
68     private OnNewTransactionFragmentInteractionListener mListener;
69     private MobileLedgerProfile mProfile;
70     public NewTransactionFragment() {
71         // Required empty public constructor
72         setHasOptionsMenu(true);
73     }
74     @Override
75     public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
76         super.onCreateOptionsMenu(menu, inflater);
77         final FragmentActivity activity = getActivity();
78
79         inflater.inflate(R.menu.new_transaction_fragment, menu);
80         menu.findItem(R.id.action_reset_new_transaction_activity)
81             .setOnMenuItemClickListener(item -> {
82                 listAdapter.reset();
83                 return true;
84             });
85
86         final MenuItem toggleCurrencyItem = menu.findItem(R.id.toggle_currency);
87         toggleCurrencyItem.setOnMenuItemClickListener(item -> {
88             viewModel.toggleCurrencyVisible();
89             return true;
90         });
91         if (activity != null)
92             viewModel.showCurrency.observe(activity, toggleCurrencyItem::setChecked);
93
94         final MenuItem toggleCommentsItem = menu.findItem(R.id.toggle_comments);
95         toggleCommentsItem.setOnMenuItemClickListener(item -> {
96             viewModel.toggleShowComments();
97             return true;
98         });
99         if (activity != null)
100             viewModel.showComments.observe(activity, toggleCommentsItem::setChecked);
101     }
102     @Override
103     public View onCreateView(LayoutInflater inflater, ViewGroup container,
104                              Bundle savedInstanceState) {
105         // Inflate the layout for this fragment
106         return inflater.inflate(R.layout.fragment_new_transaction, container, false);
107     }
108
109     @Override
110     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
111         super.onActivityCreated(savedInstanceState);
112         FragmentActivity activity = getActivity();
113         if (activity == null)
114             throw new RSInvalidStateException(
115                     "getActivity() returned null within onActivityCreated()");
116
117         viewModel = new ViewModelProvider(activity).get(NewTransactionModel.class);
118         viewModel.observeDataProfile(this);
119         mProfile = Data.profile.getValue();
120         listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
121         list.setAdapter(listAdapter);
122         list.setLayoutManager(new LinearLayoutManager(activity));
123         Data.profile.observe(getViewLifecycleOwner(), profile -> {
124             mProfile = profile;
125             listAdapter.setProfile(profile);
126         });
127         listAdapter.notifyDataSetChanged();
128         viewModel.isSubmittable()
129                  .observe(getViewLifecycleOwner(), isSubmittable -> {
130                      if (isSubmittable) {
131                          if (fab != null) {
132                              fab.show();
133                          }
134                      }
135                      else {
136                          if (fab != null) {
137                              fab.hide();
138                          }
139                      }
140                  });
141 //        viewModel.checkTransactionSubmittable(listAdapter);
142
143         fab = activity.findViewById(R.id.fab);
144         fab.setOnClickListener(v -> onFabPressed());
145
146         boolean keep = false;
147
148         Bundle args = getArguments();
149         if (args != null) {
150             String error = args.getString("error");
151             if (error != null) {
152                 Logger.debug("new-trans-f", String.format("Got error: %s", error));
153                 Snackbar.make(list, error, Snackbar.LENGTH_LONG)
154                         .show();
155                 keep = true;
156             }
157         }
158
159         int focused = 0;
160         if (savedInstanceState != null) {
161             keep |= savedInstanceState.getBoolean("keep", true);
162             focused = savedInstanceState.getInt("focused", 0);
163         }
164
165         if (!keep)
166             viewModel.reset();
167         else {
168             viewModel.setFocusedItem(focused);
169         }
170
171         ProgressBar p = activity.findViewById(R.id.progressBar);
172         viewModel.observeBusyFlag(getViewLifecycleOwner(), isBusy -> {
173             if (isBusy) {
174 //                Handler h = new Handler();
175 //                h.postDelayed(() -> {
176 //                    if (viewModel.getBusyFlag())
177 //                        p.setVisibility(View.VISIBLE);
178 //
179 //                }, 10);
180                 p.setVisibility(View.VISIBLE);
181             }
182             else
183                 p.setVisibility(View.INVISIBLE);
184         });
185     }
186     @Override
187     public void onSaveInstanceState(@NonNull Bundle outState) {
188         super.onSaveInstanceState(outState);
189         outState.putBoolean("keep", true);
190         final int focusedItem = viewModel.getFocusedItem();
191         outState.putInt("focused", focusedItem);
192     }
193     private void onFabPressed() {
194         fab.hide();
195         Misc.hideSoftKeyboard(this);
196         if (mListener != null) {
197             SimpleDate date = viewModel.getDate();
198             LedgerTransaction tr =
199                     new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
200
201             tr.setComment(viewModel.getComment());
202             LedgerTransactionAccount emptyAmountAccount = null;
203             float emptyAmountAccountBalance = 0;
204             for (int i = 0; i < viewModel.getAccountCount(); i++) {
205                 LedgerTransactionAccount acc =
206                         new LedgerTransactionAccount(viewModel.getAccount(i));
207                 if (acc.getAccountName()
208                        .trim()
209                        .isEmpty())
210                     continue;
211
212                 if (acc.isAmountSet()) {
213                     emptyAmountAccountBalance += acc.getAmount();
214                 }
215                 else {
216                     emptyAmountAccount = acc;
217                 }
218
219                 tr.addAccount(acc);
220             }
221
222             if (emptyAmountAccount != null)
223                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
224
225             mListener.onTransactionSave(tr);
226         }
227     }
228
229     @Override
230     public void onAttach(@NotNull Context context) {
231         super.onAttach(context);
232         if (context instanceof OnNewTransactionFragmentInteractionListener) {
233             mListener = (OnNewTransactionFragmentInteractionListener) context;
234         }
235         else {
236             throw new RuntimeException(
237                     context.toString() + " must implement OnFragmentInteractionListener");
238         }
239     }
240
241     @Override
242     public void onDetach() {
243         super.onDetach();
244         mListener = null;
245     }
246
247     /**
248      * This interface must be implemented by activities that contain this
249      * fragment to allow an interaction in this fragment to be communicated
250      * to the activity and potentially other fragments contained in that
251      * activity.
252      * <p>
253      * See the Android Training lesson <a href=
254      * "http://developer.android.com/training/basics/fragments/communicating.html"
255      * >Communicating with Other Fragments</a> for more information.
256      */
257     public interface OnNewTransactionFragmentInteractionListener {
258         void onTransactionSave(LedgerTransaction tr);
259     }
260 }