Exemplo n.º 1
1
    def handle_next_action(self, action, data):
        """
        """        
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        id = self.request.get("form.id")

        # figure out payment method type
        if id.startswith("bank_account"):
            payment_method = "direct-debit"
        elif id.startswith("credit_card"):
            payment_method = "credit-card"
        else:
            payment_method = id
        
        if id == "bank_account_new":
            depositor = self.request.get("form.depositor", u"")
            account_number = self.request.get("form.account_number", u"")
            bank_identification_code = self.request.get("form.bank_identification_code", u"")
            bank_name = self.request.get("form.bank_name", u"")

            id = self.context.generateUniqueId("BankAccount")
            bank_account = BankAccount(id)
            bank_account.account_number = account_number
            bank_account.bank_identification_code = bank_identification_code
            bank_account.bank_name = bank_name
            bank_account.depositor = depositor
        
            customer._setObject(id, bank_account)

        if id == "credit_card_new":            
            card_type = self.request.get("form.card_type", u"")
            card_number = self.request.get("form.card_number", u"")
            card_owner = self.request.get("form.card_owner", u"")
            card_expiration_date_month = self.request.get("form.card_expiration_date_month", u"")
            card_expiration_date_year = self.request.get("form.card_expiration_date_year", u"")
            
            id = self.context.generateUniqueId("CreditCard")
            credit_card = CreditCard(id)
            credit_card.card_type = card_type
            credit_card.card_number = card_number
            credit_card.card_owner = card_owner
            credit_card.card_expiration_date_month = card_expiration_date_month
            credit_card.card_expiration_date_year  = card_expiration_date_year
            
            customer._setObject(id, credit_card)
            
        elif id.startswith("bank_account_existing") or \
             id.startswith("credit_card_existing"):
            id = id.split(":")[1]
                
        customer.selected_payment_method      = payment_method
        customer.selected_payment_information = id
                    
        ICheckoutManagement(self.context).redirectToNextURL("SELECTED_PAYMENT_METHOD")
Exemplo n.º 2
0
    def testPaymentMethod(self):
        """
        """
        self.shop.manage_addProduct["easyshop.core"].addPaymentMethodCriteria(
            "c")
        v = IValidity(self.shop.c)

        self.login("newmember")

        cm = ICustomerManagement(self.shop)
        customer = cm.getAuthenticatedCustomer()

        customer.selected_payment_method = u"cash-on-delivery"
        self.assertEqual(v.isValid(), False)

        customer.selected_payment_method = u"prepayment"
        self.assertEqual(v.isValid(), False)

        self.shop.c.setPaymentMethods(["direct-debit"])
        self.assertEqual(v.isValid(), False)

        self.shop.c.setPaymentMethods(["prepayment"])
        self.assertEqual(v.isValid(), True)

        self.shop.c.setPaymentMethods(["prepayment", "direct-debit"])
        self.assertEqual(v.isValid(), True)
Exemplo n.º 3
0
    def getMyAccountURL(self):
        """
        """
        shop = IShopManagement(self.context).getShop()
        customer = ICustomerManagement(shop).getAuthenticatedCustomer()

        return customer.absolute_url() + "/" + "my-account"
Exemplo n.º 4
0
    def _calcTaxRateForCustomer(self):
        """Calculates the special tax for a given product and customer.
        """

        # If the customer has a VAT registration and the shop has a VAT
        # registration, and his country ID is different to the shop's
        # country ID, then don't apply customer taxes (default taxes
        # still apply)
        customer = ICustomerManagement(
            self.shop).getAuthenticatedCustomer(createIfNotExist=False)
        if customer is not None:
            vatreg = customer.getVATRegistration()
        else:
            vatreg = None
        if not self.shop.__dict__.has_key(
                'VATCountry'
        ) or self.shop.VATCountry == "None" or not vatreg or vatreg[:
                                                                    2] == self.shop.VATCountry:

            # 1. Try to find a Tax for actual Customer
            tm = ITaxManagement(self.shop)
            for tax in tm.getCustomerTaxes():
                if IValidity(tax).isValid(self.context) == True:
                    return tax.getRate()

        # 2. If nothing is found, returns the default tax for the product.
        return self._calcTaxRateForProduct()
