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.PatternAccount;
53 import net.ktnx.mobileledger.db.PatternHeader;
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.patterns.PatternsActivity;
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(), PatternsActivity.class);
94 Bundle args = new Bundle();
95 args.putString(PatternsActivity.ARG_ADD_PATTERN, 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_pattern_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<PatternHeader>> allPatterns = DB.get()
116 allPatterns.observe(getViewLifecycleOwner(), patternHeaders -> {
117 ArrayList<PatternHeader> matchingPatterns = new ArrayList<>();
119 for (PatternHeader 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<PatternHeader> matchingPatterns, String matchedText) {
151 final String patternNameColumn = getString(R.string.pattern_name);
152 AbstractCursor cursor = new AbstractCursor() {
154 public int getCount() {
155 return matchingPatterns.size();
158 public String[] getColumnNames() {
159 return new String[]{patternNameColumn};
162 public String getString(int column) {
163 return matchingPatterns.get(getPosition())
167 public short getShort(int column) {
171 public int getInt(int column) {
175 public long getLong(int column) {
179 public float getFloat(int column) {
183 public double getDouble(int column) {
187 public boolean isNull(int column) {
192 MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireContext());
193 builder.setCancelable(true)
194 .setTitle(R.string.choose_pattern_to_apply)
195 .setSingleChoiceItems(cursor, -1, patternNameColumn,
196 (dialog, which) -> applyPattern(matchingPatterns.get(which), matchedText))
200 private void applyPattern(PatternHeader patternHeader, String text) {
201 Pattern pattern = Pattern.compile(patternHeader.getRegularExpression());
203 Matcher m = pattern.matcher(text);
206 Snackbar.make(requireView(), R.string.pattern_does_not_match,
207 BaseTransientBottomBar.LENGTH_INDEFINITE)
212 SimpleDate transactionDate;
214 int day = extractIntFromMatches(m, patternHeader.getDateDayMatchGroup(),
215 patternHeader.getDateDay());
216 int month = extractIntFromMatches(m, patternHeader.getDateMonthMatchGroup(),
217 patternHeader.getDateMonth());
218 int year = extractIntFromMatches(m, patternHeader.getDateYearMatchGroup(),
219 patternHeader.getDateYear());
221 SimpleDate today = SimpleDate.today();
229 transactionDate = new SimpleDate(year, month, day);
231 Logger.debug("pattern", "setting transaction date to " + transactionDate);
234 NewTransactionModel.Item head = viewModel.getItem(0);
235 head.ensureType(NewTransactionModel.ItemType.generalData);
236 final String transactionDescription =
237 extractStringFromMatches(m, patternHeader.getTransactionDescriptionMatchGroup(),
238 patternHeader.getTransactionDescription());
239 head.setDescription(transactionDescription);
240 Logger.debug("pattern", "Setting transaction description to " + transactionDescription);
241 final String transactionComment =
242 extractStringFromMatches(m, patternHeader.getTransactionCommentMatchGroup(),
243 patternHeader.getTransactionComment());
244 head.setTransactionComment(transactionComment);
245 Logger.debug("pattern", "Setting transaction comment to " + transactionComment);
246 head.setDate(transactionDate);
247 listAdapter.notifyItemChanged(0);
251 .getPatternWithAccounts(patternHeader.getId())
252 .observe(getViewLifecycleOwner(), entry -> {
254 final boolean accountsInInitialState = viewModel.accountsInInitialState();
255 for (PatternAccount acc : entry.accounts) {
258 String accountName = extractStringFromMatches(m, acc.getAccountNameMatchGroup(),
259 acc.getAccountName());
260 String accountComment =
261 extractStringFromMatches(m, acc.getAccountCommentMatchGroup(),
262 acc.getAccountComment());
264 extractFloatFromMatches(m, acc.getAmountMatchGroup(), acc.getAmount());
266 if (accountsInInitialState) {
267 NewTransactionModel.Item item = viewModel.getItem(rowIndex);
269 Logger.debug("pattern", String.format(Locale.US,
270 "Adding new account item [%s][c:%s][a:%s]", accountName,
271 accountComment, amount));
272 final LedgerTransactionAccount ledgerAccount =
273 new LedgerTransactionAccount(accountName);
274 ledgerAccount.setComment(accountComment);
276 ledgerAccount.setAmount(amount);
278 viewModel.addAccount(ledgerAccount);
279 listAdapter.notifyItemInserted(viewModel.items.size() - 1);
282 Logger.debug("pattern", String.format(Locale.US,
283 "Stamping account item #%d [%s][c:%s][a:%s]", rowIndex,
284 accountName, accountComment, amount));
286 item.setAccountName(accountName);
287 item.setComment(accountComment);
292 listAdapter.notifyItemChanged(rowIndex);
296 final LedgerTransactionAccount transactionAccount =
297 new LedgerTransactionAccount(accountName);
298 transactionAccount.setComment(accountComment);
300 transactionAccount.setAmount(amount);
302 Logger.debug("pattern", String.format(Locale.US,
303 "Adding trailing account item [%s][c:%s][a:%s]", accountName,
304 accountComment, amount));
306 viewModel.addAccount(transactionAccount);
307 listAdapter.notifyItemInserted(viewModel.items.size() - 1);
311 listAdapter.checkTransactionSubmittable();
314 private int extractIntFromMatches(Matcher m, Integer group, Integer literal) {
320 if (grp > 0 & grp <= m.groupCount())
322 return Integer.parseInt(m.group(grp));
324 catch (NumberFormatException e) {
325 Snackbar.make(requireView(),
326 "Error extracting transaction date: " + e.getMessage(),
327 BaseTransientBottomBar.LENGTH_INDEFINITE)
334 private String extractStringFromMatches(Matcher m, Integer group, String literal) {
340 if (grp > 0 & grp <= m.groupCount())
346 private Float extractFloatFromMatches(Matcher m, Integer group, Float literal) {
352 if (grp > 0 & grp <= m.groupCount())
354 return Float.valueOf(m.group(grp));
356 catch (NumberFormatException e) {
357 Snackbar.make(requireView(),
358 "Error extracting transaction amount: " + e.getMessage(),
359 BaseTransientBottomBar.LENGTH_INDEFINITE)
367 public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
368 super.onCreateOptionsMenu(menu, inflater);
369 final FragmentActivity activity = getActivity();
371 inflater.inflate(R.menu.new_transaction_fragment, menu);
373 menu.findItem(R.id.scan_qr)
374 .setOnMenuItemClickListener(this::onScanQrAction);
376 menu.findItem(R.id.action_reset_new_transaction_activity)
377 .setOnMenuItemClickListener(item -> {
382 final MenuItem toggleCurrencyItem = menu.findItem(R.id.toggle_currency);
383 toggleCurrencyItem.setOnMenuItemClickListener(item -> {
384 viewModel.toggleCurrencyVisible();
387 if (activity != null)
388 viewModel.showCurrency.observe(activity, toggleCurrencyItem::setChecked);
390 final MenuItem toggleCommentsItem = menu.findItem(R.id.toggle_comments);
391 toggleCommentsItem.setOnMenuItemClickListener(item -> {
392 viewModel.toggleShowComments();
395 if (activity != null)
396 viewModel.showComments.observe(activity, toggleCommentsItem::setChecked);
398 private boolean onScanQrAction(MenuItem item) {
400 scanQrLauncher.launch(null);
402 catch (Exception e) {
403 Logger.debug("qr", "Error launching QR scanner", e);
409 public View onCreateView(LayoutInflater inflater, ViewGroup container,
410 Bundle savedInstanceState) {
411 // Inflate the layout for this fragment
412 return inflater.inflate(R.layout.fragment_new_transaction, container, false);
416 public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
417 super.onViewCreated(view, savedInstanceState);
418 FragmentActivity activity = getActivity();
419 if (activity == null)
420 throw new RSInvalidStateException(
421 "getActivity() returned null within onActivityCreated()");
423 viewModel = new ViewModelProvider(activity).get(NewTransactionModel.class);
424 viewModel.observeDataProfile(this);
425 mProfile = Data.getProfile();
426 listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
428 RecyclerView list = activity.findViewById(R.id.new_transaction_accounts);
429 list.setAdapter(listAdapter);
430 list.setLayoutManager(new LinearLayoutManager(activity));
432 Data.observeProfile(getViewLifecycleOwner(), profile -> {
434 listAdapter.setProfile(profile);
436 listAdapter.notifyDataSetChanged();
437 viewModel.isSubmittable()
438 .observe(getViewLifecycleOwner(), isSubmittable -> {
450 // viewModel.checkTransactionSubmittable(listAdapter);
452 fab = activity.findViewById(R.id.fabAdd);
453 fab.setOnClickListener(v -> onFabPressed());
455 boolean keep = false;
457 Bundle args = getArguments();
459 String error = args.getString("error");
461 Logger.debug("new-trans-f", String.format("Got error: %s", error));
463 Context context = getContext();
464 if (context != null) {
465 AlertDialog.Builder builder = new AlertDialog.Builder(context);
466 final Resources resources = context.getResources();
467 final StringBuilder message = new StringBuilder();
468 message.append(resources.getString(R.string.err_json_send_error_head));
469 message.append("\n\n");
470 message.append(error);
471 if (mProfile.getApiVersion()
474 resources.getString(R.string.err_json_send_error_unsupported));
476 message.append(resources.getString(R.string.err_json_send_error_tail));
477 builder.setPositiveButton(R.string.btn_profile_options, (dialog, which) -> {
478 Logger.debug("error", "will start profile editor");
479 MobileLedgerProfile.startEditProfileActivity(context, mProfile);
482 builder.setMessage(message);
487 Snackbar.make(list, error, Snackbar.LENGTH_INDEFINITE)
495 if (savedInstanceState != null) {
496 keep |= savedInstanceState.getBoolean("keep", true);
497 focused = savedInstanceState.getInt("focused", 0);
503 viewModel.setFocusedItem(focused);
506 ProgressBar p = activity.findViewById(R.id.progressBar);
507 viewModel.observeBusyFlag(getViewLifecycleOwner(), isBusy -> {
509 // Handler h = new Handler();
510 // h.postDelayed(() -> {
511 // if (viewModel.getBusyFlag())
512 // p.setVisibility(View.VISIBLE);
515 p.setVisibility(View.VISIBLE);
518 p.setVisibility(View.INVISIBLE);
522 public void onSaveInstanceState(@NonNull Bundle outState) {
523 super.onSaveInstanceState(outState);
524 outState.putBoolean("keep", true);
525 final int focusedItem = viewModel.getFocusedItem();
526 outState.putInt("focused", focusedItem);
528 private void onFabPressed() {
530 Misc.hideSoftKeyboard(this);
531 if (mListener != null) {
532 SimpleDate date = viewModel.getDate();
533 LedgerTransaction tr =
534 new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
536 tr.setComment(viewModel.getComment());
537 LedgerTransactionAccount emptyAmountAccount = null;
538 float emptyAmountAccountBalance = 0;
539 for (int i = 0; i < viewModel.getAccountCount(); i++) {
540 LedgerTransactionAccount acc =
541 new LedgerTransactionAccount(viewModel.getAccount(i));
542 if (acc.getAccountName()
547 if (acc.isAmountSet()) {
548 emptyAmountAccountBalance += acc.getAmount();
551 emptyAmountAccount = acc;
557 if (emptyAmountAccount != null)
558 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
560 mListener.onTransactionSave(tr);
565 public void onAttach(@NotNull Context context) {
566 super.onAttach(context);
567 if (context instanceof OnNewTransactionFragmentInteractionListener) {
568 mListener = (OnNewTransactionFragmentInteractionListener) context;
571 throw new RuntimeException(
572 context.toString() + " must implement OnFragmentInteractionListener");
577 public void onDetach() {
583 * This interface must be implemented by activities that contain this
584 * fragment to allow an interaction in this fragment to be communicated
585 * to the activity and potentially other fragments contained in that
588 * See the Android Training lesson <a href=
589 * "http://developer.android.com/training/basics/fragments/communicating.html"
590 * >Communicating with Other Fragments</a> for more information.
592 public interface OnNewTransactionFragmentInteractionListener {
593 void onTransactionSave(LedgerTransaction tr);