Exemplo n.º 1
0
def check_with_akismet(comment=None, request=None, **kwargs):
    if config_value("PRODUCT", "AKISMET_ENABLE"):
        akismet_key = config_value("PRODUCT", "AKISMET_KEY")
        if akismet_key:             
            site = Site.objects.get_current()
            shop = urlresolvers.reverse('satchmo_shop_home')
            from akismet import Akismet
            akismet = Akismet(
                key=akismet_key,
                blog_url='http://%s' % url_join(site.domain, shop))
            if akismet.verify_key():
                akismet_data = { 'comment_type': 'comment',
                                 'referrer': request.META.get('HTTP_REFERER', ""),
                                 'user_ip': comment.ip_address,
                                 'user_agent': '' }
                if akismet.comment_check(smart_str(comment.comment), data=akismet_data, build_data=True):
                    comment.is_public=False
                    comment.save()
                    log.info("Akismet marked comment #%i as spam", comment.id)
                else:
                    log.debug("Akismet accepted comment #%i", comment.id)
            else:
                log.warn("Akismet key '%s' not accepted by akismet service.", akismet_key)
        else:
            log.info("Akismet enabled, but no key found.  Please put in your admin settings.")
Exemplo n.º 2
0
def send_order_notice(order, template='', template_html=''):
    """Send an order confirmation mail to the owner.
    """

    if config_value("PAYMENT", "ORDER_EMAIL_OWNER"):
        try:
            sale = Discount.objects.by_code(order.discount_code, raises=True)
        except Discount.DoesNotExist:
            sale = None

        c = {'order': order, 'sale': sale}
        subject = _("New order on %(shop_name)s")

        eddresses = []
        more = config_value("PAYMENT", "ORDER_EMAIL_EXTRA")
        if more:
            eddresses = set([m.strip() for m in more.split(',')])
            eddresses = [e for e in eddresses if e]

        try:
            send_store_mail(subject,
                            c,
                            template,
                            eddresses,
                            template_html=template_html,
                            format_subject=True,
                            send_to_store=True,
                            sender=order_notice_sender)
        except NoRecipientsException:
            log.warn("No shop owner email specified, skipping owner_email")
            return
Exemplo n.º 3
0
def send_order_notice(order, template='', template_html=''):
    """Send an order confirmation mail to the owner.
    """

    if config_value("PAYMENT", "ORDER_EMAIL_OWNER"):
        try:
            sale = Discount.objects.by_code(order.discount_code, raises=True)
        except Discount.DoesNotExist:
            sale = None

        c = {'order': order, 'sale' : sale}
        subject = _("New order on %(shop_name)s")

        eddresses = []
        more = config_value("PAYMENT", "ORDER_EMAIL_EXTRA")
        if more:
            eddresses = set([m.strip() for m in more.split(',')])
            eddresses = [e for e in eddresses if e]

        try:
            send_store_mail(subject, c, template, eddresses,
                            template_html=template_html, format_subject=True,
                            send_to_store=True, sender=order_notice_sender)
        except NoRecipientsException:
            log.warn("No shop owner email specified, skipping owner_email")
            return
Exemplo n.º 4
0
    def process(self, order=None):
        """
        Calculate the tax and return it
        """
        if order:
            self.order = order
        else:
            order = self.order

        percent = config_value('TAX', 'PERCENT')

        sub_total = Decimal("0.00")
        for item in order.orderitem_set.filter(product__taxable=True):
            sub_total += item.sub_total

        itemtax = sub_total * (percent / 100)
        taxrates = {'%i%%' % percent: itemtax}

        if config_value('TAX', 'TAX_SHIPPING_PERCENT'):
            shipping = order.shipping_sub_total
            sub_total += shipping
            ship_tax = shipping * (percent / 100)
            taxrates['Shipping'] = ship_tax

        tax = sub_total * (percent / 100)
        return tax, taxrates
Exemplo n.º 5
0
def check_with_akismet(comment=None, request=None, **kwargs):
    if config_value("PRODUCT", "AKISMET_ENABLE"):
        akismet_key = config_value("PRODUCT", "AKISMET_KEY")
        if akismet_key:
            site = Site.objects.get_current()
            shop = urlresolvers.reverse('satchmo_shop_home')
            from akismet import Akismet
            akismet = Akismet(key=akismet_key,
                              blog_url='http://%s' %
                              url_join(site.domain, shop))
            if akismet.verify_key():
                akismet_data = {
                    'comment_type': 'comment',
                    'referrer': request.META.get('HTTP_REFERER', ""),
                    'user_ip': comment.ip_address,
                    'user_agent': ''
                }
                if akismet.comment_check(smart_str(comment.comment),
                                         data=akismet_data,
                                         build_data=True):
                    comment.is_public = False
                    comment.save()
                    log.info("Akismet marked comment #%i as spam", comment.id)
                else:
                    log.debug("Akismet accepted comment #%i", comment.id)
            else:
                log.warn("Akismet key '%s' not accepted by akismet service.",
                         akismet_key)
        else:
            log.info(
                "Akismet enabled, but no key found.  Please put in your admin settings."
            )
Exemplo n.º 6
0
    def process(self, order=None):
        """
        Calculate the tax and return it
        """
        if order:
            self.order = order
        else:
            order = self.order

        percent = config_value('TAX','PERCENT')    

        sub_total = Decimal("0.00")
        for item in order.orderitem_set.filter(product__taxable=True):
            sub_total += item.sub_total
        
        itemtax = sub_total * (percent/100)
        taxrates = {'%i%%' % percent :  itemtax}
        
        if config_value('TAX','TAX_SHIPPING_PERCENT'):
            shipping = order.shipping_sub_total
            sub_total += shipping
            ship_tax = shipping * (percent/100)
            taxrates['Shipping'] = ship_tax
        
        tax = sub_total * (percent/100)
        return tax, taxrates
