]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionFragment.java
new transaction: hide currency/commodity selector by default; add menu item for showing
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / NewTransactionFragment.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.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
30 import androidx.annotation.NonNull;
31 import androidx.annotation.Nullable;
32 import androidx.fragment.app.Fragment;
33 import androidx.fragment.app.FragmentActivity;
34 import androidx.lifecycle.ViewModelProvider;
35 import androidx.recyclerview.widget.LinearLayoutManager;
36 import androidx.recyclerview.widget.RecyclerView;
37
38 import com.google.android.material.floatingactionbutton.FloatingActionButton;
39 import com.google.android.material.snackbar.Snackbar;
40
41 import net.ktnx.mobileledger.R;
42 import net.ktnx.mobileledger.model.Data;
43 import net.ktnx.mobileledger.model.LedgerTransaction;
44 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
45 import net.ktnx.mobileledger.model.MobileLedgerProfile;
46 import net.ktnx.mobileledger.utils.Logger;
47 import net.ktnx.mobileledger.utils.Misc;
48
49 import org.jetbrains.annotations.NotNull;
50
51 import java.util.Date;
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
62 public class NewTransactionFragment extends Fragment {
63     private NewTransactionItemsAdapter listAdapter;
64     private NewTransactionModel viewModel;
65     private RecyclerView list;
66     private FloatingActionButton fab;
67     private OnNewTransactionFragmentInteractionListener mListener;
68     private MobileLedgerProfile mProfile;
69     public NewTransactionFragment() {
70         // Required empty public constructor
71         setHasOptionsMenu(true);
72     }
73     @Override
74     public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
75         super.onCreateOptionsMenu(menu, inflater);
76         inflater.inflate(R.menu.new_transaction_fragment, menu);
77         menu.findItem(R.id.action_reset_new_transaction_activity)
78             .setOnMenuItemClickListener(item -> {
79                 listAdapter.reset();
80                 return true;
81             });
82         final MenuItem toggleCurrencyItem = menu.findItem(R.id.toggle_currency);
83         toggleCurrencyItem.setOnMenuItemClickListener(item -> {
84             viewModel.toggleCurrencyVisible();
85             return true;
86         });
87         final FragmentActivity activity = getActivity();
88         if (activity != null)
89             viewModel.showCurrency.observe(activity, toggleCurrencyItem::setChecked);
90     }
91     @Override
92     public View onCreateView(LayoutInflater inflater, ViewGroup container,
93                              Bundle savedInstanceState) {
94         // Inflate the layout for this fragment
95         return inflater.inflate(R.layout.fragment_new_transaction, container, false);
96     }
97
98     @Override
99     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
100         super.onActivityCreated(savedInstanceState);
101         FragmentActivity activity = getActivity();
102         if (activity == null)
103             throw new RSInvalidStateException(
104                     "getActivity() returned null within onActivityCreated()");
105
106         list = activity.findViewById(R.id.new_transaction_accounts);
107         viewModel = new ViewModelProvider(activity).get(NewTransactionModel.class);
108         mProfile = Data.profile.getValue();
109         listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
110         list.setAdapter(listAdapter);
111         list.setLayoutManager(new LinearLayoutManager(activity));
112         Data.profile.observe(getViewLifecycleOwner(), profile -> {
113             mProfile = profile;
114             listAdapter.setProfile(profile);
115         });
116         listAdapter.notifyDataSetChanged();
117         viewModel.isSubmittable()
118                  .observe(getViewLifecycleOwner(), isSubmittable -> {
119                      if (isSubmittable) {
120                          if (fab != null) {
121                              fab.show();
122                              fab.setEnabled(true);
123                          }
124                      }
125                      else {
126                          if (fab != null) {
127                              fab.hide();
128                          }
129                      }
130                  });
131         viewModel.checkTransactionSubmittable(listAdapter);
132
133         fab = activity.findViewById(R.id.fab);
134         fab.setOnClickListener(v -> onFabPressed());
135
136         boolean keep = false;
137
138         Bundle args = getArguments();
139         if (args != null) {
140             String error = args.getString("error");
141             if (error != null) {
142                 Logger.debug("new-trans-f", String.format("Got error: %s", error));
143                 Snackbar.make(list, error, Snackbar.LENGTH_LONG)
144                         .show();
145                 keep = true;
146             }
147         }
148
149         int focused = 0;
150         if (savedInstanceState != null) {
151             keep |= savedInstanceState.getBoolean("keep", true);
152             focused = savedInstanceState.getInt("focused", 0);
153         }
154
155         if (!keep)
156             viewModel.reset();
157         else {
158             viewModel.setFocusedItem(focused);
159         }
160     }
161     @Override
162     public void onSaveInstanceState(@NonNull Bundle outState) {
163         super.onSaveInstanceState(outState);
164         outState.putBoolean("keep", true);
165         final int focusedItem = viewModel.getFocusedItem();
166         outState.putInt("focused", focusedItem);
167     }
168     private void onFabPressed() {
169         fab.setEnabled(false);
170         Misc.hideSoftKeyboard(this);
171         if (mListener != null) {
172             Date date = viewModel.getDate();
173             LedgerTransaction tr =
174                     new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
175
176             LedgerTransactionAccount emptyAmountAccount = null;
177             float emptyAmountAccountBalance = 0;
178             for (int i = 0; i < viewModel.getAccountCount(); i++) {
179                 LedgerTransactionAccount acc =
180                         new LedgerTransactionAccount(viewModel.getAccount(i));
181                 if (acc.getAccountName()
182                        .trim()
183                        .isEmpty())
184                     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
199             mListener.onTransactionSave(tr);
200         }
201     }
202
203     @Override
204     public void onAttach(@NotNull Context context) {
205         super.onAttach(context);
206         if (context instanceof OnNewTransactionFragmentInteractionListener) {
207             mListener = (OnNewTransactionFragmentInteractionListener) context;
208         }
209         else {
210             throw new RuntimeException(
211                     context.toString() + " must implement OnFragmentInteractionListener");
212         }
213     }
214
215     @Override
216     public void onDetach() {
217         super.onDetach();
218         mListener = null;
219     }
220
221     /**
222      * This interface must be implemented by activities that contain this
223      * fragment to allow an interaction in this fragment to be communicated
224      * to the activity and potentially other fragments contained in that
225      * activity.
226      * <p>
227      * See the Android Training lesson <a href=
228      * "http://developer.android.com/training/basics/fragments/communicating.html"
229      * >Communicating with Other Fragments</a> for more information.
230      */
231     public interface OnNewTransactionFragmentInteractionListener {
232         void onTransactionSave(LedgerTransaction tr);
233     }
234 }