🏭 Refactor Handle Booking form function (#9)

* 🧹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
This commit is contained in:
Ruidy 2020-07-31 13:47:51 +02:00 committed by GitHub
parent c55ff54032
commit 2ad33ca153
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 68 additions and 86 deletions

View file

@ -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/'
)

View file

@ -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

View file

@ -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'