示例#1
0
    def getPriceNet(self, with_discount=False):
        """Returns the net price for a cart item. This is just the net
        product price plus the properties net prices (can be positiv or 
        negative) multiply with the amount.
        """
        product = self.context.getProduct()
        price  = IPrices(product).getPriceNet()
        
        pm = IPropertyManagement(product)
        for selected_property in self.context.getProperties():
            price += pm.getPriceNet(
                selected_property["id"], 
                selected_property["selected_option"]
            )
        
        price *= self.context.getAmount()

        if with_discount == True:
            discount = IDiscountsCalculation(self.context).getDiscount()
            if discount is not None:
                discount_value = getMultiAdapter(
                    (discount, self.context)).getPriceNet()
                    
                price -= discount_value

        return price
示例#2
0
文件: cart.py 项目: viona/Easyshop
    def _getPropertiesForConfiguration(self, cart_item):
        """
        """
        u = getUtility(INumberConverter)
        cm = ICurrencyManagement(self.context)

        # Store all selected options for lookup below
        selected_options = {}

        for property in cart_item.getProperties():
            selected_options[property["id"]] = property["selected_option"]

        product = cart_item.getProduct()
        pm = IPropertyManagement(product)

        result = []
        for property in pm.getProperties():

            # Only properties with at least one option are displayed.
            if len(property.getOptions()) == 0:
                continue

            options = []
            for option in property.getOptions():

                # generate value string
                option_id = option["id"]
                option_name = option["name"]
                option_price = option["price"]

                if option_price != "0.0":
                    option_price = u.stringToFloat(option_price)
                    option_price = cm.priceToString(option_price,
                                                    "long",
                                                    "after",
                                                    suffix=None)
                    content = "%s %s" % (option_name, option_price)
                else:
                    content = option_name

                # is option selected?
                selected_option = selected_options.get(property.getId(), "")
                selected = option_id == selected_option

                options.append({
                    "id": option_id,
                    "title": content,
                    "selected": selected,
                })

            result.append({
                "id":
                "property_%s_%s" % (product.UID(), property.getId()),
                "title":
                property.Title(),
                "options":
                options,
            })

        return result
示例#3
0
 def getBuyLabel(self):
     """
     """
     pm = IPropertyManagement(self.context)
     if len(pm.getProperties()) > 0:
         return "Buy Product"
     else:
         return "Add to Cart"
示例#4
0
def getOptionsForProperty(product, property_id):
    """Returns all options for a given property id.
    """
    if IProductVariant.providedBy(product) == True:
        product = product.aq_inner.aq_parent

    pm = IPropertyManagement(product)
    return pm.getOptionsForProperty(property_id)
示例#5
0
def getOptionsForProperty(product, property_id):
    """Returns all options for a given property id.
    """
    if IProductVariant.providedBy(product) == True:
        product = product.aq_inner.aq_parent

    pm = IPropertyManagement(product)
    return pm.getOptionsForProperty(property_id)
示例#6
0
    def _getPropertiesForConfiguration(self):
        """
        """
        u = queryUtility(INumberConverter)
        cm = ICurrencyManagement(self.context)

        selected_options = {}
        for name, value in self.request.items():
            if name.startswith("property"):
                selected_options[name[42:]] = value

        pm = IPropertyManagement(self.context)

        result = []
        for property in pm.getProperties():

            # Only properties with at least one option are displayed.
            if len(property.getOptions()) == 0:
                continue

            # Preset with select option
            options = [{
                "id"       : "select",
                "title"    : _(u"Select"),
                "selected" : False,
            }]

            for option in property.getOptions():

                # generate value string
                option_id    = option["id"]
                option_name  = option["name"]
                option_price = option["price"]

                if option_price != "0.0":
                    option_price = u.stringToFloat(option_price)
                    option_price = cm.priceToString(option_price, "long", "after", suffix=None)
                    content = "%s %s" % (option_name, option_price)
                else:
                    content = option_name

                # is option selected?
                selected_option = selected_options.get(property.getId(), "")
                selected = option_id == selected_option

                options.append({
                    "id"       : option_id,
                    "title"    : content,
                    "selected" : selected,
                })

            result.append({
                "id"      : "property_%s_%s" % (self.context.UID(), property.getId()),
                "title"   : property.Title(),
                "options" : options,
            })

        return result
    def testGetProperty(self):
        """
        """
        pm = IPropertyManagement(self.shop.products.product_1)

        p = pm.getProperty("color")        
        self.assertEqual(p.aq_inner.aq_parent.portal_type, "Product")

        p = pm.getProperty("size")        
        self.assertEqual(p.aq_inner.aq_parent.portal_type, "ProductGroup")
示例#8
0
    def testGetProperty(self):
        """
        """
        pm = IPropertyManagement(self.shop.products.product_1)

        p = pm.getProperty("color")
        self.assertEqual(p.aq_inner.aq_parent.portal_type, "Product")

        p = pm.getProperty("size")
        self.assertEqual(p.aq_inner.aq_parent.portal_type, "ProductGroup")
