Exemple #1
0
    def testGetOrders(self):
        """
        """
        om = IOrderManagement(self.shop)

        o = self.shop.orders
        o.invokeFactory("Order", "o1")

        o.invokeFactory("Order", "o5")
        o.invokeFactory("Order", "o3")
        o.invokeFactory("Order", "o4")
        o.invokeFactory("Order", "o2")
        o.reindexObject()

        ids = [
            o.getId()
            for o in om.getOrders(sorting="id", sort_order="descending")
        ]
        self.assertEqual(ids, ["o5", "o4", "o3", "o2", "o1"])

        ids = [
            o.getId()
            for o in om.getOrders(sorting="id", sort_order="ascending")
        ]
        self.assertEqual(ids, ["o1", "o2", "o3", "o4", "o5"])

        ids = [
            o.getId()
            for o in om.getOrders("created", sorting="getObjPositionInParent")
        ]
        self.assertEqual(ids, ["o2", "o4", "o3", "o5", "o1"])
Exemple #2
0
    def getOrders(self):
        """
        """
        shop = IShopManagement(self.context).getShop()
        om = IOrderManagement(shop)
        orders = om.getOrdersForAuthenticatedCustomer()
        wftool = getToolByName(self.context, "portal_workflow")
        ttool  = getToolByName(self.context, 'translation_service')
        
        result = []
        for order in orders:
            # TODO: Get rid of using order view
            order_view = getMultiAdapter((order, self.request), name="order")
            created = ttool.ulocalized_time(order.created(), long_format=True)
            temp = {
                "id"            : order.getId(),
                "url"           : order.absolute_url(),
                "price_gross"   : order_view.getPriceForCustomer(),
                "shipping"      : order_view.getShipping(),
                "payment"       : order_view.getPaymentValues(),
                "items_"        : order_view.getItems(),
                "creation_date" : created,
                "state"         : wftool.getInfoFor(order, "review_state"),
                "tax"           : order_view.getTax(),
            }
            result.append(temp)

        return result
Exemple #3
0
    def getOrders(self):
        """
        """
        shop = IShopManagement(self.context).getShop()
        om = IOrderManagement(shop)
        orders = om.getOrdersForAuthenticatedCustomer()
        wftool = getToolByName(self.context, "portal_workflow")
        ttool = getToolByName(self.context, 'translation_service')

        result = []
        for order in orders:
            # TODO: Get rid of using order view
            order_view = getMultiAdapter((order, self.request), name="order")
            created = ttool.ulocalized_time(order.created(), long_format=True)
            temp = {
                "id": order.getId(),
                "url": order.absolute_url(),
                "price_gross": order_view.getPriceForCustomer(),
                "shipping": order_view.getShipping(),
                "payment": order_view.getPaymentValues(),
                "items_": order_view.getItems(),
                "creation_date": created,
                "state": wftool.getInfoFor(order, "review_state"),
                "tax": order_view.getTax(),
            }
            result.append(temp)

        return result
Exemple #4
0
    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
Exemple #5
0
    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
Exemple #6
0
def createTestOrder(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()

    om = IOrderManagement(self.shop)
    self.order = om.addOrder()
Exemple #7
0
    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)
Exemple #8
0
    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 testGetOrdersForAuthenticatedCustomer(self):
        """
        """
        self.login("newmember")
        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()
            
        om = IOrderManagement(self.shop)            
        new_order = om.addOrder()

        order = om.getOrdersForAuthenticatedCustomer()[0]
        self.assertEqual(order, new_order)
    def testGetOrderByUID(self):
        """
        """
        self.login("newmember")
        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()
            
        om = IOrderManagement(self.shop)            
        new_order = om.addOrder()
        
        order = om.getOrderByUID(new_order.UID())
        self.assertEqual(order, new_order)
