]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/new_transaction/NewTransactionFragment.java
rename Patterns to Templates
[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.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;
34
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;
44
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;
49
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;
64
65 import org.jetbrains.annotations.NotNull;
66
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;
72
73 /**
74  * A simple {@link Fragment} subclass.
75  * Activities that contain this fragment must implement the
76  * {@link OnNewTransactionFragmentInteractionListener} interface
77  * to handle interaction events.
78  */
79
80 // TODO: offer to undo account remove-on-swipe
81
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);
91     }
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);
97     }
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))
104                .create()
105                .show();
106     }
107     protected void onQrScanned(String text) {
108         Logger.debug("qr", String.format("Got QR scan result [%s]", text));
109
110         if (Misc.emptyIsNull(text) == null)
111             return;
112
113         LiveData<List<TemplateHeader>> allPatterns = DB.get()
114                                                        .getPatternDAO()
115                                                        .getTemplates();
116         allPatterns.observe(getViewLifecycleOwner(), patternHeaders -> {
117             ArrayList<TemplateHeader> matchingPatterns = new ArrayList<>();
118
119             for (TemplateHeader ph : patternHeaders) {
120                 String patternSource = ph.getRegularExpression();
121                 if (Misc.emptyIsNull(patternSource) == null)
122                     continue;
123                 try {
124                     Pattern pattern = Pattern.compile(patternSource);
125                     Matcher matcher = pattern.matcher(text);
126                     if (!matcher.matches())
127                         continue;
128
129                     Logger.debug("pattern",
130                             String.format("Pattern '%s' [%s] matches '%s'", ph.getName(),
131                                     patternSource, text));
132                     matchingPatterns.add(ph);
133                 }
134                 catch (ParcelFormatException e) {
135                     // ignored
136                     Logger.debug("pattern",
137                             String.format("Error compiling regular expression '%s'", patternSource),
138                             e);
139                 }
140             }
141
142             if (matchingPatterns.isEmpty())
143                 alertNoPatternMatch(text);
144             else if (matchingPatterns.size() == 1)
145                 applyPattern(matchingPatterns.get(0), text);
146             else
147                 choosePattern(matchingPatterns, text);
148         });
149     }
150     private void choosePattern(ArrayList<TemplateHeader> matchingPatterns, String matchedText) {
151         final String patternNameColumn = "name";
152         AbstractCursor cursor = new AbstractCursor() {
153             @Override
154             public int getCount() {
155                 return matchingPatterns.size();
156             }
157             @Override
158             public String[] getColumnNames() {
159                 return new String[]{"_id", patternNameColumn};
160             }
161             @Override
162             public String getString(int column) {
163                 if (column == 0)
164                     return String.valueOf(getPosition());
165                 return matchingPatterns.get(getPosition())
166                                        .getName();
167             }
168             @Override
169             public short getShort(int column) {
170                 if (column == 0)
171                     return (short) getPosition();
172                 return -1;
173             }
174             @Override
175             public int getInt(int column) {
176                 return getShort(column);
177             }
178             @Override
179             public long getLong(int column) {
180                 return getShort(column);
181             }
182             @Override
183             public float getFloat(int column) {
184                 return getShort(column);
185             }
186             @Override
187             public double getDouble(int column) {
188                 return getShort(column);
189             }
190             @Override
191             public boolean isNull(int column) {
192                 return false;
193             }
194             @Override
195             public int getColumnCount() {
196                 return 2;
197             }
198         };
199
200         MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(requireContext());
201         builder.setCancelable(true)
202                .setTitle(R.string.choose_template_to_apply)
203                .setSingleChoiceItems(cursor, -1, patternNameColumn, (dialog, which) -> {
204                    applyPattern(matchingPatterns.get(which), matchedText);
205                    dialog.dismiss();
206                })
207                .create()
208                .show();
209     }
210     private void applyPattern(TemplateHeader patternHeader, String text) {
211         Pattern pattern = Pattern.compile(patternHeader.getRegularExpression());
212
213         Matcher m = pattern.matcher(text);
214
215         if (!m.matches()) {
216             Snackbar.make(requireView(), R.string.pattern_does_not_match,
217                     BaseTransientBottomBar.LENGTH_INDEFINITE)
218                     .show();
219             return;
220         }
221
222         SimpleDate transactionDate;
223         {
224             int day = extractIntFromMatches(m, patternHeader.getDateDayMatchGroup(),
225                     patternHeader.getDateDay());
226             int month = extractIntFromMatches(m, patternHeader.getDateMonthMatchGroup(),
227                     patternHeader.getDateMonth());
228             int year = extractIntFromMatches(m, patternHeader.getDateYearMatchGroup(),
229                     patternHeader.getDateYear());
230
231             SimpleDate today = SimpleDate.today();
232             if (year <= 0)
233                 year = today.year;
234             if (month <= 0)
235                 month = today.month;
236             if (day <= 0)
237                 day = today.day;
238
239             transactionDate = new SimpleDate(year, month, day);
240
241             Logger.debug("pattern", "setting transaction date to " + transactionDate);
242         }
243
244         NewTransactionModel.Item head = viewModel.getItem(0);
245         head.ensureType(NewTransactionModel.ItemType.generalData);
246         final String transactionDescription =
247                 extractStringFromMatches(m, patternHeader.getTransactionDescriptionMatchGroup(),
248                         patternHeader.getTransactionDescription());
249         head.setDescription(transactionDescription);
250         Logger.debug("pattern", "Setting transaction description to " + transactionDescription);
251         final String transactionComment =
252                 extractStringFromMatches(m, patternHeader.getTransactionCommentMatchGroup(),
253                         patternHeader.getTransactionComment());
254         head.setTransactionComment(transactionComment);
255         Logger.debug("pattern", "Setting transaction comment to " + transactionComment);
256         head.setDate(transactionDate);
257         listAdapter.notifyItemChanged(0);
258
259         DB.get()
260           .getPatternDAO()
261           .getTemplateWithAccounts(patternHeader.getId())
262           .observe(getViewLifecycleOwner(), entry -> {
263               int rowIndex = 0;
264               final boolean accountsInInitialState = viewModel.accountsInInitialState();
265               for (TemplateAccount acc : entry.accounts) {
266                   rowIndex++;
267
268                   String accountName = extractStringFromMatches(m, acc.getAccountNameMatchGroup(),
269                           acc.getAccountName());
270                   String accountComment =
271                           extractStringFromMatches(m, acc.getAccountCommentMatchGroup(),
272                                   acc.getAccountComment());
273                   Float amount =
274                           extractFloatFromMatches(m, acc.getAmountMatchGroup(), acc.getAmount());
275                   if (amount != null && acc.getNegateAmount() != null && acc.getNegateAmount())
276                       amount = -amount;
277
278                   if (accountsInInitialState) {
279                       NewTransactionModel.Item item = viewModel.getItem(rowIndex);
280                       if (item == null) {
281                           Logger.debug("pattern", String.format(Locale.US,
282                                   "Adding new account item [%s][c:%s][a:%s]", accountName,
283                                   accountComment, amount));
284                           final LedgerTransactionAccount ledgerAccount =
285                                   new LedgerTransactionAccount(accountName);
286                           ledgerAccount.setComment(accountComment);
287                           if (amount != null)
288                               ledgerAccount.setAmount(amount);
289                           // TODO currency
290                           viewModel.addAccount(ledgerAccount);
291                           listAdapter.notifyItemInserted(viewModel.items.size() - 1);
292                       }
293                       else {
294                           Logger.debug("pattern", String.format(Locale.US,
295                                   "Stamping account item #%d [%s][c:%s][a:%s]", rowIndex,
296                                   accountName, accountComment, amount));
297
298                           item.setAccountName(accountName);
299                           item.setComment(accountComment);
300                           if (amount != null)
301                               item.getAccount()
302                                   .setAmount(amount);
303
304                           listAdapter.notifyItemChanged(rowIndex);
305                       }
306                   }
307                   else {
308                       final LedgerTransactionAccount transactionAccount =
309                               new LedgerTransactionAccount(accountName);
310                       transactionAccount.setComment(accountComment);
311                       if (amount != null)
312                           transactionAccount.setAmount(amount);
313                       // TODO currency
314                       Logger.debug("pattern", String.format(Locale.US,
315                               "Adding trailing account item [%s][c:%s][a:%s]", accountName,
316                               accountComment, amount));
317
318                       viewModel.addAccount(transactionAccount);
319                       listAdapter.notifyItemInserted(viewModel.items.size() - 1);
320                   }
321               }
322
323               listAdapter.checkTransactionSubmittable();
324           });
325     }
326     private int extractIntFromMatches(Matcher m, Integer group, Integer literal) {
327         if (literal != null)
328             return literal;
329
330         if (group != null) {
331             int grp = group;
332             if (grp > 0 & grp <= m.groupCount())
333                 try {
334                     return Integer.parseInt(m.group(grp));
335                 }
336                 catch (NumberFormatException e) {
337                     Snackbar.make(requireView(),
338                             "Error extracting transaction date: " + e.getMessage(),
339                             BaseTransientBottomBar.LENGTH_INDEFINITE)
340                             .show();
341                 }
342         }
343
344         return 0;
345     }
346     private String extractStringFromMatches(Matcher m, Integer group, String literal) {
347         if (literal != null)
348             return literal;
349
350         if (group != null) {
351             int grp = group;
352             if (grp > 0 & grp <= m.groupCount())
353                 return m.group(grp);
354         }
355
356         return null;
357     }
358     private Float extractFloatFromMatches(Matcher m, Integer group, Float literal) {
359         if (literal != null)
360             return literal;
361
362         if (group != null) {
363             int grp = group;
364             if (grp > 0 & grp <= m.groupCount())
365                 try {
366                     return Float.valueOf(m.group(grp));
367                 }
368                 catch (NumberFormatException e) {
369                     Snackbar.make(requireView(),
370                             "Error extracting transaction amount: " + e.getMessage(),
371                             BaseTransientBottomBar.LENGTH_INDEFINITE)
372                             .show();
373                 }
374         }
375
376         return null;
377     }
378     @Override
379     public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
380         super.onCreateOptionsMenu(menu, inflater);
381         final FragmentActivity activity = getActivity();
382
383         inflater.inflate(R.menu.new_transaction_fragment, menu);
384
385         menu.findItem(R.id.scan_qr)
386             .setOnMenuItemClickListener(this::onScanQrAction);
387
388         menu.findItem(R.id.action_reset_new_transaction_activity)
389             .setOnMenuItemClickListener(item -> {
390                 listAdapter.reset();
391                 return true;
392             });
393
394         final MenuItem toggleCurrencyItem = menu.findItem(R.id.toggle_currency);
395         toggleCurrencyItem.setOnMenuItemClickListener(item -> {
396             viewModel.toggleCurrencyVisible();
397             return true;
398         });
399         if (activity != null)
400             viewModel.showCurrency.observe(activity, toggleCurrencyItem::setChecked);
401
402         final MenuItem toggleCommentsItem = menu.findItem(R.id.toggle_comments);
403         toggleCommentsItem.setOnMenuItemClickListener(item -> {
404             viewModel.toggleShowComments();
405             return true;
406         });
407         if (activity != null)
408             viewModel.showComments.observe(activity, toggleCommentsItem::setChecked);
409     }
410     private boolean onScanQrAction(MenuItem item) {
411         try {
412             scanQrLauncher.launch(null);
413         }
414         catch (Exception e) {
415             Logger.debug("qr", "Error launching QR scanner", e);
416         }
417
418         return true;
419     }
420     @Override
421     public View onCreateView(LayoutInflater inflater, ViewGroup container,
422                              Bundle savedInstanceState) {
423         // Inflate the layout for this fragment
424         return inflater.inflate(R.layout.fragment_new_transaction, container, false);
425     }
426
427     @Override
428     public void onViewCreated(@NotNull View view, @Nullable Bundle savedInstanceState) {
429         super.onViewCreated(view, savedInstanceState);
430         FragmentActivity activity = getActivity();
431         if (activity == null)
432             throw new RSInvalidStateException(
433                     "getActivity() returned null within onActivityCreated()");
434
435         viewModel = new ViewModelProvider(activity).get(NewTransactionModel.class);
436         viewModel.observeDataProfile(this);
437         mProfile = Data.getProfile();
438         listAdapter = new NewTransactionItemsAdapter(viewModel, mProfile);
439
440         RecyclerView list = activity.findViewById(R.id.new_transaction_accounts);
441         list.setAdapter(listAdapter);
442         list.setLayoutManager(new LinearLayoutManager(activity));
443
444         Data.observeProfile(getViewLifecycleOwner(), profile -> {
445             mProfile = profile;
446             listAdapter.setProfile(profile);
447         });
448         listAdapter.notifyDataSetChanged();
449         viewModel.isSubmittable()
450                  .observe(getViewLifecycleOwner(), isSubmittable -> {
451                      if (isSubmittable) {
452                          if (fab != null) {
453                              fab.show();
454                          }
455                      }
456                      else {
457                          if (fab != null) {
458                              fab.hide();
459                          }
460                      }
461                  });
462 //        viewModel.checkTransactionSubmittable(listAdapter);
463
464         fab = activity.findViewById(R.id.fabAdd);
465         fab.setOnClickListener(v -> onFabPressed());
466
467         boolean keep = false;
468
469         Bundle args = getArguments();
470         if (args != null) {
471             String error = args.getString("error");
472             if (error != null) {
473                 Logger.debug("new-trans-f", String.format("Got error: %s", error));
474
475                 Context context = getContext();
476                 if (context != null) {
477                     AlertDialog.Builder builder = new AlertDialog.Builder(context);
478                     final Resources resources = context.getResources();
479                     final StringBuilder message = new StringBuilder();
480                     message.append(resources.getString(R.string.err_json_send_error_head));
481                     message.append("\n\n");
482                     message.append(error);
483                     if (mProfile.getApiVersion()
484                                 .equals(API.auto))
485                         message.append(
486                                 resources.getString(R.string.err_json_send_error_unsupported));
487                     else {
488                         message.append(resources.getString(R.string.err_json_send_error_tail));
489                         builder.setPositiveButton(R.string.btn_profile_options, (dialog, which) -> {
490                             Logger.debug("error", "will start profile editor");
491                             MobileLedgerProfile.startEditProfileActivity(context, mProfile);
492                         });
493                     }
494                     builder.setMessage(message);
495                     builder.create()
496                            .show();
497                 }
498                 else {
499                     Snackbar.make(list, error, Snackbar.LENGTH_INDEFINITE)
500                             .show();
501                 }
502                 keep = true;
503             }
504         }
505
506         int focused = 0;
507         if (savedInstanceState != null) {
508             keep |= savedInstanceState.getBoolean("keep", true);
509             focused = savedInstanceState.getInt("focused", 0);
510         }
511
512         if (!keep)
513             viewModel.reset();
514         else {
515             viewModel.setFocusedItem(focused);
516         }
517
518         ProgressBar p = activity.findViewById(R.id.progressBar);
519         viewModel.observeBusyFlag(getViewLifecycleOwner(), isBusy -> {
520             if (isBusy) {
521 //                Handler h = new Handler();
522 //                h.postDelayed(() -> {
523 //                    if (viewModel.getBusyFlag())
524 //                        p.setVisibility(View.VISIBLE);
525 //
526 //                }, 10);
527                 p.setVisibility(View.VISIBLE);
528             }
529             else
530                 p.setVisibility(View.INVISIBLE);
531         });
532     }
533     @Override
534     public void onSaveInstanceState(@NonNull Bundle outState) {
535         super.onSaveInstanceState(outState);
536         outState.putBoolean("keep", true);
537         final int focusedItem = viewModel.getFocusedItem();
538         outState.putInt("focused", focusedItem);
539     }
540     private void onFabPressed() {
541         fab.hide();
542         Misc.hideSoftKeyboard(this);
543         if (mListener != null) {
544             SimpleDate date = viewModel.getDate();
545             LedgerTransaction tr =
546                     new LedgerTransaction(null, date, viewModel.getDescription(), mProfile);
547
548             tr.setComment(viewModel.getComment());
549             LedgerTransactionAccount emptyAmountAccount = null;
550             float emptyAmountAccountBalance = 0;
551             for (int i = 0; i < viewModel.getAccountCount(); i++) {
552                 LedgerTransactionAccount acc =
553                         new LedgerTransactionAccount(viewModel.getAccount(i));
554                 if (acc.getAccountName()
555                        .trim()
556                        .isEmpty())
557                     continue;
558
559                 if (acc.isAmountSet()) {
560                     emptyAmountAccountBalance += acc.getAmount();
561                 }
562                 else {
563                     emptyAmountAccount = acc;
564                 }
565
566                 tr.addAccount(acc);
567             }
568
569             if (emptyAmountAccount != null)
570                 emptyAmountAccount.setAmount(-emptyAmountAccountBalance);
571
572             mListener.onTransactionSave(tr);
573         }
574     }
575
576     @Override
577     public void onAttach(@NotNull Context context) {
578         super.onAttach(context);
579         if (context instanceof OnNewTransactionFragmentInteractionListener) {
580             mListener = (OnNewTransactionFragmentInteractionListener) context;
581         }
582         else {
583             throw new RuntimeException(
584                     context.toString() + " must implement OnFragmentInteractionListener");
585         }
586     }
587
588     @Override
589     public void onDetach() {
590         super.onDetach();
591         mListener = null;
592     }
593
594     /**
595      * This interface must be implemented by activities that contain this
596      * fragment to allow an interaction in this fragment to be communicated
597      * to the activity and potentially other fragments contained in that
598      * activity.
599      * <p>
600      * See the Android Training lesson <a href=
601      * "http://developer.android.com/training/basics/fragments/communicating.html"
602      * >Communicating with Other Fragments</a> for more information.
603      */
604     public interface OnNewTransactionFragmentInteractionListener {
605         void onTransactionSave(LedgerTransaction tr);
606     }
607 }