From 2ad33ca1531bcf649ff22f56d14fb8fd6f43fbce Mon Sep 17 00:00:00 2001 From: Ruidy Date: Fri, 31 Jul 2020 13:47:51 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=8F=AD=20Refactor=20Handle=20Booking=20fo?= =?UTF-8?q?rm=20function=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 🧹refactor: improve handle_booking readability I removed the try except IntegrityError. This should be taken care of in the model/data layer. * doc: update comments --- rental/services/calendar.py | 45 +++++---------- rental/tasks/api_mailer.py | 2 +- rental/views/booking.py | 107 ++++++++++++++++++------------------ 3 files changed, 68 insertions(+), 86 deletions(-) diff --git a/rental/services/calendar.py b/rental/services/calendar.py index f97633d..d761eb8 100644 --- a/rental/services/calendar.py +++ b/rental/services/calendar.py @@ -15,7 +15,9 @@ from villafleurie.settings import BASE_DIR def build_service(): - """ Build Google Calendar API service and returns calendar list and service """ + """ + Build Google Calendar API service and returns calendar list and service + """ creds = None @@ -75,9 +77,11 @@ def get_bookings(place): def synchronize(place): - """ Get a complete list of existing bookings in calendar - Creates reservation if not in db, update if already in db - Delete from db reservation deleted from cal """ + """ + Get a complete list of existing bookings in calendar + Creates reservation if not in db, update if already in db + Delete from db reservation deleted from cal + """ reservation = get_bookings(place) if not reservation: @@ -110,10 +114,11 @@ def synchronize(place): db_booking.end = end - def get_bookings_from_db(place): - """ Synchronize with Master calendar via a call to synchronize_calendar - Returns a list of all related place reservations """ + """ + Synchronize with Master calendar via a call to synchronize_calendar + Returns a list of all related place reservations + """ synchronize(place) booked_dates = m_booking.Booking.objects.filter(place=place) @@ -122,7 +127,7 @@ def get_bookings_from_db(place): def check_availability(place, start_date, end_date): - """ check if the related place is available during a given period """ + """Checks if the related place is available during a given period.""" bookings = get_bookings_from_db(place) for booking in bookings: @@ -133,9 +138,9 @@ def check_availability(place, start_date, end_date): def update(reservation): - """ push new reservation to master calendar """ + """Push new reservation to master calendar.""" # authenticate and build service - + service, calendars = build_service() start = reservation.start.strftime('%Y-%m-%d') end = reservation.end.strftime('%Y-%m-%d') @@ -153,23 +158,3 @@ def update(reservation): }, } ).execute() - - -if __name__ == '__main__': - - s, c = build_service() - - from google_auth_oauthlib.flow import Flow - - SCOPES = [ - 'https://www.googleapis.com/auth/calendar', - 'https://www.googleapis.com/auth/calendar.events' - ] - - SECRETS = '/client_secrets.json' - - flow = Flow.from_client_secrets_file( - SECRETS, - scopes=SCOPES, - redirect_uri='http://localhost:8080/' - ) diff --git a/rental/tasks/api_mailer.py b/rental/tasks/api_mailer.py index f1ac1c6..43de0e4 100644 --- a/rental/tasks/api_mailer.py +++ b/rental/tasks/api_mailer.py @@ -10,8 +10,8 @@ from __future__ import absolute_import, unicode_literals -from datetime import datetime import os +from datetime import datetime import requests from celery import shared_task diff --git a/rental/views/booking.py b/rental/views/booking.py index c7bc095..46c7029 100644 --- a/rental/views/booking.py +++ b/rental/views/booking.py @@ -16,66 +16,63 @@ def view(request): return render(request, template, context) -def handle_booking_form(request, context={}, init_template='rental/reservation.html'): - """Validates form and checks if place availability a given period.""" +def handle_booking_form(request, context=None, init_template='rental/reservation.html'): + """ + Validates booking form and checks place availability for a given period. + Returns the context and the template to be rendered. + """ - if request.method == 'POST': - form = BookingForm(request.POST) - if form.is_valid(): - name = form.cleaned_data['name'] - email = form.cleaned_data['email'] - phone = form.cleaned_data['phone'] - message = form.cleaned_data['message'] - place_name = form.cleaned_data['place'] - start = form.cleaned_data['start'] - end = form.cleaned_data['end'] + if not context: + context = {} - try: - guest = Guest.objects.filter(email=email) - if not guest.exists(): - guest = Guest.objects.create( - email=email, - name=name, - phone=phone - ) - else: - guest = guest.first() + # create form and populate fields using post request data + form = BookingForm( + request.POST) if request.method == 'POST' else BookingForm() - place = get_object_or_404(Place, name=place_name) + # return is form is not valid, persist already inputed data + if not form.is_valid(): + context['form'] = form + return context, init_template - if place.is_available(start, end): - reservation = Booking.objects.create_booking( - guest=guest, - place=place, - message=message, - start=start, - end=end - ) + # parse request data + name = form.cleaned_data['name'] + email = form.cleaned_data['email'] + phone = form.cleaned_data['phone'] + message = form.cleaned_data['message'] + place_name = form.cleaned_data['place'] + start = form.cleaned_data['start'] + end = form.cleaned_data['end'] - reservation.send_quotation() - - context = { - 'reservation': reservation - } - template = 'rental/merci.html' - return context, template - - form.add_error(None, ValidationError( - _("Cet hébergement n'est pas disponible aux dates indiquées."), - code='invalid' - )) - context = {'form': form} - template = 'rental/reservation.html' - return context, template - - except IntegrityError: - form.errors['internal'] = """Une erreur interne est apparue. - Merci de recommencer votre requête.""" + # get guest + guest = Guest.objects.filter(email=email) + if guest.exists(): + guest = guest.first() else: - form = BookingForm() + guest = Guest.objects.create( + email=email, + name=name, + phone=phone + ) - context['form'] = form - context['errors'] = form.errors.items() - template = init_template + # check place availability + place = get_object_or_404(Place, name=place_name) - return context, template + if not place.is_available(start, end): + form.add_error(None, ValidationError( + _("Cet hébergement n'est pas disponible aux dates indiquées."), + code='invalid' + )) + return {'form': form}, 'rental/reservation.html' + + reservation = Booking.objects.create_booking( + guest=guest, + place=place, + message=message, + start=start, + end=end + ) + + reservation.send_quotation() + context['reservation'] = reservation + + return context, 'rental/merci.html'