示例#9
0
文件: cart.py 项目: Easyshop/Easyshop
    def _getPropertiesForConfiguration(self, cart_item):
        """
        """        
        u = getUtility(INumberConverter)
        cm = ICurrencyManagement(self.context)

        # Store all selected options for lookup below
        selected_options = {}
        
        for property in cart_item.getProperties():
            selected_options[property["id"]] = property["selected_option"]

        product = cart_item.getProduct()
        pm = IPropertyManagement(product)
        
        result = []
        for property in pm.getProperties():
            
            # Only properties with at least one option are displayed.
            if len(property.getOptions()) == 0:
                continue
            
            options = []
            for option in property.getOptions():

                # generate value string
                option_id    = option["id"]
                option_name  = option["name"]
                option_price = option["price"]

                if option_price != "0.0":
                    option_price = u.stringToFloat(option_price)
                    option_price = cm.priceToString(option_price, "long", "after", suffix=None)
                    content = "%s %s" % (option_name, option_price)
                else:
                    content = option_name
                        
                # is option selected?
                selected_option = selected_options.get(property.getId(), "")
                selected = option_id == selected_option
                
                options.append({
                    "id"       : option_id,
                    "title"    : content,
                    "selected" : selected,
                })
                
            result.append({
                "id"      : "property_%s_%s" % (product.UID(), property.getId()),
                "title"   : property.Title(),
                "options" : options,
            })

        return result
示例#10
0
def getTitlesByIds(product, property_id, option_id):
    # TODO: This may not be the cleanest way. Rethink it. YAGNI?
    """A simple wrapper to get the variants options (global options) of a 
    variant. In this way the adapter still works for local properties (price 
    changing) of a variant, which may later used additional to the global ones.
    """

    if IProductVariant.providedBy(product) == True:
        product = product.aq_inner.aq_parent

    pm = IPropertyManagement(product)
    return pm.getTitlesByIds(property_id, option_id)
示例#11
0
def getTitlesByIds(product, property_id, option_id):
    # TODO: This may not be the cleanest way. Rethink it. YAGNI?
    """A simple wrapper to get the variants options (global options) of a 
    variant. In this way the adapter still works for local properties (price 
    changing) of a variant, which may later used additional to the global ones.
    """
    
    if IProductVariant.providedBy(product) == True:
        product = product.aq_inner.aq_parent

    pm = IPropertyManagement(product)
    return pm.getTitlesByIds(property_id, option_id)
示例#12
0
    def testGetPriceGross_1(self):
        """Test a property which is in group and product.
        """
        pm = IPropertyManagement(self.shop.products.product_1)

        price = pm.getPriceGross("color", "Red")
        self.assertEqual(price, -10.0)

        price = pm.getPriceGross("color", "Blue")
        self.assertEqual(price, 0.0)

        price = pm.getPriceGross("color", "Green")
        self.assertEqual(price, 15.0)
    def testGetPriceGross_1(self):
        """Test a property which is in group and product.
        """
        pm = IPropertyManagement(self.shop.products.product_1)

        price = pm.getPriceGross("color", "Red")
        self.assertEqual(price, -10.0) 

        price = pm.getPriceGross("color", "Blue")
        self.assertEqual(price, 0.0) 

        price = pm.getPriceGross("color", "Green")
        self.assertEqual(price, 15.0) 
    def testGetPriceGross_2(self):
        """Test a properties which is just in groups
        """
        pm = IPropertyManagement(self.shop.products.product_1)

        price = pm.getPriceGross("size", "Small")
        self.assertEqual(price, -11.0) 

        price = pm.getPriceGross("size", "Medium")
        self.assertEqual(price, 1.0) 

        price = pm.getPriceGross("size", "Large")
        self.assertEqual(price, 22.0) 
    def testGetPriceNet_2(self):
        """Test a properties which is just in groups
        """
        pm = IPropertyManagement(self.shop.products.product_1)

        price = pm.getPriceNet("size", "Small")
        self.assertEqual("%.2f" % price, "-9.24")

        price = pm.getPriceNet("size", "Medium")
        self.assertEqual("%.2f" % price, "0.84") 

        price = pm.getPriceNet("size", "Large")
        self.assertEqual("%.2f" % price, "18.49") 
示例#16
0
    def testGetPriceForCustomer_1(self):
        """Test a property which is in group and product.
        """
        pm = IPropertyManagement(self.shop.products.product_1)

        price = pm.getPriceForCustomer("color", "Red")
        self.assertEqual("%.2f" % price, "-9.24")

        price = pm.getPriceForCustomer("color", "Blue")
        self.assertEqual(price, 0.0)

        price = pm.getPriceForCustomer("color", "Green")
        self.assertEqual("%.2f" % price, "13.87")
