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 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 hasCartItems(self): """ """ cart = self._getCart() if cart is None: return False im = IItemManagement(cart) if im.hasItems(): return True return False
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 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 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 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 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 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 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 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 getDiscounts(self): """ """ return [] cm = ICurrencyManagement(self.context) cart = self._getCart() if cart is None: return [] discounts = [] for cart_item in IItemManagement(cart).getItems(): discount = IDiscountsCalculation(cart_item).getDiscount() if discount is not None: value = getMultiAdapter( (discount, cart_item)).getPriceForCustomer() discounts.append({ "title": discount.Title(), "value": cm.priceToString(value, prefix="-", suffix=None), }) return discounts
def showCheckOutButton(self): """ """ cart = self._getCart() if IItemManagement(cart).hasItems(): return True return False
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 hasItems(self, order): """Returns True if order has at least one item with valid url """ for item in IItemManagement(order).getItems(): if item.getProduct() is not None: return True return False
def deleteItem(self): """ """ toDeleteItem = self.context.REQUEST.get("toDeleteItem") cart = ICartManagement(self.context).getCart() IItemManagement(cart).deleteItem(toDeleteItem) return self._render()
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 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 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)
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 getLatestOrder(self): """Returns the last order id of authenticated customer """ om = IOrderManagement(self.context) orders = om.getOrdersForAuthenticatedCustomer() orders.sort(lambda a, b: cmp(b.created(), a.created())) order = orders[0] # Address customer = order.getCustomer() address = IAddressManagement(customer).getInvoiceAddress() prices = IPrices(order) transaction = { "order_id": order.getId(), "affiliation": "", "total": prices.getPriceForCustomer(), "tax": (prices.getPriceForCustomer() - prices.getPriceNet()), "shipping": order.getShippingPriceGross(), "city": address.city, "state": "", "country": address.country_title(), } items = [] for item in IItemManagement(order).getItems(): # Product product = item.getProduct() # Category try: category = product.getCategories()[0] category_title = category.Title() except IndexError: category_title = u"" items.append({ "order_id": order.getId(), "sku": product.getArticleId(), "productname": product.Title(), "category": category_title, "price": item.getProductPriceGross(), "quantity": item.getProductQuantity() }) result = { "id": order.getId(), "url": order.absolute_url(), "google_transaction": transaction, "google_items": items, } return result
def getAmountOfShops(self): """ """ cart = self.getCart() shops = {} for item in IItemManagement(cart).getItems(): shop = IShopManagement(item.getProduct()).getShop() shops[shop.UID()] = 1 return len(shops.keys())
def getCartItems(self): """ """ shop = IShopManagement(self.context).getShop() cart = self._getCart() # If there isn't a cart yet if cart is None: return [] cm = ICurrencyManagement(self.context) result = [] for cart_item in IItemManagement(cart).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() # 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 # Product title data = IData(product).asDict() title = data["title"] result.append({ "id": cart_item.getId(), "product_title": title, "product_url": product.absolute_url(), "product_price": product_price, "price": cm.priceToString(price), "amount": cart_item.getAmount(), "properties": self._getProperties(cart_item), "total_price": cm.priceToString(total_price), "discount": discount, }) return result
def getAmountOfArticles(self): """ """ cart = self._getCart() if cart is None: return 0 amount = 0 for item in IItemManagement(cart).getItems(): amount += item.getAmount() return amount
def showCheckOutLink(self): """ """ cart = self._getCart() if cart is None: return False if IItemManagement(cart).hasItems() == False: return False return True
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 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 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 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 removeCart(self, cart): """ """ for cart_item in IItemManagement(cart).getItems(): product = cart_item.getProduct() # Remove only when product has not unlimited amount if product.getUnlimitedAmount() == False: amount = cart_item.getAmount() new_amount = product.getStockAmount() - amount product.setStockAmount(new_amount) if new_amount <= 0: notify(StockAmountIsZeroEvent(product))
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 deleteItem(self): """ """ toDeleteItem = self.context.REQUEST.get("toDeleteItem") cart = self._getCart() IItemManagement(cart).deleteItem(toDeleteItem) url = "%s/cart" % self.context.absolute_url() # keep goto goto = self.request.get("goto", "") if goto != "": url += "?goto=%s" % goto self.context.request.response.redirect(url)
def getCart(self): """ """ # Note: generally, carts aren't created until a product is put into the # cart. We create a cart here only when a member logs in and has had # already an anonymous cart. mtool = getToolByName(self.context, "portal_membership") sid = getUtility(ISessionManagement).getSID(self.context.REQUEST) # Get anonymous cart here, because we need it in any case. try: anonymous_cart = self.carts[sid] except KeyError: anonymous_cart = None # Note: Using this instead of mtool.isAnonymousUser() because this works # even if we exchange the SecurityManager. See here: # easyshop.orders.adapters.shop.order_management if mtool.getAuthenticatedMember().getId() is None: cart = anonymous_cart else: mid = mtool.getAuthenticatedMember().getId() # If there is no anonymous cart we just return the member cart if # there is one, otherwise we return nothing. if anonymous_cart is None: try: cart = self.carts[mid] except KeyError: cart = None # If there is already an anonymous cart we create a member cart and # copy the items from anonymous to member cart. else: try: cart = self.carts[mid] except KeyError: cart = self.createCart() im = IItemManagement(cart).addItemsFromCart(anonymous_cart) self.deleteCart(sid) return cart
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 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 process(self, order=None): """ """ shop = IShopManagement(self.context).getShop() customer = ICustomerManagement(shop).getAuthenticatedCustomer() credit_card = IPaymentInformationManagement(customer).getSelectedPaymentInformation() card_num = credit_card.card_number exp_date = "%s/%s" % (credit_card.card_expiration_date_month, credit_card.card_expiration_date_year) line_items = [] for i, item in enumerate(IItemManagement(order).getItems()): if item.getProductTax() > 0: tax = "Y" else: tax = "N" line_items.append(( str(i+1), item.getProduct().Title(), str(item.getProductQuantity()), str(item.getProductPriceGross()), tax, )) amount = "%.2f" % IPrices(order).getPriceForCustomer() cc = EasyShopCcProcessor( server="test.authorize.net", login="******", key="9ME22bvLnu87P4FY") # Used for authorizeAndCapture result = cc.authorizeAndCapture( amount = amount, card_num = card_num, exp_date = exp_date) if result.response == "approved": return PaymentResult(PAYED, _(u"Your order has been payed.")) else: return PaymentResult(ERROR, _(result.response_reason))
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 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 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 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 _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 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 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 __init__(self, context): """ """ self.context = context self.item_management = IItemManagement(context)
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 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 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