Пример #1
0
def countries(context):
    """
    """
    terms = []
    # terms.append(SimpleTerm("Germany", u"Germany"))
    # terms.append(SimpleTerm("USA", u"USA"))
    # terms.append(SimpleTerm("Polen", u"Polen"))

    shop = IShopManagement(context).getShop()

    if shop is None:
        # BBB: this is ugly because if we create a new address
        #      we dont have any context. try to guess the first EasyShop
        #      in portal_catalog and hope we are in luck!
        # XXX: this breaks if the site has more than one EasyShop instances!!!
        sm = getSiteManager()
        cat_query = sm.portal_catalog.queryCatalog(
            dict(portal_type='EasyShop'))

        if len(cat_query)<1:
            # this is not possible, because we weren't in this vocab if
            # we hadn't an EasyShop instance
            __traceback_info__ = "no Easyshop found in portal_catalog"
            raise Exception

        shop = cat_query[0].getObject()

    for country in shop.getCountries():
        country = safe_unicode(country)
        term_value = queryUtility(IIDNormalizer).normalize(country)
        terms.append(SimpleTerm(term_value, term_value, country))

    return SimpleVocabulary(terms)
Пример #2
0
    def process(self, order=None):
        """
        """
        shop = IShopManagement(self.context).getShop()
        callback_url = "%s/nochex?order=%s" % (shop.absolute_url(),
                                               order.UID())
        success_url = "%s/thank-you" % shop.absolute_url()

        pc = IPrices(order)
        price_gross = "%.2f" % pc.getPriceGross()

        info = {
            "merchant_id": NOCHEX_ID,
            "amount": price_gross,
            "order_id": order.getId(),
            "success_url": success_url,
            "callback_url": callback_url,
        }

        # redirect to paypal
        parameters = "&".join(["%s=%s" % (k, v) for (k, v) in info.items()])

        url = NOCHEX_URL + "?" + parameters
        self.context.REQUEST.RESPONSE.redirect(url)

        return PaymentResult(NOT_PAYED)
Пример #3
0
    def getStartupDirectoryForCategories(self):
        """
        """
        shop = IShopManagement(self).getShop()
        shop_path = "/".join(shop.getPhysicalPath())

        return shop_path
Пример #4
0
    def process(self, order=None):
        """
        """    
        shop = IShopManagement(self.context).getShop()
        callback_url = "%s/nochex?order=%s" % (shop.absolute_url(), order.UID())
        success_url  = "%s/thank-you" % shop.absolute_url()
        
        pc = IPrices(order)
        price_gross = "%.2f" % pc.getPriceGross()
        
        info = {
            "merchant_id" : NOCHEX_ID,
            "amount" : price_gross,
            "order_id": order.getId(),
            "success_url" : success_url,
            "callback_url" : callback_url,
        }

        # redirect to paypal    
        parameters = "&".join(["%s=%s" % (k, v) for (k, v) in info.items()])                
        
        url = NOCHEX_URL + "?" + parameters
        self.context.REQUEST.RESPONSE.redirect(url)
        
        return PaymentResult(NOT_PAYED)
Пример #5
0
 def getStartupDirectoryForCategories(self):
     """
     """
     shop = IShopManagement(self).getShop()
     shop_path = "/".join(shop.getPhysicalPath())
     
     return shop_path
Пример #6
0
    def addCategory(self):
        """
        """
        category_name = self.request.get("category_name", "")
        if category_name == "":
            return self._showView()
            
        shop = IShopManagement(self.context).getShop()

        putils = getToolByName(self.context, "plone_utils")        
        normalized_id = putils.normalizeString(category_name)

        if base_hasattr(shop, normalized_id) == True:
            putils.addPortalMessage(MESSAGES["CATEGORY_ALREADY_EXISTS"], "error")
            return self._showView()
        else:
            shop.invokeFactory("Category", id=normalized_id, title=category_name)
            putils.addPortalMessage(MESSAGES["ADDED_CATEGORY"])
            
        new_category = shop[normalized_id]
        
        if self.hasSelectedCategories() == True:
            catalog = getToolByName(self.context, "portal_catalog")
            brains = catalog.searchResults(UID = self.selected_categories)            
            parent_categories = [b.getObject() for b in brains]            
            new_category.setParentCategory(parent_categories)
            new_category.reindexObject()

        return self._showView()