Exemplo n.º 7
0
 def get_context(self, request, order_id, doc):
     return {
         'order': get_object_or_404(Order, pk=order_id),
         'doc': doc,
         'iconURI': config_value('SHOP', 'LOGO_URI'),
         'shopDetails': Config.objects.get_current(),
         'default_view_tax': config_value('TAX', 'DEFAULT_VIEW_TAX')
     }
Exemplo n.º 8
0
def index(request):
    image_count = config_value('MyApp', 'NUM_IMAGES')
    # Note, the measurement_system will return a list of selected values
    # in this case, we use the first one
    measurement_system = config_value('MyApp', 'MEASUREMENT_SYSTEM')
    return render_to_response('myapp/index.html',
                              {'image_count': image_count,
                               'measurement_system': measurement_system[0]})
Exemplo n.º 9
0
def index(request):
    image_count = config_value('MyApp', 'NUM_IMAGES')
    # Note, the measurement_system will return a list of selected values
    # in this case, we use the first one
    measurement_system = config_value('MyApp', 'MEASUREMENT_SYSTEM')
    return render_to_response('myapp/index.html', {
        'image_count': image_count,
        'measurement_system': measurement_system[0]
    })
Exemplo n.º 10
0
def labelled_gateway_choices():
    choices = []
    for module, group in active_gateways():
        defaultlabel = module.split('.')[-1]
        label = _(config_value(group, 'LABEL', default=defaultlabel))
        key = config_value(group, 'KEY')
        choices.append((key, label))

    signals.payment_choices.send(None, choices=choices)
    return choices
Exemplo n.º 11
0
def labelled_gateway_choices():
    choices = []
    for module, group in active_gateways():
        defaultlabel = module.split('.')[-1]
        label = _(config_value(group, 'LABEL', default = defaultlabel))
        key = config_value(group,'KEY')
        choices.append((key, label))
        
    signals.payment_choices.send(None, choices=choices)
    return choices
Exemplo n.º 12
0
 def __init__(self, *args, **kwargs):
     super(Charge, self).__init__(*args, **kwargs)
     import stripe
     DEBUG = settings.DEBUG
     STRIPE_TEST_MODE = config_value('laurenmcmanus', 'STRIPE_TEST_MODE')
     if DEBUG == True or STRIPE_TEST_MODE == True:
         stripe.api_key = config_value('laurenmcmanus', 'STRIPE_TEST_PUBLIC_KEY')
     else:
         stripe.api_key = config_value('laurenmcmanus', 'STRIPE_LIVE_PUBLIC_KEY')
     self.stripe = stripe
Exemplo n.º 13
0
def add(request, id=0, redirect_to='satchmo_cart'):
    """Add an item to the cart."""
    log.debug('FORM: %s', request.POST)
    formdata = request.POST.copy()
    productslug = None

    cartplaces = config_value('SHOP', 'CART_PRECISION')
    roundfactor = config_value('SHOP', 'CART_ROUNDING')


    if formdata.has_key('productname'):
        productslug = formdata['productname']
    try:
        product, details = product_from_post(productslug, formdata)

        if not (product and product.active):
            log.debug("product %s is not active" % productslug)
            return bad_or_missing(request, _("That product is not available at the moment."))
        else:
            log.debug("product %s is active" % productslug)

    except (Product.DoesNotExist, MultiValueDictKeyError):
        log.debug("Could not find product: %s", productslug)
        return bad_or_missing(request, _('The product you have requested does not exist.'))

    # First we validate that the number isn't too big.
    if decimal_too_big(formdata['quantity']):
        return _product_error(request, product, _("Please enter a smaller number."))

    # Then we validate that we can round it appropriately.
    try:
        quantity = round_decimal(formdata['quantity'], places=cartplaces, roundfactor=roundfactor)
    except RoundedDecimalError:
        return _product_error(request, product,
            _("Invalid quantity."))

    if quantity <= Decimal('0'):
        return _product_error(request, product,
            _("Please enter a positive number."))

    cart = Cart.objects.from_request(request, create=True)
    # send a signal so that listeners can update product details before we add it to the cart.
    satchmo_cart_details_query.send(
            cart,
            product=product,
            quantity=quantity,
            details=details,
            request=request,
            form=formdata
            )
    try:
        added_item = cart.add_item(product, number_added=quantity, details=details)

    except CartAddProhibited, cap:
        return _product_error(request, product, cap.message)
Exemplo n.º 14
0
 def get_context(self, request, order_id, doc):
     order = get_object_or_404(Order, pk=order_id)
     shopDetails = Config.objects.get_current()
     icon_uri = config_value('SHOP', 'LOGO_URI')
     context = {
         'doc': doc,
         'iconURI': icon_uri,
         'shopDetails': shopDetails,
         'order': order,
         'default_view_tax': config_value('TAX', 'DEFAULT_VIEW_TAX')
     }
     return context