Exemplo n.º 5
0
    def testPaymentMethod(self):
        """
        """
        self.shop.manage_addProduct["easyshop.core"].addPaymentMethodCriteria("c")
        v = IValidity(self.shop.c)

        self.login("newmember")

        cm = ICustomerManagement(self.shop)
        customer = cm.getAuthenticatedCustomer()

        customer.selected_payment_method = u"cash-on-delivery"
        self.assertEqual(v.isValid(), False)

        customer.selected_payment_method = u"prepayment"
        self.assertEqual(v.isValid(), False)

        self.shop.c.setPaymentMethods(["direct-debit"])
        self.assertEqual(v.isValid(), False)

        self.shop.c.setPaymentMethods(["prepayment"])
        self.assertEqual(v.isValid(), True)

        self.shop.c.setPaymentMethods(["prepayment", "direct-debit"])
        self.assertEqual(v.isValid(), True)
Exemplo n.º 6
0
    def addAddress(self, form):
        """
        """
        shop = IShopManagement(self.context).getShop()
        customer = ICustomerManagement(shop).getAuthenticatedCustomer()
        
        id = self.context.generateUniqueId("Address")

        customer.invokeFactory("Address", id=id, title=form.get("address1"))
        address = getattr(customer, id)

        # set data
        address.setFirstname(form.get("firstname", ""))
        address.setLastname(form.get("lastname", ""))
        address.setLastname(form.get("companyName", ""))
        address.setAddress1(form.get("address1", ""))
        address.setAddress2(form.get("address2", ""))
        address.setZipCode(form.get("zipCode", ""))
        address.setCity(form.get("city", ""))
        address.setCountry(form.get("country", ""))
        address.setPhone(form.get("phone", ""))

        # Refresh addresses
        kss_core = self.getCommandSet("core")
        kss_zope = self.getCommandSet("zope")

        selector = kss_core.getHtmlIdSelector("manage-address-book")        
        kss_zope.refreshViewlet(selector,
                                manager="easyshop.manager.addresses",
                                name="easyshop.addresses")
Exemplo n.º 7
0
 def isCustomerComplete(self):
     """
     """
     cm = ICustomerManagement(self.context)
     customer = cm.getAuthenticatedCustomer()
     
     return ICompleteness(customer).isComplete()
Exemplo n.º 8
0
    def getBankAccounts(self):
        """
        """
        if self._isValid("direct-debit") == False:
            return []

        cm = ICustomerManagement(self.context)
        customer = cm.getAuthenticatedCustomer()

        result = []
        pm = IPaymentInformationManagement(customer)

        for bank_account in pm.getPaymentInformations(interface=IBankAccount,
                                                      check_validity=True):

            selected_payment_information = \
                pm.getSelectedPaymentInformation(check_validity=True)

            if selected_payment_information and \
               selected_payment_information.getId() == bank_account.getId():
                checked = True
            else:
                checked = False

            result.append({
                "id": bank_account.getId(),
                "bic": bank_account.bank_identification_code,
                "account_no": bank_account.account_number,
                "depositor": bank_account.depositor,
                "bank_name": bank_account.bank_name,
                "checked": checked,
            })

        return result
Exemplo n.º 9
0
    def isCustomerComplete(self):
        """
        """
        cm = ICustomerManagement(self.context)
        customer = cm.getAuthenticatedCustomer()

        return ICompleteness(customer).isComplete()
Exemplo n.º 10
0
    def getMyAccountURL(self):
        """
        """
        shop = IShopManagement(self.context).getShop()
        customer = ICustomerManagement(shop).getAuthenticatedCustomer()

        return customer.absolute_url() + "/" + "my-account"
Exemplo n.º 11
0
 def handle_next_action(self, action, data):
     """
     """
     customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
     customer.selected_shipping_method  = data.get("shipping_method", "")
     
     ICheckoutManagement(self.context).redirectToNextURL("SELECTED_SHIPPING_METHOD")
Exemplo n.º 12
0
    def getBankAccounts(self):
        """
        """
        if self._isValid("direct-debit") == False:
            return []
        
        cm = ICustomerManagement(self.context)
        customer = cm.getAuthenticatedCustomer()
                
        result = []        
        pm = IPaymentInformationManagement(customer)

        for bank_account in pm.getPaymentInformations(
            interface=IBankAccount, check_validity=True):

            selected_payment_information = \
                pm.getSelectedPaymentInformation(check_validity=True)
                
            if selected_payment_information and \
               selected_payment_information.getId() == bank_account.getId():
                checked = True
            else:
                checked = False            
            
            result.append({
                "id"         : bank_account.getId(),
                "bic"        : bank_account.bank_identification_code,
                "account_no" : bank_account.account_number,
                "depositor"  : bank_account.depositor,
                "bank_name"  : bank_account.bank_name,
                "checked"    : checked,
            })
        
        return result
