From 9994e96c84e74ebc8413ef6f0e5ecb08df3b72e3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Laur=C3=A9line=20Gu=C3=A9rin?= <zebuline@entrouvert.com>
Date: Fri, 16 Apr 2021 10:11:58 +0200
Subject: [PATCH 1/2] api: booking, user_name and first/last_name (#53172)

---
 .../migrations/0079_booking_user_name.py      | 21 +++++++
 chrono/agendas/models.py                      | 10 ++-
 chrono/api/views.py                           |  7 ++-
 chrono/manager/views.py                       |  4 +-
 tests/manager/test_all.py                     |  6 +-
 tests/manager/test_event.py                   | 24 ++++----
 tests/test_agendas.py                         |  6 +-
 tests/test_api.py                             | 61 +++++++++++++------
 8 files changed, 100 insertions(+), 39 deletions(-)
 create mode 100644 chrono/agendas/migrations/0079_booking_user_name.py

diff --git a/chrono/agendas/migrations/0079_booking_user_name.py b/chrono/agendas/migrations/0079_booking_user_name.py
new file mode 100644
index 0000000..6683066
--- /dev/null
+++ b/chrono/agendas/migrations/0079_booking_user_name.py
@@ -0,0 +1,21 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+        ('agendas', '0078_absence_reasons'),
+    ]
+
+    operations = [
+        migrations.RenameField(
+            model_name='booking',
+            old_name='user_name',
+            new_name='user_last_name',
+        ),
+        migrations.AddField(
+            model_name='booking',
+            name='user_first_name',
+            field=models.CharField(blank=True, max_length=250),
+        ),
+    ]
diff --git a/chrono/agendas/models.py b/chrono/agendas/models.py
index 81b0888..2fda6dc 100644
--- a/chrono/agendas/models.py
+++ b/chrono/agendas/models.py
@@ -1509,7 +1509,8 @@ class Booking(models.Model):
         verbose_name=_('Label displayed to user'), max_length=250, blank=True
     )
     user_external_id = models.CharField(max_length=250, blank=True)
-    user_name = models.CharField(max_length=250, blank=True)
+    user_last_name = models.CharField(max_length=250, blank=True)
+    user_first_name = models.CharField(max_length=250, blank=True)
     user_email = models.EmailField(blank=True)
     user_phone_number = models.CharField(max_length=16, blank=True)
     user_was_present = models.NullBooleanField()
@@ -1520,6 +1521,10 @@ class Booking(models.Model):
     cancel_callback_url = models.URLField(blank=True)
     color = models.ForeignKey(BookingColor, null=True, on_delete=models.SET_NULL, related_name='bookings')
 
+    @property
+    def user_name(self):
+        return ('%s %s' % (self.user_first_name.strip(), self.user_last_name.strip())).strip()
+
     def save(self, *args, **kwargs):
         with transaction.atomic():
             super(Booking, self).save(*args, **kwargs)
@@ -1556,7 +1561,8 @@ class Booking(models.Model):
             label='',
             user_display_label='',
             user_external_id='',
-            user_name='',
+            user_last_name='',
+            user_first_name='',
             extra_data={},
             anonymization_datetime=now(),
         )
diff --git a/chrono/api/views.py b/chrono/api/views.py
index e11bca7..79dc09e 100644
--- a/chrono/api/views.py
+++ b/chrono/api/views.py
@@ -852,7 +852,9 @@ class SlotSerializer(serializers.Serializer):
 
     label = serializers.CharField(max_length=250, allow_blank=True)
     user_external_id = serializers.CharField(max_length=250, allow_blank=True)
-    user_name = serializers.CharField(max_length=250, allow_blank=True)
+    user_name = serializers.CharField(max_length=250, allow_blank=True)  # compatibility
+    user_first_name = serializers.CharField(max_length=250, allow_blank=True)
+    user_last_name = serializers.CharField(max_length=250, allow_blank=True)
     user_display_label = serializers.CharField(max_length=250, allow_blank=True)
     user_email = serializers.CharField(max_length=250, allow_blank=True)
     user_phone_number = serializers.CharField(max_length=16, allow_blank=True)