Exemplo n.º 15
0
    def save(self, cart, request):
        log.debug('saving')
        self.full_clean()
        cartplaces = config_value('SHOP', 'CART_PRECISION')
        roundfactor = config_value('SHOP', 'CART_ROUNDING')
        site = Site.objects.get_current()

        for name, value in self.cleaned_data.items():
            opt, key = name.split('__')
            log.debug('%s=%s', opt, key)

            quantity = 0
            product = None

            if opt == 'qty':
                try:
                    quantity = round_decimal(value,
                                             places=cartplaces,
                                             roundfactor=roundfactor)
                except RoundedDecimalError:
                    quantity = 0

            if not key in self.slugs:
                log.debug('caught attempt to add product not in the form: %s',
                          key)
            else:
                try:
                    product = Product.objects.get(slug=key, site=site)
                except Product.DoesNotExist:
                    log.debug(
                        'caught attempt to add an non-existent product, ignoring: %s',
                        key)

            if product and quantity > Decimal('0'):
                log.debug('Adding %s=%s to cart from MultipleProductForm', key,
                          value)
                details = []
                formdata = request.POST
                satchmo_cart_details_query.send(cart,
                                                product=product,
                                                quantity=quantity,
                                                details=details,
                                                request=request,
                                                form=formdata)
                added_item = cart.add_item(product,
                                           number_added=quantity,
                                           details=details)
                satchmo_cart_add_complete.send(cart,
                                               cart=cart,
                                               cartitem=added_item,
                                               product=product,
                                               request=request,
                                               form=formdata)
Exemplo n.º 16
0
 def get_context(self, request, order_id, doc):
     order = get_object_or_404(Order, pk=order_id)
     shopDetails = Config.objects.get_current()
     icon_uri = config_value('SHOP', 'LOGO_URI')
     context = {
         'doc': doc,
         'iconURI' : icon_uri,
         'shopDetails' : shopDetails,
         'order' : order,
         'default_view_tax': config_value('TAX','DEFAULT_VIEW_TAX')
     }
     return context
Exemplo n.º 17
0
def _set_quantity(request, force_delete=False):
    """Set the quantity for a specific cartitem.
    Checks to make sure the item is actually in the user's cart.
    """
    cart = Cart.objects.from_request(request, create=False)
    if isinstance(cart, NullCart):
        return (False, None, None, _("No cart to update."))

    cartplaces = config_value('SHOP', 'CART_PRECISION')

    if decimal_too_big(request.POST.get('quantity', 0)):
        return (False,cart,None,_("Bad quantity."))

    if force_delete:
        qty = Decimal('0')
    else:
        try:
            roundfactor = config_value('SHOP', 'CART_ROUNDING')
            qty = round_decimal(request.POST.get('quantity', 0), places=cartplaces, roundfactor=roundfactor, normalize=True)
        except RoundedDecimalError as P:
            return (False, cart, None, _("Bad quantity."))

        if qty < Decimal('0'):
            qty = Decimal('0')

    try:
        itemid = int(request.POST.get('cartitem'))
    except (TypeError, ValueError):
        return (False, cart, None, _("Bad item number."))

    try:
        cartitem = CartItem.objects.get(pk=itemid, cart=cart)
    except CartItem.DoesNotExist:
        return (False, cart, None, _("No such item in your cart."))

    if qty == Decimal('0'):
        cartitem.delete()
        cartitem = NullCartItem(itemid)
    else:
        if config_value('PRODUCT','NO_STOCK_CHECKOUT') == False:
            stock = cartitem.product.items_in_stock
            log.debug('checking stock quantity.  Have %d, need %d', stock, qty)
            if stock < qty:
                return (False, cart, cartitem, _("Unfortunately we only have %(stock)d '%(cartitem_name)s' in stock.") % {'stock': stock, 'cartitem_name': cartitem.product.translated_name()})

        cartitem.quantity = round_decimal(qty, places=cartplaces)
        cartitem.save()

    satchmo_cart_changed.send(cart, cart=cart, request=request)
    return (True, cart, cartitem, "")
Exemplo n.º 18
0
def index(request):
    image_count = config_value('MyApp', 'NUM_IMAGES')
    # Note, the measurement_system will return a list of selected values
    # in this case, we use the first one
    measurement_system = config_value('MyApp', 'MEASUREMENT_SYSTEM')
    image_url = config_value('Images', 'IMAGE_URL')
    example_url = config_value('Urls', 'EXAMPLE_URL')
    return render_to_response(
        'myapp/index.html', {
            'image_count': image_count,
            'measurement_system': measurement_system[0],
            'image_url': image_url,
            'example_url': example_url
        })
Exemplo n.º 19
0
    def shipping(self, subtotal=None):
        if subtotal is None and self.order:
            subtotal = self.order.shipping_sub_total

        if subtotal:
            subtotal = self.order.shipping_sub_total
            if config_value('TAX', 'TAX_SHIPPING_PERCENT'):
                percent = config_value('TAX', 'PERCENT')
                t = subtotal * (percent / 100)
            else:
                t = Decimal("0.00")
        else:
            t = Decimal("0.00")

        return t
Exemplo n.º 20
0
def display_featured(num_to_display=None, random_display=None):
    """
    Used by the index generic view to choose how the featured products are displayed.
    Items can be displayed randomly or all in order
    """
    if num_to_display is None:
        num_to_display = config_value('PRODUCT', 'NUM_DISPLAY')
    if random_display is None:
        random_display = config_value('PRODUCT', 'RANDOM_FEATURED')

    q = Product.objects.featured_by_site()
    if not random_display:
        return q[:num_to_display]
    else:
        return q.order_by('?')[:num_to_display]
Exemplo n.º 21
0
    def shipping(self, subtotal=None):
        if subtotal is None and self.order:
            subtotal = self.order.shipping_sub_total

        if subtotal:
            subtotal = self.order.shipping_sub_total
            if config_value('TAX','TAX_SHIPPING_PERCENT'):
                percent = config_value('TAX','PERCENT')
                t = subtotal * (percent/100)
            else:
                t = Decimal("0.00")
        else:
            t = Decimal("0.00")
                
        return t
