]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionFragment.java
TODO: transaction-level comments (displaying and entering)
[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 // 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         inflater.inflate(R.menu.new_transaction_fragment, menu);
78         menu.findItem(R.id.action_reset_new_transaction_activity)
79             .setOnMenuItemClickListener(item -> {
80                 listAdapter.reset();
81                 return true;
82             });
83         final MenuItem toggleCurrencyItem = menu.findItem(R.id.toggle_currency);
84         toggleCurrencyItem.setOnMenuItemClickListener(item -> {
85             viewModel.toggleCurrencyVisible();
86             return true;
87         });
88         final FragmentActivity activity = getActivity();
89         if (activity != null)
90             viewModel.showCurrency.observe(activity, toggleCurrencyItem::setChecked);
91     }
92     @Override
93     public View onCreateView(LayoutInflater inflater, ViewGroup container,
94                              Bundle savedInstanceState) {
95         // Inflate the layout for this fragment
96         return inflater.inflate(R.layout.fragment_new_transaction, container, false);
97     }
98
99     @Override
100     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
101         super.onActivityCreated(savedInstanceState);
102         FragmentActivity activity = getActivity();
103         if (activity == null)
104             throw new RSInvalidStateException(
105                     "getActivity() returned null within onActivityCreated()");
106
107         list = activity.findViewById(R.id.new_transaction_accounts);
108         viewModel = new ViewModelProvider(activity).get(NewTransactionModel.class);
109         viewModel.observeDataProfile(this);
110         mProfile = Data.profile.getValue();
111         listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
112         list.setAdapter(listAdapter);
113         list.setLayoutManager(new LinearLayoutManager(activity));
114         Data.profile.observe(getViewLifecycleOwner(), profile -> {
115             mProfile = profile;
116             listAdapter.setProfile(profile);
117         });
118         listAdapter.notifyDataSetChanged();
119         viewModel.isSubmittable()
120                  .observe(getViewLifecycleOwner(), isSubmittable -> {
121                      if (isSubmittable) {
122                          if (fab != null) {
123                              fab.show();
124                              fab.setEnabled(true);
125                          }
126                      }
127                      else {
128                          if (fab != null) {
129                              fab.hide();
130                          }
131                      }
132                  });
133 //        viewModel.checkTransactionSubmittable(listAdapter);
134
135         fab = activity.findViewById(R.id.fab);
136         fab.setOnClickListener(v -> onFabPressed());
137
138         boolean keep = false;
139
140         Bundle args = getArguments();
141         if (args != null) {
142             String error = args.getString("error");
143             if (error != null) {
144                 Logger.debug("new-trans-f", String.format("Got error: %s", error));
145                 Snackbar.make(list, error, Snackbar.LENGTH_LONG)
146                         .show();
147                 keep = true;
148             }
149         }
150
151         int focused = 0;
152         if (savedInstanceState != null) {
153             keep |= savedInstanceState.getBoolean("keep", true);
154             focused = savedInstanceState.getInt("focused", 0);
155         }
156
157         if (!keep)
158             viewModel.reset();
159         else {
160             viewModel.setFocusedItem(focused);
161         }
162     }
163     @Override
164     public void onSaveInstanceState(@NonNull Bundle outState) {
165         super.onSaveInstanceState(outState);
166         outState.putBoolean("keep", true);
167         final int focusedItem = viewModel.getFocusedItem();
168         outState.putInt("focused", focusedItem);
169     }
170     private void onFabPressed() {
171         fab.setEnabled(false);
172         Misc.hideSoftKeyboard(this);
173         if (mListener != null) {
174             Date date = viewModel.getDate();
175             LedgerTransaction tr =
176                     new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
177
178             LedgerTransactionAccount emptyAmountAccount = null;
179             float emptyAmountAccountBalance = 0;
180             for (int i = 0; i < viewModel.getAccountCount(); i++) {
181                 LedgerTransactionAccount acc =
182                         new LedgerTransactionAccount(viewModel.getAccount(i));
183                 if (acc.getAccountName()
184                        .trim()
185                        .isEmpty())
186                     continue;
187
188                 if (acc.isAmountSet()) {
189                     emptyAmountAccountBalance += acc.getAmount();
190                 }
191                 else {
192                     emptyAmountAccount = acc;
193                 }
194
195                 tr.addAccount(acc);
196             }
197
198             if (emptyAmountAccount != null)
199                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
200
201             mListener.onTransactionSave(tr);
202         }
203     }
204
205     @Override
206     public void onAttach(@NotNull Context context) {
207         super.onAttach(context);
208         if (context instanceof OnNewTransactionFragmentInteractionListener) {
209             mListener = (OnNewTransactionFragmentInteractionListener) context;
210         }
211         else {
212             throw new RuntimeException(
213                     context.toString() + " must implement OnFragmentInteractionListener");
214         }
215     }
216
217     @Override
218     public void onDetach() {
219         super.onDetach();
220         mListener = null;
221     }
222
223     /**
224      * This interface must be implemented by activities that contain this
225      * fragment to allow an interaction in this fragment to be communicated
226      * to the activity and potentially other fragments contained in that
227      * activity.
228      * <p>
229      * See the Android Training lesson <a href=
230      * "http://developer.android.com/training/basics/fragments/communicating.html"
231      * >Communicating with Other Fragments</a> for more information.
232      */
233     public interface OnNewTransactionFragmentInteractionListener {
234         void onTransactionSave(LedgerTransaction tr);
235     }
236 }