Пример #7
0
    def isValid(self, product=None):
        """Returns False if the PayPal id is not filled in.
        """
        shop = IShopManagement(self.context).getShop()
        if shop.getPayPalId() == "":
            return False

        return super(PayPalValidity, self).isValid(product)
Пример #8
0
 def __init__(self, discount, cart_item):
     """
     """
     self.discount = discount
     self.cart_item = cart_item
     self.product = cart_item.getProduct()
     self.taxes = ITaxes(self.product)
     self.shop = IShopManagement(self.product).getShop()
Пример #9
0
class CurrencyManagement:
    """Provides ICurrencyManagement for serveral content objects.
    """
    implements(ICurrencyManagement)
    adapts(Interface)
    
    def __init__(self, context):
        """
        """
        self.shop = IShopManagement(context).getShop()
        
    def getLongName(self):
        """
        """
        currency = self.shop.getCurrency()
        return CURRENCIES[currency]["long"]
        
    def getShortName(self):
        """
        """
        currency = self.shop.getCurrency()
        return CURRENCIES[currency]["short"]
        
    def getSymbol(self):
        """
        """
        currency = self.shop.getCurrency()
        return CURRENCIES[currency]["symbol"]
        
    def priceToString(self, price, symbol="symbol", position="before", prefix=None, suffix="*"):
        """
        """
        price = "%.2f" % price
        # How do you determine the current rendition language? If it's not english you want this
        #price = price.replace(".", ",")
        
        if symbol == "short":
            currency = self.getShortName()    
        elif symbol == "long":
            currency = self.getLongName()    
        else:
            currency = self.getSymbol()

        if prefix is not None:
            price = "%s%s" % (prefix, price)

        if suffix is not None:
            price = "%s%s" % (price, suffix)
            
        if position == "before":
            price = "%s %s" % (currency, price)
        else:
            price = "%s %s" % (price, currency)

        return price
Пример #10
0
 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())
Пример #11
0
    def getBackToOverViewUrl(self):
        """
        """
        if IShop.providedBy(self.context):
            return None

        parent_category = self.context.getRefs("parent_category")
        if len(parent_category) > 0:
            return parent_category[0].absolute_url()

        shop = IShopManagement(self.context).getShop()
        return shop.absolute_url()
Пример #12
0
    def getBackToOverViewUrl(self):
        """
        """
        if IShop.providedBy(self.context):
            return None
        
        parent_category = self.context.getRefs("parent_category")
        if len(parent_category) > 0:
            return parent_category[0].absolute_url()

        shop = IShopManagement(self.context).getShop()
        return shop.absolute_url()
Пример #13
0
    def getBackToOverViewUrl(self):
        """
        """
        parent = self.context.aq_inner.aq_parent
        if ICategory.providedBy(parent):
            parent_url = parent.absolute_url()
        elif ICategoriesContainer.providedBy(parent):
            shop = IShopManagement(self.context).getShop()
            parent_url = shop.absolute_url()
        else:
            parent_url = None

        return parent_url
Пример #14
0
 def getBackToOverViewUrl(self):
     """
     """
     parent = self.context.aq_inner.aq_parent
     if ICategory.providedBy(parent):
         parent_url = parent.absolute_url()
     elif ICategoriesContainer.providedBy(parent):
         shop = IShopManagement(self.context).getShop()
         parent_url = shop.absolute_url()
     else:
         parent_url = None
         
     return parent_url
Пример #15
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    
Пример #16
0
 def getCountries(self):
     """
     """
     selected_country = self.request.get("country", "Deutschland")
     shop = IShopManagement(self.context).getShop()
     
     result = []
     for country in shop.getCountries():
         result.append({
             "name" : country,
             "selected" : (selected_country == country)
         })
         
     return result    
Пример #17
0
    def getAllProducts(self, **kargs):
        """
        """
        shop = IShopManagement(self.context).getShop()
        catalog = getToolByName(self.context, "portal_catalog")
        brains = catalog.searchResults(path="/".join(shop.getPhysicalPath()),
                                       portal_type="Product",
                                       sort_on="sortable_title")

        # TODO: This is ugly!
        result = []
        for brain in brains:
            result.append(brain.getObject())
        return result