Exemplo n.º 22
0
    def valid(self, order=None):
        """
        Can do complex validation about whether or not this option is valid.
        For example, may check to see if the recipient is in an allowed country
        or location.
        """
        if order:
            if config_value('SHIPPING_TIERED',
                            'MIN_PRICE_FOR') == 'NOT_DISCOUNTABLE':
                sub_total = order.sub_total
            else:
                itemprices = [
                    item.sub_total for item in order.orderitem_set.all()
                    if item.product.is_shippable
                ]
                if itemprices:
                    sub_total = reduce(operator.add, itemprices)
                else:
                    sub_total = Decimal('0.00')

            try:
                price = self.carrier.price(sub_total)

            except TieredPriceException:
                return False

        elif self.cart:
            try:
                price = self.cost()

            except TieredPriceException:
                return False

        return True
Exemplo n.º 23
0
def get_newsletter_module():
    try:
        modulename = config_value('NEWSLETTER', 'MODULE')
    except AttributeError:
        modulename = 'satchmo_ext.newsletter.ignore'
        
    return load_module(modulename)
Exemplo n.º 24
0
def register(request, redirect=None, template='registration/registration_form.html'):
    """
    Allows a new user to register an account.
    """

    ret = register_handle_form(request, redirect)
    success = ret[0]
    todo = ret[1]
    if len(ret) > 2:
        extra_context = ret[2]
    else:
        extra_context = {}

    if success:
        return todo
    else:
        if config_get_group('NEWSLETTER'):
            show_newsletter = True
        else:
            show_newsletter = False

        ctx = {
            'form': todo,
            'title' : _('Registration Form'),
            'show_newsletter' : show_newsletter,
            'allow_nickname' : config_value('SHOP', 'ALLOW_NICKNAME_USERNAME')
        }

        if extra_context:
            ctx.update(extra_context)

        context = RequestContext(request, ctx)
        return render_to_response(template, context_instance=context)
Exemplo n.º 25
0
def add_newsletter_urls(sender, patterns=(), **kwargs):
    newsbase = r'^' + config_value('NEWSLETTER','NEWSLETTER_SLUG') + '/'    
    log.debug("Adding newsletter urls at %s", newsbase)
    newspatterns = patterns_fn('',
        (newsbase, include('satchmo_ext.newsletter.urls'))
    )
    patterns += newspatterns
Exemplo n.º 26
0
def credit_choices(settings=None, include_module_if_no_choices=False):
    choices = []
    keys = []
    for module, group in active_gateways():
        vals = config_choice_values(group, 'CREDITCHOICES')
        for key, label in vals:
            if not key in keys:
                keys.append(key)
                pair = (key, ugettext(label))
                choices.append(pair)
        if include_module_if_no_choices and not vals:
            key = config_value(group, 'KEY')
            label = config_value(group, 'LABEL')
            pair = (key, ugettext(label))
            choices.append(pair)
    return choices
Exemplo n.º 27
0
def cartitem_total(parser, token):
    """Returns the line total for the cartitem, possibly with tax added.  If currency evaluates true,
    then return the total formatted through moneyfmt.

    Example::

        {% cartitem_total cartitem [show_tax] [currency] %}
    """

    tokens = token.contents.split()
    if len(tokens) < 2:
        raise template.TemplateSyntaxError, "'%s' tag requires a cartitem argument" % tokens[
            0]

    cartitem = tokens[1]

    if len(tokens) > 2:
        show_tax = tokens[2]
    else:
        show_tax = config_value('TAX', 'DEFAULT_VIEW_TAX')

    if len(tokens) > 3:
        show_currency = tokens[3]
    else:
        show_currency = 'True'

    return CartitemTotalNode(cartitem, show_currency, show_tax)
Exemplo n.º 28
0
def success(request):
    """
    The order has been succesfully processed.
    We clear out the cart but let the payment processing get called by IPN
    """
    try:
        order = Order.objects.from_request(request)
    except Order.DoesNotExist:
        return bad_or_missing(request,
                              _('Your order has already been processed.'))

    # Added to track total sold for each product
    for item in order.orderitem_set.all():
        product = item.product
        product.total_sold += item.quantity
        if config_value('PRODUCT', 'TRACK_INVENTORY'):
            product.items_in_stock -= item.quantity
        product.save()

    # Clean up cart now, the rest of the order will be cleaned on paypal IPN
    for cart in Cart.objects.filter(customer=order.contact):
        cart.empty()

    del request.session['orderID']
    context = RequestContext(request, {'order': order})
    return render_to_response('shop/checkout/success.html', context)
Exemplo n.º 29
0
def _protected_dir(instance, filename):
    # if we get a SettingNotSet exception (even though we've already
    # imported/loaded it), that's bad, so let it bubble up.
    raw = config_value('PRODUCT', 'PROTECTED_DIR')
    updir = os.path.normpath(normalize_dir(raw))
    file_name = os.path.normpath(instance.file.field.storage.get_valid_name(os.path.basename(filename)))
    return os.path.join(updir, file_name)
Exemplo n.º 30
0
def google_adwords_signup(context):
    """
    Output signup info in the format that Google adwords needs.
    """
    request = context['request']
    try:
        request = context['request']
    except KeyError:
        print >> sys.stderr, "Template satchmo.show.templatetags.google.google_adwords_sale couldn't get the request from the context.  Are you missing the request context_processor?"
        return ""

    secure = request.is_secure()
    try:
        language_code = request.LANGUAGE_CODE
    except AttributeError:
        language_code = settings.LANGUAGE_CODE

    return ({
        "GOOGLE_ADWORDS_ID": config_value('GOOGLE', 'ADWORDS_ID'),
        'Store': settings.SITE_NAME,
        'value': 1,
        'label': 'signup',
        'secure': secure,
        'language_code': language_code
    })
