Esempio n. 1
0
def get_shopping_cart(user, db=None):
    """
    Gets all ShoppingCartItems for user

    :param user: User, the user to request for
    :param db: optional, the database connection
    """
    db = db or get_db()
    cur = db.cursor()
    cur.execute("""
        SELECT InventoryItemID, Price, Quantity
        FROM ShoppingCartItem
        WHERE UserID = ?
    """, [user.id_])

    cart = ShoppingCart(user)
    for row in cur.fetchall():
        try:
            item = get_inventory_item(InventoryItem(id_=row[0]), db)
            cart.items.append(ShoppingCartItem(item=item, price=row[1], qty=row[2]))
        except Exception as e:
            print("invalid purchase item:", e)

    cur.close()
    return cart
Esempio n. 2
0
def get_user_purchases(user, db=None):
    """
    Gets all purchases by user.

    :param user: User, the user to find purchases for
    :param db: optional, the database connection
    """
    db = db or get_db()
    cur = db.cursor()

    # insert the purchase
    cur.execute("""
        SELECT PurchaseID, TotalPrice, CreditCard, Address
        FROM Purchase
        WHERE Username=? 
    """, [user.username])

    purchases = []
    for row1 in cur.fetchall():
        purchase = Purchase(username=user.username, id_=row1[0], total_price=row1[1],
                            credit_card=row1[2], address=Address().from_str(row1[3]))
        cur.execute("""
            SELECT InventoryItemID, Price, Quantity
            FROM PurchaseItem
            WHERE PurchaseID=?
        """, [purchase.id_])
        for row2 in cur.fetchall():
            item = get_inventory_item(InventoryItem(row2[0]), db)
            purchase.items.append(ShoppingCartItem(item=item, price=row2[1], qty=row2[2]))
        purchases.append(purchase)

    cur.close()
    return purchases
Esempio n. 3
0
def cart_remove():
    if request.args.get('id') is None:
        return redirect('/cart')

    id_ = request.args.get('id')
    qty = request.args.get('qty')

    db.remove_from_cart(user=User(current_user.get_id()),
                        item=ShoppingCartItem(item=InventoryItem(id_=id_)),
                        qty=qty)
    return redirect('/cart')
Esempio n. 4
0
def cart_update():
    for id_, qty in request.args.items():
        # this makes sure we only use ints
        # noinspection PyBroadException
        try:
            qty = int(qty)
            inv_item = db.get_inventory_item(InventoryItem(id_))
            if inv_item.quantity >= qty:
                db.update_cart(user=User(current_user.get_id()),
                               item=ShoppingCartItem(item=inv_item),
                               qty=qty)
            else:
                flask.flash(
                    "<b>Exceeds stock:</b> {} has no more than {} items available."
                    .format(inv_item.name, inv_item.quantity), "warning")
        except Exception:
            continue
    return redirect('/cart')
Esempio n. 5
0
def get_purchase(purchase, db=None):
    """
    Gets a purchase from the database based on PurchaseID

    :param purchase: Purchase, must have id
    :param db: optional, the database connection
    """
    db = db or get_db()
    cur = db.cursor()
    cur.execute("""
        SELECT Username, TotalPrice, CreditCard, Address
        FROM Purchase
        WHERE PurchaseID = ?
    """, [purchase.id_])

    row = cur.fetchone()
    try:
        purchase = Purchase(id_=purchase.id_, username=row[0], total_price=row[1],
                            credit_card=row[2], address=Address().from_str(row[3]))
    except Exception as e:
        print("invalid purchase:", e)

    cur.execute("""
        SELECT InventoryItemID, Price, Quantity
        FROM PurchaseItem
        WHERE pi.PurchaseID = ?
    """, [purchase.id_])

    for row in cur.fetchall():
        try:
            item = get_inventory_item(InventoryItem(id_=row[0]), db)
            purchase.items.append(ShoppingCartItem(item=item, price=row[1], qty=row[2]))
        except Exception as e:
            print("invalid purchase item:", e)

    cur.close()
    return purchase
Esempio n. 6
0
 def clean_hdnValidationHash(self):
     """ Ensures that the validation hash gotten from sent form is correct. """
     given_hash = self.cleaned_data.get("hdnValidationHash")
     our_hash = ShoppingCartItem.validation_hash_for_shopping_cart(request)
     if not given_hash == our_hash:
         self.add_common_error(CHECKOUT_ERR_MSG_INVALID_HASH)
