def testDeleteItemByOrd(self): """ """ self.logout() cm = ICartManagement(self.shop) cart = cm.createCart() im = IItemManagement(cart) im.addItem(self.product_1, properties=()) self.assertEqual(len(im.getItems()), 1) im.addItem(self.product_2, properties=(), quantity=3) self.assertEqual(len(im.getItems()), 2) # Try to delete non existing ord result = im.deleteItemByOrd(3) self.assertEqual(result, False) # Still 2 items in there self.assertEqual(len(im.getItems()), 2) # delete first item result = im.deleteItemByOrd(0) self.assertEqual(result, True) self.assertEqual(len(im.getItems()), 1) # Once again, but now it should be another result = im.deleteItemByOrd(0) self.assertEqual(result, True) self.assertEqual(len(im.getItems()), 0)
def testDeleteItem(self): """ """ self.logout() cm = ICartManagement(self.shop) cart = cm.createCart() im = IItemManagement(cart) im.addItem(self.product_1, properties=()) self.assertEqual(len(im.getItems()), 1) im.addItem(self.product_2, properties=(), quantity=3) self.assertEqual(len(im.getItems()), 2) # Try to delete non existing id result = im.deleteItem("3") self.assertEqual(result, False) # Still 2 items in there self.assertEqual(len(im.getItems()), 2) # delete first item result = im.deleteItem("0") self.assertEqual(result, True) self.assertEqual(len(im.getItems()), 1) # delete second item result = im.deleteItem("1") self.assertEqual(result, True) self.assertEqual(len(im.getItems()), 0)
def testAddItemsAndGetItems(self): """ """ self.logout() cm = ICartManagement(self.shop) cart = cm.createCart() im = IItemManagement(cart) im.addItem(self.product_1, properties=()) self.assertEqual(len(im.getItems()), 1) im.addItem(self.product_1, properties=()) self.assertEqual(len(im.getItems()), 1) im.addItem(self.product_1, properties=(), quantity=2) self.assertEqual(len(im.getItems()), 1) im.addItem(self.product_2, properties=(), quantity=3) self.assertEqual(len(im.getItems()), 2) i1, i2 = im.getItems() i1.getId() == "0" i1.getProduct() == self.product_1 i1.getAmount() == 4 i1.getId() == "1" i1.getProduct() == self.product_2 i1.getAmount() == 2
def afterSetUp(self): """ """ super(TestCartItemProperties, self).afterSetUp() self.login("newmember") cm = ICartManagement(self.shop) cart = cm.createCart() im = IItemManagement(cart) properties = ( { "id": "color", "selected_option": "Red" }, # -10.0 { "id": "material", "selected_option": "Wood" }, # 0.0 { "id": "quality", "selected_option": "High" }, # 1500.0 ) im.addItem(self.product_1, properties=properties, quantity=3) self.item1 = im.getItems()[0]
def getPriceNet(self, with_shipping=True, with_payment=True, with_discount=True): """Returns the net price of the cart. This is just a sum over net prices of all items of the cart plus shipping and payment. """ im = IItemManagement(self.context) if im.hasItems() == False: return 0.0 price = 0.0 for cart_item in im.getItems(): # NOTE: with_discount is passed here price += IPrices(cart_item).getPriceNet( with_discount=with_discount) if with_shipping == True: sm = IShippingPriceManagement(self.shop) shipping_price = sm.getPriceNet() price += shipping_price if with_payment == True: sm = IPaymentPriceManagement(self.shop) payment_price = sm.getPriceNet() price += payment_price return price
class OrderPrices: """Adapter which provides IPrices for order content objects. """ implements(IPrices) adapts(IOrder) def __init__(self, context): """ """ self.context = context self.item_management = IItemManagement(context) def getPriceNet(self): """Returns the total net price of the order. """ total = 0.0 for item in self.item_management.getItems(): total += item.getPriceNet() total -= item.getDiscountNet() total += self.context.getPaymentPriceNet() total += self.context.getShippingPriceNet() return total def getPriceGross(self): """Returns the total gross price of the order. """ total = 0.0 for item in self.item_management.getItems(): total += item.getPriceGross() total -= item.getDiscountGross() total += self.context.getPaymentPriceGross() total += self.context.getShippingPriceGross() return total def getPriceForCustomer(self): """In the context of an order PriceGross and PriceForCustomer are equal. """ return self.getPriceGross()
def testGetItems(self): """ """ self.order.invokeFactory("OrderItem", "item_1") self.order.invokeFactory("OrderItem", "item_2") im = IItemManagement(self.order) item_ids = [item.getId() for item in im.getItems()] self.assertEqual(item_ids, ["item_1", "item_2"])
def testGetItems(self): """ """ self.order.invokeFactory("OrderItem", "item_1") self.order.invokeFactory("OrderItem", "item_2") im = IItemManagement(self.order) item_ids = [item.getId() for item in im.getItems()] self.assertEqual(item_ids, ["item_1", "item_2"])
def testAddItemFromCartItem(self): """ """ cm = ICartManagement(self.shop) cart = cm.createCart() properties = ( { "id": "color", "selected_option": "Red" }, # -10.0 { "id": "material", "selected_option": "Wood" }, # 0.0 { "id": "quality", "selected_option": "High" }, # 1500.0 ) cim = IItemManagement(cart) cim.addItem(self.product_1, properties=properties, quantity=3) cart_item = IItemManagement(cart).getItems()[0] oim = IItemManagement(self.order) oim._addItemFromCartItem("0", cart_item) order_item = oim.getItems()[0] self.assertEqual(order_item.getProductQuantity(), 3) self.assertEqual("%.2f" % order_item.getProductPriceGross(), "22.00") self.assertEqual("%.2f" % order_item.getProductPriceNet(), "18.49") self.assertEqual("%.2f" % order_item.getProductTax(), "3.51") self.assertEqual("%.2f" % order_item.getPriceGross(), "4536.00") self.assertEqual("%.2f" % order_item.getPriceNet(), "3811.76") self.assertEqual(order_item.getTaxRate(), 19.0) self.assertEqual("%.2f" % order_item.getTax(), "724.24") self.assertEqual(order_item.getProduct(), self.product_1) properties = order_item.getProperties() self.assertEqual(properties[0]["title"], "Color") self.assertEqual(properties[0]["selected_option"], "Red") self.assertEqual(properties[0]["price"], "-10.0") self.assertEqual(properties[1]["title"], "Material") self.assertEqual(properties[1]["selected_option"], "Wood") self.assertEqual(properties[1]["price"], "0.0") self.assertEqual(properties[2]["title"], "Quality") self.assertEqual(properties[2]["selected_option"], "High") self.assertEqual(properties[2]["price"], "1500.0")
def getItems(self): """ """ nc = queryUtility(INumberConverter) cm = ICurrencyManagement(self.context) items = [] item_manager = IItemManagement(self.context) for item in item_manager.getItems(): product_price_gross = cm.priceToString(item.getProductPriceGross(), suffix=None) tax_rate = nc.floatToTaxString(item.getTaxRate()) tax = cm.priceToString(item.getTax(), suffix=None) price_gross = cm.priceToString(item.getPriceGross(), suffix=None) # Get url. Takes care of, if the product has been deleted in the # meanwhile. product = item.getProduct() if product is None: url = None articleId = None else: url = product.absolute_url() articleId = product.getArticleId() # Properties for property in item.getProperties(): if IProductVariant.providedBy(product) == True: property["show_price"] = False else: property["show_price"] = True temp = { "product_title" : item.getProductTitle(), "product_quantity" : "%.0f" % item.getProductQuantity(), "product_url" : url, "product_articleid" : articleId, "product_price_gross" : product_price_gross, "price_gross" : price_gross, "tax_rate" : tax_rate, "tax" : tax, "properties" : item.getProperties(), "has_discount" : abs(item.getDiscountGross()) > 0, "discount_description" : item.getDiscountDescription(), "discount" : cm.priceToString(item.getDiscountGross(), prefix="-", suffix=None), } items.append(temp) return items
def getOrders(self): """ """ om = IOrderManagement(IShopManagement(self.context).getShop()) result = [] for order in om.getOrders(): # omit closed orders wftool = getToolByName(self.context, "portal_workflow") if wftool.getInfoFor(order, "review_state") == "closed": continue customer = order.getCustomer() # am = IAddressManagement(customer) # shipping_address = am.getShippingAddress() im = IItemManagement(order) for item in im.getItems(): product = item.getProduct() row = ( order.getId(), customer.getId(), # shipping_address.getFirstname() + " " + shipping_address.getLastname(), product.getArticleId(), product.Title(), "%s" % item.getProductQuantity(), "%.2f" % item.getProductPriceGross(), "%.2f" % item.getProductPriceNet(), "%.2f" % item.getProductTax(), "%.2f" % item.getTax(), "%.2f" % item.getTaxRate(), "%.2f" % item.getPriceGross(), "%.2f" % item.getPriceNet(), ) # row = ['"%s"' % field for field in row] row = ";".join(row) result.append(row) self.request.response.setHeader('Content-type', 'text/plain') self.request.response.setHeader( 'Content-disposition', 'attachment; filename=%s' % "orders.csv" ) return "\n".join(result)
def afterSetUp(self): """ """ super(TestCartItems, self).afterSetUp() self.login("newmember") cm = ICartManagement(self.shop) cart = cm.createCart() im = IItemManagement(cart) im.addItem(self.product_1, properties=(), quantity=2) im.addItem(self.product_2, properties=(), quantity=3) self.item1, self.item2 = im.getItems()
def afterSetUp(self): """ """ super(TestCartItems, self).afterSetUp() self.login("newmember") cm = ICartManagement(self.shop) cart = cm.createCart() im = IItemManagement(cart) im.addItem(self.product_1, properties=(), quantity=2) im.addItem(self.product_2, properties=(), quantity=3) self.item1, self.item2 = im.getItems()
def getItems(self): """ """ nc = queryUtility(INumberConverter) cm = ICurrencyManagement(self.context) items = [] item_manager = IItemManagement(self.context) for item in item_manager.getItems(): product_price_gross = cm.priceToString(item.getProductPriceGross(), suffix=None) tax_rate = nc.floatToTaxString(item.getTaxRate()) tax = cm.priceToString(item.getTax(), suffix=None) price_gross = cm.priceToString(item.getPriceGross(), suffix=None) # Get url. Takes care of, if the product has been deleted in the # meanwhile. product = item.getProduct() if product is None: url = None else: if IProductVariant.providedBy(product): url = product.aq_inner.aq_parent.absolute_url() else: url = product.absolute_url() # Properties for property in item.getProperties(): if IProductVariant.providedBy(product) == True: property["show_price"] = False else: property["show_price"] = True temp = { "product_title" : item.getProductTitle(), "product_quantity" : item.getProductQuantity(), "product_url" : url, "product_price_gross" : product_price_gross, "price_gross" : price_gross, "tax_rate" : tax_rate, "tax" : tax, "properties" : item.getProperties(), "has_discount" : abs(item.getDiscountGross()) > 0, "discount_description" : item.getDiscountDescription(), "discount" : cm.priceToString(item.getDiscountGross(), prefix="-", suffix=None), } items.append(temp) return items
def process(self, order): """ """ info = dict() pc = IPrices(order) customer = order.getCustomer() am = IAddressManagement(customer) invoice_address = am.getInvoiceAddress() shipping_address = am.getShippingAddress() info = { "cmd" : "_cart", "upload" : "1", "business" : "*****@*****.**", "currency_code" : "EUR", "notify_url" : "", "return" : "", "last_name" : shipping_address.getName(), "address1" : shipping_address.address_1, "city" : shipping_address.city, "state" : shipping_address.country_title(), "zip" : shipping_address.zip_code, "shipping_1" : order.getShippingPriceNet(), "tax_1" : pc.getPriceGross() - pc.getPriceNet() } im = IItemManagement(order) for i, item in enumerate(im.getItems()): j = i + 1 name = "item_name_%s" % j quantity = "quantity_%s" % j amount = "amount_%s" % j product = item.getProduct() info[name] = product.Title() info[quantity] = str(int(item.getProductQuantity())) info[amount] = str(item.getProductPriceGross()) # redirect to paypal parameters = "&".join(["%s=%s" % (k, v) for (k, v) in info.items()]) url = PAYPAL_URL + "?" + parameters self.context.REQUEST.RESPONSE.redirect(url) return PaymentResult(NOT_PAYED)
def getOrders(self): """ """ om = IOrderManagement(IShopManagement(self.context).getShop()) result = [] for order in om.getOrders(): # omit closed orders wftool = getToolByName(self.context, "portal_workflow") if wftool.getInfoFor(order, "review_state") == "closed": continue customer = order.getCustomer() # am = IAddressManagement(customer) # shipping_address = am.getShippingAddress() im = IItemManagement(order) for item in im.getItems(): product = item.getProduct() row = ( order.getId(), customer.getId(), # shipping_address.getFirstname() + " " + shipping_address.getLastname(), product.getArticleId(), product.Title(), "%s" % item.getProductQuantity(), "%.2f" % item.getProductPriceGross(), "%.2f" % item.getProductPriceNet(), "%.2f" % item.getProductTax(), "%.2f" % item.getTax(), "%.2f" % item.getTaxRate(), "%.2f" % item.getPriceGross(), "%.2f" % item.getPriceNet(), ) # row = ['"%s"' % field for field in row] row = ";".join(row) result.append(row) self.request.response.setHeader('Content-type', 'text/plain') self.request.response.setHeader( 'Content-disposition', 'attachment; filename=%s' % "orders.csv") return "\n".join(result)
def testAddItemFromCartItem(self): """ """ cm = ICartManagement(self.shop) cart = cm.createCart() properties = ( {"id" : "color" , "selected_option" : "Red" }, # -10.0 {"id" : "material", "selected_option" : "Wood"}, # 0.0 {"id" : "quality" , "selected_option" : "High"}, # 1500.0 ) cim = IItemManagement(cart) cim.addItem(self.product_1, properties=properties, quantity=3) cart_item = IItemManagement(cart).getItems()[0] oim = IItemManagement(self.order) oim._addItemFromCartItem("0", cart_item) order_item = oim.getItems()[0] self.assertEqual(order_item.getProductQuantity(), 3) self.assertEqual("%.2f" % order_item.getProductPriceGross(), "22.00") self.assertEqual("%.2f" % order_item.getProductPriceNet(), "18.49") self.assertEqual("%.2f" % order_item.getProductTax(), "3.51") self.assertEqual("%.2f" % order_item.getPriceGross(), "4536.00") self.assertEqual("%.2f" % order_item.getPriceNet(), "3811.76") self.assertEqual(order_item.getTaxRate(), 19.0) self.assertEqual("%.2f" % order_item.getTax(), "724.24") self.assertEqual(order_item.getProduct(), self.product_1) properties = order_item.getProperties() self.assertEqual(properties[0]["title"], "Color") self.assertEqual(properties[0]["selected_option"], "Red") self.assertEqual(properties[0]["price"], "-10.0") self.assertEqual(properties[1]["title"], "Material") self.assertEqual(properties[1]["selected_option"], "Wood") self.assertEqual(properties[1]["price"], "0.0") self.assertEqual(properties[2]["title"], "Quality") self.assertEqual(properties[2]["selected_option"], "High") self.assertEqual(properties[2]["price"], "1500.0")
def afterSetUp(self): """ """ super(TestCartItemProperties, self).afterSetUp() self.login("newmember") cm = ICartManagement(self.shop) cart = cm.createCart() im = IItemManagement(cart) properties = ( {"id" : "color" , "selected_option" : "Red" }, # -10.0 {"id" : "material", "selected_option" : "Wood"}, # 0.0 {"id" : "quality" , "selected_option" : "High"}, # 1500.0 ) im.addItem(self.product_1, properties=properties, quantity=3) self.item1 = im.getItems()[0]
def testAddItemsFromCart(self): """ """ cm = ICartManagement(self.shop) cart1 = cm.createCart() im1 = IItemManagement(cart1) im1.addItem(self.product_1, properties=()) im1.addItem(self.product_2, properties=(), quantity=3) self.login("newmember") cart2 = cm.createCart() im2 = IItemManagement(cart2) im2.addItemsFromCart(cart1) self.assertEqual(len(im2.getItems()), 2)
def testAddItemsFromCart(self): """ """ view = getMultiAdapter((self.shop.products.product_1, self.shop.products.product_1.REQUEST), name="addToCart") view.addToCart() view = getMultiAdapter((self.shop.products.product_2, self.shop.products.product_2.REQUEST), name="addToCart") view.addToCart() cm = ICartManagement(self.shop) cart = cm.getCart() im = IItemManagement(self.order) im.addItemsFromCart(cart) product_ids = [item.getProduct().getId() for item in im.getItems()] self.assertEqual(product_ids, ["product_1", "product_2"])
def getTaxForCustomer(self): """ """ im = IItemManagement(self.context) if im.hasItems() == False: return 0.0 tax = 0.0 for cart_item in im.getItems(): taxes = ITaxes(cart_item) tax += taxes.getTaxForCustomer() # Get shop shop = IShopManagement(self.context).getShop() # Shipping tax += IShippingPriceManagement(shop).getTaxForCustomer() # Payment tax += IPaymentPriceManagement(shop).getTaxForCustomer() return tax
def testAddItemsFromCart(self): """ """ view = getMultiAdapter((self.shop.products.product_1, self.shop.products.product_1.REQUEST), name="addToCart") view.addToCart() view = getMultiAdapter((self.shop.products.product_2, self.shop.products.product_2.REQUEST), name="addToCart") view.addToCart() cm = ICartManagement(self.shop) cart = cm.getCart() im = IItemManagement(self.order) im.addItemsFromCart(cart) product_ids = [item.getProduct().getId() for item in im.getItems()] self.assertEqual(product_ids, ["product_1", "product_2"])
def getTaxForCustomer(self): """ """ im = IItemManagement(self.context) if im.hasItems() == False: return 0.0 tax = 0.0 for cart_item in im.getItems(): taxes = ITaxes(cart_item) tax += taxes.getTaxForCustomer() # Get shop shop = IShopManagement(self.context).getShop() # Shipping tax += IShippingPriceManagement(shop).getTaxForCustomer() # Payment tax += IPaymentPriceManagement(shop).getTaxForCustomer() return tax
def getPriceNet(self, with_shipping=True, with_payment=True, with_discount=True): """Returns the net price of the cart. This is just a sum over net prices of all items of the cart plus shipping and payment. """ im = IItemManagement(self.context) if im.hasItems() == False: return 0.0 price = 0.0 for cart_item in im.getItems(): # NOTE: with_discount is passed here price += IPrices(cart_item).getPriceNet(with_discount=with_discount) if with_shipping == True: sm = IShippingPriceManagement(self.shop) shipping_price = sm.getPriceNet() price += shipping_price if with_payment == True: sm = IPaymentPriceManagement(self.shop) payment_price = sm.getPriceNet() price += payment_price return price
def getCarts(self): """ """ sort_on = self.request.get("sort_on", "modified") sort_order = self.request.get("sort_order", "descending") shop = IShopManagement(self.context).getShop() cm = ICartManagement(shop) ttool = getToolByName(self.context, 'translation_service') result = [] for cart in cm.getCarts(): cart_object = cart.getObject() # items im = IItemManagement(cart_object) items = im.getItems() amount_of_items = len(items) if len(items) > 0: last_item = items[-1] modified = last_item.modified() else: modified = cart.modified # price price_float = IPrices(cart_object).getPriceGross() price = ICurrencyManagement(shop).priceToString(price_float) # created created = ttool.ulocalized_time(cart.created, long_format=True) modified = ttool.ulocalized_time(modified, long_format=True) result.append({ "id" : cart.getId, "url" : cart.getURL(), "created" : created, "modified" : modified, "amount_of_items" : amount_of_items, "price_float" : price_float, # for sorting reasons "price" : price, }) # There is no index for price, amount_of_items, modified (the # modification date of the cart is dependend on the items, # so default modification date is not working). So we have # to order the result in another way # Yes. there is a index for id and created, but to differ makes the # code more complicate than it gains speed, imo. In addition that this # is (just) a admin view. if sort_order == "descending": result.sort(lambda a, b: cmp(b[sort_on], a[sort_on])) else: result.sort(lambda a, b: cmp(a[sort_on], b[sort_on])) return result
def _refreshCart(self): """ """ customer = ICustomerManagement(self.context).getAuthenticatedCustomer() cart = ICartManagement(self.context).getCart() if cart is None: return # Collect cart item properties for lookup selected_properties = {} for key, value in self.context.request.items(): if key.startswith("property_"): property_id, cart_item_id = key.split(":") property_id = property_id[42:] if selected_properties.has_key(cart_item_id) == False: selected_properties[cart_item_id] = [] selected_properties[cart_item_id].append({ "id": property_id, "selected_option": value }) im = IItemManagement(cart) total_items = 0 i = 1 for cart_item in im.getItems(): ci = "cart_item_%s" % i amount = self.context.REQUEST.get(ci) try: amount = int(amount) except ValueError: continue if amount < 0: continue if amount == 0: im.deleteItemByOrd(i - 1) else: cart_item.setAmount(amount) i += 1 # Set properties product = cart_item.getProduct() if IProductVariant.providedBy(product): product = product.aq_inner.aq_parent pvm = IProductVariantsManagement(product) # We need the properties also as dict to get the selected # variant. Feels somewhat dirty. TODO: Try to unify the data # model for properties. properties = {} for property in selected_properties[cart_item.getId()]: properties[property["id"]] = property["selected_option"] variant = pvm.getSelectedVariant(properties) cart_item.setProduct(variant) # TODO: At the moment we have to set the properties of the cart # item too. This is used in checkout-order-preview. Think about # to get rid of this because the properties are already available # in the variant. cart_item.setProperties(selected_properties[cart_item.getId()]) else: if selected_properties.has_key(cart_item.getId()): cart_item.setProperties( selected_properties[cart_item.getId()]) # Set selected country global and within current selected invoice # address. Why? If a customer delete all addresses the current selected # country is still saved global and can be used to calculate the # shipping price. selected_country = safe_unicode(self.request.get("selected_country")) customer.selected_country = selected_country #invoice_address = IAddressManagement(customer).getInvoiceAddress() #if invoice_address is not None: # invoice_address.country = selected_country shipping_address = IAddressManagement(customer).getShippingAddress() if shipping_address is not None: shipping_address.country = queryUtility(IIDNormalizer).normalize( selected_country) 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] # Set selected payment method type customer.selected_payment_method = \ safe_unicode(self.request.get("selected_payment_method")) # Set selected VAT registration selected_vat_country = safe_unicode( self.request.get("selected_vat_country")) selected_vat_number = safe_unicode( self.request.get("selected_vat_number")) if selected_vat_country == "" or selected_vat_country is None or selected_vat_number is None: customer.vatreg = None elif selected_vat_country == "XX": customer.vatreg = selected_vat_country else: customer.vatreg = selected_vat_country + selected_vat_number
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
def _refreshCart(self): """ """ customer = ICustomerManagement(self.context).getAuthenticatedCustomer() cart = ICartManagement(self.context).getCart() if cart is None: return # Collect cart item properties for lookup selected_properties = {} for key, value in self.context.request.items(): if key.startswith("property_"): property_id, cart_item_id = key.split(":") property_id = property_id[42:] if selected_properties.has_key(cart_item_id) == False: selected_properties[cart_item_id] = [] selected_properties[cart_item_id].append({ "id" : property_id, "selected_option" : value}) im = IItemManagement(cart) total_items = 0 i = 1 for cart_item in im.getItems(): ci = "cart_item_%s" % i amount = self.context.REQUEST.get(ci) try: amount = int(amount) except ValueError: continue if amount < 0: continue if amount == 0: im.deleteItemByOrd(i-1) else: cart_item.setAmount(amount) i += 1 # Set properties product = cart_item.getProduct() if IProductVariant.providedBy(product): product = product.aq_inner.aq_parent pvm = IProductVariantsManagement(product) # We need the properties also as dict to get the selected # variant. Feels somewhat dirty. TODO: Try to unify the data # model for properties. properties = {} for property in selected_properties[cart_item.getId()]: properties[property["id"]] = property["selected_option"] variant = pvm.getSelectedVariant(properties) cart_item.setProduct(variant) # TODO: At the moment we have to set the properties of the cart # item too. This is used in checkout-order-preview. Think about # to get rid of this because the properties are already available # in the variant. cart_item.setProperties(selected_properties[cart_item.getId()]) else: if selected_properties.has_key(cart_item.getId()): cart_item.setProperties(selected_properties[cart_item.getId()]) # Set selected country global and within current selected invoice # address. Why? If a customer delete all addresses the current selected # country is still saved global and can be used to calculate the # shipping price. selected_country = safe_unicode(self.request.get("selected_country")) customer.selected_country = selected_country #invoice_address = IAddressManagement(customer).getInvoiceAddress() #if invoice_address is not None: # invoice_address.country = selected_country shipping_address = IAddressManagement(customer).getShippingAddress() if shipping_address is not None: shipping_address.country = queryUtility(IIDNormalizer).normalize(selected_country) 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] # Set selected payment method type customer.selected_payment_method = \ safe_unicode(self.request.get("selected_payment_method")) # Set selected VAT registration selected_vat_country = safe_unicode(self.request.get("selected_vat_country")) selected_vat_number = safe_unicode(self.request.get("selected_vat_number")) if selected_vat_country == "" or selected_vat_country is None or selected_vat_number is None: customer.vatreg = None elif selected_vat_country == "XX": customer.vatreg = selected_vat_country else: customer.vatreg = selected_vat_country + selected_vat_number
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