예제 #1
0
def _check_for_valid_field_keys(cart_item_instance, is_post_request=True):
    if not is_post_request:
        if set(cart_item_instance) != {'quantity'}:
            raise handle_exception(
                'Bad Request: You can only include the "quantity" field in your PUT request.',
                400)
        return

    if set(cart_item_instance) != {'quantity', 'product_id'}:
        raise handle_exception(
            'Bad Request: Please include the following fields in your POST request: "quantity", "product_id"',
            400)
def _check_for_valid_field_keys(user_instance, is_post_request=True):
    if not is_post_request:
        if not set(user_instance).issubset({'username', 'password'}):
            raise handle_exception(
                'Bad Request: You may only include the "username" and "password" fields in your PUT request.',
                400)
        return

    if set(user_instance) != {'username', 'password'}:
        raise handle_exception(
            'Bad Request: Your POST request must include (only) the "username" and "password" fields.',
            400)
예제 #3
0
def _check_for_valid_field_keys(product_instance, is_post_request=True):
    if not is_post_request:
        if not set(product_instance).issubset(
            {'title', 'inventory_count', 'price'}):
            raise handle_exception(
                'Bad Request: Your PUT request can only include the "title", "inventory_count" and "price" fields.',
                400)
        return

    if set(product_instance) != {'title', 'inventory_count', 'price'}:
        raise handle_exception(
            'Bad Request: Your POST request must include (only) the "title", "inventory_count" and "price" fields.',
            400)
예제 #4
0
def create(order_instance, current_user):
    _check_for_valid_field_keys(order_instance)

    cart_id = order_instance['cart_id']

    if cart_id not in [
            str(cart.id) for cart in current_user.carts if not cart.order
    ]:
        raise handle_exception(
            'Unauthorized: You can only place an order on your cart (that has not already been ordered).',
            401)

    cart = cart_service.get(cart_id, False)

    subtotal = _ensure_order_quantities_are_valid_and_get_subtotal(cart)
    order_instance.update({'subtotal': subtotal})
    order = database_service.post_entity_instance(Order, order_instance)

    for item in cart.cart_items:
        product_id = item.product_id
        product = product_service.get(product_id)

        product_service.update(
            item.product_id,
            {'inventory_count': product['inventory_count'] - item.quantity},
            item.id)

    return order
 def validate():
     for field in request_body:
         if field not in allowed_fields:
             raise handle_exception(
                 f'Bad Request: Field "{field}" is not allowed. Allowed fields are: {", ".join(allowed_fields)}',
                 400
             )
예제 #6
0
def list_all(cart_ids):
    try:
        orders = Order.query.filter(Order.cart_id.in_(cart_ids)).order_by(
            Order.date_ordered).all()
    except Exception:
        raise handle_exception(f'Exception encountered while querying orders.')

    return [order.serialize() for order in orders]
예제 #7
0
def _ensure_cart_item_is_not_ordered(cart_item_id):
    cart_item = get(cart_item_id, False)
    cart = cart_service.get(cart_item.cart_id)

    if cart['is_ordered']:
        raise handle_exception(
            f'Bad Request: You cannot delete or update cart item with id "{cart_item_id}" that is already ordered.',
            400)
예제 #8
0
def _validate_authorized_user(requested_url, current_user):
    resource = requested_url.split('/')[-2]
    resource_id = requested_url.split('/')[-1]

    if resource == 'users':
        if str(current_user.id) != resource_id:
            raise handle_exception(
                'Unauthorized: You can only modify your own account.', 401)

    elif resource == 'events':
        if resource_id not in [str(event.id) for event in current_user.events]:
            raise handle_exception(
                'Unauthorized: You can only fetch or modify your events.', 401)

        event = event_service.get(resource_id)
        if event['organizer_id'] != current_user.id:
            raise handle_exception(
                'Unauthorized: You can only modify your events.', 401)
def delete_entity_instance(db_model, entity_id, is_id_primary_key=True):
    try:
        entity = (db_model.query.get_or_404(entity_id) if is_id_primary_key
                  else db_model.query.filter_by(id=entity_id).first())
    except exceptions.NotFound:
        raise handle_exception(
            f'Entity type "{db_model.__name__}" with id "{entity_id}" is not found.',
            404)

    db.session.delete(entity)
    db.session.commit()
    return '', 204
def get_entity_instances(db_model, order_by=None, filter_by=None):
    try:
        if filter_by:
            entities = (db_model.query.order_by(order_by).filter_by(
                **filter_by.to_dict()).all() if type(filter_by) != dict else
                        db_model.query.order_by(order_by).filter_by(
                            **filter_by).all())
        else:
            entities = db_model.query.order_by(order_by).all()
    except Exception:
        raise handle_exception(
            f'Exception encountered while querying "{db_model.__name__}" ordered by "{order_by}" '
            f'filtered by "{filter_by}".')

    return [entity.serialize() for entity in entities]