@@ -1197,7 +1199,8 @@ class Fillslots(APIView):
                         in_waiting_list=in_waiting_list,
                         label=payload.get('label', ''),
                         user_external_id=payload.get('user_external_id', ''),
-                        user_name=payload.get('user_name', ''),
+                        user_first_name=payload.get('user_first_name', ''),
+                        user_last_name=payload.get('user_last_name') or payload.get('user_name') or '',
                         user_email=payload.get('user_email', ''),
                         user_phone_number=payload.get('user_phone_number', ''),
                         form_url=payload.get('form_url', ''),
diff --git a/chrono/manager/views.py b/chrono/manager/views.py
index 0275b09..bb001e7 100644
--- a/chrono/manager/views.py
+++ b/chrono/manager/views.py
@@ -1949,10 +1949,10 @@ class EventCheckView(ViewableAgendaMixin, DetailView):
         event = self.object
         context['booked'] = event.booking_set.filter(
             cancellation_datetime__isnull=True, in_waiting_list=False
-        ).order_by('user_name')
+        ).order_by('user_last_name', 'user_first_name')
         context['waiting'] = event.booking_set.filter(
             cancellation_datetime__isnull=True, in_waiting_list=True
-        ).order_by('user_name')
+        ).order_by('user_last_name', 'user_first_name')
         for booking in context['booked']:
             booking.form = BookingAbsenceReasonForm(
                 agenda=self.agenda, initial={'reason': booking.user_absence_reason}
diff --git a/tests/manager/test_all.py b/tests/manager/test_all.py
index 1f85d90..78bcd75 100644
--- a/tests/manager/test_all.py
+++ b/tests/manager/test_all.py
@@ -3195,10 +3195,12 @@ def test_agenda_view_event(app, manager_user):
             booking.creation_datetime = make_aware(datetime.datetime(2019, 12, 21, 14, 0 + i))
         if i == 5:
             booking.creation_datetime = make_aware(datetime.datetime(2019, 12, 21, 15, 0))
-            booking.user_name = 'Foo Bar User'
+            booking.user_first_name = 'Foo Bar'
+            booking.user_last_name = 'User'
         if i == 6:
             booking.creation_datetime = make_aware(datetime.datetime(2019, 12, 21, 16, 0))
-            booking.user_name = 'Foo Bar User 2'
+            booking.user_first_name = 'Foo Bar'
+            booking.user_last_name = 'User 2'
             booking.label = 'Foo Bar Label 2'
         if i == 7:
             booking.creation_datetime = make_aware(datetime.datetime(2019, 12, 21, 17, 0))
diff --git a/tests/manager/test_event.py b/tests/manager/test_event.py
index 4ff1b45..42b4486 100644
--- a/tests/manager/test_event.py
+++ b/tests/manager/test_event.py
@@ -1062,14 +1062,16 @@ def test_event_check(app, admin_user):
         waiting_list_places=5,
         agenda=agenda,
     )
-    booking1 = Booking.objects.create(event=event, user_name='User 42')
-    Booking.objects.create(event=event, user_name='User 1')
-    Booking.objects.create(event=event, user_name='User 17')
-    Booking.objects.create(event=event, user_name='User 35')
-    Booking.objects.create(event=event, user_name='User 5')
-    booking6 = Booking.objects.create(event=event, user_name='User Cancelled')
+    booking1 = Booking.objects.create(event=event, user_first_name='User', user_last_name='42')
+    Booking.objects.create(event=event, user_first_name='User', user_last_name='01')
+    Booking.objects.create(event=event, user_first_name='User', user_last_name='17')
+    Booking.objects.create(event=event, user_first_name='User', user_last_name='35')
+    Booking.objects.create(event=event, user_first_name='User', user_last_name='05')
+    booking6 = Booking.objects.create(event=event, user_first_name='User', user_last_name=' Cancelled')
     booking6.cancel()