Exemplo n.º 13
0
    def getCreditCards(self):
        """
        """
        if self._isValid("credit-card") == False:
            return []
        
        cm = ICustomerManagement(self.context)
        customer = cm.getAuthenticatedCustomer()

        result = []        
        pm = IPaymentInformationManagement(customer)
        for credit_card in pm.getPaymentInformations(
            interface=ICreditCard, check_validity=True):

            selected_payment_information = \
                pm.getSelectedPaymentInformation(check_validity=True)
                
            if selected_payment_information and \
               selected_payment_information.getId() == credit_card.getId():
                checked = True
            else:
                checked = False            
            
            exp_date = "%s/%s" % (credit_card.card_expiration_date_month, 
                                  credit_card.card_expiration_date_year)
            result.append({
                "id"               : credit_card.getId(),
                "type"             : credit_card.card_type,
                "owner"            : credit_card.card_owner,
                "number"           : credit_card.card_number,
                "expiration_date"  : exp_date,
                "checked"          : checked,
            })
        
        return result
Exemplo n.º 14
0
    def getCreditCards(self):
        """
        """
        if self._isValid("credit-card") == False:
            return []

        cm = ICustomerManagement(self.context)
        customer = cm.getAuthenticatedCustomer()

        result = []
        pm = IPaymentInformationManagement(customer)
        for credit_card in pm.getPaymentInformations(interface=ICreditCard,
                                                     check_validity=True):

            selected_payment_information = \
                pm.getSelectedPaymentInformation(check_validity=True)

            if selected_payment_information and \
               selected_payment_information.getId() == credit_card.getId():
                checked = True
            else:
                checked = False

            exp_date = "%s/%s" % (credit_card.card_expiration_date_month,
                                  credit_card.card_expiration_date_year)
            result.append({
                "id": credit_card.getId(),
                "type": credit_card.card_type,
                "owner": credit_card.card_owner,
                "number": credit_card.card_number,
                "expiration_date": exp_date,
                "checked": checked,
            })

        return result
Exemplo n.º 15
0
    def addAddress(self, form):
        """
        """
        shop = IShopManagement(self.context).getShop()
        customer = ICustomerManagement(shop).getAuthenticatedCustomer()

        id = self.context.generateUniqueId("Address")

        customer.invokeFactory("Address", id=id, title=form.get("address1"))
        address = getattr(customer, id)

        # set data
        address.setFirstname(form.get("firstname", ""))
        address.setLastname(form.get("lastname", ""))
        address.setLastname(form.get("companyName", ""))
        address.setAddress1(form.get("address1", ""))
        address.setAddress2(form.get("address2", ""))
        address.setZipCode(form.get("zipCode", ""))
        address.setCity(form.get("city", ""))
        address.setCountry(form.get("country", ""))
        address.setPhone(form.get("phone", ""))

        # Refresh addresses
        kss_core = self.getCommandSet("core")
        kss_zope = self.getCommandSet("zope")

        selector = kss_core.getHtmlIdSelector("manage-address-book")
        kss_zope.refreshViewlet(selector,
                                manager="easyshop.manager.addresses",
                                name="easyshop.addresses")
Exemplo n.º 16
0
    def getAddressInfo(self):
        """
        """
        id = self.request.get("id")
        cm = ICustomerManagement(self.context)
        customer = cm.getAuthenticatedCustomer()
        
        am = IAddressManagement(customer)
        address = am.getAddress(id)
        
        result = {}
        result["id"] = id
         
        if self.request.get("firstname", "") != "":
            result["firstname"] = self.request.get("firstname")
        else:
            result["firstname"] = address.getFirstname()

        if self.request.get("lastname", "") != "":
            result["lastname"] = self.request.get("lastname")
        else:
            result["lastname"] = address.getLastname()

        if self.request.get("companyname", "") != "":
            result["companyname"] = self.request.get("companyname")
        else:
            result["companyname"] = address.getCompanyName()

        if self.request.get("address1", "") != "":
            result["address1"] = self.request.get("address1")
        else:
            result["address1"] = address.getAddress1()

        if self.request.get("address2", "") != "":
            result["address2"] = self.request.get("address2")
        else:
            result["address2"] = address.getAddress2()

        if self.request.get("zipcode", "") != "":
            result["zipcode"] = self.request.get("zipcode")
        else:
            result["zipcode"] = address.getZipCode()

        if self.request.get("city", "") != "":
            result["city"] = self.request.get("city")
        else:
            result["city"] = address.getCity()

        if self.request.get("country", "") != "":
            result["country"] = self.request.get("country")
        else:
            result["country"] = address.getCountry()

        if self.request.get("phone", "") != "":
            result["phone"] = self.request.get("phone")
        else:
            result["phone"] = address.getPhone()
            
        return result