Пример #18
0
    def __init__(self, context):
        """
        """
        pvm = IProductVariantsManagement(context)
        shop = IShopManagement(context).getShop()

        self.context = context

        self.gross_prices = shop.getGrossPrices()
        self.has_variants = pvm.hasVariants()
        self.taxes = ITaxes(context)

        if self.has_variants:
            self.product_variant = \
                pvm.getSelectedVariant() or pvm.getDefaultVariant()
Пример #19
0
    def _getGroupsAsDL(self):
        """Returns all Categories as DisplayList
        """
        shop = IShopManagement(self).getShop()

        dl = DisplayList()
        catalog = getToolByName(self, "portal_catalog")

        brains = catalog.searchResults(path="/".join(shop.getPhysicalPath()),
                                       portal_type="ProductGroup")

        for brain in brains:
            dl.add(brain.id, brain.Title)

        return dl
Пример #20
0
    def __init__(self, context):
        """
        """
        pvm  = IProductVariantsManagement(context)
        shop = IShopManagement(context).getShop()
        
        self.context = context

        self.gross_prices = shop.getGrossPrices()
        self.has_variants = pvm.hasVariants()
        self.taxes = ITaxes(context)

        if self.has_variants:
            self.product_variant = \
                pvm.getSelectedVariant() or pvm.getDefaultVariant()
Пример #21
0
 def available(self):
     """
     """
     mtool = getToolByName(self.context, "portal_membership")
     if mtool.checkPermission("Manage portal", self.context):
         return True
     
     
     member_id = mtool.getAuthenticatedMember().getId()
     shop = IShopManagement(self.context).getShop()
     
     if shop.getShopOwnerId() == member_id:
         return True
         
     return False
Пример #22
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
Пример #23
0
    def getProducts(self):
        """
        """
        shop = IShopManagement(self.context).getShop()
        pm = IProductManagement(shop)

        result = []
        for product in pm.getProducts():
            result.append({
                "uid": product.UID,
                "title": product.Title,
            })

        # Get start page
        b_start = self.request.get('b_start', 0)
        if b_start == "None":
            b_start = 0

        batch = Batch(result, 20, int(b_start), orphan=0)

        # Calculate Batch
        return {
            "batch": batch,
            "next_url": self._getNextUrl(batch),
            "previous_url": self._getPreviousUrl(batch)
        }
Пример #24
0
    def getPriceGross(self, property_id, option_id):
        """
        """
        shop     = IShopManagement(self.context).getShop()
        tax_rate = ITaxes(self.context).getTaxRate()
        price    = self._calcPrice(property_id, option_id)

        # The price entered is considered as gross price, so we simply
        # return it.
        if shop.getGrossPrices() == True:
            return price

        # The price entered is considered as net price. So we have to calculate 
        # the gross price first.
        else:
            return price * ((tax_rate + 100) / 100)
Пример #25
0
    def getPriceGross(self, property_id, option_id):
        """
        """
        shop = IShopManagement(self.context).getShop()
        tax_rate = ITaxes(self.context).getTaxRate()
        price = self._calcPrice(property_id, option_id)

        # The price entered is considered as gross price, so we simply
        # return it.
        if shop.getGrossPrices() == True:
            return price

        # The price entered is considered as net price. So we have to calculate
        # the gross price first.
        else:
            return price * ((tax_rate + 100) / 100)
Пример #26
0
    def getCategories(self):
        """
        """
        shop = IShopManagement(self.context).getShop()
        categories = ICategoryManagement(shop).getTopLevelCategories(
            full_objects=False)

        result = []
        for category in categories:

            klass = ""
            if self._isCurrentItem(category) == True:
                klass += "navTreeCurrentItem"

            result.append({
                "klass": klass,
                "url": category.getURL(),
                "description": category.Description,
                "title": category.Title,
                "amount_of_products": category.total_amount_of_products,
                "subcategories": self._getSubCategories(category),
                "products": self._getProducts(category),
            })

        return result
Пример #27
0
    def getTopLevelCategories(self):
        """
        """
        shop = IShopManagement(self.context).getShop()

        cm = ICategoryManagement(shop)
        return cm.getTopLevelCategories()
