]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionFragment.java
rework transaction date handling
[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         list = activity.findViewById(R.id.new_transaction_accounts);
118         viewModel = new ViewModelProvider(activity).get(NewTransactionModel.class);
119         viewModel.observeDataProfile(this);
120         mProfile = Data.profile.getValue();
121         listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
122         list.setAdapter(listAdapter);
123         list.setLayoutManager(new LinearLayoutManager(activity));
124         Data.profile.observe(getViewLifecycleOwner(), profile -> {
125             mProfile = profile;
126             listAdapter.setProfile(profile);
127         });
128         listAdapter.notifyDataSetChanged();
129         viewModel.isSubmittable()
130                  .observe(getViewLifecycleOwner(), isSubmittable -> {
131                      if (isSubmittable) {
132                          if (fab != null) {
133                              fab.show();
134                              fab.setEnabled(true);
135                          }
136                      }
137                      else {
138                          if (fab != null) {
139                              fab.hide();
140                          }
141                      }
142                  });
143 //        viewModel.checkTransactionSubmittable(listAdapter);
144
145         fab = activity.findViewById(R.id.fab);
146         fab.setOnClickListener(v -> onFabPressed());
147
148         boolean keep = false;
149
150         Bundle args = getArguments();
151         if (args != null) {
152             String error = args.getString("error");
153             if (error != null) {
154                 Logger.debug("new-trans-f", String.format("Got error: %s", error));
155                 Snackbar.make(list, error, Snackbar.LENGTH_LONG)
156                         .show();
157                 keep = true;
158             }
159         }
160
161         int focused = 0;
162         if (savedInstanceState != null) {
163             keep |= savedInstanceState.getBoolean("keep", true);
164             focused = savedInstanceState.getInt("focused", 0);
165         }
166
167         if (!keep)
168             viewModel.reset();
169         else {
170             viewModel.setFocusedItem(focused);
171         }
172
173         ProgressBar p = activity.findViewById(R.id.progressBar);
174         viewModel.observeBusyFlag(getViewLifecycleOwner(), isBusy -> {
175             if (isBusy) {
176 //                Handler h = new Handler();
177 //                h.postDelayed(() -> {
178 //                    if (viewModel.getBusyFlag())
179 //                        p.setVisibility(View.VISIBLE);
180 //
181 //                }, 10);
182                         p.setVisibility(View.VISIBLE);
183             }
184             else
185                 p.setVisibility(View.INVISIBLE);
186         });
187     }
188     @Override
189     public void onSaveInstanceState(@NonNull Bundle outState) {
190         super.onSaveInstanceState(outState);
191         outState.putBoolean("keep", true);
192         final int focusedItem = viewModel.getFocusedItem();
193         outState.putInt("focused", focusedItem);
194     }
195     private void onFabPressed() {
196         fab.setEnabled(false);
197         Misc.hideSoftKeyboard(this);
198         if (mListener != null) {
199             SimpleDate date = viewModel.getDate();
200             LedgerTransaction tr =
201                     new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
202
203             tr.setComment(viewModel.getComment());
204             LedgerTransactionAccount emptyAmountAccount = null;
205             float emptyAmountAccountBalance = 0;
206             for (int i = 0; i < viewModel.getAccountCount(); i++) {
207                 LedgerTransactionAccount acc =
208                         new LedgerTransactionAccount(viewModel.getAccount(i));
209                 if (acc.getAccountName()
210                        .trim()
211                        .isEmpty())
212                     continue;
213
214                 if (acc.isAmountSet()) {
215                     emptyAmountAccountBalance += acc.getAmount();
216                 }
217                 else {
218                     emptyAmountAccount = acc;
219                 }
220
221                 tr.addAccount(acc);
222             }
223
224             if (emptyAmountAccount != null)
225                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
226
227             mListener.onTransactionSave(tr);
228         }
229     }
230
231     @Override
232     public void onAttach(@NotNull Context context) {
233         super.onAttach(context);
234         if (context instanceof OnNewTransactionFragmentInteractionListener) {
235             mListener = (OnNewTransactionFragmentInteractionListener) context;
236         }
237         else {
238             throw new RuntimeException(
239                     context.toString() + " must implement OnFragmentInteractionListener");
240         }
241     }
242
243     @Override
244     public void onDetach() {
245         super.onDetach();
246         mListener = null;
247     }
248
249     /**
250      * This interface must be implemented by activities that contain this
251      * fragment to allow an interaction in this fragment to be communicated
252      * to the activity and potentially other fragments contained in that
253      * activity.
254      * <p>
255      * See the Android Training lesson <a href=
256      * "http://developer.android.com/training/basics/fragments/communicating.html"
257      * >Communicating with Other Fragments</a> for more information.
258      */
259     public interface OnNewTransactionFragmentInteractionListener {
260         void onTransactionSave(LedgerTransaction tr);
261     }
262 }