Exemplo n.º 17
0
class TestCustomerManagement(EasyShopTestCase):
    """
    """
    def afterSetUp(self):
        """
        """
        super(TestCustomerManagement, self).afterSetUp()
        self.cm = ICustomerManagement(self.shop)

    def testAddCustomers(self):
        """
        """
        result = self.cm.addCustomer("c1")
        self.failIf(result == False)

        result = self.cm.addCustomer("c2")
        self.failIf(result == False)

        result = self.cm.addCustomer("c3")
        self.failIf(result == False)

        result = self.cm.addCustomer("c4")
        self.failIf(result == False)

        ids = [c.getId for c in self.cm.getCustomers()]
        self.assertEqual(ids, ["c1", "c2", "c3", "c4"])

    def testGetAuthenticatedCustomer_1(self):
        """As anonymous, returns standard customer
        """
        self.logout()
        customer = self.cm.getAuthenticatedCustomer()
        self.assertEqual(customer.getId(), "123")

    def testGetAuthenticatedCustomer_2(self):
        """As member
        """
        self.login("newmember")
        customer = self.cm.getAuthenticatedCustomer()

        self.failUnless(ICustomer.providedBy(customer))
        self.assertEqual(customer.getId(), "newmember")

    def testGetCustomerById_1(self):
        """Existing customer
        """
        result = self.cm.addCustomer("c1")
        self.failIf(result == False)

        customer = self.cm.getCustomerById("c1")

        self.assertEqual(customer.getId(), "c1")
        self.failUnless(ICustomer.providedBy(customer))

    def testGetCustomerById_2(self):
        """Non-existing customer
        """
        customer = self.cm.getCustomerById("doe")
        self.assertEqual(customer, None)
Exemplo n.º 18
0
class TestCustomerManagement(EasyShopTestCase):
    """
    """
    def afterSetUp(self):
        """
        """
        super(TestCustomerManagement, self).afterSetUp()
        self.cm = ICustomerManagement(self.shop)

    def testAddCustomers(self):
        """
        """
        result = self.cm.addCustomer("c1")
        self.failIf(result == False)

        result = self.cm.addCustomer("c2")
        self.failIf(result == False)

        result = self.cm.addCustomer("c3")
        self.failIf(result == False)

        result = self.cm.addCustomer("c4")
        self.failIf(result == False)

        ids = [c.getId for c in self.cm.getCustomers()]
        self.assertEqual(ids, ["c1", "c2", "c3", "c4"])

    def testGetAuthenticatedCustomer_1(self):
        """As anonymous, returns standard customer
        """
        self.logout()
        customer = self.cm.getAuthenticatedCustomer()
        self.assertEqual(customer.getId(), "123")

    def testGetAuthenticatedCustomer_2(self):
        """As member
        """
        self.login("newmember")
        customer = self.cm.getAuthenticatedCustomer()

        self.failUnless(ICustomer.providedBy(customer))
        self.assertEqual(customer.getId(), "newmember")

    def testGetCustomerById_1(self):
        """Existing customer
        """
        result = self.cm.addCustomer("c1")
        self.failIf(result == False)

        customer = self.cm.getCustomerById("c1")

        self.assertEqual(customer.getId(), "c1")
        self.failUnless(ICustomer.providedBy(customer))

    def testGetCustomerById_2(self):
        """Non-existing customer
        """
        customer = self.cm.getCustomerById("doe")
        self.assertEqual(customer, None)
Exemplo n.º 19
0
    def handle_next_action(self, action, data):
        """
        """
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        customer.selected_shipping_method = data.get("shipping_method", "")

        ICheckoutManagement(
            self.context).redirectToNextURL("SELECTED_SHIPPING_METHOD")
Exemplo n.º 20
0
    def getSelectedShippingMethod(self):
        """
        """
        cm = ICustomerManagement(IShopManagement(self.context).getShop())
        customer = cm.getAuthenticatedCustomer()
        shipping_method_id = customer.selected_shipping_method

        return self.getShippingMethod(shipping_method_id)