def get_entity_instance_by_id(db_model,
                              entity_id,
                              serialize=True,
                              is_id_primary_key=True):
    try:
        entity = (db_model.query.get_or_404(entity_id) if is_id_primary_key
                  else db_model.query.filter_by(id=entity_id).first())

    except exceptions.NotFound:
        raise handle_exception(
            f'Entity type "{db_model.__name__}" with id "{entity_id}" is not found.',
            404)

    if not serialize:
        return entity

    return entity.serialize()
def edit_entity_instance(db_model,
                         entity_id,
                         updated_entity_instance,
                         is_id_primary_key=True):
    try:
        entity = (db_model.query.get_or_404(entity_id) if is_id_primary_key
                  else db_model.query.filter_by(id=entity_id).first())
    except exceptions.NotFound:
        raise handle_exception(
            f'Entity type "{db_model.__name__}" with id "{entity_id}" is not found.',
            404)

    for key in updated_entity_instance:
        setattr(entity, key, updated_entity_instance[key])

    db.session.commit()

    return entity.serialize()
예제 #13
0
def _ensure_order_quantities_are_valid_and_get_subtotal(cart):
    cart_id = cart.id

    if len(cart.cart_items) == 0:
        raise handle_exception(
            f'Bad Request: Cart with id "{cart_id}" does not contain any items to order.',
            400)

    subtotal = 0
    for item in cart.cart_items:
        product_id = item.product_id
        product = product_service.get(product_id)
        product_inventory = product['inventory_count']
        order_quantity = item.quantity
        subtotal += item.quantity * product['price']
        validate_cart_item_quantity_is_not_more_than_product_inventory(
            product_inventory, order_quantity, product_id)

    return subtotal
예제 #14
0
def create(cart_item_instance, current_user):
    if not current_user.carts or all(
        [cart.order for cart in current_user.carts]):
        cart = cart_service.create(current_user.id)
        cart_id = cart['id']
    else:
        cart = [cart for cart in current_user.carts if not cart.order][0]
        cart_id = cart.id

    _check_for_valid_field_keys(cart_item_instance)

    cart_quantity = cart_item_instance['quantity']
    if cart_quantity == 0:
        raise handle_exception(
            'Bad Request: Cart item quantity must be more than 0.', 400)

    _ensure_product_id_and_quantity_are_valid(cart_item_instance)
    cart_item_instance.update({'cart_id': cart_id})

    return database_service.post_entity_instance(CartItem, cart_item_instance)
예제 #15
0
def save_response(response_form):
    def _find_event_and_get_recipient_id_object(event_code, from_number):
        event = Event.query.filter_by(event_code=event_code).first().serialize()

        for event_invitee in event['event_invitees']:
            # recipient must be one of the event invitees
            invitee = invitee_service.get(event_invitee['invitee_id'])
            if invitee['phone'] == from_number:
                return {'recipient_id': event_invitee['invitee_id'], 'recipient_group_id': event_invitee['id']}

        return None

    def _find_message_recipient_and_get_parent_message_id(recipient_id_object):
        message_recipient = MessageRecipient.query.filter_by(recipient_id=recipient_id_object['recipient_id']).first()

        if not message_recipient:
            message_recipient = MessageRecipient.query.filter_by(
                recipient_group_id=recipient_id_object['recipient_group_id']
            ).first()

        message_recipient = message_recipient.serialize()
        return message_recipient['message_id']


    # https://stackoverflow.com/questions/50075375/receiving-and-processing-an-sms-with-twilio-in-python
    from_number = response_form['From']
    body = response_form['Body'].strip().split(' ')
    response, event_code = body[0].lower(), body[1]

    recipient_id_object = _find_event_and_get_recipient_id_object(event_code, from_number)

    if not recipient_id_object:
        raise handle_exception('Incoming number could not be matched to an invitee for the specified event.', 500)

    parent_message_id = _find_message_recipient_and_get_parent_message_id(recipient_id_object)
    parent_message = message_service.get(parent_message_id)
    message_service.create(response_form['MessageSid'], response, parent_message['creator_id'], parent_message_id)

    resp = MessagingResponse()
    resp.message("Thanks! Your response has been sent to the event organizer.")
    return str(resp)
예제 #16
0
def _check_for_valid_field_keys(order_instance):
    if set(order_instance) != {'cart_id'}:
        raise handle_exception(
            'Bad Request: Your POST request must include (only) the "cart_id" field.',
            400)
 def validate():
     if set(request_body) != set(required_fields):
         raise handle_exception(
             f'Bad Request: One or more required fields are missing or invalid: {", ".join(required_fields)}', 400
         )
def _ensure_current_user_has_carts(carts):
    if not carts:
        raise handle_exception(
            'Bad Request: Your account has no carts (and thus no cart items). POST a cart item to automatically '
            'create a cart for your account.', 400)
 def validate():
     if not request_body:
         return handle_exception('Bad Request: Request must have a body.', 400)