Esempio n. 7
0
def build_delivery_address_form(request):
    """ Builds a form class representing form asking for delivery addresses for items of an order. """
    def init(self, *args, **kwargs):
        kwargs["initial"] = self.__initial
        super(self.__class__, self).__init__(*args, **kwargs)

    def has_items(self):
        """ Returns True if there are items which to choose addresses for. """
        return self.__items.exists()

    def has_addresses(self):
        """ Returns True if there are addresses which to choose from. """
        return self.__addresses.exists()

    def get_address_fields(self):
        """ Iterates through all address field_dict in form. """
        for name in self.__address_fields:
            yield BoundField(self, self.__address_fields[name], name)

    def get_item_address_pairs(self):
        """ Iterates through all (order items / address) pairs displayed on the form. """
        for field_name in self.__address_fields:
            yield (self.__items.get(id__exact=field_name.split("_")[1]),
                   self.cleaned_data.get(field_name))

    def clean_hdnValidationHash(self):
        """ Ensures that the validation hash gotten from sent form is correct. """
        given_hash = self.cleaned_data.get("hdnValidationHash")
        our_hash = ShoppingCartItem.validation_hash_for_shopping_cart(request)
        if not given_hash == our_hash:
            self.add_common_error(CHECKOUT_ERR_MSG_INVALID_HASH)

    items = ShoppingCartItem.items_of_user_with_albums_and_addresses(
        request.user)
    addresses = Address.addresses_of_user(request.user)
    validation_hash = ShoppingCartItem.validation_hash_for_shopping_cart(
        request)

    field_dict = {}
    address_field_dict = {}
    initial_value_dict = {}

    field_dict["hdnValidationHash"] = forms.CharField(
        widget=forms.HiddenInput())
    initial_value_dict["hdnValidationHash"] = validation_hash

    for item in items:
        field_name = u"cmbAddress_" + unicode(item.id)

        new_field = DeliveryAddressChoiceField(queryset=addresses,
                                               empty_label=None,
                                               label=item.album.title)
        field_dict[field_name] = new_field
        address_field_dict[field_name] = new_field

        if item.deliveryAddress:
            initial_value_dict[field_name] = item.deliveryAddress

    members = {
        "__request": request,
        "__items": items,
        "__addresses": addresses,
        "__validation_hash": validation_hash,
        "base_fields": field_dict,
        "__address_fields": address_field_dict,
        "__initial": initial_value_dict,
        "has_items": has_items,
        "has_addresses": has_addresses,
        "address_fields": get_address_fields,
        "item_address_pairs": get_item_address_pairs,
        "clean_hdnValidationHash": clean_hdnValidationHash,
        "__init__": init
    }

    return type("DeliveryAddressForm", (CommonAlbumizerBaseForm, ), members)
Esempio n. 8
0
 def clean_hdnValidationHash(self):
     """ Ensures that the validation hash gotten from sent form is correct. """
     given_hash = self.cleaned_data.get("hdnValidationHash")
     our_hash = ShoppingCartItem.validation_hash_for_shopping_cart(request)
     if not given_hash == our_hash:
         self.add_common_error(CHECKOUT_ERR_MSG_INVALID_HASH)
Esempio n. 9
0
def build_delivery_address_form(request):
    """ Builds a form class representing form asking for delivery addresses for items of an order. """

    def init(self, *args, **kwargs):
        kwargs["initial"] = self.__initial
        super(self.__class__, self).__init__(*args, **kwargs)

    def has_items(self):
        """ Returns True if there are items which to choose addresses for. """
        return self.__items.exists()

    def has_addresses(self):
        """ Returns True if there are addresses which to choose from. """
        return self.__addresses.exists()

    def get_address_fields(self):
        """ Iterates through all address field_dict in form. """
        for name in self.__address_fields:
            yield BoundField(self, self.__address_fields[name], name)

    def get_item_address_pairs(self):
        """ Iterates through all (order items / address) pairs displayed on the form. """
        for field_name in self.__address_fields:
            yield (self.__items.get(id__exact = field_name.split("_")[1]),
                   self.cleaned_data.get(field_name))

    def clean_hdnValidationHash(self):
        """ Ensures that the validation hash gotten from sent form is correct. """
        given_hash = self.cleaned_data.get("hdnValidationHash")
        our_hash = ShoppingCartItem.validation_hash_for_shopping_cart(request)
        if not given_hash == our_hash:
            self.add_common_error(CHECKOUT_ERR_MSG_INVALID_HASH)

    items = ShoppingCartItem.items_of_user_with_albums_and_addresses(request.user)
    addresses = Address.addresses_of_user(request.user)
    validation_hash = ShoppingCartItem.validation_hash_for_shopping_cart(request)

    field_dict = {}
    address_field_dict = {}
    initial_value_dict = {}

    field_dict["hdnValidationHash"] = forms.CharField(
        widget = forms.HiddenInput()
    )
    initial_value_dict["hdnValidationHash"] = validation_hash

    for item in items:
        field_name = u"cmbAddress_" + unicode(item.id)

        new_field = DeliveryAddressChoiceField(
            queryset = addresses,
            empty_label = None,
            label = item.album.title
        )
        field_dict[field_name] = new_field
        address_field_dict[field_name] = new_field

        if item.deliveryAddress:
            initial_value_dict[field_name] = item.deliveryAddress

    members = {
        "__request": request,
        "__items": items,
        "__addresses": addresses,
        "__validation_hash": validation_hash,
        "base_fields": field_dict,
        "__address_fields": address_field_dict,
        "__initial": initial_value_dict,
        "has_items": has_items,
        "has_addresses": has_addresses,
        "address_fields": get_address_fields,
        "item_address_pairs": get_item_address_pairs,
        "clean_hdnValidationHash": clean_hdnValidationHash,
        "__init__": init
    }

    return type("DeliveryAddressForm", (CommonAlbumizerBaseForm,), members)