Exemple #11
0
    def receivePayment(self):
        """
        """
        shop = self.context

        # Get cart - Note: self.request.get("order") doesn't work!
        order_uid = self.request.get("QUERY_STRING")[6:]
        order = IOrderManagement(shop).getOrderByUID(order_uid)

        # change order state to "payed_not_sent"
        wftool = getToolByName(self, "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(order, "pay_not_sent")

        ## Reset security manager
        setSecurityManager(old_sm)
Exemple #12
0
    def __call__(self):
        om = IOrderManagement(self.context)
        tid = self.request.get('TID','')
        order = getattr(om.orders,tid,None)

        log("\n%s\n%s\n%s" % (order, tid, self.request.get('STATUS')))

        if order and self.request.get('STATUS') in ['RESERVED','BILLED']:

            # 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)

            try:
                # set to pending (send emails)
                wftool.doActionFor(order, "submit")
                # set to payed
                wftool.doActionFor(order, "pay_not_sent")
            except Exception, msg:
                self.status = msg

            # Reset security manager
            setSecurityManager(old_sm)
Exemple #13
0
    def getOrders(self):
        """
        """
        tool = getToolByName(self.context, 'translation_service')

        shop = IShopManagement(self.context).getShop()

        wftool = getToolByName(self.context, "portal_workflow")
        filter = self.request.get("filter", "all")
        if filter == "all": filter = None

        sorting = self.request.get("sorting", "created")
        order = self.request.get("order", "descending")

        orders = []
        om = IOrderManagement(shop)

        for order in om.getOrders(filter, sorting, order):

            # get fullname
            fullname = "There is no customer."
            customer = order.getCustomer()
            if customer is not None:
                am = IAddressManagement(customer)
                address = am.getInvoiceAddress()
                if address is not None:
                    fullname = address.getName(reverse=True)

            # created
            created = tool.ulocalized_time(order.created(), long_format=True)

            orders.append({
                "id":
                order.getId(),
                "url":
                order.absolute_url(),
                "created":
                created,
                "customer_name":
                fullname,
                "review_state":
                wftool.getInfoFor(order, "review_state")
            })

        return orders
Exemple #14
0
    def testGetOrdersForAuthenticatedCustomer(self):
        """
        """
        self.login("newmember")
        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()

        om = IOrderManagement(self.shop)
        new_order = om.addOrder()

        order = om.getOrdersForAuthenticatedCustomer()[0]
        self.assertEqual(order, new_order)
Exemple #15
0
    def testGetOrderByUID(self):
        """
        """
        self.login("newmember")
        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()

        om = IOrderManagement(self.shop)
        new_order = om.addOrder()

        order = om.getOrderByUID(new_order.UID())
        self.assertEqual(order, new_order)
Exemple #16
0
    def getOrders(self):
        """
        """
        ttool = getToolByName(self.context, 'translation_service')
        wftool = getToolByName(self.context, "portal_workflow")

        customer = self._getCustomer()
        if customer is None:
            return []

        om = IOrderManagement(self._getShop())

        orders = []
        for order in om.getOrdersForCustomer(customer.getId()):

            # get fullname
            fullname = "There is no customer."
            customer = order.getCustomer()
            if customer is not None:
                am = IAddressManagement(customer)
                address = am.getInvoiceAddress()
                if address is not None:
                    fullname = address.getName(reverse=True)

            # created
            created = ttool.ulocalized_time(order.created(), long_format=True)

            orders.append({
                "id":
                order.getId(),
                "url":
                order.absolute_url(),
                "created":
                created,
                "customer_name":
                fullname,
                "review_state":
                wftool.getInfoFor(order, "review_state")
            })

        return orders
    def testGetOrders(self):
        """
        """
        om = IOrderManagement(self.shop)
                
        o = self.shop.orders
        o.invokeFactory("Order", "o1")
        
        o.invokeFactory("Order", "o5")        
        o.invokeFactory("Order", "o3")
        o.invokeFactory("Order", "o4")
        o.invokeFactory("Order", "o2")        
        o.reindexObject()
        
        ids = [o.getId() for o in om.getOrders(sorting="id", sort_order="descending")]
        self.assertEqual(ids, ["o5", "o4", "o3", "o2", "o1"])

        ids = [o.getId() for o in om.getOrders(sorting="id", sort_order="ascending")]
        self.assertEqual(ids, ["o1", "o2", "o3", "o4", "o5"])

        ids = [o.getId() for o in om.getOrders("created", sorting="getObjPositionInParent")]
        self.assertEqual(ids, ["o2", "o4", "o3", "o5", "o1"])
    def getOrders(self):
        """
        """
        ttool = getToolByName(self.context, 'translation_service')
        wftool = getToolByName(self.context, "portal_workflow")

        customer = self._getCustomer()
        if customer is  None:
            return []

        om = IOrderManagement(self._getShop())

        orders = []
        for order in om.getOrdersForCustomer(customer.getId()):

            # get fullname
            fullname = "There is no customer."
            customer = order.getCustomer()
            if customer is not None:
                am = IAddressManagement(customer)
                address = am.getInvoiceAddress()
                if address is not None:
                    fullname = address.getName(reverse=True)

            # created
            created = ttool.ulocalized_time(order.created(), long_format=True)

            orders.append({
                "id"            : order.getId(),
                "url"           : order.absolute_url(),
                "created"       : created,
                "customer_name" : fullname,
                "review_state"  : wftool.getInfoFor(order, "review_state")
            })

        return orders
    def send_rating_mails(self):
        """
        """
        live = self.request.get("live")

        now = DateTime()

        # Get sender
        mail_addresses = IMailAddresses(self.context)
        sender         = mail_addresses.getSender()
        bcc            = ["*****@*****.**", "*****@*****.**"]

        wftool = getToolByName(self.context, "portal_workflow")

        # Get all relevant orders
        om = IOrderManagement(self.context)

        for order in om.getOrders():

            # Send mail only once (below "rating-mail" is set)
            if "rating-mail" in order.getMarketingInfo():
                continue

            try:    
                last_state = wftool.getInfoFor(order, "review_history")[-1]
            except IndexError:
                continue                
            
            # Send mail only for closed orders
            if last_state["review_state"] != "closed":
                continue

            # Send only mails for orders which closed at lease2 weeks
            # ago
            if now - last_state["time"] < (2*7):
                continue

            # Send only mails for orders which have at least on product with
            # a valid url (aka product which is not deleted in the meanwhile)
            if self.hasItems(order) == False:
                continue

            if live is None:
                receiver = "*****@*****.**"
                if sender and receiver:
                    view = getMultiAdapter((order, order.REQUEST), name="rating-mail")
                    text = view()

                    # get charset
                    props = getToolByName(order, "portal_properties").site_properties
                    charset = props.getProperty("default_charset")

                    sendMultipartMail(
                        context  = order,
                        sender   = sender,
                        receiver = receiver,
                        subject  = "Bitte bewerten Sie Ihr Produkt",
                        text     = text,
                        charset  = charset)
            else:
                # Get receiver
                customer = order.getCustomer()
                address = IAddressManagement(customer).getShippingAddress()
                receiver = address.email

                if sender and receiver:
                    view = getMultiAdapter((order, order.REQUEST), name="rating-mail")
                    text = view()

                    # get charset
                    props = getToolByName(order, "portal_properties").site_properties
                    charset = props.getProperty("default_charset")

                    sendMultipartMail(
                        context  = order,
                        sender   = sender,
                        receiver = receiver,
                        bcc      = bcc,
                        subject  = "Bitte bewerten Sie Ihr Produkt",
                        text     = text,
                        charset  = charset)

                    # set marketing info
                    mi = list(order.getMarketingInfo())
                    mi.append("rating-mail")
                    order.setMarketingInfo(mi)
Exemple #20
0
    def send_rating_mails(self):
        """
        """
        live = self.request.get("live")

        now = DateTime()

        # Get sender
        mail_addresses = IMailAddresses(self.context)
        sender = mail_addresses.getSender()
        bcc = ["*****@*****.**", "*****@*****.**"]

        wftool = getToolByName(self.context, "portal_workflow")

        # Get all relevant orders
        om = IOrderManagement(self.context)

        for order in om.getOrders():

            # Send mail only once (below "rating-mail" is set)
            if "rating-mail" in order.getMarketingInfo():
                continue

            try:
                last_state = wftool.getInfoFor(order, "review_history")[-1]
            except IndexError:
                continue

            # Send mail only for closed orders
            if last_state["review_state"] != "closed":
                continue

            # Send only mails for orders which closed at lease2 weeks
            # ago
            if now - last_state["time"] < (2 * 7):
                continue

            # Send only mails for orders which have at least on product with
            # a valid url (aka product which is not deleted in the meanwhile)
            if self.hasItems(order) == False:
                continue

            if live is None:
                receiver = "*****@*****.**"
                if sender and receiver:
                    view = getMultiAdapter((order, order.REQUEST),
                                           name="rating-mail")
                    text = view()

                    # get charset
                    props = getToolByName(order,
                                          "portal_properties").site_properties
                    charset = props.getProperty("default_charset")

                    sendMultipartMail(context=order,
                                      sender=sender,
                                      receiver=receiver,
                                      subject="Bitte bewerten Sie Ihr Produkt",
                                      text=text,
                                      charset=charset)
            else:
                # Get receiver
                customer = order.getCustomer()
                address = IAddressManagement(customer).getShippingAddress()
                receiver = address.email

                if sender and receiver:
                    view = getMultiAdapter((order, order.REQUEST),
                                           name="rating-mail")
                    text = view()

                    # get charset
                    props = getToolByName(order,
                                          "portal_properties").site_properties
                    charset = props.getProperty("default_charset")

                    sendMultipartMail(context=order,
                                      sender=sender,
                                      receiver=receiver,
                                      bcc=bcc,
                                      subject="Bitte bewerten Sie Ihr Produkt",
                                      text=text,
                                      charset=charset)

                    # set marketing info
                    mi = list(order.getMarketingInfo())
                    mi.append("rating-mail")
                    order.setMarketingInfo(mi)
Exemple #21
0
    def testAddOrder(self):
        """
        """
        self.login("newmember")
        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()

        new_order = IOrderManagement(self.shop).addOrder()

        self.assertEqual(new_order.getShippingPriceGross(), 10.0)
        self.assertEqual("%.2f" % new_order.getShippingPriceNet(), "8.40")
        self.assertEqual("%.2f" % new_order.getShippingTax(), "1.60")
        self.assertEqual(new_order.getShippingTaxRate(), 19.0)

        self.assertEqual(new_order.getPaymentPriceGross(), 100.0)
        self.assertEqual("%.2f" % new_order.getPaymentPriceNet(), "84.03")
        self.assertEqual("%.2f" % new_order.getPaymentTax(), "15.97")
        self.assertEqual(new_order.getPaymentTaxRate(), 19.0)

        # items should be overtaken (more concise tests for item managment are
        # in a seperated file)
        self.failUnless(len(new_order.objectIds("OrderItem")) == 2)

        # customer should be copied
        self.assertEqual(new_order.getCustomer().getId(), "newmember")

        # The cart should still be there, because we need it until the payment
        # has been successfully processed. See order_preview.py/handle_buy_action
        # for more.
        self.failUnless(self.shop.carts.get("newmember"))
    def testAddOrder(self):
        """
        """
        self.login("newmember")
        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()
        
        new_order = IOrderManagement(self.shop).addOrder()
        
        self.assertEqual(new_order.getShippingPriceGross(), 10.0)
        self.assertEqual("%.2f" % new_order.getShippingPriceNet(), "8.40")
        self.assertEqual("%.2f" % new_order.getShippingTax(), "1.60")
        self.assertEqual(new_order.getShippingTaxRate(), 19.0)

        self.assertEqual(new_order.getPaymentPriceGross(), 100.0)
        self.assertEqual("%.2f" % new_order.getPaymentPriceNet(), "84.03")
        self.assertEqual("%.2f" % new_order.getPaymentTax(), "15.97")
        self.assertEqual(new_order.getPaymentTaxRate(), 19.0)

        # items should be overtaken (more concise tests for item managment are
        # in a seperated file)
        self.failUnless(len(new_order.objectIds("OrderItem")) == 2)
        
        # customer should be copied
        self.assertEqual(new_order.getCustomer().getId(), "newmember")
        
        # The cart should still be there, because we need it until the payment 
        # has been successfully processed. See order_preview.py/handle_buy_action
        # for more.
        self.failUnless(self.shop.carts.get("newmember"))
Exemple #23
0
    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")
Exemple #24
0
    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")