Exemplo n.º 21
0
    def getSelectedShippingMethod(self):
        """
        """
        cm = ICustomerManagement(IShopManagement(self.context).getShop())
        customer = cm.getAuthenticatedCustomer()
        shipping_method_id = customer.selected_shipping_method

        return self.getShippingMethod(shipping_method_id)
Exemplo n.º 22
0
    def handle_next_action(self, action, data):
        """
        """
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        customer.selected_invoice_address  = data.get("invoice_address", "")
        customer.selected_shipping_address = data.get("shipping_address", "")

        ICheckoutManagement(self.context).redirectToNextURL("SELECTED_ADDRESSES")
Exemplo n.º 23
0
    def handle_next_action(self, action, data):
        """
        """
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        customer.selected_invoice_address = data.get("invoice_address", "")
        customer.selected_shipping_address = data.get("shipping_address", "")

        ICheckoutManagement(
            self.context).redirectToNextURL("SELECTED_ADDRESSES")
Exemplo n.º 24
0
    def handle_add_address_action(self, action, data):
        """
        """
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        customer_url = customer.absolute_url()
        template_url = self.context.absolute_url() + "/checkout-select-addresses"

        url = customer_url + "/add-address?goto=" + template_url
        self.request.response.redirect(url)
Exemplo n.º 25
0
    def getInvoiceAddress(self):
        """Returns invoice address of the current customer.
        """
        cm = ICustomerManagement(self.context)
        customer = cm.getAuthenticatedCustomer()

        am = IAddressManagement(customer)
        address = am.getInvoiceAddress()

        return addressToDict(address)
Exemplo n.º 26
0
    def getShippingAddress(self):
        """
        """
        cm = ICustomerManagement(self.context)
        customer = cm.getAuthenticatedCustomer()

        am = IAddressManagement(customer)
        address = am.getShippingAddress()

        return addressToDict(address)
Exemplo n.º 27
0
    def getOrdersForAuthenticatedCustomer(self):
        """
        """
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        orders = []
        for order in self.getOrders():
            if order.getCustomer().getId() == customer.getId():
                orders.append(order)

        return orders
Exemplo n.º 28
0
    def handle_add_address_action(self, action, data):
        """
        """
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        customer_url = customer.absolute_url()
        template_url = self.context.absolute_url(
        ) + "/checkout-select-addresses"

        url = customer_url + "/add-address?goto=" + template_url
        self.request.response.redirect(url)
Exemplo n.º 29
0
 def getInvoiceAddress(self):
     """Returns invoice address of the current customer.
     """
     cm = ICustomerManagement(self.context)
     customer = cm.getAuthenticatedCustomer()
     
     am = IAddressManagement(customer)
     address = am.getInvoiceAddress()
     
     return addressToDict(address)
Exemplo n.º 30
0
    def getOrdersForAuthenticatedCustomer(self):
        """
        """
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        orders = []
        for order in self.getOrders():
            if order.getCustomer().getId() == customer.getId():
                orders.append(order)

        return orders
Exemplo n.º 31
0
    def getShippingAddress(self):
        """
        """
        cm = ICustomerManagement(self.context)
        customer = cm.getAuthenticatedCustomer()
        
        am = IAddressManagement(customer)
        address = am.getShippingAddress()

        return addressToDict(address)
 def afterSetUp(self):
     """
     """
     super(TestDirectDebit, self).afterSetUp()
     
     self.login("newmember")
     cm = ICustomerManagement(self.shop)
     self.customer = cm.getAuthenticatedCustomer()
     
     self.customer.invokeFactory(
         "BankAccount",
         id = "bank-account",
         )
Exemplo n.º 33
0
    def handle_next_action(self, action, data):
        """
        """
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        id = self.request.get("form.id")

        # figure out payment method type
        if id.startswith("bank_account"):
            payment_method = "direct-debit"
        elif id.startswith("credit_card"):
            payment_method = "credit-card"
        else:
            payment_method = id

        if id == "bank_account_new":
            depositor = self.request.get("form.depositor", u"")
            account_number = self.request.get("form.account_number", u"")
            bank_identification_code = self.request.get(
                "form.bank_identification_code", u"")
            bank_name = self.request.get("form.bank_name", u"")

            id = self.context.generateUniqueId("BankAccount")
            bank_account = BankAccount(id)
            bank_account.account_number = account_number
            bank_account.bank_identification_code = bank_identification_code
            bank_account.bank_name = bank_name
            bank_account.depositor = depositor

            customer._setObject(id, bank_account)

        if id == "credit_card_new":
            card_type = self.request.get("form.card_type", u"")
            card_number = self.request.get("form.card_number", u"")
            card_owner = self.request.get("form.card_owner", u"")
            card_expiration_date_month = self.request.get(
                "form.card_expiration_date_month", u"")
            card_expiration_date_year = self.request.get(
                "form.card_expiration_date_year", u"")

            id = self.context.generateUniqueId("CreditCard")
            credit_card = CreditCard(id)
            credit_card.card_type = card_type
            credit_card.card_number = card_number
            credit_card.card_owner = card_owner
            credit_card.card_expiration_date_month = card_expiration_date_month
            credit_card.card_expiration_date_year = card_expiration_date_year

            customer._setObject(id, credit_card)

        elif id.startswith("bank_account_existing") or \
             id.startswith("credit_card_existing"):
            id = id.split(":")[1]

        customer.selected_payment_method = payment_method
        customer.selected_payment_information = id

        ICheckoutManagement(
            self.context).redirectToNextURL("SELECTED_PAYMENT_METHOD")