Пример #28
0
    def getShippingPrices(self):
        """
        """
        shop = IShopManagement(self.context).getShop()
        sm = IShippingPriceManagement(shop)
        cm = ICurrencyManagement(shop)

        result = []
        for shipping_price in sm.getShippingPrices():

            price = cm.priceToString(shipping_price.getPrice())

            result.append({
                "id":
                shipping_price.getId(),
                "title":
                shipping_price.Title(),
                "description":
                shipping_price.Description(),
                "price":
                price,
                "url":
                shipping_price.absolute_url(),
                "up_url":
                "%s/es_folder_position?position=up&id=%s" %
                (self.context.absolute_url(), shipping_price.getId()),
                "down_url":
                "%s/es_folder_position?position=down&id=%s" %
                (self.context.absolute_url(), shipping_price.getId()),
                "amount_of_criteria":
                self._getAmountOfCriteria(shipping_price.getId())
            })

        return result
Пример #29
0
    def getStartupDirectoryForGroups(self):
        """
        """
        shop = IShopManagement(self).getShop()
        shop_path = "/".join(shop.getPhysicalPath())

        catalog = getToolByName(self, "portal_catalog")
        brains = catalog.searchResults(
            path=shop_path,
            object_provides="easyshop.core.interfaces.groups.IGroupsContainer")

        if len(brains) > 0:
            products_folder = brains[0]
            return products_folder.getPath()
        else:
            return shop_path
Пример #30
0
    def getPaymentMethods(self):
        """
        """
        shop = IShopManagement(self.context).getShop()
        pm = IPaymentMethodManagement(shop)

        result = []
        for payment_method in pm.getPaymentMethods():
            result.append({
                "id":
                payment_method.getId(),
                "title":
                payment_method.Title(),
                "url":
                payment_method.absolute_url(),
                "up_url":
                "%s/es_folder_position?position=up&id=%s" %
                (self.context.absolute_url(), payment_method.getId()),
                "down_url":
                "%s/es_folder_position?position=down&id=%s" %
                (self.context.absolute_url(), payment_method.getId()),
                "amount_of_criteria":
                self._getAmountOfCriteria(payment_method.getId())
            })

        return result
Пример #31
0
 def getAllProducts(self, **kargs):
     """
     """
     shop = IShopManagement(self.context).getShop()
     catalog = getToolByName(self.context, "portal_catalog")
     brains = catalog.searchResults(
         path = "/".join(shop.getPhysicalPath()),
         portal_type = "Product",
         sort_on = "sortable_title"
     )
     
     # TODO: This is ugly!
     result = []
     for brain in brains:
         result.append(brain.getObject())
     return result
Пример #32
0
    def getInformationPages(self):
        """
        """
        shop = IShopManagement(self.context).getShop()
        im = IInformationManagement(shop)

        result = []
        for information in im.getInformationPages():

            result.append({
                "id":
                information.getId(),
                "title":
                information.Title(),
                "url":
                information.absolute_url(),
                "description":
                information.Description(),
                "up_url":
                "%s/es_folder_position?position=up&id=%s" %
                (self.context.absolute_url(), information.getId()),
                "down_url":
                "%s/es_folder_position?position=down&id=%s" %
                (self.context.absolute_url(), information.getId()),
                "amount_of_criteria":
                len(information.objectIds()),
            })

        return result
Пример #33
0
    def _getGroupsAsDL(self):
        """Returns all Categories as DisplayList
        """
        shop = IShopManagement(self).getShop()

        dl = DisplayList()
        catalog = getToolByName(self, "portal_catalog")

        brains = catalog.searchResults(
            path = "/".join(shop.getPhysicalPath()),
            portal_type="ProductGroup")
            
        for brain in brains:
            dl.add(brain.id, brain.Title)

        return dl
Пример #34
0
    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        
Пример #35
0
    def getDiscounts(self):
        """
        """
        shop = IShopManagement(self.context).getShop()
        dm = IDiscountsManagement(shop)
        cm = ICurrencyManagement(shop)

        result = []
        for discount in dm.getDiscounts():

            value = cm.priceToString(discount.getValue())

            result.append({
                "id":
                discount.getId(),
                "title":
                discount.Title(),
                "description":
                discount.Description(),
                "value":
                value,
                "url":
                discount.absolute_url(),
                "up_url":
                "%s/es_folder_position?position=up&id=%s" %
                (self.context.absolute_url(), discount.getId()),
                "down_url":
                "%s/es_folder_position?position=down&id=%s" %
                (self.context.absolute_url(), discount.getId()),
                "amount_of_criteria":
                self._getAmountOfCriteria(discount.getId())
            })

        return result
