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