示例#17
0
    def testGetPriceNet_2(self):
        """Test a properties which is just in groups
        """
        pm = IPropertyManagement(self.shop.products.product_1)

        price = pm.getPriceNet("size", "Small")
        self.assertEqual("%.2f" % price, "-9.24")

        price = pm.getPriceNet("size", "Medium")
        self.assertEqual("%.2f" % price, "0.84")

        price = pm.getPriceNet("size", "Large")
        self.assertEqual("%.2f" % price, "18.49")
示例#18
0
    def testGetPriceGross_2(self):
        """Test a properties which is just in groups
        """
        pm = IPropertyManagement(self.shop.products.product_1)

        price = pm.getPriceGross("size", "Small")
        self.assertEqual(price, -11.0)

        price = pm.getPriceGross("size", "Medium")
        self.assertEqual(price, 1.0)

        price = pm.getPriceGross("size", "Large")
        self.assertEqual(price, 22.0)
    def testGetPriceForCustomer_2(self):
        """Test a property which is just in group.
        """
        pm = IPropertyManagement(self.shop.products.product_1)

        price = pm.getPriceForCustomer("size", "Small")
        self.assertEqual("%.2f" % price, "-10.17")

        price = pm.getPriceForCustomer("size", "Medium")
        self.assertEqual("%.2f" % price, "0.92") 

        price = pm.getPriceForCustomer("size", "Large")
        self.assertEqual("%.2f" % price, "20.34") 
示例#20
0
    def testGetPriceForCustomer_2(self):
        """Test a property which is just in group.
        """
        pm = IPropertyManagement(self.shop.products.product_1)

        price = pm.getPriceForCustomer("size", "Small")
        self.assertEqual("%.2f" % price, "-10.17")

        price = pm.getPriceForCustomer("size", "Medium")
        self.assertEqual("%.2f" % price, "0.92")

        price = pm.getPriceForCustomer("size", "Large")
        self.assertEqual("%.2f" % price, "20.34")
    def testGetPriceForCustomer_1(self):
        """Test a property which is in group and product.
        """
        pm = IPropertyManagement(self.shop.products.product_1)

        price = pm.getPriceForCustomer("color", "Red")
        self.assertEqual("%.2f" % price, "-9.24")

        price = pm.getPriceForCustomer("color", "Blue")
        self.assertEqual(price, 0.0) 

        price = pm.getPriceForCustomer("color", "Green")
        self.assertEqual("%.2f" % price, "13.87") 
示例#22
0
文件: cart.py 项目: viona/Easyshop
    def _getPropertiesForVariants(self, cart_item):
        """
        """
        u = getUtility(INumberConverter)
        cm = ICurrencyManagement(self.context)

        variant = cart_item.getProduct()
        product = variant.aq_inner.aq_parent

        selected_options = {}
        for property in variant.getForProperties():
            name, value = property.split(":")
            selected_options[name] = value

        pm = IPropertyManagement(product)

        result = []
        for property in pm.getProperties():

            # Only properties with at least one option are displayed.
            if len(property.getOptions()) == 0:
                continue

            options = []
            for option in property.getOptions():

                # generate value string
                option_id = option["id"]
                option_name = option["name"]
                content = option_name

                # is option selected?
                selected_option = selected_options.get(property.getId(), "")
                selected = option_id == selected_option

                options.append({
                    "id": option_id,
                    "title": content,
                    "selected": selected,
                })

            result.append({
                "id":
                "property_%s_%s" % (product.UID(), property.getId()),
                "title":
                property.Title(),
                "options":
                options,
            })

        return result
示例#23
0
    def testGetPriceNet_1(self):
        """Test a property which is in group and product
        """
        pm = IPropertyManagement(self.shop.products.product_1)

        # Note that color prices are taken from product not from group
        price = pm.getPriceNet("color", "Red")
        self.assertEqual("%.2f" % price, "-8.40")

        price = pm.getPriceNet("color", "Blue")
        self.assertEqual(price, 0.0)

        price = pm.getPriceNet("color", "Green")
        self.assertEqual("%.2f" % price, "12.61")
    def testGetPriceNet_1(self):
        """Test a property which is in group and product
        """
        pm = IPropertyManagement(self.shop.products.product_1)

        # Note that color prices are taken from product not from group
        price = pm.getPriceNet("color", "Red")
        self.assertEqual("%.2f" % price, "-8.40")

        price = pm.getPriceNet("color", "Blue")
        self.assertEqual(price, 0.0) 

        price = pm.getPriceNet("color", "Green")
        self.assertEqual("%.2f" % price, "12.61") 
示例#25
0
    def testGetProperties(self):
        """Get properties from product.
        
        Note:
            product 1 is in group 1
            group 1 has color property too
            but products properties are choosen

        Note that properties are taken from group and product
        """

        pm = IPropertyManagement(self.shop.products.product_1)
        ids = [p.getId() for p in pm.getProperties()]

        self.assertEqual(ids, ['color', 'size', 'material', 'quality'])
    def testGetProperties(self):
        """Get properties from product.
        
        Note:
            product 1 is in group 1
            group 1 has color property too
            but products properties are choosen

        Note that properties are taken from group and product
        """
        
        pm = IPropertyManagement(self.shop.products.product_1)
        ids = [p.getId() for p in pm.getProperties()]
        
        self.assertEqual(ids, ['color', 'size', 'material', 'quality'])
