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