-    booking7 = Booking.objects.create(event=event, user_name='User Waiting', in_waiting_list=True)
+    booking7 = Booking.objects.create(
+        event=event, user_first_name='User', user_last_name=' Waiting', in_waiting_list=True
+    )
     login(app)
 
     # event not in past
@@ -1092,11 +1094,11 @@ def test_event_check(app, admin_user):
     assert 'Waiting List (1/5)' in resp
     assert (
         resp.text.index('Bookings (5/10)')
-        < resp.text.index('User 1')
+        < resp.text.index('User 01')
+        < resp.text.index('User 05')
         < resp.text.index('User 17')
         < resp.text.index('User 35')
         < resp.text.index('User 42')
-        < resp.text.index('User 5')
         < resp.text.index('Waiting List (1/5)')
         < resp.text.index('User Waiting')
     )  # user ordering is not optimal ...
@@ -1168,7 +1170,7 @@ def test_event_check_booking(app, admin_user):
         waiting_list_places=5,
         agenda=agenda,
     )
-    booking = Booking.objects.create(event=event, user_name='User 42')
+    booking = Booking.objects.create(event=event, user_first_name='User', user_last_name='42')
 
     login(app)
     resp = app.get('/manage/agendas/%s/events/%s/check' % (agenda.pk, event.pk))
@@ -1242,7 +1244,7 @@ def test_event_check_booking_ajax(app, admin_user):
         waiting_list_places=5,
         agenda=agenda,
     )
-    booking = Booking.objects.create(event=event, user_name='User 42')
+    booking = Booking.objects.create(event=event, user_first_name='User', user_last_name='42')
 
     login(app)
     resp = app.get('/manage/agendas/%s/events/%s/check' % (agenda.pk, event.pk))
diff --git a/tests/test_agendas.py b/tests/test_agendas.py
index 667a84f..063ed2b 100644
--- a/tests/test_agendas.py
+++ b/tests/test_agendas.py
@@ -1806,7 +1806,8 @@ def test_anonymize_bookings(freezer):
             label='john',
             user_display_label='john',
             user_external_id='john',
-            user_name='john',
+            user_first_name='john',
+            user_last_name='doe',
             backoffice_url='https://example.org',
         )
 
@@ -1833,7 +1834,8 @@ def test_anonymize_bookings(freezer):
             label='',
             user_display_label='',
             user_external_id='',
-            user_name='',
+            user_first_name='',
+            user_last_name='',
             backoffice_url='https://example.org',
             extra_data={},
             anonymization_datetime=now(),
diff --git a/tests/test_api.py b/tests/test_api.py
index 6b2389c..ea87ae7 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -1178,7 +1178,31 @@ def test_booking_api(app, some_data, user):
     )
     booking = Booking.objects.get(id=resp.json['booking_id'])
     assert booking.label == 'foo'
-    assert booking.user_name == 'bar'
+    assert booking.user_first_name == ''
+    assert booking.user_last_name == 'bar'
+    assert booking.backoffice_url == 'http://example.net/'
+    assert booking.cancel_callback_url == 'http://example.net/jump/trigger/'
+    assert booking.user_email == 'bar@bar.com'
+    assert booking.user_phone_number == '+33123456789'
+    assert booking.form_url == 'http://example.net/'
+
+    resp = app.post_json(
+        '/api/agenda/%s/fillslot/%s/' % (agenda.id, event.id),
+        params={
+            'label': 'foo',
+            'user_first_name': 'foo',
+            'user_last_name': 'bar',
+            'backoffice_url': 'http://example.net/',
+            'cancel_callback_url': 'http://example.net/jump/trigger/',
+            'user_email': 'bar@bar.com',
+            'user_phone_number': '+33123456789',
+            'form_url': 'http://example.net/',
+        },
+    )
+    booking = Booking.objects.get(id=resp.json['booking_id'])
+    assert booking.label == 'foo'
+    assert booking.user_first_name == 'foo'
+    assert booking.user_last_name == 'bar'
     assert booking.backoffice_url == 'http://example.net/'
     assert booking.cancel_callback_url == 'http://example.net/jump/trigger/'
     assert booking.user_email == 'bar@bar.com'