示例#27
0
文件: cart.py 项目: Easyshop/Easyshop
    def _getPropertiesForVariants(self, cart_item):
        """
        """        
        u = getUtility(INumberConverter)
        cm = ICurrencyManagement(self.context)

        variant = cart_item.getProduct()
        product = variant.aq_inner.aq_parent

        selected_options = {}
        for property in variant.getForProperties():
            name, value = property.split(":")
            selected_options[name] = value
            
        pm = IPropertyManagement(product)
        
        result = []
        for property in pm.getProperties():
            
            # Only properties with at least one option are displayed.
            if len(property.getOptions()) == 0:
                continue
            
            options = []
            for option in property.getOptions():

                # generate value string
                option_id = option["id"]
                option_name = option["name"]
                content = option_name
                        
                # is option selected?
                selected_option = selected_options.get(property.getId(), "")
                selected = option_id == selected_option
                
                options.append({
                    "id"       : option_id,
                    "title"    : content,
                    "selected" : selected,
                })
                
            result.append({
                "id"      : "property_%s_%s" % (product.UID(), property.getId()),
                "title"   : property.Title(),
                "options" : options,
            })

        return result
示例#28
0
    def getProperties(self):
        """
        """
        u = queryUtility(INumberConverter)
        cm = ICurrencyManagement(self.context)

        selected_properties = {}
        for name, value in self.request.form.items():
            if name.startswith("property"):
                selected_properties[name[42:]] = value

        pm = IPropertyManagement(self.context)

        result = []
        for property in pm.getProperties():
            options = []
            for option in property.getOptions():

                # generate value string
                name = option["name"]
                price = option["price"]

                if price != "":
                    price = u.stringToFloat(price)
                    price = cm.priceToString(price, "long", "after")
                    content = "%s %s" % (name, price)
                else:
                    content = name

                # is option selected?
                selected = name == selected_properties.get(
                    property.getId(), False)

                options.append({
                    "content": content,
                    "value": name,
                    "selected": selected,
                })

            result.append({
                "id": property.getId(),
                "title": property.Title(),
                "options": options,
            })

        return result
示例#29
0
    def getProperties(self):
        """
        """
        u = queryUtility(INumberConverter)
        cm = ICurrencyManagement(self.context)
                
        selected_properties = {}
        for name, value in self.request.form.items():
            if name.startswith("property"):
                selected_properties[name[42:]] = value

        pm = IPropertyManagement(self.context)
        
        result = []
        for property in pm.getProperties():
            options = []
            for option in property.getOptions():

                # generate value string
                name  = option["name"]
                price = option["price"]

                if price != "":
                    price = u.stringToFloat(price)
                    price = cm.priceToString(price, "long", "after")
                    content = "%s %s" % (name, price)
                else:
                    content = name
                        
                # is option selected?
                selected = name == selected_properties.get(property.getId(), False)
                
                options.append({
                    "content"  : content,
                    "value"    : name,
                    "selected" : selected,
                })            
                
            result.append({
                "id"      : property.getId(),
                "title"   : property.Title(),
                "options" : options,
            })

        return result
示例#30
0
    def getProperties(self):
        """
        """
        result = []
        pm = IPropertyManagement(self.context)
        for property in pm.getProperties():

            # Only properties with at least one option are displayed.
            options = property.getOptions()
            if len(options) == 0:
                continue

            result.append({
                "id": property.getId(),
                "name": "property_" + property.getId(),
                "title": property.Title(),
                "options": options,
            })

        return result
示例#31
0
    def getProperties(self):
        """
        """
        result = []
        pm = IPropertyManagement(self.context)
        for property in pm.getProperties():

            # Only properties with at least one option are displayed.
            options = property.getOptions()
            if len(options) == 0:
                continue

            result.append({
                "id"      : property.getId(),
                "name"    : "property_" + property.getId(),
                "title"   : property.Title(),
                "options" : options,
            })

        return result
示例#32
0
    def getPriceForCustomer(self, formatted=True):
        """
        """
        p = IPrices(self.context)
        price = p.getPriceForCustomer()

        if IProductVariantsManagement(self.context).hasVariants() == False:
            total_diff = 0.0
            pm = IPropertyManagement(self.context)
            for property_id, selected_option in self.request.form.items():
                if property_id.startswith("property"):
                    total_diff += pm.getPriceForCustomer(
                        property_id[42:],
                        selected_option
                    )
            price += total_diff

        if formatted == True:
            cm = ICurrencyManagement(self.context)
            return cm.priceToString(price, suffix=None)
        else:
            return price
