]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/NewTransactionFragment.java
move new transaction UI into a fragment, have a clean saving progress
[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.app.Activity;
21 import android.content.Context;
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.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.lifecycle.ViewModelProviders;
34 import androidx.recyclerview.widget.ItemTouchHelper;
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
47 import org.jetbrains.annotations.NotNull;
48
49 import java.util.Date;
50
51 /**
52  * A simple {@link Fragment} subclass.
53  * Activities that contain this fragment must implement the
54  * {@link OnNewTransactionFragmentInteractionListener} interface
55  * to handle interaction events.
56  */
57 public class NewTransactionFragment extends Fragment {
58     private NewTransactionItemsAdapter listAdapter;
59     private NewTransactionModel viewModel;
60     private RecyclerView list;
61     private FloatingActionButton fab;
62     private OnNewTransactionFragmentInteractionListener mListener;
63     private MobileLedgerProfile mProfile;
64     public NewTransactionFragment() {
65         // Required empty public constructor
66         setHasOptionsMenu(true);
67     }
68     @Override
69     public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
70         super.onCreateOptionsMenu(menu, inflater);
71         inflater.inflate(R.menu.new_transaction_fragment, menu);
72         menu.findItem(R.id.action_reset_new_transaction_activity)
73             .setOnMenuItemClickListener(item -> {
74                 listAdapter.reset();
75                 return true;
76             });
77     }
78     @Override
79     public View onCreateView(LayoutInflater inflater, ViewGroup container,
80                              Bundle savedInstanceState) {
81         // Inflate the layout for this fragment
82         return inflater.inflate(R.layout.fragment_new_transaction, container, false);
83     }
84
85     @Override
86     public void onActivityCreated(@Nullable Bundle savedInstanceState) {
87         super.onActivityCreated(savedInstanceState);
88         Activity activity = getActivity();
89         if (activity == null)
90             throw new RSInvalidStateException(
91                     "getActivity() returned null within onActivityCreated()");
92
93         list = activity.findViewById(R.id.new_transaction_accounts);
94         viewModel = ViewModelProviders.of(this)
95                                       .get(NewTransactionModel.class);
96         mProfile = Data.profile.getValue();
97         listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
98         list.setAdapter(listAdapter);
99         list.setLayoutManager(new LinearLayoutManager(activity));
100         Data.profile.observe(this, profile -> {
101             mProfile = profile;
102             listAdapter.setProfile(profile);
103         });
104         listAdapter.notifyDataSetChanged();
105         new ItemTouchHelper(new ItemTouchHelper.Callback() {
106             @Override
107             public int getMovementFlags(@NonNull RecyclerView recyclerView,
108                                         @NonNull RecyclerView.ViewHolder viewHolder) {
109                 int flags = makeFlag(ItemTouchHelper.ACTION_STATE_IDLE, ItemTouchHelper.END);
110                 // the top item is always there (date and description)
111                 if (viewHolder.getAdapterPosition() > 0) {
112                     if (viewModel.getAccountCount() > 2) {
113                         flags |= makeFlag(ItemTouchHelper.ACTION_STATE_SWIPE,
114                                 ItemTouchHelper.START | ItemTouchHelper.END);
115                     }
116                 }
117
118                 return flags;
119             }
120             @Override
121             public boolean onMove(@NonNull RecyclerView recyclerView,
122                                   @NonNull RecyclerView.ViewHolder viewHolder,
123                                   @NonNull RecyclerView.ViewHolder target) {
124                 return false;
125             }
126             @Override
127             public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
128                 if (viewModel.getAccountCount() == 2)
129                     Snackbar.make(list, R.string.msg_at_least_two_accounts_are_required,
130                             Snackbar.LENGTH_LONG)
131                             .setAction("Action", null)
132                             .show();
133                 else {
134                     int pos = viewHolder.getAdapterPosition();
135                     viewModel.removeItem(pos - 1);
136                     listAdapter.notifyItemRemoved(pos);
137                     viewModel.sendCountNotifications(); // needed after items re-arrangement
138                     viewModel.checkTransactionSubmittable(listAdapter);
139                 }
140             }
141         }).attachToRecyclerView(list);
142
143         viewModel.isSubmittable()
144                  .observe(this, isSubmittable -> {
145                      if (isSubmittable) {
146                          if (fab != null) {
147                              fab.show();
148                              fab.setEnabled(true);
149                          }
150                      }
151                      else {
152                          if (fab != null) {
153                              fab.hide();
154                          }
155                      }
156                  });
157         viewModel.checkTransactionSubmittable(listAdapter);
158
159         fab = activity.findViewById(R.id.fab);
160         fab.setOnClickListener(v -> onFabPressed());
161
162         Bundle args = getArguments();
163         if (args != null) {
164             String error = args.getString("error");
165             if (error != null) {
166                 // TODO display error
167             }
168             else {
169                 viewModel.reset();
170             }
171         }
172     }
173     private void onFabPressed() {
174         fab.setEnabled(false);
175         if (mListener != null) {
176             Date date = viewModel.getDate();
177             LedgerTransaction tr =
178                     new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
179
180             LedgerTransactionAccount emptyAmountAccount = null;
181             float emptyAmountAccountBalance = 0;
182             for (int i = 0; i < viewModel.getAccountCount(); i++) {
183                 LedgerTransactionAccount acc = viewModel.getAccount(i);
184                 if (acc.getAccountName()
185                        .trim()
186                        .isEmpty())
187                     continue;
188
189                 if (acc.isAmountSet()) {
190                     emptyAmountAccountBalance += acc.getAmount();
191                 }
192                 else {
193                     emptyAmountAccount = acc;
194                 }
195
196                 tr.addAccount(acc);
197             }
198
199             if (emptyAmountAccount != null)
200                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
201
202             mListener.onTransactionSave(tr);
203         }
204     }
205
206     @Override
207     public void onAttach(@NotNull Context context) {
208         super.onAttach(context);
209         if (context instanceof OnNewTransactionFragmentInteractionListener) {
210             mListener = (OnNewTransactionFragmentInteractionListener) context;
211         }
212         else {
213             throw new RuntimeException(
214                     context.toString() + " must implement OnFragmentInteractionListener");
215         }
216     }
217
218     @Override
219     public void onDetach() {
220         super.onDetach();
221         mListener = null;
222     }
223
224     /**
225      * This interface must be implemented by activities that contain this
226      * fragment to allow an interaction in this fragment to be communicated
227      * to the activity and potentially other fragments contained in that
228      * activity.
229      * <p>
230      * See the Android Training lesson <a href=
231      * "http://developer.android.com/training/basics/fragments/communicating.html"
232      * >Communicating with Other Fragments</a> for more information.
233      */
234     public interface OnNewTransactionFragmentInteractionListener {
235         void onTransactionSave(LedgerTransaction tr);
236     }
237 }