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.Intent;
22 import android.content.res.Resources;
23 import android.database.AbstractCursor;
24 import android.os.Bundle;
25 import android.os.ParcelFormatException;
26 import android.renderscript.RSInvalidStateException;
27 import android.view.LayoutInflater;
28 import android.view.Menu;
29 import android.view.MenuInflater;
30 import android.view.MenuItem;
31 import android.view.View;
32 import android.view.ViewGroup;
33 import android.widget.ProgressBar;
35 import androidx.annotation.NonNull;
36 import androidx.annotation.Nullable;
37 import androidx.appcompat.app.AlertDialog;
38 import androidx.fragment.app.Fragment;
39 import androidx.fragment.app.FragmentActivity;
40 import androidx.lifecycle.LiveData;
41 import androidx.lifecycle.ViewModelProvider;
42 import androidx.recyclerview.widget.LinearLayoutManager;
43 import androidx.recyclerview.widget.RecyclerView;
45 import com.google.android.material.dialog.MaterialAlertDialogBuilder;
46 import com.google.android.material.floatingactionbutton.FloatingActionButton;
47 import com.google.android.material.snackbar.BaseTransientBottomBar;
48 import com.google.android.material.snackbar.Snackbar;
50 import net.ktnx.mobileledger.R;
51 import net.ktnx.mobileledger.db.DB;
52 import net.ktnx.mobileledger.db.TemplateAccount;
53 import net.ktnx.mobileledger.db.TemplateHeader;
54 import net.ktnx.mobileledger.json.API;
55 import net.ktnx.mobileledger.model.Data;
56 import net.ktnx.mobileledger.model.LedgerTransaction;
57 import net.ktnx.mobileledger.model.LedgerTransactionAccount;
58 import net.ktnx.mobileledger.model.MobileLedgerProfile;
59 import net.ktnx.mobileledger.ui.QRScanCapableFragment;
60 import net.ktnx.mobileledger.ui.templates.TemplatesActivity;
61 import net.ktnx.mobileledger.utils.Logger;
62 import net.ktnx.mobileledger.utils.Misc;
63 import net.ktnx.mobileledger.utils.SimpleDate;
65 import org.jetbrains.annotations.NotNull;
67 import java.util.ArrayList;
68 import java.util.List;
69 import java.util.Locale;
70 import java.util.regex.Matcher;
71 import java.util.regex.Pattern;
74 * A simple {@link Fragment} subclass.
75 * Activities that contain this fragment must implement the
76 * {@link OnNewTransactionFragmentInteractionListener} interface
77 * to handle interaction events.
80 // TODO: offer to undo account remove-on-swipe
82 public class NewTransactionFragment extends QRScanCapableFragment {
83 private NewTransactionItemsAdapter listAdapter;
84 private NewTransactionModel viewModel;
85 private FloatingActionButton fab;
86 private OnNewTransactionFragmentInteractionListener mListener;
87 private MobileLedgerProfile mProfile;
88 public NewTransactionFragment() {
89 // Required empty public constructor
90 setHasOptionsMenu(true);
92 private void startNewPatternActivity(String scanned) {
93 Intent intent = new Intent(requireContext(), TemplatesActivity.class);
94 Bundle args = new Bundle();
95 args.putString(TemplatesActivity.ARG_ADD_TEMPLATE, scanned);
96 requireContext().startActivity(intent, args);
98 private void alertNoPatternMatch(String scanned) {
99 MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireContext());
100 builder.setCancelable(true)
101 .setMessage(R.string.no_template_matches)
102 .setPositiveButton(R.string.add_button,
103 (dialog, which) -> startNewPatternActivity(scanned))
107 protected void onQrScanned(String text) {
108 Logger.debug("qr", String.format("Got QR scan result [%s]", text));
110 if (Misc.emptyIsNull(text) == null)
113 LiveData<List<TemplateHeader>> allPatterns = DB.get()
116 allPatterns.observe(getViewLifecycleOwner(), patternHeaders -> {
117 ArrayList<TemplateHeader> matchingPatterns = new ArrayList<>();
119 for (TemplateHeader ph : patternHeaders) {
120 String patternSource = ph.getRegularExpression();
121 if (Misc.emptyIsNull(patternSource) == null)
124 Pattern pattern = Pattern.compile(patternSource);
125 Matcher matcher = pattern.matcher(text);
126 if (!matcher.matches())
129 Logger.debug("pattern",
130 String.format("Pattern '%s' [%s] matches '%s'", ph.getName(),
131 patternSource, text));
132 matchingPatterns.add(ph);
134 catch (ParcelFormatException e) {
136 Logger.debug("pattern",
137 String.format("Error compiling regular expression '%s'", patternSource),
142 if (matchingPatterns.isEmpty())
143 alertNoPatternMatch(text);
144 else if (matchingPatterns.size() == 1)
145 applyPattern(matchingPatterns.get(0), text);
147 choosePattern(matchingPatterns, text);
150 private void choosePattern(ArrayList<TemplateHeader> matchingPatterns, String matchedText) {
151 final String patternNameColumn = "name";
152 AbstractCursor cursor = new AbstractCursor() {
154 public int getCount() {
155 return matchingPatterns.size();
158 public String[] getColumnNames() {
159 return new String[]{"_id", patternNameColumn};
162 public String getString(int column) {
164 return String.valueOf(getPosition());
165 return matchingPatterns.get(getPosition())
169 public short getShort(int column) {
171 return (short) getPosition();
175 public int getInt(int column) {
176 return getShort(column);
179 public long getLong(int column) {
180 return getShort(column);
183 public float getFloat(int column) {
184 return getShort(column);
187 public double getDouble(int column) {
188 return getShort(column);
191 public boolean isNull(int column) {
195 public int getColumnCount() {
200 MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireContext());
201 builder.setCancelable(true)
202 .setTitle(R.string.choose_template_to_apply)
203 .setIcon(R.drawable.ic_baseline_auto_graph_24)
204 .setSingleChoiceItems(cursor, -1, patternNameColumn, (dialog, which) -> {
205 applyPattern(matchingPatterns.get(which), matchedText);
211 private void applyPattern(TemplateHeader patternHeader, String text) {
212 Pattern pattern = Pattern.compile(patternHeader.getRegularExpression());
214 Matcher m = pattern.matcher(text);
217 Snackbar.make(requireView(), R.string.pattern_does_not_match,
218 BaseTransientBottomBar.LENGTH_INDEFINITE)
223 SimpleDate transactionDate;
225 int day = extractIntFromMatches(m, patternHeader.getDateDayMatchGroup(),
226 patternHeader.getDateDay());
227 int month = extractIntFromMatches(m, patternHeader.getDateMonthMatchGroup(),
228 patternHeader.getDateMonth());
229 int year = extractIntFromMatches(m, patternHeader.getDateYearMatchGroup(),
230 patternHeader.getDateYear());
232 SimpleDate today = SimpleDate.today();
240 transactionDate = new SimpleDate(year, month, day);
242 Logger.debug("pattern", "setting transaction date to " + transactionDate);
245 NewTransactionModel.Item head = viewModel.getItem(0);
246 head.ensureType(NewTransactionModel.ItemType.generalData);
247 final String transactionDescription =
248 extractStringFromMatches(m, patternHeader.getTransactionDescriptionMatchGroup(),
249 patternHeader.getTransactionDescription());
250 head.setDescription(transactionDescription);
251 Logger.debug("pattern", "Setting transaction description to " + transactionDescription);
252 final String transactionComment =
253 extractStringFromMatches(m, patternHeader.getTransactionCommentMatchGroup(),
254 patternHeader.getTransactionComment());
255 head.setTransactionComment(transactionComment);
256 Logger.debug("pattern", "Setting transaction comment to " + transactionComment);
257 head.setDate(transactionDate);
258 listAdapter.notifyItemChanged(0);
262 .getTemplateWithAccounts(patternHeader.getId())
263 .observe(getViewLifecycleOwner(), entry -> {
265 final boolean accountsInInitialState = viewModel.accountsInInitialState();
266 for (TemplateAccount acc : entry.accounts) {
269 String accountName = extractStringFromMatches(m, acc.getAccountNameMatchGroup(),
270 acc.getAccountName());
271 String accountComment =
272 extractStringFromMatches(m, acc.getAccountCommentMatchGroup(),
273 acc.getAccountComment());
275 extractFloatFromMatches(m, acc.getAmountMatchGroup(), acc.getAmount());
276 if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
279 if (accountsInInitialState) {
280 NewTransactionModel.Item item = viewModel.getItem(rowIndex);
282 Logger.debug("pattern", String.format(Locale.US,
283 "Adding new account item [%s][c:%s][a:%s]", accountName,
284 accountComment, amount));
285 final LedgerTransactionAccount ledgerAccount =
286 new LedgerTransactionAccount(accountName);
287 ledgerAccount.setComment(accountComment);
289 ledgerAccount.setAmount(amount);
291 viewModel.addAccount(ledgerAccount);
292 listAdapter.notifyItemInserted(viewModel.items.size() - 1);
295 Logger.debug("pattern", String.format(Locale.US,
296 "Stamping account item #%d [%s][c:%s][a:%s]", rowIndex,
297 accountName, accountComment, amount));
299 item.setAccountName(accountName);
300 item.setComment(accountComment);
305 listAdapter.notifyItemChanged(rowIndex);
309 final LedgerTransactionAccount transactionAccount =
310 new LedgerTransactionAccount(accountName);
311 transactionAccount.setComment(accountComment);
313 transactionAccount.setAmount(amount);
315 Logger.debug("pattern", String.format(Locale.US,
316 "Adding trailing account item [%s][c:%s][a:%s]", accountName,
317 accountComment, amount));
319 viewModel.addAccount(transactionAccount);
320 listAdapter.notifyItemInserted(viewModel.items.size() - 1);
324 listAdapter.checkTransactionSubmittable();
327 private int extractIntFromMatches(Matcher m, Integer group, Integer literal) {
333 if (grp > 0 & grp <= m.groupCount())
335 return Integer.parseInt(m.group(grp));
337 catch (NumberFormatException e) {
338 Snackbar.make(requireView(),
339 "Error extracting transaction date: " + e.getMessage(),
340 BaseTransientBottomBar.LENGTH_INDEFINITE)
347 private String extractStringFromMatches(Matcher m, Integer group, String literal) {
353 if (grp > 0 & grp <= m.groupCount())
359 private Float extractFloatFromMatches(Matcher m, Integer group, Float literal) {
365 if (grp > 0 & grp <= m.groupCount())
367 return Float.valueOf(m.group(grp));
369 catch (NumberFormatException e) {
370 Snackbar.make(requireView(),
371 "Error extracting transaction amount: " + e.getMessage(),
372 BaseTransientBottomBar.LENGTH_INDEFINITE)
380 public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
381 super.onCreateOptionsMenu(menu, inflater);
382 final FragmentActivity activity = getActivity();
384 inflater.inflate(R.menu.new_transaction_fragment, menu);
386 menu.findItem(R.id.scan_qr)
387 .setOnMenuItemClickListener(this::onScanQrAction);
389 menu.findItem(R.id.action_reset_new_transaction_activity)
390 .setOnMenuItemClickListener(item -> {
395 final MenuItem toggleCurrencyItem = menu.findItem(R.id.toggle_currency);
396 toggleCurrencyItem.setOnMenuItemClickListener(item -> {
397 viewModel.toggleCurrencyVisible();
400 if (activity != null)
401 viewModel.showCurrency.observe(activity, toggleCurrencyItem::setChecked);
403 final MenuItem toggleCommentsItem = menu.findItem(R.id.toggle_comments);
404 toggleCommentsItem.setOnMenuItemClickListener(item -> {
405 viewModel.toggleShowComments();
408 if (activity != null)
409 viewModel.showComments.observe(activity, toggleCommentsItem::setChecked);
411 private boolean onScanQrAction(MenuItem item) {
413 scanQrLauncher.launch(null);
415 catch (Exception e) {
416 Logger.debug("qr", "Error launching QR scanner", e);
422 public View onCreateView(LayoutInflater inflater, ViewGroup container,
423 Bundle savedInstanceState) {
424 // Inflate the layout for this fragment
425 return inflater.inflate(R.layout.fragment_new_transaction, container, false);
429 public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
430 super.onViewCreated(view, savedInstanceState);
431 FragmentActivity activity = getActivity();
432 if (activity == null)
433 throw new RSInvalidStateException(
434 "getActivity() returned null within onActivityCreated()");
436 viewModel = new ViewModelProvider(activity).get(NewTransactionModel.class);
437 viewModel.observeDataProfile(this);
438 mProfile = Data.getProfile();
439 listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
441 RecyclerView list = activity.findViewById(R.id.new_transaction_accounts);
442 list.setAdapter(listAdapter);
443 list.setLayoutManager(new LinearLayoutManager(activity));
445 Data.observeProfile(getViewLifecycleOwner(), profile -> {
447 listAdapter.setProfile(profile);
449 listAdapter.notifyDataSetChanged();
450 viewModel.isSubmittable()
451 .observe(getViewLifecycleOwner(), isSubmittable -> {
463 // viewModel.checkTransactionSubmittable(listAdapter);
465 fab = activity.findViewById(R.id.fabAdd);
466 fab.setOnClickListener(v -> onFabPressed());
468 boolean keep = false;
470 Bundle args = getArguments();
472 String error = args.getString("error");
474 Logger.debug("new-trans-f", String.format("Got error: %s", error));
476 Context context = getContext();
477 if (context != null) {
478 AlertDialog.Builder builder = new AlertDialog.Builder(context);
479 final Resources resources = context.getResources();
480 final StringBuilder message = new StringBuilder();
481 message.append(resources.getString(R.string.err_json_send_error_head));
482 message.append("\n\n");
483 message.append(error);
484 if (mProfile.getApiVersion()
487 resources.getString(R.string.err_json_send_error_unsupported));
489 message.append(resources.getString(R.string.err_json_send_error_tail));
490 builder.setPositiveButton(R.string.btn_profile_options, (dialog, which) -> {
491 Logger.debug("error", "will start profile editor");
492 MobileLedgerProfile.startEditProfileActivity(context, mProfile);
495 builder.setMessage(message);
500 Snackbar.make(list, error, Snackbar.LENGTH_INDEFINITE)
508 if (savedInstanceState != null) {
509 keep |= savedInstanceState.getBoolean("keep", true);
510 focused = savedInstanceState.getInt("focused", 0);
516 viewModel.setFocusedItem(focused);
519 ProgressBar p = activity.findViewById(R.id.progressBar);
520 viewModel.observeBusyFlag(getViewLifecycleOwner(), isBusy -> {
522 // Handler h = new Handler();
523 // h.postDelayed(() -> {
524 // if (viewModel.getBusyFlag())
525 // p.setVisibility(View.VISIBLE);
528 p.setVisibility(View.VISIBLE);
531 p.setVisibility(View.INVISIBLE);
535 public void onSaveInstanceState(@NonNull Bundle outState) {
536 super.onSaveInstanceState(outState);
537 outState.putBoolean("keep", true);
538 final int focusedItem = viewModel.getFocusedItem();
539 outState.putInt("focused", focusedItem);
541 private void onFabPressed() {
543 Misc.hideSoftKeyboard(this);
544 if (mListener != null) {
545 SimpleDate date = viewModel.getDate();
546 LedgerTransaction tr =
547 new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
549 tr.setComment(viewModel.getComment());
550 LedgerTransactionAccount emptyAmountAccount = null;
551 float emptyAmountAccountBalance = 0;
552 for (int i = 0; i < viewModel.getAccountCount(); i++) {
553 LedgerTransactionAccount acc =
554 new LedgerTransactionAccount(viewModel.getAccount(i));
555 if (acc.getAccountName()
560 if (acc.isAmountSet()) {
561 emptyAmountAccountBalance += acc.getAmount();
564 emptyAmountAccount = acc;
570 if (emptyAmountAccount != null)
571 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
573 mListener.onTransactionSave(tr);
578 public void onAttach(@NotNull Context context) {
579 super.onAttach(context);
580 if (context instanceof OnNewTransactionFragmentInteractionListener) {
581 mListener = (OnNewTransactionFragmentInteractionListener) context;
584 throw new RuntimeException(
585 context.toString() + " must implement OnFragmentInteractionListener");
590 public void onDetach() {
596 * This interface must be implemented by activities that contain this
597 * fragment to allow an interaction in this fragment to be communicated
598 * to the activity and potentially other fragments contained in that
601 * See the Android Training lesson <a href=
602 * "http://developer.android.com/training/basics/fragments/communicating.html"
603 * >Communicating with Other Fragments</a> for more information.
605 public interface OnNewTransactionFragmentInteractionListener {
606 void onTransactionSave(LedgerTransaction tr);