示例#33
0
    def getPriceGross(self, with_discount=False):
        """Returns the gross price for a cart item. This is just the gross
        product price plus the properties gross prices (can be positiv or 
        negative) multiply with the amount.
        """
        product = self.context.getProduct()
        price = IPrices(product).getPriceGross()

        pm = IPropertyManagement(product)
        for selected_property in self.context.getProperties():
            price += pm.getPriceGross(selected_property["id"],
                                      selected_property["selected_option"])

        price *= self.context.getAmount()

        if with_discount == True:
            discount = IDiscountsCalculation(self.context).getDiscount()
            if discount is not None:
                discount_value = getMultiAdapter(
                    (discount, self.context)).getPriceGross()
                price -= discount_value

        return price
示例#34
0
    def getStandardPriceForCustomer(self, formatted=True):
        """Returns the standard price for a customer when the product is for
        sale. Used to display the crossed-out standard price.
        """
        p = IPrices(self.context)
        price = p.getPriceForCustomer(effective=False)

        if IProductVariantsManagement(self.context).hasVariants() == False:
            total_diff = 0.0
            pm = IPropertyManagement(self.context)
            for property_id, selected_option in self.request.form.items():
                if property_id.startswith("property"):
                    total_diff += pm.getPriceForCustomer(
                        property_id[42:],
                        selected_option
                    )
            price + total_diff

        if formatted == True:
            cm = ICurrencyManagement(self.context)
            return cm.priceToString(price, suffix = None)
        else:
            return price
示例#35
0
    def _addItemFromCartItem(self, id, cart_item):
        """Sets the item by given cart item.
        """        
        self.context.manage_addProduct["easyshop.core"].addOrderItem(id=str(id))
        new_item = getattr(self.context, str(id))

        # set product quantity        
        new_item.setProductQuantity(cart_item.getAmount())
                
        # Set product prices & taxes
        product_taxes  = ITaxes(cart_item.getProduct())
        product_prices = IPrices(cart_item.getProduct())
        item_prices = IPrices(cart_item)
        item_taxes  = ITaxes(cart_item)
        
        new_item.setTaxRate(product_taxes.getTaxRateForCustomer())
        new_item.setProductTax(product_taxes.getTaxForCustomer())
        
        new_item.setProductPriceGross(product_prices.getPriceForCustomer())
        new_item.setProductPriceNet(product_prices.getPriceNet())

        # Set item prices & taxes
        new_item.setTax(item_taxes.getTaxForCustomer())
        new_item.setPriceGross(item_prices.getPriceForCustomer())
        new_item.setPriceNet(item_prices.getPriceNet())

        # Discount
        discount = IDiscountsCalculation(cart_item).getDiscount()
        if discount is not None:
            new_item.setDiscountDescription(discount.Title())

            dp = getMultiAdapter((discount, cart_item))
            new_item.setDiscountGross(dp.getPriceForCustomer())
            new_item.setDiscountNet(dp.getPriceNet())
        
        # Set product
        product = cart_item.getProduct()
        new_item.setProduct(product)

        # Set product name and id
        data = IData(product).asDict()
        new_item.setProductTitle(data["title"])
        new_item.setArticleId(data["article_id"])

        # Set properties
        properties = []
        pm = IPropertyManagement(product)
        for selected_property in cart_item.getProperties():

            # Get the price
            property_price = pm.getPriceForCustomer(
                selected_property["id"], 
                selected_property["selected_option"])

            # By default we save the titles of the properties and selected 
            # options In this way they are kept if the title of a property or 
            # option will be changed after the product has been bought.
            titles = getTitlesByIds(
                product,
                selected_property["id"], 
                selected_property["selected_option"])

            # If we don't find the property or option we ignore the property. 
            # This can only happen if the property has been deleted after a 
            # product has been added to the cart. In this case we don't want the 
            # property at all (I think).
            if titles is None:
                continue
                                    
            properties.append({
                "title" : titles["property"],
                "selected_option" : titles["option"],
                "price" : str(property_price),
            })
                            
        new_item.setProperties(properties)
示例#36
0
    def getCartItems(self):
        """Returns the items of the current cart.
        """
        cart = self._getCart()

        cm = ICurrencyManagement(self.context)
        im = IItemManagement(cart)

        result = []
        for cart_item in im.getItems():
            product = cart_item.getProduct()

            product_price = IPrices(
                cart_item).getPriceForCustomer() / cart_item.getAmount()
            product_price = cm.priceToString(product_price)

            price = IPrices(cart_item).getPriceForCustomer()

            # Todo: Think about to factoring out properties stuff
            # because same has to be uses there: cart.py / getCartItems()
            properties = []
            pm = IPropertyManagement(product)
            for selected_property in cart_item.getProperties():
                property_price = pm.getPriceForCustomer(
                    selected_property["id"],
                    selected_property["selected_option"])

                # Get titles of property and option
                titles = getTitlesByIds(product, selected_property["id"],
                                        selected_property["selected_option"])

                if titles is None:
                    continue

                if IProductVariant.providedBy(product) == True:
                    show_price = False
                else:
                    show_price = True

                properties.append({
                    "id": selected_property["id"],
                    "selected_option": titles["option"],
                    "title": titles["property"],
                    "price": cm.priceToString(property_price),
                    "show_price": show_price,
                })

            # Discount
            total_price = 0
            discount = IDiscountsCalculation(cart_item).getDiscount()
            if discount is not None:
                discount_price = getMultiAdapter(
                    (discount, cart_item)).getPriceForCustomer()

                discount = {
                    "title": discount.Title(),
                    "value": cm.priceToString(discount_price, prefix="-"),
                }

                total_price = price - discount_price

            # Data
            data = IData(product).asDict()

            result.append({
                "product_title": data["title"],
                "product_price": product_price,
                "properties": properties,
                "price": cm.priceToString(price),
                "amount": cart_item.getAmount(),
                "total_price": cm.priceToString(total_price),
                "discount": discount,
            })

        return result