Exemplo n.º 34
0
    def getShippingMethods(self):
        """
        """
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        selected_shipping_id = customer.selected_shipping_method

        sm = IShippingMethodManagement(self.context)

        shipping_methods = []
        for shipping in sm.getShippingMethods(check_validity=True):

            if selected_shipping_id == safe_unicode(shipping.getId()):
                checked = True
            elif selected_shipping_id == u"" and shipping.getId() == "default":
                checked = True
            else:
                checked = False

            shipping_methods.append({
                "id": shipping.getId(),
                "title": shipping.Title,
                "description": shipping.Description,
                "checked": checked,
            })

        return shipping_methods
Exemplo n.º 35
0
    def getSelectablePaymentMethods(self):
        """Returns selectable payment methods.
        """
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        pm = IPaymentInformationManagement(customer)

        selected_payment_method = \
            pm.getSelectedPaymentMethod(check_validity=True)

        result = []
        pm = IPaymentMethodManagement(self.context)
        for payment in pm.getSelectablePaymentMethods(check_validity=True):

            # Todo: Make default payment method editable. ATM it is prepayment.
            # So if nothing is selected checked is true for prepayment.

            # If id is bank_account_new (this happens when customer wants to
            # add a new direct debit and is due to validation errors redirected to
            # the form).

            checked = False
            if (self.request.get("form.id", "") not in ("bank_account_new", "credit_card_new")) and \
               (selected_payment_method.getId() == safe_unicode(payment.getId())):
                checked = True

            result.append({
                "id": payment.getId(),
                "title": payment.Title(),
                "description": payment.Description(),
                "checked": checked,
            })

        return result
Exemplo n.º 36
0
    def getShippingAddresses(self):
        """Returns all addresses with the currently selected invoice address
        checked.
        """
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        am = IAddressManagement(customer)

        found_selected_address = False
        result = []
        line = []

        for index, address in enumerate(am.getAddresses()):

            checked = False
            if safe_unicode(
                    address.getId()) == customer.selected_shipping_address:
                checked = "checked"
                found_selected_address = True

            address_as_dict = self._getAddressAsDict(address)
            address_as_dict["checked"] = checked

            line.append(address_as_dict)

            if (index + 1) % 3 == 0:
                result.append(line)
                line = []

        result.append(line)

        if len(result) > 0 and found_selected_address == False:
            result[0][0]["checked"] = True

        return result
Exemplo n.º 37
0
    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
Exemplo n.º 38
0
    def getMailInfo(self):
        """
        """
        cm = ICustomerManagement(self.context)
        customer = cm.getAuthenticatedCustomer()
        am = IAddressManagement(customer)
        shipping_address = am.getShippingAddress()

        mtool = getToolByName(self.context, "portal_membership")        
        member = mtool.getAuthenticatedMember()
        
        name  = shipping_address.getFirstname() + " "
        name += shipping_address.getLastname()
                
        return {
            "email" : member.getProperty("email"),
            "name"  : name,
        }
Exemplo n.º 39
0
    def testCountry(self):
        """
        """
        self.shop.manage_addProduct["easyshop.core"].addCountryCriteria("c")
        self.shop.c.setCountries((u"USA",))
        v = IValidity(self.shop.c)

        self.login("newmember")

        cm = ICustomerManagement(self.shop)
        customer = cm.getAuthenticatedCustomer()

        customer.invokeFactory("Address", "address_1")

        customer.address_1.country = u"USA"
        self.assertEqual(v.isValid(), True)

        customer.address_1.country = u"Germany"
        self.assertEqual(v.isValid(), False)
