From 9f7a3b263b63076e676d541ff84eed6e587d72df Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Laur=C3=A9line=20Gu=C3=A9rin?= <zebuline@entrouvert.com>
Date: Thu, 28 Jul 2022 11:36:04 +0200
Subject: [PATCH 10/14] pricing: add an agenda selector in test tool (#67675)

---
 lingo/pricing/forms.py                        | 18 +++++++--------
 .../manager_agenda_pricing_detail.html        | 20 ++++++++--------
 tests/pricing/manager/test_agenda_pricing.py  | 23 ++++++++-----------
 3 files changed, 27 insertions(+), 34 deletions(-)

diff --git a/lingo/pricing/forms.py b/lingo/pricing/forms.py
index 786f333..b6ec1ed 100644
--- a/lingo/pricing/forms.py
+++ b/lingo/pricing/forms.py
@@ -287,6 +287,7 @@ class PricingMatrixForm(forms.Form):
 
 
 class PricingTestToolForm(forms.Form):
+    agenda = forms.ModelChoiceField(label=_('Agenda'), empty_label=None, queryset=Agenda.objects.none())
     event_slug = forms.CharField(label=_('Event identifier'))
     user_external_id = forms.CharField(label=_('User external identifier'))
     adult_external_id = forms.CharField(label=_('Adult external identifier'))
@@ -296,13 +297,14 @@ class PricingTestToolForm(forms.Form):
         self.request = kwargs.pop('request')
         self.agenda_pricing = kwargs.pop('agenda_pricing')
         self.agenda = None
-        if kwargs['data'] and kwargs['data'].get('event_slug'):
-            self.init_agenda(kwargs['data']['event_slug'])
+        if kwargs['data'] and kwargs['data'].get('agenda'):
+            self.init_agenda(kwargs['data']['agenda'])
         self.serialized_event = None
         self.serialized_subscription = None
         self.check_type_slug = None
         self.booking_status = None
         super().__init__(*args, **kwargs)
+        self.fields['agenda'].queryset = self.agenda_pricing.agendas.all()
         presence_check_types = (
             self.agenda.check_type_group.check_types.presences()
             if self.agenda and self.agenda.check_type_group
@@ -325,22 +327,18 @@ class PricingTestToolForm(forms.Form):
         ]
         self.fields['booking_status'].choices = status_choices
 
-    def init_agenda(self, event_slug):
-        agenda_slug = event_slug.split('@')[0]
+    def init_agenda(self, agenda_id):
         try:
-            self.agenda = self.agenda_pricing.agendas.get(slug=agenda_slug)
+            self.agenda = self.agenda_pricing.agendas.get(pk=agenda_id)
         except Agenda.DoesNotExist:
             pass
 
     def clean_event_slug(self):
         event_slug = self.cleaned_data['event_slug']
-        if '@' not in event_slug:
-            raise ValidationError(_('Missing agenda identifier'))
-        agenda_slug = event_slug.split('@')[0]
         if not self.agenda:
-            raise ValidationError(_('The agenda identifier is wrong (%s)') % agenda_slug)
+            return event_slug
         try:
-            self.serialized_event = get_event(event_slug)
+            self.serialized_event = get_event('%s@%s' % (self.agenda.slug, event_slug))
         except ChronoError as e:
             raise forms.ValidationError(e)
 
diff --git a/lingo/pricing/templates/lingo/pricing/manager_agenda_pricing_detail.html b/lingo/pricing/templates/lingo/pricing/manager_agenda_pricing_detail.html
index 1feff4b..8cdd647 100644
--- a/lingo/pricing/templates/lingo/pricing/manager_agenda_pricing_detail.html
+++ b/lingo/pricing/templates/lingo/pricing/manager_agenda_pricing_detail.html
@@ -79,29 +79,29 @@
             var presences = {};
             var absences = {};
             {% for agenda in agendas %}
-              presences['{{ agenda.slug }}'] = [];
-              absences['{{ agenda.slug }}'] = [];
+              presences['{{ agenda.pk }}'] = [];
+              absences['{{ agenda.pk }}'] = [];
               {% for check_type in agenda.check_type_group.check_types.all %}
                 {% if check_type.kind == "presence" %}
-                  presences['{{ agenda.slug }}'].push({slug: '{{ check_type.slug }}', label: '{{ check_type.label }}'});
+                  presences['{{ agenda.pk }}'].push({slug: '{{ check_type.slug }}', label: '{{ check_type.label }}'});
                 {% else %}
-                  absences['{{ agenda.slug }}'].push({slug: '{{ check_type.slug }}', label: '{{ check_type.label }}'});
+                  absences['{{ agenda.pk }}'].push({slug: '{{ check_type.slug }}', label: '{{ check_type.label }}'});
                 {% endif %}
               {% endfor %}
             {% endfor %}
-            $('#id_event_slug').on('change', function() {
-              var agenda_slug = $(this).val().split('@')[0];
+            $('#id_agenda').on('change', function() {
+              var agenda_id = $(this).val();
               var $select = $('#id_booking_status');
               var current_value = $select.val();
               $select.find('option').remove().end().append('<option value="presence">' + '{% trans "Presence" %}' + '</option>');
-              if (presences[agenda_slug]) {
-                $.each(presences[agenda_slug], function(index, value) {
+              if (presences[agenda_id]) {
+                $.each(presences[agenda_id], function(index, value) {
                   $select.append('<option value="presence::' + value.slug + '">' + '{% trans "Presence" %} (' + value.label + ')</option>');
                 });
               }
               $select.append('<option value="absence">' + '{% trans "Absence" %}' + '</option>');
-              if (absences[agenda_slug]) {
-                $.each(absences[agenda_slug], function(index, value) {
+              if (absences[agenda_id]) {
+                $.each(absences[agenda_id], function(index, value) {
                   $select.append('<option value="absence::' + value.slug + '">' + '{% trans "Absence" %} (' + value.label + ')</option>');
                 });
               }
diff --git a/tests/pricing/manager/test_agenda_pricing.py b/tests/pricing/manager/test_agenda_pricing.py
index 8c2865a..0aa62f2 100644
--- a/tests/pricing/manager/test_agenda_pricing.py
+++ b/tests/pricing/manager/test_agenda_pricing.py
@@ -840,7 +840,8 @@ def test_detail_agenda_pricing_test_tool(
 
     # check event date
     mock_event.return_value = {'start_datetime': '2021-08-31T12:00:00+02:00'}
-    resp.form['event_slug'] = 'foo-bar@foo'
+    resp.form['agenda'] = agenda.pk
+    resp.form['event_slug'] = 'foo'
     resp.form['user_external_id'] = 'user:1'
     resp.form['adult_external_id'] = 'adult:1'
     resp.form['booking_status'] = 'presence'
@@ -859,18 +860,9 @@ def test_detail_agenda_pricing_test_tool(
 
     mock_event.return_value = {'start_datetime': '2021-09-01T12:00:00+02:00'}
 
-    # check event_slug & agenda
-    resp.form['event_slug'] = 'foo'
-    resp = resp.form.submit().follow()
-    assert resp.context['test_tool_form'].errors['event_slug'] == ['Missing agenda identifier']
-    resp.form['event_slug'] = 'foo@foo'
-    resp = resp.form.submit().follow()
-    assert resp.context['test_tool_form'].errors['event_slug'] == ['The agenda identifier is wrong (foo)']
-
     # check subscriptions dates
     mock_subscriptions.return_value = []
     mock_event.reset_mock()
-    resp.form['event_slug'] = 'foo-bar@foo'
     resp = resp.form.submit().follow()
     assert mock_pricing_data_event.call_args_list == []
     assert 'Computed pricing data' not in resp
@@ -944,16 +936,17 @@ def test_detail_agenda_pricing_test_tool_event_error(mock_subscriptions, mock_ev
     )
     agenda_pricing.agendas.add(agenda)
 
-    mock_event.side_effect = ChronoError('foo bar foo-bar@foo-event')
+    mock_event.side_effect = ChronoError('foo bar foo-event')
 
     app = login(app)
     resp = app.get('/manage/pricing/agenda-pricing/%s/' % agenda_pricing.pk)
-    resp.form['event_slug'] = 'foo-bar@foo-event'
+    resp.form['agenda'] = agenda.pk
+    resp.form['event_slug'] = 'foo-event'
     resp.form['user_external_id'] = 'user:1'
     resp.form['adult_external_id'] = 'adult:1'
     resp.form['booking_status'] = 'presence'
     resp = resp.form.submit().follow()
-    assert resp.context['test_tool_form'].errors['event_slug'] == ['foo bar foo-bar@foo-event']
+    assert resp.context['test_tool_form'].errors['event_slug'] == ['foo bar foo-event']
 
 
 @mock.patch('lingo.pricing.forms.get_event')
@@ -973,6 +966,7 @@ def test_detail_agenda_pricing_test_tool_subscription_error(mock_subscriptions,
 
     app = login(app)
     resp = app.get('/manage/pricing/agenda-pricing/%s/' % agenda_pricing.pk)
+    resp.form['agenda'] = agenda.pk
     resp.form['event_slug'] = 'foo-bar@foo-event'
     resp.form['user_external_id'] = 'user:1'
     resp.form['adult_external_id'] = 'adult:1'
@@ -1022,7 +1016,8 @@ def test_detail_agenda_pricing_test_tool_booking_status(
         ('presence', False, 'Presence'),
         ('absence', False, 'Absence'),
     ]
-    resp.form['event_slug'] = 'foo-bar@foo'
+    resp.form['agenda'] = agenda.pk
+    resp.form['event_slug'] = 'foo'
     resp.form['user_external_id'] = 'user:1'
     resp.form['adult_external_id'] = 'adult:1'
     resp.form['booking_status'] = 'presence'
-- 
2.35.1