示例#37
0
    def getProducts(self):
        """Returns the last products, which are added to the cart.
        """
        cm = ICurrencyManagement(self.context)

        result = []
        for cart_item_id in self.request.SESSION.get("added-to-cart", []):

            cart = ICartManagement(self.context).getCart()
            cart_item = IItemManagement(cart).getItem(cart_item_id)
            if cart_item is None:
                continue

            product = cart_item.getProduct()
            if product is None:
                continue

            # Price
            price = IPrices(product).getPriceForCustomer()

            # Image
            product = cart_item.getProduct()
            image = IImageManagement(product).getMainImage()
            if image is not None:
                image_url = image.absolute_url()
            else:
                image_url = None

            # Get selected properties
            properties = []
            pm = IPropertyManagement(product)

            for selected_property in cart_item.getProperties():
                property_price = pm.getPriceForCustomer(
                    selected_property["id"],
                    selected_property["selected_option"])

                # Get titles of property and option
                titles = getTitlesByIds(product, selected_property["id"],
                                        selected_property["selected_option"])

                if titles is None:
                    continue

                if (property_price == 0.0) or \
                   (IProductVariant.providedBy(product)) == True:
                    show_price = False
                else:
                    show_price = True

                properties.append({
                    "id": selected_property["id"],
                    "selected_option": titles["option"],
                    "title": titles["property"],
                    "price": cm.priceToString(property_price),
                    "show_price": show_price,
                })

                price += property_price

            total = cart_item.getAmount() * price

            result.append({
                "title": product.Title(),
                "url": product.absolute_url(),
                "amount": cart_item.getAmount(),
                "total": cm.priceToString(total),
                "price": cm.priceToString(price),
                "image_url": image_url,
                "properties": properties,
            })

        # Update selected shipping method. TODO: This should be factored out and
        # made available via a event or similar. It is also used within
        # ajax/cart/_refresh_cart
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()

        shop = IShopManagement(self.context).getShop()
        shipping_methods = IShippingMethodManagement(shop).getShippingMethods(
            check_validity=True)
        shipping_methods_ids = [sm.getId() for sm in shipping_methods]
        selected_shipping_method = self.request.get("selected_shipping_method")

        # Set selected shipping method
        if selected_shipping_method in shipping_methods_ids:
            customer.selected_shipping_method = \
                safe_unicode(self.request.get("selected_shipping_method"))
        else:
            customer.selected_shipping_method = shipping_methods_ids[0]

        # Reset session
        if self.request.SESSION.has_key("added-to-cart"):
            del self.request.SESSION["added-to-cart"]
        return result
示例#38
0
    def _getPropertiesForVariants(self):
        """
        """
        u = queryUtility(INumberConverter)
        cm = ICurrencyManagement(self.context)

        selected_options = {}
        for name, value in self.request.items():
            if name.startswith("property"):
                if len(name) > 42:
                    selected_options[name[42:]] = value
                else:
                    selected_options[name[9:]] = value

        # If nothing is selected we select the default variant
        if selected_options == {}:
            pvm = IProductVariantsManagement(self.context)
            default_variant = pvm.getDefaultVariant()

            # If there is no default variant return empty list
            if default_variant is None:
                return []

            for property in default_variant.getForProperties():
                name, value = property.split(":")
                selected_options[name] = value

        pm = IPropertyManagement(self.context)

        result = []
        for property in pm.getProperties():

            # Only properties with at least one option are displayed.
            if len(property.getOptions()) == 0:
                continue

            options = []
            for option in property.getOptions():

                # generate value string
                option_id    = option["id"]
                option_name  = option["name"]
                # option_price = option["price"]
                # option_price = u.stringToFloat(option_price)
                # option_price = cm.priceToString(option_price, "long", "after")
                # content = "%s %s" % (option_name, option_price)
                content = option_name

                # is option selected?
                selected_option = selected_options.get(property.getId(), "")
                selected = option_id == selected_option

                options.append({
                    "id"       : option_id,
                    "title"    : content,
                    "selected" : selected,
                })

            result.append({
                "id"      : "property_%s_%s" % (self.context.UID(), property.getId()),
                "title"   : property.Title(),
                "options" : options,
            })

        return result