@@ -1188,19 +1212,20 @@ def test_booking_api(app, some_data, user):
     # blank data are OK
     resp = app.post_json(
         '/api/agenda/%s/fillslot/%s/' % (agenda.id, event.id),
-        params={'label': '', 'user_name': '', 'backoffice_url': ''},
+        params={'label': '', 'user_first_name': '', 'user_last_name': '', 'backoffice_url': ''},
     )
     assert Booking.objects.get(id=resp.json['booking_id']).label == ''
-    assert Booking.objects.get(id=resp.json['booking_id']).user_name == ''
+    assert Booking.objects.get(id=resp.json['booking_id']).user_first_name == ''
+    assert Booking.objects.get(id=resp.json['booking_id']).user_last_name == ''
     assert Booking.objects.get(id=resp.json['booking_id']).backoffice_url == ''
 
     # extra data stored in extra_data field
     resp = app.post_json(
         '/api/agenda/%s/fillslot/%s/' % (agenda.id, event.id),
-        params={'label': 'l', 'user_name': 'u', 'backoffice_url': '', 'foo': 'bar'},
+        params={'label': 'l', 'user_last_name': 'u', 'backoffice_url': '', 'foo': 'bar'},
     )
     assert Booking.objects.get(id=resp.json['booking_id']).label == 'l'
-    assert Booking.objects.get(id=resp.json['booking_id']).user_name == 'u'
+    assert Booking.objects.get(id=resp.json['booking_id']).user_last_name == 'u'
     assert Booking.objects.get(id=resp.json['booking_id']).backoffice_url == ''
     assert Booking.objects.get(id=resp.json['booking_id']).extra_data == {'foo': 'bar'}
 
@@ -1212,7 +1237,7 @@ def test_booking_api(app, some_data, user):
     # test invalid data are refused
     resp = app.post_json(
         '/api/agenda/%s/fillslot/%s/' % (agenda.id, event.id),
-        params={'user_name': {'foo': 'bar'}},
+        params={'user_last_name': {'foo': 'bar'}},
         status=400,
     )
     assert resp.json['err'] == 1
@@ -1220,7 +1245,7 @@ def test_booking_api(app, some_data, user):
     assert resp.json['err_class'] == 'invalid payload'
     assert resp.json['err_desc'] == 'invalid payload'
     assert len(resp.json['errors']) == 1
-    assert 'user_name' in resp.json['errors']
+    assert 'user_last_name' in resp.json['errors']
 
     resp = app.post('/api/agenda/foobar/fillslot/%s/' % event.id, status=404)
 