Exemplo n.º 31
0
    def __init__(self, request, paymentmodule, *args, **kwargs):
        creditchoices = paymentmodule.CREDITCHOICES.choice_values
        super(CreditPayShipForm, self).__init__(request, paymentmodule, *args, **kwargs)

        self.cc = None

        self.fields['credit_type'].choices = creditchoices

        num_years = config_value('PAYMENT', 'CC_NUM_YEARS')
        year_now = datetime.date.today().year
        self.fields['year_expires'].choices = [(year, year) for year in range(year_now, year_now+num_years+1)]

        self.tempCart = Cart.objects.from_request(request)

        initial = kwargs.get('initial', None)
        if initial:
            if initial.get('credit_number', None):
                self.fields['credit_number'].widget = forms.PasswordInput()
            if initial.get('ccv', None):
                self.fields['ccv'].widget = forms.PasswordInput()

        try:
            self.tempContact = Contact.objects.from_request(request)
        except Contact.DoesNotExist:
            self.tempContact = None
Exemplo n.º 32
0
        def __init__(self, *args, **kwargs):
            super(PaymentContactInfoForm, self).__init__(*args, **kwargs)
            if not self.cart:
                request = threadlocals.get_current_request()
                self.cart = Cart.objects.from_request(request)

            self.fields['discount'] = forms.CharField(max_length=30, required=False)

            self.payment_required_fields = {}

            if config_value('PAYMENT', 'USE_DISCOUNTS'):
                if not self.fields['discount'].initial:
                    sale = _find_sale(self.cart)
                    if sale:
                        self.fields['discount'].initial = sale.code
            else:
                self.fields['discount'].widget = forms.HiddenInput()

            # Listeners of the form_init signal (below) may modify the dict of
            # payment_required_fields. For example, if your CUSTOM_PAYMENT requires
            # customer's city, put the following code in the listener:
            #
            #   form.payment_required_fields['CUSTOM_PAYMENT'] = ['city']
            #
            form_init.send(PaymentContactInfoForm, form=self)
Exemplo n.º 33
0
def cart_total(parser, token):
    """Returns the total for the cart, possibly with tax added.  If currency evaluates true,
    then return the total formatted through moneyfmt.

    Example::

        {% cart_total cart [show_tax] [currency] [discounted] %}
    """

    tokens = token.contents.split()
    if len(tokens) < 2:
        raise template.TemplateSyntaxError("'%s' tag requires a cart argument" % tokens[0])

    cart = tokens[1]

    if len(tokens) > 2:
        show_tax = tokens[2]
    else:
        show_tax = config_value('TAX', 'DEFAULT_VIEW_TAX')

    if len(tokens) > 3:
        show_currency = tokens[3]
    else:
        show_currency = True

    if len(tokens) > 4:
        show_discount = tokens[4]
    else:
        show_discount = False

    return CartTotalNode(cart, show_currency, show_tax, show_discount)
Exemplo n.º 34
0
def make_urlpatterns():
    patterns = []
    try:
        from django.apps import apps
        app_list = [app_config.models_module for app_config in apps.get_app_configs() if app_config.models_module is not None]
    except ImportError:
        from django.db import models
        app_list = models.get_apps()
    for app in app_list:
        if hasattr(app, 'PAYMENT_PROCESSOR'):
            parts = app.__name__.split('.')
            key = parts[-2].upper()
            modulename = 'PAYMENT_%s' % key
            name = app.__name__
            name = name[:name.rfind('.')]
            #log.debug('payment module=%s, key=%s', modulename, key)
            # BJK: commenting out Bursar settings here
            # try:
            #     cfg = config_get(modulename, 'INTERFACE_MODULE')
            #     interface = cfg.editor_value
            # except SettingNotSet:
            #     interface = name[:name.rfind('.')]
            # urlmodule = "%s.urls" % interface
            urlmodule = '.'.join(parts[:-1]) + '.urls'
            urlbase = config_value(modulename, 'URL_BASE')
            log.debug('Found payment processor: %s, adding urls at %s', key, urlbase)
            patterns.append(url(urlbase, [urlmodule, '', '']))
    return tuple(patterns)
Exemplo n.º 35
0
def cartitem_total(parser, token):
    """Returns the line total for the cartitem, possibly with tax added.  If currency evaluates true,
    then return the total formatted through moneyfmt.

    Example::

        {% cartitem_total cartitem [show_tax] [currency] %}
    """

    tokens = token.contents.split()
    if len(tokens) < 2:
        raise template.TemplateSyntaxError, "'%s' tag requires a cartitem argument" % tokens[0]

    cartitem = tokens[1]

    if len(tokens) > 2:
        show_tax = tokens[2]
    else:
        show_tax = config_value('TAX', 'DEFAULT_VIEW_TAX')

    if len(tokens) >3:
        show_currency = tokens[3]
    else:
        show_currency = 'True'

    return CartitemTotalNode(cartitem, show_currency, show_tax)
