🏭 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(): 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 creds = None
@ -75,9 +77,11 @@ def get_bookings(place):
def synchronize(place): def synchronize(place):
""" Get a complete list of existing bookings in calendar """
Creates reservation if not in db, update if already in db Get a complete list of existing bookings in calendar
Delete from db reservation deleted from cal """ Creates reservation if not in db, update if already in db
Delete from db reservation deleted from cal
"""
reservation = get_bookings(place) reservation = get_bookings(place)
if not reservation: if not reservation:
@ -110,10 +114,11 @@ def synchronize(place):
db_booking.end = end db_booking.end = end
def get_bookings_from_db(place): 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) synchronize(place)
booked_dates = m_booking.Booking.objects.filter(place=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): 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) bookings = get_bookings_from_db(place)
for booking in bookings: for booking in bookings:
@ -133,9 +138,9 @@ def check_availability(place, start_date, end_date):
def update(reservation): def update(reservation):
""" push new reservation to master calendar """ """Push new reservation to master calendar."""
# authenticate and build service # authenticate and build service
service, calendars = build_service() service, calendars = build_service()
start = reservation.start.strftime('%Y-%m-%d') start = reservation.start.strftime('%Y-%m-%d')
end = reservation.end.strftime('%Y-%m-%d') end = reservation.end.strftime('%Y-%m-%d')
@ -153,23 +158,3 @@ def update(reservation):
}, },
} }
).execute() ).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 __future__ import absolute_import, unicode_literals
from datetime import datetime
import os import os
from datetime import datetime
import requests import requests
from celery import shared_task from celery import shared_task

View file

@ -16,66 +16,63 @@ def view(request):
return render(request, template, context) return render(request, template, context)
def handle_booking_form(request, context={}, init_template='rental/reservation.html'): def handle_booking_form(request, context=None, init_template='rental/reservation.html'):
"""Validates form and checks if place availability a given period.""" """
Validates booking form and checks place availability for a given period.
Returns the context and the template to be rendered.
"""
if request.method == 'POST': if not context:
form = BookingForm(request.POST) context = {}
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']
try: # create form and populate fields using post request data
guest = Guest.objects.filter(email=email) form = BookingForm(
if not guest.exists(): request.POST) if request.method == 'POST' else BookingForm()
guest = Guest.objects.create(
email=email,
name=name,
phone=phone
)
else:
guest = guest.first()
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): # parse request data
reservation = Booking.objects.create_booking( name = form.cleaned_data['name']
guest=guest, email = form.cleaned_data['email']
place=place, phone = form.cleaned_data['phone']
message=message, message = form.cleaned_data['message']
start=start, place_name = form.cleaned_data['place']
end=end start = form.cleaned_data['start']
) end = form.cleaned_data['end']
reservation.send_quotation() # get guest
guest = Guest.objects.filter(email=email)
context = { if guest.exists():
'reservation': reservation guest = guest.first()
}
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."""
else: else:
form = BookingForm() guest = Guest.objects.create(
email=email,
name=name,
phone=phone
)
context['form'] = form # check place availability
context['errors'] = form.errors.items() place = get_object_or_404(Place, name=place_name)
template = init_template
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'