Exemplo n.º 40
0
    def testCountry(self):
        """
        """
        self.shop.manage_addProduct["easyshop.core"].addCountryCriteria("c")
        self.shop.c.setCountries((u"USA", ))
        v = IValidity(self.shop.c)

        self.login("newmember")

        cm = ICustomerManagement(self.shop)
        customer = cm.getAuthenticatedCustomer()

        customer.invokeFactory("Address", "address_1")

        customer.address_1.country = u"USA"
        self.assertEqual(v.isValid(), True)

        customer.address_1.country = u"Germany"
        self.assertEqual(v.isValid(), False)
Exemplo n.º 41
0
    def getVATRegistration(self):
        """Returns the VAT registration (if any) of the current customer.
        """
        result = []
        shop = IShopManagement(self.context).getShop()
        if shop.__dict__.has_key('VATCountry') and shop.VATCountry != "None" and len(ITaxManagement(self.context).getCustomerTaxes()):
        
            customermgmt = ICustomerManagement(self.context)
            customer = customermgmt.getAuthenticatedCustomer()
            vatreg = customer.getVATRegistration()
            if not vatreg: vatreg = ""
            vatcountries = VAT_COUNTRIES.keys()
            vatcountries.sort()
            
            result.append({
                "country"   : vatreg[:2],
                "number"    : vatreg[2:],
                "countries" : vatcountries,
            })

        return result
Exemplo n.º 42
0
    def isValid(self, product=None):
        """Returns True if the selected payment method of the current customer 
        is within the selected payment methods of the criterion.
        """
        shop = IShopManagement(self.context).getShop()

        customer = ICustomerManagement(shop).getAuthenticatedCustomer()
        customer_payment_method = customer.selected_payment_method

        if customer_payment_method in self.context.getPaymentMethods():
            return True
        else:
            return False
Exemplo n.º 43
0
    def createAndAdd(self, data):
        """
        """
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        am = IAddressManagement(customer)

        # Set firstname and lastname of the superior customer object.
        if len(customer.firstname) == 0:
            customer.firstname = data.get("firstname")
            customer.lastname = data.get("lastname")

        # Set email of the superior customer object.
        if len(customer.email) == 0:
            customer.email = data.get("email", u"")

        # Reset country selection.
        shop = IShopManagement(self.context).getShop()
        for country in shop.getCountries():
            if queryUtility(IIDNormalizer).normalize(country) == data.get("country"):
                customer.selected_country = country

        am.addAddress(data)
Exemplo n.º 44
0
 def isComplete(self):
     """
     """
     shop         = IShopManagement(self.context).getShop()
     customer     = ICustomerManagement(shop).getAuthenticatedCustomer()        
     pim          = IPaymentInformationManagement(customer)
     bank_account = pim.getSelectedPaymentInformation()
     
     if IBankAccount.providedBy(bank_account) == False or \
        ICompleteness(bank_account) == False:
         return False
     else:        
         return True
Exemplo n.º 45
0
    def getVATRegistration(self):
        """Returns the VAT registration (if any) of the current customer.
        """
        result = []
        shop = IShopManagement(self.context).getShop()
        if shop.__dict__.has_key(
                'VATCountry') and shop.VATCountry != "None" and len(
                    ITaxManagement(self.context).getCustomerTaxes()):

            customermgmt = ICustomerManagement(self.context)
            customer = customermgmt.getAuthenticatedCustomer()
            vatreg = customer.getVATRegistration()
            if not vatreg: vatreg = ""
            vatcountries = VAT_COUNTRIES.keys()
            vatcountries.sort()

            result.append({
                "country": vatreg[:2],
                "number": vatreg[2:],
                "countries": vatcountries,
            })

        return result
Exemplo n.º 46
0
    def _calcTaxRateForCustomer(self):
        """Calculates the special tax for a given product and customer.
        """
        
        # If the customer has a VAT registration and the shop has a VAT
        # registration, and his country ID is different to the shop's
        # country ID, then don't apply customer taxes (default taxes
        # still apply)
        customer = ICustomerManagement(self.shop).getAuthenticatedCustomer(createIfNotExist=False)
        if customer is not None:
            vatreg = customer.getVATRegistration()
        else:
            vatreg = None
        if not self.shop.__dict__.has_key('VATCountry') or self.shop.VATCountry == "None" or not vatreg or vatreg[:2] == self.shop.VATCountry:

            # 1. Try to find a Tax for actual Customer
            tm = ITaxManagement(self.shop)
            for tax in tm.getCustomerTaxes():
                if IValidity(tax).isValid(self.context) == True:
                    return tax.getRate()

        # 2. If nothing is found, returns the default tax for the product.
        return self._calcTaxRateForProduct()
