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.
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.
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/>.
18 package net.ktnx.mobileledger.ui.activity;
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;
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;
41 import com.google.android.material.floatingactionbutton.FloatingActionButton;
42 import com.google.android.material.snackbar.Snackbar;
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;
54 import org.jetbrains.annotations.NotNull;
57 * A simple {@link Fragment} subclass.
58 * Activities that contain this fragment must implement the
59 * {@link OnNewTransactionFragmentInteractionListener} interface
60 * to handle interaction events.
63 // TODO: offer to undo account remove-on-swipe
64 // TODO: transaction-level comment
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);
77 public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
78 super.onCreateOptionsMenu(menu, inflater);
79 final FragmentActivity activity = getActivity();
81 inflater.inflate(R.menu.new_transaction_fragment, menu);
82 menu.findItem(R.id.action_reset_new_transaction_activity)
83 .setOnMenuItemClickListener(item -> {
88 final MenuItem toggleCurrencyItem = menu.findItem(R.id.toggle_currency);
89 toggleCurrencyItem.setOnMenuItemClickListener(item -> {
90 viewModel.toggleCurrencyVisible();
94 viewModel.showCurrency.observe(activity, toggleCurrencyItem::setChecked);
96 final MenuItem toggleCommentsItem = menu.findItem(R.id.toggle_comments);
97 toggleCommentsItem.setOnMenuItemClickListener(item -> {
98 viewModel.toggleShowComments();
101 if (activity != null)
102 viewModel.showComments.observe(activity, toggleCommentsItem::setChecked);
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);
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()");
119 viewModel = new ViewModelProvider(activity).get(NewTransactionModel.class);
120 viewModel.observeDataProfile(this);
121 mProfile = Data.getProfile();
122 listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
124 RecyclerView list = activity.findViewById(R.id.new_transaction_accounts);
125 list.setAdapter(listAdapter);
126 list.setLayoutManager(new LinearLayoutManager(activity));
128 Data.observeProfile(getViewLifecycleOwner(), profile -> {
130 listAdapter.setProfile(profile);
132 listAdapter.notifyDataSetChanged();
133 viewModel.isSubmittable()
134 .observe(getViewLifecycleOwner(), isSubmittable -> {
146 // viewModel.checkTransactionSubmittable(listAdapter);
148 fab = activity.findViewById(R.id.fab);
149 fab.setOnClickListener(v -> onFabPressed());
151 boolean keep = false;
153 Bundle args = getArguments();
155 String error = args.getString("error");
157 Logger.debug("new-trans-f", String.format("Got error: %s", error));
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()
170 resources.getString(R.string.err_json_send_error_unsupported));
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);
178 builder.setMessage(message);
183 Snackbar.make(list, error, Snackbar.LENGTH_LONG)
191 if (savedInstanceState != null) {
192 keep |= savedInstanceState.getBoolean("keep", true);
193 focused = savedInstanceState.getInt("focused", 0);
199 viewModel.setFocusedItem(focused);
202 ProgressBar p = activity.findViewById(R.id.progressBar);
203 viewModel.observeBusyFlag(getViewLifecycleOwner(), isBusy -> {
205 // Handler h = new Handler();
206 // h.postDelayed(() -> {
207 // if (viewModel.getBusyFlag())
208 // p.setVisibility(View.VISIBLE);
211 p.setVisibility(View.VISIBLE);
214 p.setVisibility(View.INVISIBLE);
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);
224 private void onFabPressed() {
226 Misc.hideSoftKeyboard(this);
227 if (mListener != null) {
228 SimpleDate date = viewModel.getDate();
229 LedgerTransaction tr =
230 new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
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()
243 if (acc.isAmountSet()) {
244 emptyAmountAccountBalance += acc.getAmount();
247 emptyAmountAccount = acc;
253 if (emptyAmountAccount != null)
254 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
256 mListener.onTransactionSave(tr);
261 public void onAttach(@NotNull Context context) {
262 super.onAttach(context);
263 if (context instanceof OnNewTransactionFragmentInteractionListener) {
264 mListener = (OnNewTransactionFragmentInteractionListener) context;
267 throw new RuntimeException(
268 context.toString() + " must implement OnFragmentInteractionListener");
273 public void onDetach() {
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
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.
288 public interface OnNewTransactionFragmentInteractionListener {
289 void onTransactionSave(LedgerTransaction tr);