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 testAddProductAsAnonymousAndMember(self): """Proves that a member will overtake the cart items, which he has added, as anonymous user. """ self.logout() view = getMultiAdapter((self.shop.products.product_2, self.shop.products.product_2.REQUEST), name="addToCart") view.addToCart() cart = ICartManagement(self.shop).getCart() items = IItemManagement(cart).getItems() self.assertEqual(len(items), 1) view.addToCart() items = IItemManagement(cart).getItems() self.assertEqual(len(items), 1) view = getMultiAdapter((self.shop.products.product_1, self.shop.products.product_1.REQUEST), name="addToCart") view.addToCart() items = IItemManagement(cart).getItems() self.assertEqual(len(items), 2) self.login("newmember") cart = ICartManagement(self.shop).getCart() items = IItemManagement(cart).getItems() self.assertEqual(len(items), 2) self.assertEqual(cart.getId(), "newmember")
def addOrder(self, customer=None, cart=None): """ """ cartmanager = ICartManagement(self.context) if customer is None: cm = ICustomerManagement(self.context) customer = cm.getAuthenticatedCustomer() if cart is None: cart = cartmanager.getCart() portal = getToolByName(self.context, 'portal_url').getPortalObject() ## The current user may not be allowed to create an order, so we ## temporarily change the security context to use a temporary ## user with manager role. old_sm = getSecurityManager() tmp_user = UnrestrictedUser(old_sm.getUser().getId(), '', ['Manager'], '') tmp_user = tmp_user.__of__(portal.acl_users) newSecurityManager(None, tmp_user) # Add a new order new_id = self._createOrderId() self.orders.invokeFactory("Order", id=new_id) new_order = getattr(self.orders, new_id) # Copy Customer to Order customer = ICustomerManagement(self.context).getAuthenticatedCustomer() cm = ICopyManagement(customer) cm.copyTo(new_order) # Add cart items to order IItemManagement(new_order).addItemsFromCart(cart) # Add total tax new_order.setTax(ITaxes(cart).getTaxForCustomer()) # Add shipping values to order sm = IShippingPriceManagement(self.context) new_order.setShippingPriceNet(sm.getPriceNet()) new_order.setShippingPriceGross(sm.getPriceForCustomer()) new_order.setShippingTax(sm.getTaxForCustomer()) new_order.setShippingTaxRate(sm.getTaxRateForCustomer()) # Add payment price values to order pp = IPaymentPriceManagement(self.context) new_order.setPaymentPriceGross(pp.getPriceForCustomer()) new_order.setPaymentPriceNet(pp.getPriceNet()) new_order.setPaymentTax(pp.getTaxForCustomer()) new_order.setPaymentTaxRate(pp.getTaxRateForCustomer()) ## Reset security manager setSecurityManager(old_sm) # Index with customer again new_order.reindexObject() return new_order
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 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 testHasItemsAsAdmin(self): """ """ cm = ICartManagement(self.shop) cart = cm.createCart() # This caused an error as shasattr was not yet used within # CartManagement.getCart(). It returned an ATFolder. im = IItemManagement(cart)
def afterSetUp(self): """ """ super(TestCartTaxes, self).afterSetUp() cm = ICartManagement(self.shop) self.cart = cm.createCart() im = IItemManagement(self.cart) im.addItem(self.product_1, properties=(), quantity=2) im.addItem(self.product_2, properties=(), quantity=3)
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 testHasItems(self): """ """ self.logout() cm = ICartManagement(self.shop) cart = cm.createCart() im = IItemManagement(cart) self.assertEqual(im.hasItems(), False) im.addItem(self.product_1, properties=[]) self.assertEqual(im.hasItems(), True)
def getCart(self): """ """ customer = self._getCustomer() if customer is None: return None cart = ICartManagement(self._getShop()).getCartById(customer.getId()) if cart is None: return None else: return {"url": cart.absolute_url()}
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 addItemsFromCart(self, cart): """Adds all items from a given cart to the order """ shop = IShopManagement(self.context).getShop() if cart is None: cartmanager = ICartManagement(shop) cart = cartmanager.getCart() # edit cart items id = 0 for cart_item in IItemManagement(cart).getItems(): id += 1 self._addItemFromCartItem(id, cart_item)
def getCart(self): """ """ customer = self._getCustomer() if customer is None: return None cart = ICartManagement(self._getShop()).getCartById(customer.getId()) if cart is None: return None else: return { "url" : cart.absolute_url() }
def getPriceForCustomer(self): """ """ # If there a no items the payment price for cutomers is zero. cart_manager = ICartManagement(self.context) cart = cart_manager.getCart() if cart is None: return 0 cart_item_manager = IItemManagement(cart) if cart_item_manager.hasItems() == False: return 0 return self.getPriceNet() + self.getTaxForCustomer()
def getPriceForCustomer(self): """ """ # If there a no items the shipping price for cutomers is zero. cart_manager = ICartManagement(self.context) cart = cart_manager.getCart() if cart is None: return 0 cart_item_manager = IItemManagement(cart) if cart_item_manager.hasItems() == False: return 0 return self.getPriceNet() + self.getTaxForCustomer()
def testPrices3(self): """ """ self.shop.discounts.invokeFactory("Discount", id="d1", title="D1", value="1.0", base="cart_item", type="percentage") discount = self.shop.discounts.d1 view = getMultiAdapter((self.shop.products.product_1, self.shop.products.product_1.REQUEST), name="addToCart") view() view() cart = ICartManagement(self.shop).getCart() item = IItemManagement(cart).getItems()[0] prices = getMultiAdapter((discount, item), IPrices) price_net = "%.2f" % prices.getPriceNet() price_gross = "%.2f" % prices.getPriceGross() price_for_customer = "%.2f" % prices.getPriceForCustomer() self.assertEqual(price_gross, "0.44") self.assertEqual(price_for_customer, "0.44") self.assertEqual(price_net, "0.37")
def getTaxForCustomer(self): """ """ # If there a no items the shipping tax is 0 cart_manager = ICartManagement(self.context) cart = cart_manager.getCart() if cart is None: return 0 cart_item_manager = IItemManagement(cart) if cart_item_manager.hasItems() == False: return 0 temp_shipping_product = self._createTemporaryShippingProduct() return ITaxes(temp_shipping_product).getTaxForCustomer()
def isValid(self, product=None): """Returns True, if the total width of the cart is greater than the entered criteria width. """ shop = IShopManagement(self.context).getShop() cart = ICartManagement(shop).getCart() max_length = 0 max_width = 0 total_height = 0 if cart is not None: for item in IItemManagement(cart).getItems(): if max_length < item.getProduct().getLength(): max_length = item.getProduct().getLength() if max_width < item.getProduct().getWidth(): max_width = item.getProduct().getWidth() total_height += (item.getProduct().getHeight() * item.getAmount()) # Calc cart girth cart_girth = (2 * max_width) + (2 * total_height) + max_length if self.context.getOperator() == ">=": if cart_girth >= self.context.getCombinedLengthAndGirth(): return True else: if cart_girth < self.context.getCombinedLengthAndGirth(): return True return False
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 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 deleteItem(self): """ """ toDeleteItem = self.context.REQUEST.get("toDeleteItem") cart = ICartManagement(self.context).getCart() IItemManagement(cart).deleteItem(toDeleteItem) return self._render()
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): """ """ 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 getPriceGross(self): """ """ amount_of_shops = ICartManagement(self.context).getAmountOfShops() for price in self.getShippingPrices(): if IValidity(price).isValid() == True: return price.getPrice() * amount_of_shops return 0
def getCartPrice(self): """ """ shop = self._getShop() cm = ICurrencyManagement(shop) if ICartManagement(shop).hasCart(): cart = self._getCart() price = IPrices(cart).getPriceForCustomer() return cm.priceToString(price) else: return cm.priceToString(0.0)
def testDeleteItemByOrd(self): """ """ self.login("newmember") view = getMultiAdapter((self.shop.products.product_1, self.shop.products.product_1.REQUEST), name="addToCart") view.addToCart() cart = ICartManagement(self.shop).getCart() im = IItemManagement(cart) im.deleteItemByOrd(0) self.failIf(hasattr(cart, "0"))
def isComplete(self): """Checks weather the customer is complete to checkout. Customer completeness means the customer is ready to check out: 1. Invoice address is complete 2. Shipping address is complete 3. Selected payment method is complete 4. There a items in the cart """ # Get shop shop = IShopManagement(self.context).getShop() # Get shipping and invoice address adressman = IAddressManagement(self.context) s_addr = adressman.getShippingAddress() if s_addr is None: return False i_addr = adressman.getInvoiceAddress() if i_addr is None: return False # Get payment method payman = IPaymentManagement(self.context) paymeth = payman.getSelectedPaymentMethod() # Get cart of the customer cart = ICartManagement(shop).getCart() # If there is no cart, the customer hasn't selected a product, hence # he is not complete if cart is None: return False im = IItemManagement(cart) # Check all for completeness # if at least one is False customer is not complete, too. for toCheck in s_addr, i_addr, paymeth: if ICompleteness(toCheck).isComplete() == False: return False # check items in cart if im.hasItems() == False: return False return True
def isValid(self, product=None): """Returns True, if the total height of the cart is greater than the entered criteria height. """ shop = IShopManagement(self.context).getShop() cart = ICartManagement(shop).getCart() # total height cart_height = 0 if cart is not None: for item in IItemManagement(cart).getItems(): cart_height += (item.getProduct().getHeight() * item.getAmount()) if self.context.getOperator() == ">=": if cart_height >= self.context.getHeight(): return True else: if cart_height < self.context.getHeight(): return True return False
def isValid(self, product=None): """Returns True if the total price of the cart is greater than the entered criteria price. """ shop = IShopManagement(self.context).getShop() cart = ICartManagement(shop).getCart() if cart is None: cart_price = 0.0 else: if self.context.getPriceType() == "net": cart_price = IPrices(cart).getPriceForCustomer( with_shipping=False, with_payment=False) else: cart_price = IPrices(cart).getPriceGross(with_shipping=False, with_payment=False) cart_price = float("%.2f" % cart_price) if cart_price >= self.context.getPrice(): return True return False
def testRemoveCart(self): """ """ view = getMultiAdapter((self.shop.products.product_1, self.shop.products.product_1.REQUEST), name="addToCart") view.addToCart() view.addToCart() view = getMultiAdapter((self.shop.products.product_2, self.shop.products.product_2.REQUEST), name="addToCart") view.addToCart() cart = ICartManagement(self.shop).getCart() sm = IStockManagement(self.shop) sm.removeCart(cart) self.assertEqual(self.shop.products.product_1.getStockAmount(), 8.0) self.assertEqual(self.shop.products.product_2.getStockAmount(), 19.0)
def testAddProductAsMember(self): """ """ self.login("newmember") view = getMultiAdapter((self.shop.products.product_2, self.shop.products.product_2.REQUEST), name="addToCart") view.addToCart() cart = ICartManagement(self.shop).getCart() items = IItemManagement(cart).getItems() self.assertEqual(len(items), 1) view.addToCart() items = IItemManagement(cart).getItems() self.assertEqual(len(items), 1) view = getMultiAdapter((self.shop.products.product_1, self.shop.products.product_1.REQUEST), name="addToCart") view.addToCart() items = IItemManagement(cart).getItems() self.assertEqual(len(items), 2)
def isValid(self, product=None): """Returns True, if the total width of the cart is greater than the entered criteria width. """ shop = IShopManagement(self.context).getShop() cart = ICartManagement(shop).getCart() # max width cart_width = 0 if cart is not None: for item in IItemManagement(cart).getItems(): if item.getProduct().getWidth() > cart_width: cart_width = item.getProduct().getWidth() if self.context.getOperator() == ">=": if cart_width >= self.context.getWidth(): return True else: if cart_width < self.context.getWidth(): return True return False
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 handle_buy_action(self, action, data): """Buys a cart. """ putils = getToolByName(self.context, "plone_utils") # add order om = IOrderManagement(self.context) new_order = om.addOrder() # Set message to shop owner new_order.setMessage(self.context.request.get("form.message", "")) # process payment result = IPaymentProcessing(new_order).process() # Need error for payment methods for which the customer has to pay at # any case The order process should not go on if the customer is not # able to pay. if result.code == ERROR: om.deleteOrder(new_order.id) putils.addPortalMessage(result.message, type=u"error") ICheckoutManagement(self.context).redirectToNextURL("ERROR_PAYMENT") return "" else: cm = ICartManagement(self.context) # Decrease stock IStockManagement(self.context).removeCart(cm.getCart()) # Delete cart cm.deleteCart() # Set order to pending (Mails will be sent) wftool = getToolByName(self.context, "portal_workflow") wftool.doActionFor(new_order, "submit") putils.addPortalMessage(MESSAGES["ORDER_RECEIVED"]) if result.code == PAYED: # Set order to payed (Mails will be sent) wftool = getToolByName(self.context, "portal_workflow") # We need a new security manager here, because this transaction # should usually just be allowed by a Manager except here. old_sm = getSecurityManager() tmp_user = UnrestrictedUser( old_sm.getUser().getId(), '', ['Manager'], '' ) portal = getToolByName(self.context, 'portal_url').getPortalObject() tmp_user = tmp_user.__of__(portal.acl_users) newSecurityManager(None, tmp_user) wftool.doActionFor(new_order, "pay_not_sent") ## Reset security manager setSecurityManager(old_sm) # Redirect customer = \ ICustomerManagement(self.context).getAuthenticatedCustomer() selected_payment_method = \ IPaymentInformationManagement(customer).getSelectedPaymentMethod() if not IAsynchronPaymentMethod.providedBy(selected_payment_method): ICheckoutManagement(self.context).redirectToNextURL("BUYED_ORDER")
def addOrder(self, customer=None, cart=None): """ """ cartmanager = ICartManagement(self.context) if customer is None: cm = ICustomerManagement(self.context) customer = cm.getAuthenticatedCustomer() if cart is None: cart = cartmanager.getCart() portal = getToolByName(self.context, 'portal_url').getPortalObject() ## The current user may not be allowed to create an order, so we ## temporarily change the security context to use a temporary ## user with manager role. old_sm = getSecurityManager() tmp_user = UnrestrictedUser( old_sm.getUser().getId(), '', ['Manager'], '' ) tmp_user = tmp_user.__of__(portal.acl_users) newSecurityManager(None, tmp_user) # Add a new order new_id = self._createOrderId() self.orders.invokeFactory("Order", id=new_id) new_order = getattr(self.orders, new_id) # Copy Customer to Order customer = ICustomerManagement(self.context).getAuthenticatedCustomer() cm = ICopyManagement(customer) cm.copyTo(new_order) # Add cart items to order IItemManagement(new_order).addItemsFromCart(cart) # Add total tax new_order.setTax(ITaxes(cart).getTaxForCustomer()) # Add shipping values to order sm = IShippingPriceManagement(self.context) new_order.setShippingPriceNet(sm.getPriceNet()) new_order.setShippingPriceGross(sm.getPriceForCustomer()) new_order.setShippingTax(sm.getTaxForCustomer()) new_order.setShippingTaxRate(sm.getTaxRateForCustomer()) # Add payment price values to order pp = IPaymentPriceManagement(self.context) new_order.setPaymentPriceGross(pp.getPriceForCustomer()) new_order.setPaymentPriceNet(pp.getPriceNet()) new_order.setPaymentTax(pp.getTaxForCustomer()) new_order.setPaymentTaxRate(pp.getTaxRateForCustomer()) ## Reset security manager setSecurityManager(old_sm) # Index with customer again new_order.reindexObject() return new_order
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 afterSetUp(self): """ """ super(TestCartManagement, self).afterSetUp() self.cm = ICartManagement(self.shop)
class TestCartManagement(EasyShopTestCase): """ """ def afterSetUp(self): """ """ super(TestCartManagement, self).afterSetUp() self.cm = ICartManagement(self.shop) def testCreateCart_1(self): """Create cart for anonymous. """ self.logout() cart = self.cm.createCart() self.assertEqual(cart.getId(), "123") def testCreateCart_2(self): """Create cart for member. """ self.login("newmember") cart = self.cm.createCart() self.assertEqual(cart.getId(), "newmember") def testDeleteCart_1(self): """Without given id. """ self.login("newmember") self.cm.createCart() self.failUnless(self.shop.carts.get("newmember")) self.cm.deleteCart() self.failIf(self.shop.carts.get("newmember")) def testDeleteCart_2(self): """With given id. """ self.login("newmember") self.cm.createCart() self.failUnless(self.shop.carts.get("newmember")) self.cm.deleteCart("newmember") self.failIf(self.shop.carts.get("newmember")) def testGetCart_1(self): """Cart for anonmyous. There is no cart yet. """ self.logout() cart = self.cm.getCart() self.assertEqual(cart, None) def testGetCart_2(self): """Cart for anonymous. There is a cart """ self.logout() self.cm.createCart() cart = self.cm.getCart() self.assertEqual(cart.getId(), "123") def testGetCart_3(self): """Cart for member. There is no anonymous cart. Carts are only created when items are added to it. """ self.login("newmember") cart = self.cm.getCart() self.assertEqual(cart, None) def testGetCart_4(self): """Cart for member. There is an anonymous cart. """ self.logout() # create cart for anonymous self.cm.createCart() cart = self.cm.getCart() self.assertEqual(cart.getId(), "123") self.login("newmember") # After login the anonymous cart should be moved to member cart cart = self.cm.getCart() self.assertEqual(cart.getId(), "newmember") # The cart for anonymous has to be deleted self.failIf(self.shop.carts.get("123")) def testGetCarts(self): """ """ # create cart for newmember self.login("newmember") self.cm.createCart() self.setRoles(("Manager",)) ids = [c.getId for c in self.cm.getCarts()] self.assertEqual(ids, ["newmember"]) def testGetCartById(self): """ """ # create cart for newmember self.login("newmember") self.cm.createCart() cart = self.cm.getCartById("newmember") self.assertEqual(cart.getId(), "newmember") def testGetCartByUID(self): """ """ # create cart for newmember self.login("newmember") cart = self.cm.createCart() cart = self.cm.getCartByUID(cart.UID()) self.assertEqual(cart.getId(), "newmember") def testHasCart(self): """ """ self.assertEqual(self.cm.hasCart(), False) self.login("newmember") cart = self.cm.createCart() self.assertEqual(self.cm.hasCart(), True) def test_getCartId(self): """ """ self.logout() cart_id = self.cm._getCartId() self.assertEqual(cart_id, "123") self.login("newmember") cart_id = self.cm._getCartId() self.assertEqual(cart_id, "newmember")