示例#39
0
    def addToCart(self, redirect=True, add_accessories=True):
        """
        """
        shop = IShopManagement(self.context).getShop()
        cm = ICartManagement(shop)

        cart = cm.getCart()
        if cart is None:
            cart = cm.createCart()

        pvm = IProductVariantsManagement(self.context)
        if pvm.hasVariants():

            # Get the actual "product"
            product = pvm.getSelectedVariant() or pvm.getDefaultVariant()

            # Using here the selected product ensures that we save the right
            # properties. This is important when the selected variant doesn't
            # exist.
            properties = []
            for property in product.getForProperties():
                property_id, selected_option = property.split(":")
                properties.append({
                    "id": property_id,
                    "selected_option": selected_option,
                })
        else:

            # The product is the context
            product = self.context

            # Unlike above we take the properties out of the request, because
            # there is no object wich stores the different properties.
            properties = []
            for property in IPropertyManagement(product).getProperties():
                selected_option_id = self.request.get(
                    "property_%s_%s" % (product.UID(), property.getId()))

                # If nothing is selected we take the first option of the
                # property
                if (selected_option_id is None) or (selected_option_id
                                                    == "select"):
                    property = IPropertyManagement(product).getProperty(
                        property.getId())
                    property_options = property.getOptions()

                    if property_options:
                        selected_option = property.getOptions()[0]
                        selected_option_id = selected_option["id"]
                    else:
                        selected_option_id = ""

                properties.append({
                    "id": property.getId(),
                    "selected_option": selected_option_id
                })

        # get quantity
        quantity = int(
            self.context.request.get("%s_quantity" % self.context.UID(), 1))

        # returns true if the product was already within the cart
        result, item_id = IItemManagement(cart).addItem(
            product, tuple(properties), quantity)

        # Add product to session (for display on add to cart view)
        if self.request.SESSION.get("added-to-cart") is None:
            self.request.SESSION["added-to-cart"] = []
        self.request.SESSION["added-to-cart"].append(item_id)

        # Add the accessories
        if add_accessories == True:
            catalog = getToolByName(self.context, "portal_catalog")
            accessories = tuplize(self.request.get("accessories", []))
            for uid in accessories:
                try:
                    brain = catalog.searchResults(UID=uid)[0]
                except IndexError:
                    continue

                # We reuse the same view with an other context. The context are
                # the accessories
                product = brain.getObject()
                view = getMultiAdapter((product, self.request),
                                       name="addToCart")
                view.addToCart(redirect=False, add_accessories=False)

        if redirect == True:
            # Set portal message
            # putils = getToolByName(self.context, "plone_utils")
            # if result == True:
            #     putils.addPortalMessage(MESSAGES["CART_INCREASED_AMOUNT"])
            # else:
            #     putils.addPortalMessage(MESSAGES["CART_ADDED_PRODUCT"])

            url = "%s/added-to-cart" % shop.absolute_url()
            self.context.request.response.redirect(url)
示例#40
0
    def getCartItems(self):
        """Returns the items of the current cart.
        """
        cart = self._getCart()

        cm = ICurrencyManagement(self.context)
        im = IItemManagement(cart)
                
        result = []
        for cart_item in im.getItems():
            product = cart_item.getProduct()
            
            product_price = IPrices(cart_item).getPriceForCustomer() / cart_item.getAmount()
            product_price = cm.priceToString(product_price)
            
            price = IPrices(cart_item).getPriceForCustomer()

            # Todo: Think about to factoring out properties stuff
            # because same has to be uses there: cart.py / getCartItems()
            properties = []
            pm = IPropertyManagement(product)
            for selected_property in cart_item.getProperties():
                property_price = pm.getPriceForCustomer(
                    selected_property["id"], 
                    selected_property["selected_option"]) 

                # Get titles of property and option
                titles = getTitlesByIds(
                    product,
                    selected_property["id"], 
                    selected_property["selected_option"])
                    
                if titles is None:
                    continue

                if IProductVariant.providedBy(product) == True:
                    show_price = False
                else:
                    show_price = True

                properties.append({
                    "id" : selected_property["id"],
                    "selected_option" : titles["option"],
                    "title" : titles["property"],
                    "price" : cm.priceToString(property_price),
                    "show_price" : show_price,
                })

            # Discount
            total_price = 0
            discount = IDiscountsCalculation(cart_item).getDiscount()
            if discount is not None:
                discount_price = getMultiAdapter((discount, cart_item)).getPriceForCustomer()

                discount = {
                    "title" : discount.Title(),
                    "value" : cm.priceToString(discount_price, prefix="-"),
                }

                total_price = price - discount_price
            
            # Data    
            data = IData(product).asDict()
            
            result.append({
                "product_title" : data["title"],
                "product_price" : product_price,
                "properties"    : properties,
                "price"         : cm.priceToString(price),
                "amount"        : cart_item.getAmount(),
                "total_price"   : cm.priceToString(total_price),
                "discount"      : discount,
            })
        
        return result