Пример #36
0
    def getMyAccountURL(self):
        """
        """
        shop = IShopManagement(self.context).getShop()
        customer = ICustomerManagement(shop).getAuthenticatedCustomer()

        return customer.absolute_url() + "/" + "my-account"
Пример #37
0
def mailOrderSubmitted(order):
    """Sends email to shop owner that an order has been submitted.
    """
    shop = IShopManagement(order).getShop()

    # Get sender and receiver
    mail_addresses = IMailAddresses(shop)
    sender = mail_addresses.getSender()
    receivers = mail_addresses.getReceivers()

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

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

        sendMultipartMail(context=order,
                          sender=sender,
                          receiver=", ".join(receivers),
                          subject="E-Shop: New order",
                          text=text,
                          charset=charset)
Пример #38
0
def mailOrderSent(order):
    """Sends email to customer that the order has been sent.
    """
    shop = IShopManagement(order).getShop()

    # Get mail content
    view = getMultiAdapter((order, order.REQUEST), name="mail-order-sent")
    text = view()

    # Get customer
    customer = order.getCustomer()

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

    # Get sender
    sender = IMailAddresses(shop).getSender()

    sendMultipartMail(context=order,
                      sender=sender,
                      receiver=customer.email,
                      subject="Your order %s has been sent." % order.getId(),
                      text=text,
                      charset=charset)
Пример #39
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")
Пример #40
0
    def process(self, order=None):
        """
        """
        info = dict()

        shop = IShopManagement(self.context).getShop()
        notify_url = "%s/paypal?order=%s" % (shop.absolute_url(), order.UID())
        return_url = "%s/thank-you" % shop.absolute_url()

        pc = IPrices(order)
        price_net = "%.2f" % pc.getPriceNet()
        tax = "%.2f" % (pc.getPriceGross() - float(price_net))

        customer = order.getCustomer()
        am = IAddressManagement(customer)
        invoice_address  = am.getInvoiceAddress()
        shipping_address = am.getShippingAddress()

        site_encoding = self.context.plone_utils.getSiteEncoding()

        info = {
            "cmd" : "_xclick",
            "upload" : "1",
            "business" : shop.getPayPalId(),
            "currency_code" : "EUR",
            "notify_url" : notify_url,
            "return" : return_url,
            "first_name" : invoice_address.firstname.encode(site_encoding),
            "last_name" : invoice_address.lastname.encode(site_encoding),
            "address1" : invoice_address.address_1.encode(site_encoding),
            "address2" : "",
            "city" : invoice_address.city.encode(site_encoding),
            "state" : invoice_address.country_title().encode(site_encoding),
            "zip" : invoice_address.zip_code.encode(site_encoding),
            "no_shipping" : "1",
            "item_name" : shop.getShopOwner(),
            "amount" : price_net,
            "tax" : tax,
        }

        # 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)
Пример #41
0
 def getStartupDirectoryForGroups(self):
     """
     """
     shop = IShopManagement(self).getShop()
     shop_path = "/".join(shop.getPhysicalPath())
     
     catalog = getToolByName(self, "portal_catalog")
     brains = catalog.searchResults(
         path = shop_path,
         object_provides = "easyshop.core.interfaces.groups.IGroupsContainer"
     )
     
     if len(brains) > 0:
         products_folder = brains[0]
         return products_folder.getPath()
     else:
         return shop_path
Пример #42
0
 def getInformation(self):
     """Returns information for information page which is given by request.
     """
     page_id = self.request.get("page_id")    
     page = self.context.information.get(page_id)
     if page is None:
         return None
         
     shop = IShopManagement(self.context).getShop()
 
     return {
         "shop_owner"  : shop.getShopOwner(),
         "url"         : "%s/at_download/file" % page.absolute_url(),
         "title"       : page.Title(),
         "description" : page.Description(),
         "text"        : page.getText(),
     }
Пример #43
0
 def __init__(self, discount, cart_item):
     """
     """
     self.discount  = discount
     self.cart_item = cart_item
     self.product   = cart_item.getProduct()
     self.taxes     = ITaxes(self.product)
     self.shop      = IShopManagement(self.product).getShop()