@@ -1366,7 +1391,8 @@ def test_booking_ics(app, some_data, meetings_agenda, user):
         '/api/agenda/%s/fillslot/%s/' % (agenda.id, event.id),
         params={
             'label': 'foo',
-            'user_name': 'bar',
+            'user_first_name': 'foo',
+            'user_last_name': 'bar',
             'backoffice_url': 'http://example.net/',
             'url': 'http://example.com/booking',
             'user_display_label': 'your booking',
@@ -1375,7 +1401,7 @@ def test_booking_ics(app, some_data, meetings_agenda, user):
     assert Booking.objects.count() == 3
     booking_ics = Booking.objects.get(id=resp.json['booking_id']).get_ics()
     assert 'SUMMARY:your booking\r\n' in booking_ics
-    assert 'ATTENDEE:bar\r\n' in booking_ics
+    assert 'ATTENDEE:foo bar\r\n' in booking_ics
     assert 'URL:http://example.com/booking\r\n' in booking_ics
 
     # extra data stored in extra_data field
@@ -1383,7 +1409,6 @@ def test_booking_ics(app, some_data, meetings_agenda, user):
         '/api/agenda/%s/fillslot/%s/' % (agenda.id, event.id),
         params={
             'label': 'l',
-            'user_name': 'u',
             'backoffice_url': '',
             'location': 'bar',
             'comment': 'booking comment',
@@ -1489,7 +1514,7 @@ def test_booking_api_fillslots(app, some_data, user):
             'slots': events_ids,
             'label': 'foo',
             'user_external_id': 'some_external_id',
-            'user_name': 'bar',
+            'user_last_name': 'bar',
             'user_display_label': 'foo',
             'backoffice_url': 'http://example.net/',
         },
@@ -1498,7 +1523,7 @@ def test_booking_api_fillslots(app, some_data, user):
     booking = Booking.objects.get(pk=booking_id)
     assert booking.label == 'foo'
     assert booking.user_external_id == 'some_external_id'
-    assert booking.user_name == 'bar'
+    assert booking.user_last_name == 'bar'
     assert booking.user_display_label == 'foo'
     assert booking.backoffice_url == 'http://example.net/'
     assert Booking.objects.filter(primary_booking=booking_id, label='foo').count() == 2
@@ -1514,10 +1539,10 @@ def test_booking_api_fillslots(app, some_data, user):
     # extra data stored in extra_data field
     resp = app.post_json(
         '/api/agenda/%s/fillslots/' % agenda.id,
-        params={'slots': events_ids, 'label': 'l', 'user_name': 'u', 'backoffice_url': '', 'foo': 'bar'},
+        params={'slots': events_ids, 'label': 'l', 'user_last_name': 'u', 'backoffice_url': '', 'foo': 'bar'},
     )
     assert Booking.objects.get(id=resp.json['booking_id']).label == 'l'
-    assert Booking.objects.get(id=resp.json['booking_id']).user_name == 'u'
+    assert Booking.objects.get(id=resp.json['booking_id']).user_last_name == 'u'
     assert Booking.objects.get(id=resp.json['booking_id']).backoffice_url == ''
     assert Booking.objects.get(id=resp.json['booking_id']).extra_data == {'foo': 'bar'}
     for booking in Booking.objects.filter(primary_booking=resp.json['booking_id']):
@@ -1526,7 +1551,7 @@ def test_booking_api_fillslots(app, some_data, user):
     # test invalid data are refused
     resp = app.post_json(
         '/api/agenda/%s/fillslots/' % agenda.id,
-        params={'slots': events_ids, 'user_name': {'foo': 'bar'}},
+        params={'slots': events_ids, 'user_last_name': {'foo': 'bar'}},
         status=400,
     )
     assert resp.json['err'] == 1
@@ -1534,7 +1559,7 @@ def test_booking_api_fillslots(app, some_data, user):
     assert resp.json['err_class'] == 'invalid payload'
     assert resp.json['err_desc'] == 'invalid payload'
     assert len(resp.json['errors']) == 1
-    assert 'user_name' in resp.json['errors']
+    assert 'user_last_name' in resp.json['errors']
 
     # empty or missing slots
     resp = app.post_json('/api/agenda/%s/fillslots/' % agenda.id, params={'slots': []}, status=400)
@@ -1563,13 +1588,13 @@ def test_booking_api_fillslots(app, some_data, user):
         in_bookable_period.return_value = True
         resp = app.post_json(
             '/api/agenda/%s/fillslots/' % agenda.id,
-            params={'slots': events_ids, 'label': 'l', 'user_name': 'u', 'backoffice_url': '', 'foo': 'bar'},
+            params={'slots': events_ids},
         )
         assert resp.json['err'] == 0
         in_bookable_period.return_value = False
         resp = app.post_json(
             '/api/agenda/%s/fillslots/' % agenda.id,
-            params={'slots': events_ids, 'label': 'l', 'user_name': 'u', 'backoffice_url': '', 'foo': 'bar'},
+            params={'slots': events_ids},
         )
         assert resp.json['err'] == 1
         assert resp.json['reason'] == 'event not bookable'  # legacy
-- 
2.30.2