Exemplo n.º 47
0
    def getShippingMethods(self):
        """
        """
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        selected_shipping_id = customer.selected_shipping_method

        # If the available shipping methods has been changed we must update the
        # selected shipping method of the customer
        shop = IShopManagement(self.context).getShop()
        shipping_methods = IShippingMethodManagement(shop).getShippingMethods(
            check_validity=True)
        shipping_methods_ids = [sm.getId() for sm in shipping_methods]

        # Set selected shipping method
        if selected_shipping_id not in shipping_methods_ids:
            customer.selected_shipping_method = shipping_methods_ids[0]

        sm = IShippingMethodManagement(self.context)

        shipping_methods = []
        for shipping in sm.getShippingMethods(check_validity=True):

            if selected_shipping_id == safe_unicode(shipping.getId()):
                checked = True
            elif selected_shipping_id == u"" and shipping.getId() == "default":
                checked = True
            else:
                checked = False

            shipping_methods.append({
                "id": shipping.getId(),
                "title": shipping.Title,
                "description": shipping.Description,
                "checked": checked,
            })

        return shipping_methods
Exemplo n.º 48
0
    def getShippingMethods(self):
        """
        """
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        selected_shipping_id = customer.selected_shipping_method

        # If the available shipping methods has been changed we must update the 
        # selected shipping method of the customer 
        shop = IShopManagement(self.context).getShop()
        shipping_methods = IShippingMethodManagement(shop).getShippingMethods(check_validity=True)
        shipping_methods_ids = [sm.getId() for sm in shipping_methods]

        # Set selected shipping method
        if selected_shipping_id not in shipping_methods_ids:
            customer.selected_shipping_method = shipping_methods_ids[0]
        
        sm = IShippingMethodManagement(self.context)
        
        shipping_methods = []
        for shipping in sm.getShippingMethods(check_validity=True):

            if selected_shipping_id == safe_unicode(shipping.getId()):
                checked = True
            elif selected_shipping_id == u"" and shipping.getId() == "default":
                checked = True
            else:
                checked = False
                            
            shipping_methods.append({
                "id" : shipping.getId(),
                "title" : shipping.Title,
                "description" : shipping.Description,
                "checked" : checked,
            })
            
        return shipping_methods        
Exemplo n.º 49
0
    def getCountries(self):
        """Returns available countries.
        """
        result = []
        customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
        shop = IShopManagement(self.context).getShop()
        for country in shop.getCountries():
            result.append({
                "title":
                country,
                "selected":
                safe_unicode(country) == customer.selected_country
            })

        return result
Exemplo n.º 50
0
    def _editedAddress(self):
        """
        """
        if self.context.REQUEST.get("also_invoice_address", "yes") == "yes":
            url = self.context.absolute_url() + "/checkout-shipping"
        else:
            customer = ICustomerManagement(
                self.context).getAuthenticatedCustomer()
            invoice_address = IAddressManagement(customer).getInvoiceAddress()
            if invoice_address is None:
                url = self.context.absolute_url(
                ) + "/checkout-add-address?address_type=invoice"
            else:
                url = invoice_address.absolute_url() + "/checkout-edit-address"

        return url
Exemplo n.º 51
0
 def getOverviewURL(self):
     """
     """
     shop = IShopManagement(self.context).getShop()
     customer = ICustomerManagement(shop).getAuthenticatedCustomer()
     return "%s/my-orders" % customer.absolute_url()
Exemplo n.º 52
0
 def afterSetUp(self):
     """
     """
     super(TestCustomerManagement, self).afterSetUp()
     self.cm = ICustomerManagement(self.shop)
Exemplo n.º 53
0
 def getVATRegistration(self):
     """Returns the VAT registration (if any) of the current customer.
     """
     customer = ICustomerManagement(self.context).getAuthenticatedCustomer()
     vatreg = customer.getVATRegistration()
     return vatreg
Exemplo n.º 54
0
    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
Exemplo n.º 55
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
Exemplo n.º 56
0
    def getProducts(self):
        """Returns the last products, which are added to the cart.
        """
        cm = ICurrencyManagement(self.context)
        
        result = []
        for cart_item_id in self.request.SESSION.get("added-to-cart", []):

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

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

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

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

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