Пример #44
0
    def getCategoriesAsDL(self):
        """Returns all Categories as DisplayList
        """
        shop = IShopManagement(self).getShop()
        
        dl = DisplayList()
        catalog = getToolByName(self, "portal_catalog")
        
        brains = catalog.searchResults(
            path = "/".join(shop.getPhysicalPath()),
            portal_type="Category",
        )

        for brain in brains:
            dl.add(brain.getPath(), "%s (%s)" % (brain.Title, brain.getPath()))
            
        return dl
Пример #45
0
 def getStartupDirectoryForProducts(self):
     """
     """
     shop = IShopManagement(self).getShop()
     shop_path = "/".join(shop.getPhysicalPath())
     site_url = getToolByName(self, "portal_url")
     portal_path = site_url.getPortalPath()
     
     catalog = getToolByName(self, "portal_catalog")
     brains = catalog.searchResults(
         path = shop_path,
         object_provides = "easyshop.core.interfaces.catalog.IProductsContainer"
     )
     
     if len(brains) > 0:
         products_folder = brains[0]
         return products_folder.getPath().replace(portal_path,'')
     else:
         return shop_path.replace(portal_path,'')
Пример #46
0
    def getPriceNet(self, property_id, option_id):
        """
        """
        # Get the tax rate for the product to which the property belongs.
        # Note: That means, the tax rate for the product's properties is the
        # same as for the product.
        shop     = IShopManagement(self.context).getShop()
        tax_rate = ITaxes(self.context).getTaxRate()
        price    = self._calcPrice(property_id, option_id)


        # The price entered is considered as gross price. So we have to 
        # calculate the net price first.
        
        if shop.getGrossPrices() == True:
            return price * (100 / (tax_rate + 100))
            
        # The price entered is considered as net price, so we simply
        # return it.            
        else:
            return price
Пример #47
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)
Пример #48
0
    def getInfo(self):
        """
        """
        batch = self._getBatch()
        # This optimized for speed, as we need _getBatch here anyway.
        # So there is no need of an extra method call within the page 
        # template to get informations we have here already. Same is true 
        # for format infos, see below
                
        parent = self.context.aq_inner.aq_parent
        if ICategory.providedBy(parent):
            parent_url = parent.absolute_url()
        elif ICategoriesContainer.providedBy(parent):
            shop = IShopManagement(self.context).getShop()
            parent_url = shop.absolute_url()
        else:
            parent_url = None
        
        batch_infos = {
            "parent_url"       : parent_url,
            "first_url"        : self._getFirstUrl(batch),
            "previous_url"     : self._getPreviousUrl(batch),
            "previous"         : batch.previous,
            "next_url"         : self._getNextUrl(batch),
            "next"             : batch.next,
            "last_url"         : self._getLastUrl(batch),
            "navigation_list"  : batch.navlist,
            "number_of_pages"  : batch.numpages,
            "page_number"      : batch.pagenumber,
            "amount"           : batch.sequence_length,
        }
        
        sorting = self.request.SESSION.get("sorting")

        f = self.getFormatInfo()
        products_per_line = f["products_per_line"]
        
        line = []
        products = []        
        for index, product in enumerate(batch):

            # Price
            cm = ICurrencyManagement(self.context)
            p = IPrices(product)

            # Effective price
            price = p.getPriceForCustomer()                                
            price = cm.priceToString(price, symbol="symbol", position="before")
            
            # Standard price
            standard_price = p.getPriceForCustomer(effective=False)
            standard_price = cm.priceToString(standard_price, symbol="symbol", position="before")
                                    
            # Image
            image = IImageManagement(product).getMainImage()
            if image is not None:
                image = "%s/image_%s" % (image.absolute_url(), f.get("image_size"))
            
            # Text    
            temp = f.get("text")
            if temp == "description":
                text = product.getDescription()
            elif temp == "short_text":
                text = product.getShortText()
            elif temp == "text":
                text = product.getText()
            else:
                text = ""

            # Title
            temp = f.get("title")
            if temp == "title":
                title = product.Title()
            elif temp == "short_title":
                title = product.getShortTitle()

            try:
                chars = int(f.get("chars"))
            except (TypeError, ValueError):
                chars = 0
            
            if (chars != 0) and (len(title) > chars):
                title = title[:chars]
                title += "..."
                    
            # CSS Class
            if (index + 1) % products_per_line == 0:
                klass = "last"
            else:
                klass = "notlast"
                            
            line.append({
                "title"                    : title,
                "text"                     : text,
                "url"                      : product.absolute_url(),
                "image"                    : image,
                "for_sale"                 : product.getForSale(),
                "price"                    : price,
                "standard_price"           : standard_price,
                "class"                    : klass,
            })
            
            if (index + 1) % products_per_line == 0:
                products.append(line)
                line = []
        
        # the rest
        if len(line) > 0:
            products.append(line)
        
        # Return format infos here, because we need it anyway in this method
        # This is for speed reasons. See above.
        return {
            "products"    : products, 
            "batch_info"  : batch_infos,
            "format_info" : f,
        }
