diff --git a/routes.py b/routes.py index b43b597..2470e2c 100644 --- a/routes.py +++ b/routes.py @@ -144,19 +144,35 @@ def create_listing(): def booking(listing_id): listing = Listing.query.get_or_404(listing_id) booked_dates = Booking.query.filter_by(listing_id=listing_id).all() - unavailable_dates = [ - (booking.check_in.strftime('%Y-%m-%d'), booking.check_out.strftime('%Y-%m-%d')) - for booking in booked_dates - ] + unavailable_dates = [(booking.check_in.strftime('%Y-%m-%d'), booking.check_out.strftime('%Y-%m-%d')) for booking in booked_dates] if request.method == 'POST': check_in = datetime.strptime(request.form['check_in'], '%Y-%m-%d') check_out = datetime.strptime(request.form['check_out'], '%Y-%m-%d') - guests = request.form['guests'] - booking = Booking(user_id=current_user.id, listing_id=listing_id, check_in=check_in, check_out=check_out, guests=guests) - db.session.add(booking) - db.session.commit() - return redirect(url_for('home')) + + for start_date, end_date in unavailable_dates: + if (check_in.strftime('%Y-%m-%d') >= start_date and check_in.strftime('%Y-%m-%d') <= end_date) or \ + (check_out.strftime('%Y-%m-%d') >= start_date and check_out.strftime('%Y-%m-%d') <= end_date): + return render_template('booking.html', listing=listing, unavailable_dates=unavailable_dates, error="Selected dates are not available.") + try: + check_in = datetime.strptime(request.form['check_in'], '%Y-%m-%d') + check_out = datetime.strptime(request.form['check_out'], '%Y-%m-%d') + + if check_out <= check_in: + return render_template('booking.html', listing=listing, unavailable_dates=unavailable_dates, error="Check-out date must be after check-in date.") + + guests = int(request.form['guests']) + if guests > listing.guests: + return render_template('booking.html', listing=listing, unavailable_dates=unavailable_dates, error="Number of guests exceeds maximum allowed.") + + booking = Booking(user_id=current_user.id, listing_id=listing_id, check_in=check_in, check_out=check_out, guests=guests) + db.session.add(booking) + db.session.commit() + return redirect(url_for('home')) + + except ValueError: + return render_template('booking.html', listing=listing, unavailable_dates=unavailable_dates, error="Invalid date format.") + return render_template('booking.html', listing=listing, unavailable_dates=unavailable_dates) @app.route('/view/', methods=['GET']) diff --git a/templates/booking.html b/templates/booking.html index 3ccadb4..c886516 100644 --- a/templates/booking.html +++ b/templates/booking.html @@ -5,10 +5,14 @@

Book {{ listing.title }}

+ {% if error %} +
{{ error }}
+ {% endif %}
- +
@@ -22,4 +26,37 @@
-{% endblock %} + + +{% endblock %} \ No newline at end of file