示例#41
0
    def _addItemFromCartItem(self, id, cart_item):
        """Sets the item by given cart item.
        """
        self.context.manage_addProduct["easyshop.core"].addOrderItem(
            id=str(id))
        new_item = getattr(self.context, str(id))

        # set product quantity
        new_item.setProductQuantity(cart_item.getAmount())

        # Set product prices & taxes
        product_taxes = ITaxes(cart_item.getProduct())
        product_prices = IPrices(cart_item.getProduct())
        item_prices = IPrices(cart_item)
        item_taxes = ITaxes(cart_item)

        new_item.setTaxRate(product_taxes.getTaxRateForCustomer())
        new_item.setProductTax(product_taxes.getTaxForCustomer())

        new_item.setProductPriceGross(product_prices.getPriceForCustomer())
        new_item.setProductPriceNet(product_prices.getPriceNet())

        # Set item prices & taxes
        new_item.setTax(item_taxes.getTaxForCustomer())
        new_item.setPriceGross(item_prices.getPriceForCustomer())
        new_item.setPriceNet(item_prices.getPriceNet())

        # Discount
        discount = IDiscountsCalculation(cart_item).getDiscount()
        if discount is not None:
            new_item.setDiscountDescription(discount.Title())

            dp = getMultiAdapter((discount, cart_item))
            new_item.setDiscountGross(dp.getPriceForCustomer())
            new_item.setDiscountNet(dp.getPriceNet())

        # Set product
        product = cart_item.getProduct()
        new_item.setProduct(product)

        # Set product name and id
        data = IData(product).asDict()
        new_item.setProductTitle(data["title"])
        new_item.setArticleId(data["article_id"])

        # Set properties
        properties = []
        pm = IPropertyManagement(product)
        for selected_property in cart_item.getProperties():

            # Get the price
            property_price = pm.getPriceForCustomer(
                selected_property["id"], selected_property["selected_option"])

            # By default we save the titles of the properties and selected
            # options In this way they are kept if the title of a property or
            # option will be changed after the product has been bought.
            titles = getTitlesByIds(product, selected_property["id"],
                                    selected_property["selected_option"])

            # If we don't find the property or option we ignore the property.
            # This can only happen if the property has been deleted after a
            # product has been added to the cart. In this case we don't want the
            # property at all (I think).
            if titles is None:
                continue

            properties.append({
                "title": titles["property"],
                "selected_option": titles["option"],
                "price": str(property_price),
            })

        new_item.setProperties(properties)
示例#42
0
    def getProducts(self):
        """Returns the last products, which are added to the cart.
        """
        cm = ICurrencyManagement(self.context)
        
        result = []
        for cart_item_id in self.request.SESSION.get("added-to-cart", []):

            cart = ICartManagement(self.context).getCart()
            cart_item = IItemManagement(cart).getItem(cart_item_id)
            if cart_item is None:
                continue

            product = cart_item.getProduct()
            if product is None:
                continue
                
            # Price
            price = IPrices(product).getPriceForCustomer()
        
            # Image
            product = cart_item.getProduct()
            image = IImageManagement(product).getMainImage()
            if image is not None:
                image_url = image.absolute_url()
            else:
                image_url = None
        
            # Get selected properties
            properties = []
            pm = IPropertyManagement(product)
        
            for selected_property in cart_item.getProperties():
                property_price = pm.getPriceForCustomer(
                    selected_property["id"], 
                    selected_property["selected_option"]) 

                # Get titles of property and option
                titles = getTitlesByIds(
                    product,
                    selected_property["id"], 
                    selected_property["selected_option"])
                
                if titles is None:
                    continue

                if (property_price == 0.0) or \
                   (IProductVariant.providedBy(product)) == True:
                    show_price = False
                else:
                    show_price = True
                
                properties.append({
                    "id" : selected_property["id"],
                    "selected_option" : titles["option"],
                    "title" : titles["property"],
                    "price" : cm.priceToString(property_price),
                    "show_price" : show_price,
                })
            
                price += property_price
        
            total = cart_item.getAmount() * price
                        
            result.append({
                "title"      : product.Title(),
                "url"        : product.absolute_url(),
                "amount"     : cart_item.getAmount(),
                "total"      : cm.priceToString(total),
                "price"      : cm.priceToString(price),
                "image_url"  : image_url,
                "properties" : properties,
            })
        
        # Update selected shipping method. TODO: This should be factored out and
        # made available via a event or similar. It is also used within 
        # ajax/cart/_refresh_cart
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
            
        shop = IShopManagement(self.context).getShop()
        shipping_methods = IShippingMethodManagement(shop).getShippingMethods(check_validity=True)
        shipping_methods_ids = [sm.getId() for sm in shipping_methods]
        selected_shipping_method = self.request.get("selected_shipping_method")

        # Set selected shipping method
        if selected_shipping_method in shipping_methods_ids:
            customer.selected_shipping_method = \
                safe_unicode(self.request.get("selected_shipping_method"))
        else:
            customer.selected_shipping_method = shipping_methods_ids[0]
        
        # Reset session
        if self.request.SESSION.has_key("added-to-cart"):
            del self.request.SESSION["added-to-cart"]
        return result