Example #1
0
def add_coupon(coupon_code,
               value,
               threshold,
               activate_date=None,
               expire_date=None):
    # Clean the input data
    coupon_code = str(coupon_code).strip()
    value = str(value).strip()
    threshold = str(threshold).strip()

    # Check is the input valid
    if not is_money(value):
        raise ValidationError('Invalid value.')
    if not is_money(threshold):
        raise ValidationError('Invalid threshold.')

    # Check if the threshold is less than the value the coupon can deduct
    if float(value) > float(threshold):
        raise ValidationError(
            'The value should be greater than the threshold.')

    # Check the existence of the coupon
    if find_coupon(coupon_code) is not None:
        raise ValidationError('The coupon code already exists.')

    # Establish db connection
    dao = DAO()
    cursor = dao.cursor()

    sql = """INSERT INTO coupon (
        coupon_code,
        value,
        threshold,
        activate_date,
        expire_date
    ) VALUES (
        %(coupon_code)s,
        %(value)s,
        %(threshold)s,
        %(activate_date)s,
        %(expire_date)s
    )"""
    cursor.execute(
        sql, {
            'coupon_code': coupon_code,
            'value': value,
            'threshold': threshold,
            'activate_date': activate_date,
            'expire_date': expire_date
        })
    dao.commit()
def user_refund(user_id, amount, cursor):
    """The function will try to refund the given amount of moeny from 
    the user's account
    NOTE: A cursor must be provided

    Parameters:
    user_id -- the id of the user
    amount -- the amount to be refunded
    cursor -- a cursor from a DAO or a connection
    """
    # Clean the input data
    user_id = str(user_id).strip()
    amount = str(amount).strip()

    # Check if the input 'amount is valid
    if not validator.is_money(amount):
        raise ValidationError('Invalid amount.')

    # Check for the validity of the user
    user = find_user(param=user_id, method='id')
    if user is None:
        raise ValidationError('The user does not exists.')

    # Query the balance of the given user
    sql = """SELECT balance FROM user WHERE user_id = %(user_id)s"""
    cursor.execute(sql, {'user_id': user_id})
    result = cursor.fetchone()
    new_balance = result['balance'] + Decimal(amount)

    # Refund
    sql = """UPDATE user SET balance = %(new_balance)s WHERE
                user_id = %(user_id)s"""
    cursor.execute(sql, {'new_balance': new_balance, 'user_id': user_id})
def add_redeem_cards(value, batch=1):
    # Clean the input data
    value = str(value).strip()
    batch = str(batch).strip()

    # Check is the input valid
    if not is_money(value) or not batch.isdecimal():
        raise ValidationError('Invalid input type.')

    # Establish db connection
    dao = DAO()
    cursor = dao.cursor()

    sql = """INSERT INTO redeem_card (
        redeem_code,
        value
    ) VALUES (
        %(redeem_code)s,
        %(value)s
    )"""
    for i in range(int(batch)):
        cursor.execute(sql, {
            'redeem_code': generate_random_coupon_code(),
            'value': value
        })
        # Commit every 10 writes
        if (i + 1) % 10 == 0:
            dao.commit()
    dao.commit()
def add_product(product_name, categories, price, priority, description = ''):
    # Clean the input data
    product_name = str(product_name).strip()
    description = str(description).strip()
    price = str(price).strip()
    priority = str(priority).strip()
    description = str(description).strip()

    # Check is the input valid
    if (not product_name) or (not description) or (not priority.isdecimal()) or (type(categories) is not list):
        raise ValidationError('Invalid input type.')

    if not validator.is_money(price):
        raise ValidationError('Invalid pricing.')

    if len(categories) == 0:
        raise ValidationError('The product should belong to at least one category.')

    # Establish db connection
    dao = DAO()
    cursor = dao.cursor()

    # Check if the item already exists
    if find_product('product_name', product_name) is not None:
        raise ValidationError('The product already exists.')

    sql = """INSERT INTO product (
        product_name,
        description,
        price,
        priority
    ) VALUES (
        %(product_name)s,
        %(description)s,
        %(price)s,
        %(priority)s
    )"""
    cursor.execute(sql, {'product_name': product_name,
                        'description': description,
                        'priority': priority,
                        'price': price
                        })

    # Fetch the newly added order's id
    cursor.execute('SELECT LAST_INSERT_ID()')
    product_id = cursor.fetchone()['LAST_INSERT_ID()']

    # Create relationship between product and category
    sql = """INSERT INTO product_category(product_id, category_id) VALUES (
            %(product_id)s,
            %(category_id)s
    )"""
    for category_id in categories:
        cursor.execute(sql, {'product_id': product_id, 'category_id': category_id})

    dao.commit()
def update_product(product_id, product_name, categories, price, priority, description=''):
    # Clean the input data
    product_id = str(product_id).strip()
    product_name = str(product_name).strip()
    description = str(description).strip()
    price = str(price).strip()
    priority = str(priority).strip()
    description = str(description).strip()

    # Check is the input valid
    if (not product_id) or (not product_name) or (not description) or (not priority.isdecimal()) or (type(categories) is not list):
        raise ValidationError('Invalid input type.')

    if not validator.is_money(price):
        raise ValidationError('Invalid pricing.')

    if len(categories) == 0:
        raise ValidationError('The product should belong to at least one category.')

    # Establish db connection
    dao = DAO()
    cursor = dao.cursor()

    # Check if the item exists
    if find_product('product_name', product_name) is None:
        raise ValidationError('The category does not exists.')

    sql = """UPDATE product SET
            product_name = %(product_name)s,
            description = %(description)s,
            price = %(price)s,
            priority = %(priority)s
            WHERE product_id = %(product_id)s
    """
    cursor.execute(sql, {'product_name': product_name,
                        'description': description,
                        'priority': priority,
                        'price': price,
                        'product_id': product_id
                        })

    # Create relationship between product and category
    sql = """DELETE FROM product_category WHERE product_id = %(product_id)s"""
    cursor.execute(sql, {'product_id': product_id})
    sql = """INSERT INTO product_category(product_id, category_id) VALUES (
            %(product_id)s,
            %(category_id)s
    )"""
    for category_id in categories:
        cursor.execute(sql, {'product_id': product_id, 'category_id': category_id})

    dao.commit()
Example #6
0
def place_redeem(user_id, amount):
    # Clean the input data
    user_id = str(user_id).strip()
    amount = str(amount).strip()

    # Verify the amount
    if not is_money(amount):
        raise ValidationError('Invalid amount.')

    # Verify the user_id
    if find_user(method='id', param=user_id) is None:
        raise ValidationError('Invalid user id.')

    # Insert into order
    # Establish db connection
    dao = DAO()
    cursor = dao.cursor()

    sql = """INSERT INTO `order` (
        user_id,
        total,
        actual_paid,
        status
    ) VALUES (
        %(user_id)s,
        %(total)s,
        %(actual_paid)s,
        %(status)s
    )"""
    # A status code of 100 means it is a desposite
    cursor.execute(sql, {
        'user_id': user_id,
        'total': -amount,
        'actual_paid': 0,
        'status': 100
    })
    dao.commit()