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.
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.new_transaction;
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.ui.QRScanAbleFragment;
51 import net.ktnx.mobileledger.utils.Logger;
52 import net.ktnx.mobileledger.utils.Misc;
53 import net.ktnx.mobileledger.utils.SimpleDate;
55 import org.jetbrains.annotations.NotNull;
57 import java.util.regex.Matcher;
58 import java.util.regex.Pattern;
61 * A simple {@link Fragment} subclass.
62 * Activities that contain this fragment must implement the
63 * {@link OnNewTransactionFragmentInteractionListener} interface
64 * to handle interaction events.
67 // TODO: offer to undo account remove-on-swipe
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);
79 protected void onQrScanned(String text) {
80 Logger.debug("qr", String.format("Got QR scan result [%s]", text));
82 Pattern.compile("^(\\d+)\\*(\\d+)\\*(\\d+)-(\\d+)-(\\d+)\\*([:\\d]+)\\*([\\d.]+)$");
83 Matcher m = p.matcher(text);
85 float amount = Float.parseFloat(m.group(7));
87 new SimpleDate(Integer.parseInt(m.group(3)), Integer.parseInt(m.group(4)),
88 Integer.parseInt(m.group(5))));
90 if (viewModel.accountsInInitialState()) {
92 NewTransactionModel.Item firstItem = viewModel.getItem(1);
93 if (firstItem == null) {
94 viewModel.addAccount(new LedgerTransactionAccount("разход:пазар"));
95 listAdapter.notifyItemInserted(viewModel.items.size() - 1);
98 firstItem.setAccountName("разход:пазар");
99 firstItem.getAccount()
101 listAdapter.notifyItemChanged(1);
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);
112 secondItem.setAccountName("актив:кеш:дам");
113 secondItem.getAccount()
115 listAdapter.notifyItemChanged(2);
120 viewModel.addAccount(new LedgerTransactionAccount("разход:пазар"));
121 viewModel.addAccount(
122 new LedgerTransactionAccount("актив:кеш:дам", -amount, null, null));
123 listAdapter.notifyItemRangeInserted(viewModel.items.size() - 1, 2);
126 listAdapter.checkTransactionSubmittable();
130 public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
131 super.onCreateOptionsMenu(menu, inflater);
132 final FragmentActivity activity = getActivity();
134 inflater.inflate(R.menu.new_transaction_fragment, menu);
136 menu.findItem(R.id.scan_qr)
137 .setOnMenuItemClickListener(this::onScanQrAction);
139 menu.findItem(R.id.action_reset_new_transaction_activity)
140 .setOnMenuItemClickListener(item -> {
145 final MenuItem toggleCurrencyItem = menu.findItem(R.id.toggle_currency);
146 toggleCurrencyItem.setOnMenuItemClickListener(item -> {
147 viewModel.toggleCurrencyVisible();
150 if (activity != null)
151 viewModel.showCurrency.observe(activity, toggleCurrencyItem::setChecked);
153 final MenuItem toggleCommentsItem = menu.findItem(R.id.toggle_comments);
154 toggleCommentsItem.setOnMenuItemClickListener(item -> {
155 viewModel.toggleShowComments();
158 if (activity != null)
159 viewModel.showComments.observe(activity, toggleCommentsItem::setChecked);
161 private boolean onScanQrAction(MenuItem item) {
163 scanQrLauncher.launch(null);
165 catch (Exception e) {
166 Logger.debug("qr", "Error launching QR scanner", e);
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);
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()");
186 viewModel = new ViewModelProvider(activity).get(NewTransactionModel.class);
187 viewModel.observeDataProfile(this);
188 mProfile = Data.getProfile();
189 listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
191 RecyclerView list = activity.findViewById(R.id.new_transaction_accounts);
192 list.setAdapter(listAdapter);
193 list.setLayoutManager(new LinearLayoutManager(activity));
195 Data.observeProfile(getViewLifecycleOwner(), profile -> {
197 listAdapter.setProfile(profile);
199 listAdapter.notifyDataSetChanged();
200 viewModel.isSubmittable()
201 .observe(getViewLifecycleOwner(), isSubmittable -> {
213 // viewModel.checkTransactionSubmittable(listAdapter);
215 fab = activity.findViewById(R.id.fabAdd);
216 fab.setOnClickListener(v -> onFabPressed());
218 boolean keep = false;
220 Bundle args = getArguments();
222 String error = args.getString("error");
224 Logger.debug("new-trans-f", String.format("Got error: %s", error));
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()
237 resources.getString(R.string.err_json_send_error_unsupported));
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);
245 builder.setMessage(message);
250 Snackbar.make(list, error, Snackbar.LENGTH_INDEFINITE)
258 if (savedInstanceState != null) {
259 keep |= savedInstanceState.getBoolean("keep", true);
260 focused = savedInstanceState.getInt("focused", 0);
266 viewModel.setFocusedItem(focused);
269 ProgressBar p = activity.findViewById(R.id.progressBar);
270 viewModel.observeBusyFlag(getViewLifecycleOwner(), isBusy -> {
272 // Handler h = new Handler();
273 // h.postDelayed(() -> {
274 // if (viewModel.getBusyFlag())
275 // p.setVisibility(View.VISIBLE);
278 p.setVisibility(View.VISIBLE);
281 p.setVisibility(View.INVISIBLE);
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);
291 private void onFabPressed() {
293 Misc.hideSoftKeyboard(this);
294 if (mListener != null) {
295 SimpleDate date = viewModel.getDate();
296 LedgerTransaction tr =
297 new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
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()
310 if (acc.isAmountSet()) {
311 emptyAmountAccountBalance += acc.getAmount();
314 emptyAmountAccount = acc;
320 if (emptyAmountAccount != null)
321 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
323 mListener.onTransactionSave(tr);
328 public void onAttach(@NotNull Context context) {
329 super.onAttach(context);
330 if (context instanceof OnNewTransactionFragmentInteractionListener) {
331 mListener = (OnNewTransactionFragmentInteractionListener) context;
334 throw new RuntimeException(
335 context.toString() + " must implement OnFragmentInteractionListener");
340 public void onDetach() {
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
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.
355 public interface OnNewTransactionFragmentInteractionListener {
356 void onTransactionSave(LedgerTransaction tr);