Пример #49
0
    def process(self, order=None):
        """
        """
        context = aq_inner(self.context)
        shop = IShopManagement(context).getShop()
        customer = ICustomerManagement(shop).getAuthenticatedCustomer()

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

        mpay24_url = context.getUrl()
        mpay24_merchant_id = context.getMerchant_id()
        mpay24_mdxi = context.getMdxi()

        conn_query = "OPERATION=SELECTPAYMENT&MERCHANTID=%s&MDXI=%s" % \
            (mpay24_merchant_id,
             quote(mpay24_mdxi % dict(tid=order.id,
                                      price=amount,
                                      site_url=shop.absolute_url())),)

        conn_string = "%s?%s" % (mpay24_url, conn_query)

        h = httplib2.Http('.cache',timeout=10)

        try:
            http_response, data = h.request(conn_string,"GET",)
        except:
            return PaymentResult(ERROR,_('MPAY24 connection timeout'))

        if data:
            data_dict = dict([part.split('=') for part in data.split('&')])

            if data_dict.get('STATUS','')=='ERROR':
                return PaymentResult(ERROR,"%s\n%s" % \
                    (unquote(data_dict.get('RETURNCODE','')),
                     unquote(conn_string)))
            elif data_dict.get('RETURNCODE','')=='REDIRECT':
                new_loc = data_dict.get('LOCATION','').strip()

                # save redirection URL in cookie for later usage
                context.REQUEST.RESPONSE.setCookie(
                    REDIR_COOKIE_NAME,
                    quote(encodestring(new_loc)),
                    path='/',
                )

                return PaymentResult('SUCCESS', '')
            else:
                return PaymentResult(ERROR, data_dict)

        return PaymentResult(ERROR,_("no data"))
Пример #50
0
 def getStartupDirectoryForObject(self):
     """
     """
     shop = IShopManagement(self).getShop()
     return "/".join(shop.getPhysicalPath())
Пример #51
0
class ProductTaxes(object):
    """Provides ITaxes for product content objects.
    """
    implements(ITaxes)
    adapts(IProduct)

    def __init__(self, context):
        """
        """
        self.context = context
        self.shop = IShopManagement(context).getShop()

    def getTaxRate(self):
        """
        """
        return self._calcTaxRateForProduct()

    def getTaxRateForCustomer(self):
        """
        """
        return self._calcTaxRateForCustomer()        

    def getTax(self, effective=True):
        """
        """
        if effective == True:
            return self._getEffectiveTax()
        else:
            return self._getStandardTax()
        
    def getTaxForCustomer(self, effective=True):
        """
        """
        if effective == True:
            return self._getEffectiveTaxForCustomer()
        else:
            return self._getStandardTaxForCustomer()

    def _getStandardTax(self):
        """Returns the standard tax of the product. Without taking care whether 
        the product is for sale or not. We need this in any case (whether the 
        product is for sale or not) to display the default price (e.g. stroked).
        """
        tax_rate = self._calcTaxRateForProduct()
        price = self.context.getPrice()
        
        if self.shop.getGrossPrices() == True:
            tax_abs = (tax_rate/(tax_rate+100)) * price
        else:
            tax_abs = price * (tax_rate/100)

        return tax_abs
        
    def _getStandardTaxForCustomer(self):
        """Returns the standard tax of the product and customer. Without taking 
        care whether the product is for sale or not. We need this in any case 
        (whether the  product is for sale or not) to display the default price 
        (e.g. stroked).
        """
        tax_product = self.getTax(effective=False)
        tax_rate_customer = self._calcTaxRateForCustomer()
        
        if self.shop.getGrossPrices() == True:
            price_net = self.context.getPrice() - tax_product
        else:
            price_net = self.context.getPrice()
        
        return (tax_rate_customer/100) * price_net

    def _getEffectiveTax(self):
        """Returns the effective tax of the product. This means it takes care 
        whether the product is for sale for not.
        """
        tax_rate = self._calcTaxRateForProduct()

        if self.context.getForSale() == True:
            price = self.context.getSalePrice()
        else:
            price = self.context.getPrice()

        if self.shop.getGrossPrices() == True:
            tax_abs = (tax_rate/(tax_rate+100)) * price
        else:
            tax_abs = price * (tax_rate/100)

        return tax_abs
        
    def _getEffectiveTaxForCustomer(self):
        """Returns the effective tax of the product and customer. This means it
        takes care whether the product is for sale for not.
        """
        tax_product = self.getTax()
        tax_rate_customer = self._calcTaxRateForCustomer()

        if self.context.getForSale() == True:
            price_net = self.context.getSalePrice()
        else:
            price_net = self.context.getPrice()
        
        if self.shop.getGrossPrices() == True:
            price_net = price_net - tax_product
        
        return (tax_rate_customer/100) * price_net

    def _calcTaxRateForProduct(self):
        """Calculates the default tax for a given product.
        """
        # Returns the first tax rate, which is true. Taxes are sorted by 
        # position which is also the priority
        tm = ITaxManagement(self.shop)
        for tax in tm.getDefaultTaxes():
            if IValidity(tax).isValid(self.context) == True:
                return tax.getRate()

        return 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()