Exemplo n.º 36
0
def success(request):
    """
    The order has been succesfully processed.
    We clear out the cart but let the payment processing get called by IPN
    """
    try:
        order = Order.objects.from_request(request)
    except Order.DoesNotExist:
        return bad_or_missing(request, _('Your order has already been processed.'))

    # Added to track total sold for each product
    for item in order.orderitem_set.all():
        product = item.product
        product.total_sold += item.quantity
        if config_value('PRODUCT','TRACK_INVENTORY'):
            product.items_in_stock -= item.quantity
        product.save()

    # Clean up cart now, the rest of the order will be cleaned on paypal IPN
    for cart in Cart.objects.filter(customer=order.contact):
        cart.empty()

    del request.session['orderID']
    context = RequestContext(request, {'order': order})
    return render_to_response('shop/checkout/success.html', context)
Exemplo n.º 37
0
def credit_choices(settings=None, include_module_if_no_choices=False):
    choices = []
    keys = []
    for module, group in active_gateways():
        vals = config_choice_values(group, 'CREDITCHOICES')
        for key, label in vals:
            if not key in keys:
                keys.append(key)
                pair = (key, ugettext(label))
                choices.append(pair)
        if include_module_if_no_choices and not vals:
            key = config_value(group, 'KEY')
            label = config_value(group, 'LABEL')
            pair = (key, ugettext(label))
            choices.append(pair)
    return choices
Exemplo n.º 38
0
    def clean(self, value):
        """
        Normalize the field according to cart normalizing rules.
        """
        cartplaces = config_value('SHOP', 'CART_PRECISION')
        roundfactor = config_value('SHOP', 'CART_ROUNDING')

        if not value or value == '':
            value = Decimal(0)

        try:
            value = round_decimal(val=value, places=cartplaces, roundfactor=roundfactor, normalize=True)
        except RoundedDecimalError:
            raise forms.ValidationError(_('%(value)s is not a valid number') % {'value' : value})

        return value
Exemplo n.º 39
0
    def __init__(self, request, paymentmodule, *args, **kwargs):
        creditchoices = paymentmodule.CREDITCHOICES.choice_values
        super(CreditPayShipForm, self).__init__(request, paymentmodule, *args, **kwargs)

        self.cc = None

        self.fields['credit_type'].choices = creditchoices

        num_years = config_value('PAYMENT', 'CC_NUM_YEARS')
        year_now = datetime.date.today().year
        self.fields['year_expires'].choices = [(year, year) for year in range(year_now, year_now+num_years+1)]

        self.tempCart = Cart.objects.from_request(request)

        initial = kwargs.get('initial', None)
        if initial:
            if initial.get('credit_number', None):
                self.fields['credit_number'].widget = forms.PasswordInput()
            if initial.get('ccv', None):
                self.fields['ccv'].widget = forms.PasswordInput()

        try:
            self.tempContact = Contact.objects.from_request(request)
        except Contact.DoesNotExist:
            self.tempContact = None
Exemplo n.º 40
0
def activate(request, activation_key):
    """
    Activates a user's account, if their key is valid and hasn't
    expired.
    """
    from registration.models import RegistrationProfile
    activation_key = activation_key.lower()
    site = Site.objects.get_current()
    account = RegistrationProfile.objects.activate_user(activation_key, site)

    if account:
        # ** hack for logging in the user **
        # when the login form is posted, user = authenticate(username=data['username'], password=data['password'])
        # ...but we cannot authenticate without password... so we work-around authentication
        account.backend = settings.AUTHENTICATION_BACKENDS[0]
        _login(request, account)
        try:
            contact = Contact.objects.get(user=account)
            request.session[CUSTOMER_ID] = contact.id
            send_welcome_email(contact.email, contact.first_name,
                               contact.last_name)
            signals.satchmo_registration_verified.send(contact,
                                                       contact=contact)
        except Contact.DoesNotExist:
            # Treated for better compatibility with registation tests without error
            pass

    context = {
        'account': account,
        'expiration_days': config_value('SHOP', 'ACCOUNT_ACTIVATION_DAYS'),
    }
    return render(request, 'registration/activate.html', context)
Exemplo n.º 41
0
def view_user_data_listener(contact=None, contact_dict=None, **kwargs):
    module = config_value('NEWSLETTER', 'MODULE')
    if module not in ('', 'satchmo_ext.newsletter.ignore'):
        contact_dict['show_newsletter'] = True
        contact_dict['newsletter'] = is_subscribed(contact)
    else:
        contact_dict['show_newsletter'] = False
Exemplo n.º 42
0
def _login(request, redirect_to, auth_form=EmailAuthenticationForm):
    """"Altered version of the default login, intended to be called by `combined_login`.

    Returns tuple:
    - success
    - redirect (success) or form (on failure)
    """
    if request.method == 'POST':
        form = auth_form(data=request.POST)
        if form.is_valid():
            # Light security check -- make sure redirect_to isn't garbage.
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL
            login(request, form.get_user())
            # Now that we've logged in, assign this cart to our user
            _assign_cart(request)
            if config_value('SHOP', 'PERSISTENT_CART'):
                _get_prev_cart(request)
            return (True, HttpResponseRedirect(redirect_to))
        else:
            log.debug(form.errors)
    else:
        form = auth_form(request)

    return (False, form)
Exemplo n.º 43
0
def activate(request, activation_key):
    """
    Activates a user's account, if their key is valid and hasn't
    expired.
    """
    from registration.models import RegistrationProfile
    activation_key = activation_key.lower()
    account = RegistrationProfile.objects.activate_user(activation_key)

    if account:
        # ** hack for logging in the user **
        # when the login form is posted, user = authenticate(username=data['username'], password=data['password'])
        # ...but we cannot authenticate without password... so we work-around authentication
        account.backend = settings.AUTHENTICATION_BACKENDS[0]
        _login(request, account)
        try:
            contact = Contact.objects.get(user=account)
            request.session[CUSTOMER_ID] = contact.id
            send_welcome_email(contact.email, contact.first_name, contact.last_name)
            signals.satchmo_registration_verified.send(contact, contact=contact)
        except Contact.DoesNotExist:
            # Treated for better compatibility with registation tests without error
            pass

    context = RequestContext(request, {
        'account': account,
        'expiration_days': config_value('SHOP', 'ACCOUNT_ACTIVATION_DAYS'),
    })
    return render_to_response('registration/activate.html',
                              context_instance=context)
