def create_reservation():
    data = request.get_json() or {}

    error = Reservation.check_data(data=data, new=True)
    if 'user_id' in data and data['user_id'] is not None and \
            User.query.get(data['user_id']) is None:
        error = 'usuário não existe'
    if 'thirdparty_id' in data and data['thirdparty_id'] is not None and \
            Thirdparty.query.get(data['thirdparty_id']) is None:
        error = 'terceiro não existe'
    if Reservation.query.filter(
            Reservation.date_start >= data['date_start']).filter(
                Reservation.date_start <= data['date_end']).all(
                ) or Reservation.query.filter(
                    Reservation.date_end >= data['date_start']).filter(
                        Reservation.date_end <= data['date_end']).all():
        error = 'já existe um evento nesse período'

    if error:
        return bad_request(error)

    reservation = Reservation()
    reservation.from_dict(data)

    try:
        db.session.add(reservation)
        db.session.commit()
    except Exception:
        return internal_server()

    return jsonify(reservation.to_dict()), 201
Example #2
0
def create_reservation():
    data = request.get_json() or {}
    u_id = g.current_user.id
    if 'listingId' not in data:
        return bad_request('Must include listing ID')
    data['user_id'] = u_id
    reservation = Reservation()
    reservation.from_dict(data)
    db.session.add(reservation)

    # block the date
    check_in_date = reservation.check_in_date
    check_out_date = reservation.check_out_date
    # check not continuously dates
    listingDates = ListingDate.query.filter_by(
        listing_id=reservation.listing_id).filter(
            ListingDate.date <= check_out_date).filter(
                ListingDate.date >= check_in_date).all()
    if len(listingDates) > 0:
        return error_response(202, 'Please choose a continuous dates range')
    # serve the date
    date_generated = [
        check_in_date + timedelta(days=x)
        for x in range(0, (check_out_date - check_in_date).days + 1)
    ]
    for gen_d in date_generated:
        print(gen_d.strftime('%d/%m/%Y'))
        listingDate = ListingDate()
        listingDate.listing_id = data['listingId']
        listingDate.date = gen_d
        listingDate.date_type = 'reserved'
        db.session.add(listingDate)

    db.session.commit()
    response = jsonify(reservation.to_dict())
    response.status_code = 201
    return response