blob: ef51c1016e4dc76e850485e5abcc54ddecc25f3b [file] [log] [blame]
from flask import jsonify, render_template, request, url_for, g, abort
from app import db
from app.api import bp
from app.api.auth import token_auth
from app.email import send_email
from app.api.errors import bad_request
from app.models import Booking, BookingStatus, User
@bp.route('/bookings/<int:id>', methods=['GET'])
def get_booking(id):
return jsonify(Booking.query.get_or_404(id).to_dict())
@bp.route('/bookings', methods=['GET'])
def get_bookings():
page = request.args.get('page', 1, type=int)
per_page = min(request.args.get('per_page', 10, type=int), 100)
data = Booking.to_collection_dict(Booking.query, page, per_page, 'api.get_bookings')
return jsonify(data)
@bp.route('/bookings', methods=['POST'])
@token_auth.login_required
def create_booking():
data = request.get_json() or {}
if 'stack' not in data or 'scenario' not in data:
return bad_request('Request must include stack and scenario fields')
booking = Booking()
booking.from_dict(data, new_booking=True)
db.session.add(booking)
db.session.commit()
response = jsonify(booking.to_dict())
response.status_code = 201
response.headers['Location'] = url_for('api.get_booking', id=booking.id)
return response
@bp.route('/bookings/<int:id>', methods=['PUT'])
@token_auth.login_required
def update_booking(id):
booking = Booking.query.get_or_404(id)
user = User.query.filter_by(id=booking.user_id).first()
data = request.get_json() or {}
booking.from_dict(data, new_booking=False)
booking.status_id = BookingStatus.query.filter_by(status_text=data['status_text']).first().id
db.session.commit()
if booking.status_id == BookingStatus.query.filter_by(status_text='active').first().id:
email_body_html = render_template('booking/booking_status_mail.html', floating_ip=booking.floating_ip)
send_email('Your Nordix Open Labs booking is ready', user.email, email_body_html)
return jsonify(booking.to_dict())