Exemplo n.º 44
0
class CategoryOptions(admin.ModelAdmin):

    if config_value('SHOP', 'SHOW_SITE'):
        list_display = ('which_site', )
        list_filter = ('site__name', )
    else:
        list_display = ()

    list_display += ('name', '_parents_repr', 'is_active')
    list_display_links = ('name', )
    ordering = ['parent__id', 'ordering', 'name']
    inlines = [CategoryAttributeInline, CategoryImage_Inline]
    if get_l10n_setting('show_admin_translations'):
        inlines.append(CategoryTranslation_Inline)
    filter_horizontal = ('related_categories', 'site')
    form = CategoryAdminForm

    actions = ('mark_active', 'mark_inactive')

    def mark_active(self, request, queryset):
        queryset.update(is_active=True)
        return HttpResponseRedirect('')

    def mark_inactive(self, request, queryset):
        queryset.update(is_active=False)
        return HttpResponseRedirect('')

    def which_site(self, obj):
        return ', '.join(site.name for site in obj.site.all().order_by())

    which_site.short_description = 'Site'
Exemplo n.º 45
0
def _login(request, redirect_to, auth_form=EmailAuthenticationForm):
    """"Altered version of the default login, intended to be called by `combined_login`.

    Returns tuple:
    - success
    - redirect (success) or form (on failure)
    """
    if request.method == 'POST':
        form = auth_form(data=request.POST)
        if form.is_valid():
            # Light security check -- make sure redirect_to isn't garbage.
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = settings.LOGIN_REDIRECT_URL
            login(request, form.get_user())
            # Now that we've logged in, assign this cart to our user
            _assign_cart(request)
            if config_value('SHOP','PERSISTENT_CART'):
                _get_prev_cart(request)
            return (True, HttpResponseRedirect(redirect_to))
        else:
            log.debug(form.errors)
    else:
        form = auth_form(request)

    return (False, form)
Exemplo n.º 46
0
def display(request, cart=None, error_message='', default_view_tax=None):
    """Display the items in the cart."""

    if default_view_tax is None:
        default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX')

    if not cart:
        cart = Cart.objects.from_request(request)

    if cart.numItems > 0:
        products = [item.product for item in cart.cartitem_set.all()]
        sale = find_best_auto_discount(products)
    else:
        sale = None

    satchmo_cart_view.send(cart,
                           cart=cart,
                           request=request)

    context = {
        'cart': cart,
        'error_message': error_message,
        'default_view_tax' : default_view_tax,
        'sale' : sale,
        }
    return render(request, 'shop/cart.html', context)
Exemplo n.º 47
0
def home(request, template="shop/index.html"):
    # Display the category, its child categories, and its products.
    
    if request.method == "GET":
        currpage = request.GET.get('page', 1)
    else:
        currpage = 1
        
    featured = display_featured()
    
    count = config_value('PRODUCT','NUM_PAGINATED')
    
    paginator = Paginator(featured, count)
    
    is_paged = False
    page = None
    
    try:
        paginator.validate_number(currpage)
    except InvalidPage:
        return bad_or_missing(request, _("Invalid page number"))
            
    is_paged = paginator.num_pages > 1
    page = paginator.page(currpage)
        
    ctx = RequestContext(request, {
        'all_products_list' : page.object_list,        
        'is_paginated' : is_paged,
        'page_obj' : page,
        'paginator' : paginator
    })
    
    return render_to_response(template, context_instance=ctx)
Exemplo n.º 48
0
def add_wishlist_urls(sender, patterns=(), **kwargs):
    wishbase = r'^' + config_value('SHOP','WISHLIST_SLUG') + '/'    
    log.debug('adding wishlist urls at %s', wishbase)
    wishpatterns = patterns_fn('',
        (wishbase, include('satchmo_ext.wishlist.urls'))
    )
    patterns += wishpatterns
Exemplo n.º 49
0
    def clean(self, value):
        """
        Normalize the field according to cart normalizing rules.
        """
        cartplaces = config_value('SHOP', 'CART_PRECISION')
        roundfactor = config_value('SHOP', 'CART_ROUNDING')

        if not value or value == '':
            value = Decimal(0)

        try:
            value = round_decimal(val=value, places=cartplaces, roundfactor=roundfactor, normalize=True)
        except RoundedDecimalError:
            raise forms.ValidationError(_('%(value)s is not a valid number') % {'value' : value})

        return value
Exemplo n.º 50
0
def recent_products(request):
    """Puts the recently-viewed products in the page variables"""
    recent = request.session.get('RECENTLIST',[])
    maxrecent = config_value('PRODUCT','RECENT_MAX')
    products = Product.objects.active_by_site().filter(
        slug__in = recent[:maxrecent]).prefetch_related('productimage_set')    
    return {'recent_products' : products}
