]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/new_transaction/NewTransactionFragment.java
4932f9de12f2d31e4c9a3305f25ac1ee013db26e
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / new_transaction / NewTransactionFragment.java
1 /*
2  * Copyright © 2021 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.new_transaction;
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.ui.QRScanAbleFragment;
51 import net.ktnx.mobileledger.utils.Logger;
52 import net.ktnx.mobileledger.utils.Misc;
53 import net.ktnx.mobileledger.utils.SimpleDate;
54
55 import org.jetbrains.annotations.NotNull;
56
57 import java.util.regex.Matcher;
58 import java.util.regex.Pattern;
59
60 /**
61  * A simple {@link Fragment} subclass.
62  * Activities that contain this fragment must implement the
63  * {@link OnNewTransactionFragmentInteractionListener} interface
64  * to handle interaction events.
65  */
66
67 // TODO: offer to undo account remove-on-swipe
68
69 public class NewTransactionFragment extends QRScanAbleFragment {
70     private NewTransactionItemsAdapter listAdapter;
71     private NewTransactionModel viewModel;
72     private FloatingActionButton fab;
73     private OnNewTransactionFragmentInteractionListener mListener;
74     private MobileLedgerProfile mProfile;
75     public NewTransactionFragment() {
76         // Required empty public constructor
77         setHasOptionsMenu(true);
78     }
79     protected void onQrScanned(String text) {
80         Logger.debug("qr", String.format("Got QR scan result [%s]", text));
81         Pattern p =
82                 Pattern.compile("^(\\d+)\\*(\\d+)\\*(\\d+)-(\\d+)-(\\d+)\\*([:\\d]+)\\*([\\d.]+)$");
83         Matcher m = p.matcher(text);
84         if (m.matches()) {
85             float amount = Float.parseFloat(m.group(7));
86             viewModel.setDate(
87                     new SimpleDate(Integer.parseInt(m.group(3)), Integer.parseInt(m.group(4)),
88                             Integer.parseInt(m.group(5))));
89
90             if (viewModel.accountsInInitialState()) {
91                 {
92                     NewTransactionModel.Item firstItem = viewModel.getItem(1);
93                     if (firstItem == null) {
94                         viewModel.addAccount(new LedgerTransactionAccount("разход:пазар"));
95                         listAdapter.notifyItemInserted(viewModel.items.size() - 1);
96                     }
97                     else {
98                         firstItem.setAccountName("разход:пазар");
99                         firstItem.getAccount()
100                                  .resetAmount();
101                         listAdapter.notifyItemChanged(1);
102                     }
103                 }
104                 {
105                     NewTransactionModel.Item secondItem = viewModel.getItem(2);
106                     if (secondItem == null) {
107                         viewModel.addAccount(
108                                 new LedgerTransactionAccount("актив:кеш:дам", -amount, null, null));
109                         listAdapter.notifyItemInserted(viewModel.items.size() - 1);
110                     }
111                     else {
112                         secondItem.setAccountName("актив:кеш:дам");
113                         secondItem.getAccount()
114                                   .setAmount(-amount);
115                         listAdapter.notifyItemChanged(2);
116                     }
117                 }
118             }
119             else {
120                 viewModel.addAccount(new LedgerTransactionAccount("разход:пазар"));
121                 viewModel.addAccount(
122                         new LedgerTransactionAccount("актив:кеш:дам", -amount, null, null));
123                 listAdapter.notifyItemRangeInserted(viewModel.items.size() - 1, 2);
124             }
125
126             listAdapter.checkTransactionSubmittable();
127         }
128     }
129     @Override
130     public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
131         super.onCreateOptionsMenu(menu, inflater);
132         final FragmentActivity activity = getActivity();
133
134         inflater.inflate(R.menu.new_transaction_fragment, menu);
135
136         menu.findItem(R.id.scan_qr)
137             .setOnMenuItemClickListener(this::onScanQrAction);
138
139         menu.findItem(R.id.action_reset_new_transaction_activity)
140             .setOnMenuItemClickListener(item -> {
141                 listAdapter.reset();
142                 return true;
143             });
144
145         final MenuItem toggleCurrencyItem = menu.findItem(R.id.toggle_currency);
146         toggleCurrencyItem.setOnMenuItemClickListener(item -> {
147             viewModel.toggleCurrencyVisible();
148             return true;
149         });
150         if (activity != null)
151             viewModel.showCurrency.observe(activity, toggleCurrencyItem::setChecked);
152
153         final MenuItem toggleCommentsItem = menu.findItem(R.id.toggle_comments);
154         toggleCommentsItem.setOnMenuItemClickListener(item -> {
155             viewModel.toggleShowComments();
156             return true;
157         });
158         if (activity != null)
159             viewModel.showComments.observe(activity, toggleCommentsItem::setChecked);
160     }
161     private boolean onScanQrAction(MenuItem item) {
162         try {
163             scanQrLauncher.launch(null);
164         }
165         catch (Exception e) {
166             Logger.debug("qr", "Error launching QR scanner", e);
167         }
168
169         return true;
170     }
171     @Override
172     public View onCreateView(LayoutInflater inflater, ViewGroup container,
173                              Bundle savedInstanceState) {
174         // Inflate the layout for this fragment
175         return inflater.inflate(R.layout.fragment_new_transaction, container, false);
176     }
177
178     @Override
179     public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
180         super.onViewCreated(view, savedInstanceState);
181         FragmentActivity activity = getActivity();
182         if (activity == null)
183             throw new RSInvalidStateException(
184                     "getActivity() returned null within onActivityCreated()");
185
186         viewModel = new ViewModelProvider(activity).get(NewTransactionModel.class);
187         viewModel.observeDataProfile(this);
188         mProfile = Data.getProfile();
189         listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
190
191         RecyclerView list = activity.findViewById(R.id.new_transaction_accounts);
192         list.setAdapter(listAdapter);
193         list.setLayoutManager(new LinearLayoutManager(activity));
194
195         Data.observeProfile(getViewLifecycleOwner(), profile -> {
196             mProfile = profile;
197             listAdapter.setProfile(profile);
198         });
199         listAdapter.notifyDataSetChanged();
200         viewModel.isSubmittable()
201                  .observe(getViewLifecycleOwner(), isSubmittable -> {
202                      if (isSubmittable) {
203                          if (fab != null) {
204                              fab.show();
205                          }
206                      }
207                      else {
208                          if (fab != null) {
209                              fab.hide();
210                          }
211                      }
212                  });
213 //        viewModel.checkTransactionSubmittable(listAdapter);
214
215         fab = activity.findViewById(R.id.fabAdd);
216         fab.setOnClickListener(v -> onFabPressed());
217
218         boolean keep = false;
219
220         Bundle args = getArguments();
221         if (args != null) {
222             String error = args.getString("error");
223             if (error != null) {
224                 Logger.debug("new-trans-f", String.format("Got error: %s", error));
225
226                 Context context = getContext();
227                 if (context != null) {
228                     AlertDialog.Builder builder = new AlertDialog.Builder(context);
229                     final Resources resources = context.getResources();
230                     final StringBuilder message = new StringBuilder();
231                     message.append(resources.getString(R.string.err_json_send_error_head));
232                     message.append("\n\n");
233                     message.append(error);
234                     if (mProfile.getApiVersion()
235                                 .equals(API.auto))
236                         message.append(
237                                 resources.getString(R.string.err_json_send_error_unsupported));
238                     else {
239                         message.append(resources.getString(R.string.err_json_send_error_tail));
240                         builder.setPositiveButton(R.string.btn_profile_options, (dialog, which) -> {
241                             Logger.debug("error", "will start profile editor");
242                             MobileLedgerProfile.startEditProfileActivity(context, mProfile);
243                         });
244                     }
245                     builder.setMessage(message);
246                     builder.create()
247                            .show();
248                 }
249                 else {
250                     Snackbar.make(list, error, Snackbar.LENGTH_INDEFINITE)
251                             .show();
252                 }
253                 keep = true;
254             }
255         }
256
257         int focused = 0;
258         if (savedInstanceState != null) {
259             keep |= savedInstanceState.getBoolean("keep", true);
260             focused = savedInstanceState.getInt("focused", 0);
261         }
262
263         if (!keep)
264             viewModel.reset();
265         else {
266             viewModel.setFocusedItem(focused);
267         }
268
269         ProgressBar p = activity.findViewById(R.id.progressBar);
270         viewModel.observeBusyFlag(getViewLifecycleOwner(), isBusy -> {
271             if (isBusy) {
272 //                Handler h = new Handler();
273 //                h.postDelayed(() -> {
274 //                    if (viewModel.getBusyFlag())
275 //                        p.setVisibility(View.VISIBLE);
276 //
277 //                }, 10);
278                 p.setVisibility(View.VISIBLE);
279             }
280             else
281                 p.setVisibility(View.INVISIBLE);
282         });
283     }
284     @Override
285     public void onSaveInstanceState(@NonNull Bundle outState) {
286         super.onSaveInstanceState(outState);
287         outState.putBoolean("keep", true);
288         final int focusedItem = viewModel.getFocusedItem();
289         outState.putInt("focused", focusedItem);
290     }
291     private void onFabPressed() {
292         fab.hide();
293         Misc.hideSoftKeyboard(this);
294         if (mListener != null) {
295             SimpleDate date = viewModel.getDate();
296             LedgerTransaction tr =
297                     new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
298
299             tr.setComment(viewModel.getComment());
300             LedgerTransactionAccount emptyAmountAccount = null;
301             float emptyAmountAccountBalance = 0;
302             for (int i = 0; i < viewModel.getAccountCount(); i++) {
303                 LedgerTransactionAccount acc =
304                         new LedgerTransactionAccount(viewModel.getAccount(i));
305                 if (acc.getAccountName()
306                        .trim()
307                        .isEmpty())
308                     continue;
309
310                 if (acc.isAmountSet()) {
311                     emptyAmountAccountBalance += acc.getAmount();
312                 }
313                 else {
314                     emptyAmountAccount = acc;
315                 }
316
317                 tr.addAccount(acc);
318             }
319
320             if (emptyAmountAccount != null)
321                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
322
323             mListener.onTransactionSave(tr);
324         }
325     }
326
327     @Override
328     public void onAttach(@NotNull Context context) {
329         super.onAttach(context);
330         if (context instanceof OnNewTransactionFragmentInteractionListener) {
331             mListener = (OnNewTransactionFragmentInteractionListener) context;
332         }
333         else {
334             throw new RuntimeException(
335                     context.toString() + " must implement OnFragmentInteractionListener");
336         }
337     }
338
339     @Override
340     public void onDetach() {
341         super.onDetach();
342         mListener = null;
343     }
344
345     /**
346      * This interface must be implemented by activities that contain this
347      * fragment to allow an interaction in this fragment to be communicated
348      * to the activity and potentially other fragments contained in that
349      * activity.
350      * <p>
351      * See the Android Training lesson <a href=
352      * "http://developer.android.com/training/basics/fragments/communicating.html"
353      * >Communicating with Other Fragments</a> for more information.
354      */
355     public interface OnNewTransactionFragmentInteractionListener {
356         void onTransactionSave(LedgerTransaction tr);
357     }
358 }