Пример #52
0
 def __init__(self, context):
     """
     """
     self.shop = IShopManagement(context).getShop()
Пример #53
0
class DiscountPrices:
    """Multia adapter which provides IPrices for discount content objects and 
    product.
    """
    implements(IPrices)
    adapts(IDiscount, ICartItem)
    
    # NOTE: We need the product additionally as we need to calculate taxes, as 
    # the discount has the same tax rate as the related product.
    
    def __init__(self, discount, cart_item):
        """
        """
        self.discount  = discount
        self.cart_item = cart_item
        self.product   = cart_item.getProduct()
        self.taxes     = ITaxes(self.product)
        self.shop      = IShopManagement(self.product).getShop()

    def getPriceForCustomer(self):
        """
        """
        # If the discount is by percentage, we don't have to calc the tax for 
        # the discount, because the discount is a part of the already calculated
        # price, hence we can do it here.
        
        if self.discount.getType() == "percentage":
            price = IPrices(self.cart_item).getPriceForCustomer()
            return price * (self.discount.getValue() / 100)
        else:
            tax_rate_for_customer = self.taxes.getTaxRateForCustomer()
            price_net = self.getPriceNet()
        
            # We take the net price and add the customer specific taxes.
            return price_net * ((tax_rate_for_customer+100)/100)

    def getPriceGross(self):
        """
        """
        if self.discount.getType() == "percentage":
            price = IPrices(self.cart_item).getPriceGross()
            return  price * (self.discount.getValue() / 100)
        else:
            tax_rate = self.taxes.getTaxRate()
            price = self._calcTotalPrice()

            # The price entered is considered as gross price, so we simply
            # return it.
            if self.shop.getGrossPrices() == True:
                return price                

            # The price entered is considered as net price. So we have to 
            # calculate the gross price first.
            else:
                return price * ((tax_rate+100)/100)

    def getPriceNet(self):
        """
        """
        if self.discount.getType() == "percentage":
            price = IPrices(self.cart_item).getPriceNet()
            return price * (self.discount.getValue() / 100)
        else:
            tax_rate = self.taxes.getTaxRate()
            price = self._calcTotalPrice()

            # The price entered is considered as gross price. So we have to 
            # calculate the net price first.
                
            if self.shop.getGrossPrices() == True:
                return price * (100/(tax_rate+100))
                
            # The price entered is considered as net price, so we simply return 
            # it.
            else:
                return price
            
    def _calcTotalPrice(self):
        """
        """
        if self.discount.getBase() == "cart_item":
            return self.discount.getValue()
        else:
            return self.discount.getValue() * self.cart_item.getAmount()
Пример #54
0
 def getShopUrl(self):
     """
     """
     shop = IShopManagement(self.context).getShop()
     return shop.absolute_url()