Exemplo n.º 51
0
    def _save_rename(self, instance, **kwargs):
        if hasattr(self, '_renaming') and self._renaming:
            return
        if self.auto_rename is None:
            # if we get a SettingNotSet exception (even though we've already
            # imported/loaded it), that's bad, so let it bubble up; don't try
            # to guess a default (which should be set in the default config in
            # the first place.)
            self.auto_rename = config_value('THUMBNAIL', 'RENAME_IMAGES')

        image = getattr(instance, self.attname)
        if image and self.auto_rename:
            if self.name_field:
                field = getattr(instance, self.name_field)
                image = rename_by_field(image.name, '%s-%s-%s' \
                                        % (instance.__class__.__name__,
                                           self.name,
                                           field
                                           )
                                        )
            else:
                # XXX this needs testing, maybe it can generate too long image names (max is 100)
                image = rename_by_field(image.name, '%s-%s-%s' \
                                        % (instance.__class__.__name__,
                                           self.name,
                                           instance._get_pk_val()
                                           )
                                        )
            setattr(instance, self.attname, image)
            self._renaming = True
            # Remove current cached thumbnails as a new image will be used
            self._delete_thumbnail(self, instance, delete_file=False)
            instance.save()
            self._renaming = False
Exemplo n.º 52
0
def view_user_data_listener(contact=None, contact_dict=None, **kwargs):
    module = config_value('NEWSLETTER', 'MODULE')
    if module not in ('', 'satchmo_ext.newsletter.ignore'):
        contact_dict['show_newsletter'] = True
        contact_dict['newsletter'] = is_subscribed(contact)
    else:
        contact_dict['show_newsletter'] = False
Exemplo n.º 53
0
def register(request,
             redirect=None,
             template='registration/registration_form.html'):
    """
    Allows a new user to register an account.
    """

    ret = register_handle_form(request, redirect)
    success = ret[0]
    todo = ret[1]
    if len(ret) > 2:
        extra_context = ret[2]
    else:
        extra_context = {}

    if success:
        return todo
    else:
        if config_get_group('NEWSLETTER'):
            show_newsletter = True
        else:
            show_newsletter = False

        ctx = {
            'form': todo,
            'title': _('Registration Form'),
            'show_newsletter': show_newsletter,
            'allow_nickname': config_value('SHOP', 'ALLOW_NICKNAME_USERNAME')
        }

        if extra_context:
            ctx.update(extra_context)

        return render(request, template, ctx)
Exemplo n.º 54
0
def get_newsletter_module():
    try:
        modulename = config_value('NEWSLETTER', 'MODULE')
    except AttributeError:
        modulename = 'satchmo_ext.newsletter.ignore'

    return load_module(modulename)
Exemplo n.º 55
0
def recent_products(request):
    """Puts the recently-viewed products in the page variables"""
    recent = request.session.get('RECENTLIST', [])
    maxrecent = config_value('PRODUCT', 'RECENT_MAX')
    products = Product.objects.active_by_site().filter(
        slug__in=recent[:maxrecent]).prefetch_related('productimage_set')
    return {'recent_products': products}
Exemplo n.º 56
0
def shipping_methods():
    methods = []
    modules = config_value('SHIPPING', 'MODULES')
    log.debug('Getting shipping methods: %s', modules)
    for m in modules:
        module = load_module(".".join([m, 'methods']))
        methods.extend(module.get_methods())
    return methods
Exemplo n.º 57
0
def upload_dir(instance, filename):
    raw = "images/"

    try:
        raw = config_value('PRODUCT', 'IMAGE_DIR')
    except SettingNotSet:
        pass
    except ImportError, e:
        log.warn("Error getting upload_dir, OK if you are in SyncDB.")
Exemplo n.º 58
0
    def _get_location(self):
        area=country=None
        calc_by_ship_address = bool(config_value('TAX','TAX_AREA_ADDRESS') == 'ship')
        if self.order:
            if calc_by_ship_address:
                country = self.order.ship_country
                area = self.order.ship_state
            else:
                country = self.order.bill_country
                area = self.order.bill_state
        
            if country:
                try:
                    country = Country.objects.get(iso2_code__exact=country)
                except Country.DoesNotExist:
                    log.info("Couldn't find Country from string: %s", country)
                    country = None
        
        elif self.user and self.user.is_authenticated():
            try:
                contact = Contact.objects.get(user=self.user)
                try:
                    if calc_by_ship_address:
                        area = contact.shipping_address.state
                    else:
                        area = contact.billing_address.state
                except AttributeError:
                    pass
                try:
                    if calc_by_ship_address:
                        country = contact.shipping_address.country
                    else:
                        country = contact.billing_address.country
                except AttributeError:
                    pass

            except Contact.DoesNotExist:
                pass

        if not country:
            from satchmo_store.shop.models import Config
            country = Config.objects.get_current().sales_country

        if area:
            try:
                area = AdminArea.objects.get(name__iexact=area,
                                             country=country)
            except AdminArea.DoesNotExist:
                try:
                    area = AdminArea.objects.get(abbrev__iexact=area,
                                                 country=country)
                except AdminArea.DoesNotExist:
                    log.info("Couldn't find AdminArea from string: %s", area)
                    area = None


        return area, country
Exemplo n.º 59
0
 def render(self, request, context):
     filename = self.get_filename(request, context)
     content = self.convert(self.get_content(request, context))
     response = HttpResponse(content_type=self.mimetype)
     if config_value('SHIPPING','DOWNLOAD_PDFS'):
         content_disposition = 'attachment; filename=%s' % filename
         response['Content-Disposition'] = content_disposition
     response.write(content)
     return response
Exemplo n.º 60
0
def display_bestsellers(request, count=0, template='product/best_sellers.html'):
    """Display a list of the products which have sold the most"""
    if count == 0:
        count = config_value('PRODUCT','NUM_PAGINATED')
    
    ctx = RequestContext(request, {
        'products' : bestsellers(count),
    })
    return render_to_response(template, context_instance=ctx)