From e9fb6da550038e2843cfb9c18ec817279da02dc8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Laur=C3=A9line=20Gu=C3=A9rin?= <zebuline@entrouvert.com>
Date: Fri, 1 Oct 2021 15:30:09 +0200
Subject: [PATCH 1/2] lingo: filter transaction list by regie (#56651)

---
 combo/apps/lingo/forms.py                     |  9 +++++
 combo/apps/lingo/manager_views.py             | 11 +++++-
 .../templates/lingo/transaction_list.html     | 13 +++----
 tests/test_lingo_manager.py                   | 39 +++++++++++++++++--
 4 files changed, 58 insertions(+), 14 deletions(-)

diff --git a/combo/apps/lingo/forms.py b/combo/apps/lingo/forms.py
index 51d6f17d..ec2af936 100644
--- a/combo/apps/lingo/forms.py
+++ b/combo/apps/lingo/forms.py
@@ -152,3 +152,12 @@ class TransactionExportForm(forms.Form):
         today = datetime.date.today()
         self.initial['start_date'] = today - datetime.timedelta(days=30)
         self.initial['end_date'] = today
+
+
+class TransactionSearchForm(forms.Form):
+    regie = forms.ModelChoiceField(queryset=Regie.objects.none(), empty_label=_('All regies'), required=False)
+    q = forms.CharField(required=False)
+
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+        self.fields['regie'].queryset = Regie.objects.all()
diff --git a/combo/apps/lingo/manager_views.py b/combo/apps/lingo/manager_views.py
index 84498f1a..4afb3e74 100644
--- a/combo/apps/lingo/manager_views.py
+++ b/combo/apps/lingo/manager_views.py
@@ -30,7 +30,7 @@ from django.utils.timezone import make_aware, now
 from django.utils.translation import ugettext_lazy as _
 from django.views.generic import CreateView, DeleteView, ListView, UpdateView, View
 
-from .forms import PaymentBackendForm, RegieForm, TransactionExportForm
+from .forms import PaymentBackendForm, RegieForm, TransactionExportForm, TransactionSearchForm
 from .models import BasketItem, PaymentBackend, Regie, Transaction
 
 
@@ -96,16 +96,23 @@ class TransactionListView(ListView):
     def get_context_data(self, **kwargs):
         context = super().get_context_data(**kwargs)
         context['query'] = self.request.GET.get('q') or ''
+        context['form'] = self.form
         return context
 
     def get_queryset(self):
+        self.form = TransactionSearchForm(data=self.request.GET)
         qs = (
             Transaction.objects.select_related('user')
             .prefetch_related(Prefetch('items', to_attr='prefetched_items'))
             .filter(status__in=(eopayment.PAID, eopayment.ACCEPTED))
             .order_by('-start_date')
         )
-        query = self.request.GET.get('q')
+        query, regie = None, None
+        if self.form.is_valid():
+            query = self.form.cleaned_data['q']
+            regie = self.form.cleaned_data['regie']
+        if regie:
+            qs = qs.filter(regie=regie)
         if query:
             try:
                 date = date_parser.parse(query, dayfirst=True)
diff --git a/combo/apps/lingo/templates/lingo/transaction_list.html b/combo/apps/lingo/templates/lingo/transaction_list.html
index e4eeaa5c..f614d236 100644
--- a/combo/apps/lingo/templates/lingo/transaction_list.html
+++ b/combo/apps/lingo/templates/lingo/transaction_list.html
@@ -14,7 +14,8 @@
 {% block content %}
 
 <form>
-  <p><input name="q" type="search" value="{{query}}"> <button>{% trans 'Search' %}</button>
+  <p>
+  {{ form.regie }} <input name="q" type="search" value="{{ form.cleaned_data.q }}"> <button>{% trans 'Search' %}</button>
   <span class="help_text">{% trans "(supports order identifiers, transaction identifiers, and dates)" %}</span>
   </p>
 </form>
@@ -55,14 +56,10 @@
 
 {% else %}
 <div class="big-msg-info">
-  {% if query %}
-  {% blocktrans %}
-  No transactions found matching "{{query}}".
-  {% endblocktrans %}
+  {% if form.cleaned_data.q or form.cleaned_data.regie %}
+  {% trans "No transactions found matching the current search." %}
   {% else %}
-  {% blocktrans %}
-  This site doesn't have any transaction yet.
-  {% endblocktrans %}
+  {% trans "This site doesn't have any transaction yet." %}
   {% endif %}
 </div>
 {% endif %}
diff --git a/tests/test_lingo_manager.py b/tests/test_lingo_manager.py
index be2f5b54..f5a7e213 100644
--- a/tests/test_lingo_manager.py
+++ b/tests/test_lingo_manager.py
@@ -27,6 +27,11 @@ def payment_backend():
     return PaymentBackend.objects.create(label='test1', slug='test1', service='dummy', service_options={})
 
 
+@pytest.fixture
+def regie(payment_backend):
+    return Regie.objects.create(label='Test', slug='test', payment_backend=payment_backend)
+
+
 def login(app, username='admin', password='admin'):
     login_page = app.get('/login/')
     login_form = login_page.forms[0]
@@ -235,20 +240,26 @@ def test_download_transaction(app, admin_user, payment_backend):
     assert Decimal(row[6]) == b_item.amount
 
 
-def test_transactions_search(app, admin_user):
+def test_transactions_search(app, admin_user, payment_backend, regie):
+    regie2 = Regie.objects.create(label='Test-2', slug='regie-2', payment_backend=payment_backend)
     for i in range(50):
-        Transaction(
+        transaction = Transaction(
             status=eopayment.PAID,
             order_id='order id %s' % (i + 1),
             bank_transaction_id='bank id %s' % (i + 1),
             amount=1 + i,
-        ).save()
+        )
+        if i % 3 == 0:
+            transaction.regie = regie
+        elif i % 3 == 1:
+            transaction.regie = regie2
+        transaction.save()
 
     app = login(app)
     with CaptureQueriesContext(connection) as ctx:
         resp = app.get('/manage/lingo/', status=200)
     assert resp.text.count('<tr') == 11
-    assert len(ctx.captured_queries) == 5
+    assert len(ctx.captured_queries) == 6
 
     resp.form['q'] = 'order id 16'
     resp = resp.form.submit()
@@ -263,6 +274,26 @@ def test_transactions_search(app, admin_user):
     assert resp.text.count('<tr') == 0
     assert 'No transactions found matching' in resp.text
 
+    resp.form['q'] = ''
+    resp.form['regie'] = regie.pk
+    resp = resp.form.submit()
+    assert resp.text.count('<tr') == 11
+
+    resp.form['q'] = ''
+    resp.form['regie'] = regie2.pk
+    resp = resp.form.submit()
+    assert resp.text.count('<tr') == 11
+
+    resp.form['q'] = 'order id 5'
+    resp.form['regie'] = regie.pk
+    resp = resp.form.submit()
+    assert resp.text.count('<tr') == 0
+
+    resp.form['q'] = 'order id 5'
+    resp.form['regie'] = regie2.pk
+    resp = resp.form.submit()
+    assert resp.text.count('<tr') == 2
+
 
 def test_basketitem_error_list(app, admin_user, payment_backend):
     regie = Regie.objects.create(label='test-regie', slug='test-regie', payment_backend=payment_backend)
-- 
2.33.0

