Exemplo n.º 1
0
def displayDoc(request, id, doc):
    import trml2pdf
    # Create the HttpResponse object with the appropriate PDF headers for an invoice or a packing slip
    order = get_object_or_404(Order, pk=id)
    shopDetails = Config.objects.get_current()
    filename_prefix = shopDetails.site.domain
    if doc == "invoice":
        filename = "%s-invoice.pdf" % filename_prefix
        template = "invoice.rml"
    elif doc == "packingslip":
        filename = "%s-packingslip.pdf" % filename_prefix
        template = "packing-slip.rml"
    elif doc == "shippinglabel":
        filename = "%s-shippinglabel.pdf" % filename_prefix
        template = "shipping-label.rml"
    else:
        return HttpResponseRedirect('/admin')
    response = HttpResponse(mimetype='application/pdf')
    if config_value('SHIPPING','DOWNLOAD_PDFS'):
        response['Content-Disposition'] = 'attachment; filename=%s' % filename
    icon_uri = config_value('SHOP', 'LOGO_URI')
    t = loader.get_template(os.path.join('shop/pdf', template))
    c = Context({
                'filename' : filename,
                'iconURI' : icon_uri,
                'shopDetails' : shopDetails,
                'order' : order,
                'default_view_tax': config_value('TAX','DEFAULT_VIEW_TAX')
                })
    pdf = trml2pdf.parseString(smart_str(t.render(c)))
    response.write(pdf)
    return response
Exemplo n.º 2
0
Arquivo: notification.py Projeto: 34/T
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 activate(request, activation_key, template = 'registration/activate.html'):
    """
    Activates a user's account, if their key is valid and hasn't
    expired.
    """
    activation_key = activation_key.lower()
    account = AdminRegistrationProfile.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]
        contact = Contact.objects.get(user=account)
        #send_welcome_email(contact.email, contact.first_name, contact.last_name)
        # Send an email to the user if an Administrator has activated his/her account
        if config_value('SHOP', 'ACCOUNT_VERIFICATION') == "ADMINISTRATOR":
            site = Site.objects.get_current()
            profile = AdminRegistrationProfile.objects.get(user=account)
            profile.send_welcome_email(site)
            template = 'registration/administrator_activate.html'
        else:
            # Otherwise login the user as he/she is the one activating his/her account
            _login(request, account)
            request.session[CUSTOMER_ID] = contact.id

        signals.satchmo_registration_verified.send(contact, contact=contact)

    context = RequestContext(request, {
        'account': account,
        'expiration_days': config_value('SHOP', 'ACCOUNT_ACTIVATION_DAYS'),
        "page_info": _get_page_parameters(),
    })
    return render_to_response(template,
                              context_instance=context)
Exemplo n.º 4
0
Arquivo: cart.py Projeto: 34/T
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, P:
        return _product_error(request, product,
            _("Invalid quantity."))
Exemplo n.º 5
0
def check_with_akismet(comment=None, request=None, **kwargs):
    if config_value("PRODUCT", "AKISMET_ENABLE"):
        key = config_value("PRODUCT", "AKISMET_KEY")
        if key:             
            site = Site.objects.get_current()
            shop = urlresolvers.reverse('satchmo_shop_home')
            from akismet import Akismet
            akismet = Akismet(
                key=settings.AKISMET_API_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_api.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.", key)
        else:
            log.info("Akismet enabled, but no key found.  Please put in your admin settings.")
Exemplo n.º 6
0
    def send(self, timestamp = datetime.now(), send = True, headers = {}, extra_context = {}):
        """Метод для отправки дайджеста. Для всех пользователей вызывается self.get_content,
           результат отдается в self.render (можно использовать extra_context), после чего письмо отправляется.
        """
        for user in self.users:
            digest_pref = user.digestpreference_set.get(digest = self.digest)
            if timestamp - self.digest.get_last(user) < timedelta(hours=digest_pref.interval):
                continue
            qs = self.get_content(user, timestamp)
            if not qs:
                continue
            current_site = Site.objects.get_current()
            subject = _("%(prefix)sEmail digest for %(digest)s") % {
                'prefix': config_value('EmailServer', 'EMAIL_SUBJECT_PREFIX'),
                'digest': self.digest,
            }
            context = {
                'user': user,
                'from': self.digest.get_last(user),
                'till': timestamp,
                'site': current_site,
            }
            email = EmailMultiAlternatives(subject,
                                           self.render_txt(qs, context, extra_context={}),
                                           config_value('EmailServer', 'DEFAULT_FROM_EMAIL'),
                                           [user.email, ],
                                           [],
                                           headers=headers,)
            email.attach_alternative(self.render(qs, context, extra_context={}), "text/html")

            if send:
                email.send()
                journal = DigestJournal(user=user, digest=self.digest)
                journal.save()
Exemplo n.º 7
0
    def shipping(self, subtotal=None, with_details=False):
        if subtotal is None and self.order:
            subtotal = self.order.shipping_sub_total

        tax_details = {}
        if subtotal:
            full_rate = None
            taxes = []
            if config_value('TAX','TAX_SHIPPING_CANADIAN'):
                try:
                    # get the tax class used for taxing shipping
                    taxclass = TaxClass.objects.get(title=config_value('TAX', 'TAX_CLASS'))
                    full_rate, taxes = self.get_rate(taxclass=taxclass, get_object=True)
                except ObjectDoesNotExist:
                    log.error("'Shipping' TaxClass doesn't exist.")

            if full_rate:
                ship_tax = full_rate * subtotal
            else:
                ship_tax = Decimal("0.00")

            if with_details:
                for taxcode, rate in taxes:
                    if taxcode not in tax_details:
                        tax_details[taxcode] = Decimal('0.00')
                    tax_details[taxcode] += rate * subtotal
            
        else:
            ship_tax = Decimal("0.00")
        
        if with_details:
            return ship_tax, tax_details
        else:
            return ship_tax
Exemplo n.º 8
0
def map(request):
    return {
        'GOOGLE_API_KEY': getattr(settings, 'GOOGLE_API_KEY'),
        'newevent_highlight': config_value('EventsMap', 'newevent-highlight'),
        'newevent_sound': config_value('EventsMap', 'newevent-sound'),
        'wakeup_interval': config_value('EventsMap', 'operator-wake-up-alert-interval')
    }
Exemplo n.º 9
0
Arquivo: forms.py Projeto: 34/T
    def __init__(self, *args, **kwargs):
        contact = kwargs.pop('contact', None)
        self._contact = contact
        shop = kwargs.pop('shop', None)
        if not shop:
            shop = Config.objects.get_current()
        self._shop = shop
        
        super(AddressBookForm, self).__init__(*args, **kwargs)
        
        self.required_shipping_data = config_value('SHOP', 'REQUIRED_SHIPPING_DATA')
        self._local_only = shop.in_country_only
        self.enforce_state = config_value('SHOP','ENFORCE_STATE')
        
        self._default_country = shop.sales_country
        shipping_country = (self._contact and getattr(self._contact.shipping_address, 'country', None)) or self._default_country
        self.fields['country'] = forms.ModelChoiceField(shop.countries(), required=False, label=_(u'国家'), empty_label=None, initial=shipping_country.pk)
        
        if self.enforce_state:
            # Get areas for the initial country selected.
            shipping_areas = area_choices_for_country(shipping_country)

            shipping_state = (self._contact and getattr(self._contact.shipping_address, 'state', None)) or selection
            self.fields['province'] = forms.ChoiceField(choices=shipping_areas, initial=shipping_state, required=False, label=_(u'地区'))

        for f in self.fields:
            fld = self.fields[f]
            if fld.required:
                fld.label = (fld.label or f) + '*'
                
        log.info('Sending form_init signal: %s', self.__class__)
        form_init.send(self.__class__, form=self)
Exemplo n.º 10
0
Arquivo: views.py Projeto: kpx13/mznak
def get_common_context(request):
    c = {}
    
    form = OrderForm()
    if request.method == 'POST':
        form = OrderForm(request.POST)
        if form.is_valid():
            form.save(request.POST['action'])
            if request.POST['action'] == 'request':
                c['order_ok'] = True
            else: 
                c['feedback_ok'] = True
            form = OrderForm()
    c['form'] = form
    
    c['request_url'] = request.path
    c['is_debug'] = settings.DEBUG
    c['phone'] = config_value('MyApp', 'PHONE')
    ORDERS_COUNT = int(config_value('MyApp', 'ORDERS_COUNT'))
    c['oc_3'] = ORDERS_COUNT % 10
    ORDERS_COUNT = ORDERS_COUNT / 10
    c['oc_2'] = ORDERS_COUNT % 10
    c['oc_1'] = ORDERS_COUNT / 10
    c.update(csrf(request))
    return c
Exemplo n.º 11
0
def displayDoc(request, id, doc):
    import trml2pdf

    # Create the HttpResponse object with the appropriate PDF headers for an invoice or a packing slip
    order = get_object_or_404(Order, pk=id)
    shopDetails = Config.objects.get_current()
    filename_prefix = shopDetails.site.domain
    if doc == "invoice":
        filename = "%s-invoice.pdf" % filename_prefix
        template = "invoice.rml"
    elif doc == "packingslip":
        filename = "%s-packingslip.pdf" % filename_prefix
        template = "packing-slip.rml"
    elif doc == "shippinglabel":
        filename = "%s-shippinglabel.pdf" % filename_prefix
        template = "shipping-label.rml"
    else:
        return HttpResponseRedirect("/admin")
    response = HttpResponse(mimetype="application/pdf")
    if config_value("SHIPPING", "DOWNLOAD_PDFS"):
        response["Content-Disposition"] = "attachment; filename=%s" % filename
    icon_uri = config_value("SHOP", "LOGO_URI")
    t = loader.get_template(os.path.join("shop/pdf", template))
    c = Context({"filename": filename, "iconURI": icon_uri, "shopDetails": shopDetails, "order": order})
    pdf = trml2pdf.parseString(smart_str(t.render(c)))
    response.write(pdf)
    return response
Exemplo n.º 12
0
def multisuccess_view(request):
    """
    The order has been succesfully processed.  
    This can be used to generate a receipt or some other confirmation
    """
    
    target_view = None
    
    try:
        order = Order.objects.from_request(request)
    except Order.DoesNotExist:
        return bad_or_missing(request, 
            _('Your order has already been processed.'))
        
    del request.session['orderID']
    payments_completed = order.payments_completed()
    if payments_completed:
        payment_completed = payments_completed[0].payment
    else:
        payment_completed = ''
    
    shop = Config.objects.get_current()
    postal_code = shop.postal_code
    city = shop.city
    phone = shop.phone
    fax = ""
    store_email = shop.store_email
    store_name = shop.store_name
    street1 = shop.street1
    state = shop.state
    p_iva = config_value('SHOP_CONFIG','VAT')
    iban = config_value('SHOP_CONFIG','IBAN')
    
    # Cablare il campo per il rilevamento della tipologia 
    # di pagamento
    target_view = []
    if payment_completed:
        target_view.append(
            "shop/checkout/success_%s.html" % payment_completed.lower()
        )
    target_view.append("shop/checkout/success_generic.html")
    
    return render_to_response(
          target_view,
          {
              'order': order,
              'payment': payment_completed,
              'p_iva' : p_iva,
              'iban' : iban,
              'store_postal_code' : postal_code,
              'store_phone' : phone,
              'store_fax' : fax,
              'store_email' : store_email,
              'store_name' : store_name,
              'store_street1' : street1,
              'store_state' : state,
              'store_city' : city,
          },
          context_instance=RequestContext(request)
    )
Exemplo n.º 13
0
def confirm_info(request, template="shop/checkout/reward/confirm.html"):
    checkout_url = reverse('satchmo_checkout-step1')
    try:
        order = Order.objects.from_request(request)
    except Order.DoesNotExist:
        return HttpResponseRedirect(checkout_url)
    
    contact = Contact.objects.from_request(request)
    reward, created = Reward.objects.get_or_create(contact=contact)
    
    point_modifier = config_value('PAYMENT_REWARD', 'POINTS_VALUE')
    total_point_value = point_modifier * reward.points
    
    needs_total = config_value('PAYMENT_REWARD', 'REWARDS_NEED_TOTAL')
        
    if total_point_value > order.balance:
        point_value_used = order.balance
        points_used = point_value_used / point_modifier
    else:
        points_used = reward.points
        point_value_used = total_point_value
    
    controller = RewardConfirmController(request, payment_module)
    controller.templates['CONFIRM'] = template
    controller.extra_context={'points_used' : points_used, 'points_balance' : reward.points, 'needs_total':needs_total}
    controller.confirm()
    
    return controller.response
Exemplo n.º 14
0
 def __call__(self, request, id, doc):
     order = get_object_or_404(Order, pk=id)
     shopDetails = Config.objects.get_current()
     filename_prefix = shopDetails.site.domain
     converter_ = getattr(self, self.converter)
     if doc == "invoice":
         filename = "%s-invoice.pdf" % filename_prefix
         template = "invoice." + converter_.dd_extension
     elif doc == "packingslip":
         filename = "%s-packingslip.pdf" % filename_prefix
         template = "packing-slip." + converter_.dd_extension
     elif doc == "shippinglabel":
         filename = "%s-shippinglabel.pdf" % filename_prefix
         template = "shipping-label." + converter_.dd_extension
     else:
         return HttpResponseRedirect('/admin')
     icon_uri = config_value('SHOP', 'LOGO_URI')
     t = loader.get_template(os.path.join('shop/pdf', template))
     c = Context({
         'filename' : filename,
         'iconURI' : icon_uri,
         'shopDetails' : shopDetails,
         'order' : order
     })
     data = converter_(t.render(c))
     response = HttpResponse(mimetype='application/pdf')
     if config_value('SHIPPING','DOWNLOAD_PDFS'):
         response['Content-Disposition'] = 'attachment; filename=%s' % (
             filename,
         )
     response.write(data)
     return response
Exemplo n.º 15
0
Arquivo: processor.py Projeto: 34/T
    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'):
            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.º 16
0
def index(request):
    """
    Page shell for the client-side application.

    Bootstraps read-once data onto the page.
    """
    serializer = Serializer()
    cr = CategoryResource()

    categories = list(Category.objects.annotate(dataset_count=Count('datasets')))

    bundles = [cr.build_bundle(obj=c) for c in categories]
    categories_bootstrap = [cr.full_dehydrate(b) for b in bundles]

    uncategorized = Category(
        id=settings.PANDA_UNCATEGORIZED_ID,
        slug=settings.PANDA_UNCATEGORIZED_SLUG,
        name=settings.PANDA_UNCATEGORIZED_NAME)
    uncategorized.__dict__['dataset_count'] = Dataset.objects.filter(categories=None).count() 
    uncategorized_bundle = cr.full_dehydrate(cr.build_bundle(obj=uncategorized))

    categories_bootstrap.append(uncategorized_bundle)

    return render_to_response('index.html', {
        'settings': settings,
        'max_upload_size': int(config_value('MISC', 'MAX_UPLOAD_SIZE')),
        'email_enabled': int(config_value('EMAIL', 'EMAIL_ENABLED')),
        'demo_mode_enabled': int(config_value('MISC', 'DEMO_MODE_ENABLED')),
        'bootstrap_data': serializer.to_json({
            'categories': categories_bootstrap
        }),
        'moment_lang_code': settings.MOMENT_LANGUAGE_MAPPING.get(settings.LANGUAGE_CODE, None),
    })
Exemplo n.º 17
0
def send_digest(now=datetime.now()):
    from exmo2010.mail import ExmoEmail

    users = User.objects.filter(
        userprofile__notification_type=UserProfile.NOTIFICATION_DIGEST,
        is_active=True,
        email__isnull=False)

    subject = _("%(prefix)s Email digest") % {
        'prefix': config_value('EmailServer', 'EMAIL_SUBJECT_PREFIX'),
    }
    context = {
        'masked_expert_name': config_value('GlobalParameters', 'EXPERT'),
        'site': Site.objects.get_current(),
    }
    for user in users.exclude(email__exact='').select_related('userprofile'):
        profile = user.userprofile
        last_date = profile.digest_date_journal
        if not last_date:
            last_date = now - timedelta(days=profile.notification_interval)
        interval = profile.notification_interval
        if now - last_date < timedelta(hours=interval):
            continue

        if profile.is_expertA:
            score_pk = Score.objects.all()
        elif profile.is_expertB:
            score_pk = Score.objects.filter(task__user=user)
        elif profile.is_organization:
            score_pk = Score.objects.filter(task__organization__in=profile.organization.all())
        else:
            score_pk = Score.objects.none()

        comments = Comment.objects.filter(
            content_type__model='score',
            object_pk__in=score_pk.values_list('id', flat=True),
        ).order_by('submit_date')

        if last_date:
            comments = comments.filter(submit_date__gte=last_date)
        if not user.userprofile.notification_self:
            comments = comments.exclude(user=user)

        if not comments:
            continue

        context.update({
            'comments': comments,
            'from': last_date,
            'till': now,
            'user': user,
        })

        with translation.override(profile.language or settings.LANGUAGE_CODE):
            message = ExmoEmail(template_basename='mail/digest', context=context, to=[user.email], subject=subject)

        send_email.delay(message)
        profile.digest_date_journal = now
        profile.save()
Exemplo n.º 18
0
def make_urlpatterns():
    patterns = []
    for key in config_value('PAYMENT', 'MODULES'):
        cfg = config_get(key, 'MODULE')
        modulename = cfg.editor_value
        urlmodule = "%s.urls" % modulename
        patterns.append(url(config_value(key, 'URL_BASE'), [urlmodule]))    
    return tuple(patterns)
Exemplo n.º 19
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.º 20
0
def get_connection():
    return mail.get_connection(
        host=config_value('EMAIL', 'EMAIL_HOST'),
        port=config_value('EMAIL', 'EMAIL_PORT'),
        # See http://bugs.python.org/issue8489
        username=str(config_value('EMAIL', 'EMAIL_HOST_USER')),
        password=str(config_value('EMAIL', 'EMAIL_HOST_PASSWORD')),
        use_tls=config_value('EMAIL', 'EMAIL_USE_TLS')) 
Exemplo n.º 21
0
def send_digest(timestamp=datetime.now()):
    """
    Send digest.

    """
    users = User.objects.filter(userprofile__notification_type=UserProfile.NOTIFICATION_DIGEST,
                                is_active=True,
                                email__isnull=False)\
                        .exclude(email__exact='')

    current_site = Site.objects.get_current()
    expert = config_value('GlobalParameters', 'EXPERT')
    subject = _("%(prefix)s Email digest") % {
        'prefix': config_value('EmailServer', 'EMAIL_SUBJECT_PREFIX'),
    }
    for user in users:
        profile = user.userprofile
        last_date = profile.digest_date_journal
        if not last_date:
            last_date = datetime.now() - timedelta(days=profile.notification_interval)
        interval = profile.notification_interval
        if timestamp - last_date < timedelta(hours=interval):
            continue

        if profile.is_expertA or profile.is_manager_expertB:
            score_pk = Score.objects.all()
        elif profile.is_expertB:
            score_pk = Score.objects.filter(task__user=user)
        elif profile.is_organization:
            score_pk = Score.objects.filter(task__organization__in=profile.organization.all())
        else:
            score_pk = Score.objects.none()

        comments = Comment.objects.filter(
            content_type__model='score',
            object_pk__in=score_pk.values_list('id', flat=True),
        ).order_by('submit_date')

        if last_date:
            comments = comments.filter(submit_date__gte=last_date)
        if not user.userprofile.notification_self:
            comments = comments.exclude(user=user)

        if not comments:
            continue
        context = {
            'comments': comments,
            'expert': expert,
            'from': last_date,
            'site': current_site,
            'till': timestamp,
            'user': user,
        }

        send_email.delay(user.email, subject, 'digest', context=context)

        profile.digest_date_journal = datetime.now()
        profile.save()
Exemplo n.º 22
0
def add_points_on_order(order=None, **kwargs):
    log.debug("Caught order, attempting to add customer points pending.")
    rewards_enabled = config_value('PAYMENT_REWARD', 'REWARD_ENABLE')
    if order and rewards_enabled:
        if order.contact.user:
            if not RewardItem.objects.filter(order=order).filter(status=POINTS_PENDING).exists():
                #reward = Reward.objects.get_or_create(contact=order.contact)
                points = math.floor(order.sub_total * config_value('PAYMENT_REWARD', 'POINTS_EARNT') /100)
                RewardItem.objects.update_or_create(order.contact,order,points,POINTS_PENDING, _('Points from Order'))
Exemplo n.º 23
0
 def testLcrLoad(self):
     """docstring for testLcrLoad"""
     resp = '<result>\n  <row id="1">    <prefix>380</prefix>    <carrier_name>ukrtelecom</carrier_name>    <rate>0.22800</rate>    <codec></codec>    <cid></cid>    <dialstring>[lcr_carrier=ukrtelecom,lcr_rate=0.22800]sofia/external/380443615162</dialstring>  </row></result>'
     self.assertEquals(config_value("SERVER", "rcphost"), "127.0.0.1")
     self.assertEquals(config_value("SERVER", "rcpport"), "8080")
     self.assertEquals(config_value("SERVER", "rcpuser"), "freeswitch")
     self.assertEquals(config_value("SERVER", "rcppasswd"), "works")
     xml_resp = Soup(resp)
     self.assertEquals(xml_resp.row.rate.string, "0.22800")
Exemplo n.º 24
0
def claim_notification(sender, **kwargs):
    """
    Оповещение о претензиях.

    """

    claim = kwargs['claim']
    request = kwargs['request']
    creation = kwargs['creation']
    score = claim.score

    theme = _('New claim') if creation else _('Delete claim')

    subject = _('%(prefix)s%(monitoring)s - %(org)s: %(code)s - %(theme)s') % {
        'prefix': config_value('EmailServer', 'EMAIL_SUBJECT_PREFIX'),
        'monitoring': score.task.organization.monitoring,
        'org': score.task.organization.name.split(':')[0],
        'code': score.parameter.code,
        'theme': theme,
    }

    url = '%s://%s%s' % (request.is_secure() and 'https' or 'http',
                         request.get_host(),
                         reverse('exmo2010:score_view',
                                 args=[score.pk]))

    t_plain = loader.get_template('score_claim.txt')
    t_html = loader.get_template('score_claim.html')

    c = Context({'score': score,
                 'claim': claim,
                 'url': url,
                 'creation': creation,
                 'current_user': request.user.userprofile.legal_name,
                 })

    message_plain = t_plain.render(c)
    message_html = t_html.render(c)

    headers = {
        'X-iifd-exmo': 'claim_notification'
    }

    recipients = list(get_experts().values_list('email', flat=True))

    if score.task.user.email and score.task.user.email not in recipients:
        recipients.append(score.task.user.email)

    for r in recipients:
        email = EmailMultiAlternatives(subject,
                                       message_plain,
                                       config_value('EmailServer', 'DEFAULT_FROM_EMAIL'),
                                       [r],
                                       [],
                                       headers=headers,)
        email.attach_alternative(message_html, "text/html")
        email.send()
Exemplo n.º 25
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.º 26
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.º 27
0
def add_dumb_urls(sender, patterns=None, **kwargs):
    """
    Payment in satchmo is unfriendly towards us; it only adds urls for modules
    with `PAYMENT_PROCESSOR` in their model.

    (See models.py on why we don't define `PAYMENT_PROCESSOR`.)
    """
    patterns.append(
        url(r'^checkout/%s/' % config_value(config_group, 'URL_BASE'),
            include('%s.urls' % config_value(config_group, 'MODULE').__name__),)
    )
Exemplo n.º 28
0
def send_mail(subject, message, recipients):
    log = logging.getLogger('panda.utils.mail')

    if not config_value('EMAIL', 'EMAIL_ENABLED'):
        log.info('Email is disabled, not sending message to %s' % recipients)
        return

    try:
        mail.send_mail('[PANDA] %s' % subject, message, str(config_value('EMAIL', 'DEFAULT_FROM_EMAIL')), recipients, connection=get_connection())
    except socket.error:
        log.error('Failed connecting to email server. (Sending to %s.)' % recipients)
Exemplo n.º 29
0
    def test_checkout(self):
        """
        Run through a full checkout process
        """
        cache_delete()
        tax = config_get("TAX", "MODULE")
        tax.update("tax.modules.percent")
        pcnt = config_get("TAX", "PERCENT")
        pcnt.update("10")
        shp = config_get("TAX", "TAX_SHIPPING")
        shp.update(False)

        self.test_cart_adding()
        response = self.client.post(url("satchmo_checkout-step1"), get_step1_post_data(self.US))
        self.assertRedirects(response, url("DUMMY_satchmo_checkout-step2"), status_code=302, target_status_code=200)
        data = {
            "credit_type": "Visa",
            "credit_number": "4485079141095836",
            "month_expires": "1",
            "year_expires": "2014",
            "ccv": "552",
            "shipping": "FlatRate",
        }
        response = self.client.post(url("DUMMY_satchmo_checkout-step2"), data)
        self.assertRedirects(response, url("DUMMY_satchmo_checkout-step3"), status_code=302, target_status_code=200)
        response = self.client.get(url("DUMMY_satchmo_checkout-step3"))
        self.assertContains(
            response, smart_str("Shipping + %s4.00" % config_value("LANGUAGE", "CURRENCY")), count=1, status_code=200
        )
        self.assertContains(
            response, smart_str("Tax + %s4.60" % config_value("LANGUAGE", "CURRENCY")), count=1, status_code=200
        )
        self.assertContains(
            response, smart_str("Total = %s54.60" % config_value("LANGUAGE", "CURRENCY")), count=1, status_code=200
        )
        response = self.client.post(url("DUMMY_satchmo_checkout-step3"), {"process": "True"})
        self.assertRedirects(response, url("DUMMY_satchmo_checkout-success"), status_code=302, target_status_code=200)
        self.assertEqual(len(mail.outbox), 1)

        # Log in as a superuser
        user = User.objects.create_user("fredsu", "*****@*****.**", "passwd")
        user.is_staff = True
        user.is_superuser = True
        user.save()
        self.client.login(username="******", password="******")

        # Test pdf generation
        response = self.client.get("/admin/print/invoice/1/")
        self.assertContains(response, "reportlab", status_code=200)
        response = self.client.get("/admin/print/packingslip/1/")
        self.assertContains(response, "reportlab", status_code=200)
        response = self.client.get("/admin/print/shippinglabel/1/")
        self.assertContains(response, "reportlab", status_code=200)
Exemplo n.º 30
0
def display_featured():
    """
    Used by the index generic view to choose how the featured products are displayed.
    Items can be displayed randomly or all in order
    """
    random_display = config_value('PRODUCT','RANDOM_FEATURED')
    num_to_display = config_value('PRODUCT','NUM_DISPLAY')
    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.º 31
0
class OptionGroupOptions(admin.ModelAdmin):
    inlines = [Option_Inline]
    if get_l10n_setting('show_admin_translations'):
        inlines.append(OptionGroupTranslation_Inline)
    if config_value('SHOP', 'SHOW_SITE'):
        list_display = ('site', )
    else:
        list_display = ()
    list_display += ('name', )
Exemplo n.º 32
0
def discount_price(product, discount):
    """Returns the product price with the discount applied, including tax if that is the default.

    Ex: product|discount_price:sale
    """
    if config_value('TAX', 'DEFAULT_VIEW_TAX'):
        return taxed_discount_price(product, discount)
    else:
        return untaxed_discount_price(product, discount)
Exemplo n.º 33
0
def make_thumbnail(photo_url,
                   width=None,
                   height=None,
                   root=settings.MEDIA_ROOT,
                   url_root=settings.MEDIA_URL):
    """ create thumbnail """

    # one of width/height is required
    assert (width is not None) or (height is not None)

    if not photo_url: return None

    th_url = _get_thumbnail_path(photo_url, width, height)
    th_path = _get_path_from_url(th_url, root, url_root)
    photo_path = _get_path_from_url(photo_url, root, url_root)

    if _has_thumbnail(photo_url, width, height, root, url_root):
        # thumbnail already exists
        if not (os.path.getmtime(photo_path) > os.path.getmtime(th_path)):
            # if photo mtime is newer than thumbnail recreate thumbnail
            return th_url

    # make thumbnail

    # get original image size
    orig_w, orig_h = get_image_size(photo_url, root, url_root)
    if (orig_w is None) and (orig_h) is None:
        # something is wrong with image
        return photo_url

    # make proper size
    if (width is not None) and (height is not None):
        if (orig_w == width) and (orig_h == height):
            # same dimensions
            return None
        size = (width, height)
    elif width is not None:
        if orig_w == width:
            # same dimensions
            return None
        size = (width, orig_h)
    elif height is not None:
        if orig_h == height:
            # same dimensions
            return None
        size = (orig_w, height)

    try:
        img = Image.open(photo_path).copy()
        img.thumbnail(size, Image.ANTIALIAS)
        img.save(th_path, quality=config_value('THUMBNAIL', 'IMAGE_QUALITY'))
    except Exception, err:
        # this goes to webserver error log
        import sys
        print >> sys.stderr, '[MAKE THUMBNAIL] error %s for file %r' % (
            err, photo_url)
        return photo_url
Exemplo n.º 34
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.º 35
0
def category_view_kamel(request,
                        slug,
                        parent_slugs='',
                        template='product/category.html'):
    """Display the category, its child categories, and its products.

    Parameters:
     - slug: slug of category
     - parent_slugs: ignored
    """
    if request.method == "GET":
        currpage = request.GET.get('page', 1)
        town = request.GET.get('town')
    else:
        currpage = 1
        town = 'Gdansk'

    is_paged = False
    page = None

    try:
        category = Category.objects.get_by_site(slug=slug)
        products = list(category.active_products())
        sale = find_best_auto_discount(products)
        count = config_value('PRODUCT', 'NUM_PAGINATED')
        paginator = Paginator(products, count)
        try:
            paginator.validate_number(currpage)
        except EmptyPage:
            return bad_or_missing(request, _("Invalid page number"))
        is_paged = paginator.num_pages > 1
        page = paginator.page(currpage)

    except Category.DoesNotExist:
        return bad_or_missing(
            request, _('The category you have requested does not exist.'))

    child_categories = category.get_all_children()

    ctx = {
        'category': category,
        'child_categories': child_categories,
        'sale': sale,
        'town': town,
        'products': page.object_list,
        'is_paginated': is_paged,
        'page_obj': page,
        'paginator': paginator
    }
    index_prerender.send(Product,
                         request=request,
                         context=ctx,
                         category=category,
                         object_list=products)
    return render_to_response(template,
                              context_instance=RequestContext(request, ctx))
Exemplo n.º 36
0
 def cost(self):
     """
     Complex calculations can be done here as long as the return value is a dollar figure
     """
     fee = Decimal("0.00")
     rate = config_value('SHIPPING', 'PER_RATE')
     for cartitem in self.cart.cartitem_set.all():
         if cartitem.product.is_shippable:
             fee += rate * cartitem.quantity
     return fee
Exemplo n.º 37
0
def mail_comment(request, comment):
    score = comment.content_object
    monitoring = score.task.organization.monitoring
    if not monitoring.status in [MONITORING_INTERACTION, MONITORING_FINALIZING]:
        return

    users = User.objects.filter(
        userprofile__notification_type=UserProfile.NOTIFICATION_ONEBYONE,
        is_active=True,
        email__isnull=False)
    users = users.exclude(pk=comment.user.pk, userprofile__notification_self=False)

    experts = users.filter(Q(is_superuser=True) | Q(groups__name=UserProfile.expertA_group) | Q(pk=score.task.user.pk))
    experts_thread = experts.filter(userprofile__notification_thread=True)
    experts_one = experts.filter(userprofile__notification_thread=False)

    orgusers = users.filter(userprofile__organization=score.task.organization)
    orgusers_thread = orgusers.filter(userprofile__notification_thread=True)
    orgusers_one = orgusers.filter(userprofile__notification_thread=False)

    subject = u'%(prefix)s%(monitoring)s - %(org)s: %(code)s' % {
        'prefix': config_value('EmailServer', 'EMAIL_SUBJECT_PREFIX'),
        'monitoring': monitoring,
        'org': score.task.organization.name.split(':')[0],
        'code': score.parameter.code}

    context = {
        'title': '%s: %s' % (score.task.organization, score.parameter),
        'masked_expert_name': _(config_value('GlobalParameters', 'EXPERT'))}

    comment_url = request.build_absolute_uri(reverse('exmo2010:score', args=[score.pk])) + '#c%s' % comment.pk
    recommendation_url = request.build_absolute_uri(reverse('exmo2010:recommendations', args=[score.task.pk])) + \
        '#param%s' % score.parameter.pk

    # Send notifications with single comment.
    _mail_comment(experts_one, subject, dict(context, comments=[comment], url=comment_url, mask_expert_name=False))
    _mail_comment(orgusers_one, subject, dict(context, comments=[comment], url=recommendation_url, mask_expert_name=True))

    thread = CommentExmo.objects.filter(object_pk=score.pk)

    # Send notifications with whole comments thread.
    _mail_comment(experts_thread, subject, dict(context, comments=thread, url=comment_url, mask_expert_name=False))
    _mail_comment(orgusers_thread, subject, dict(context, comments=thread, url=recommendation_url, mask_expert_name=True))
Exemplo n.º 38
0
 def _decryptCC(self):
     ccnum = _decrypt_code(self.encrypted_cc)
     if not config_value('PAYMENT', 'STORE_CREDIT_NUMBERS'):
         try:
             key = _encrypt_code(ccnum + '-card')
             encrypted_ccnum = keyedcache.cache_get(key)
             ccnum = _decrypt_code(encrypted_ccnum)
         except keyedcache.NotCachedError:
             ccnum = ""
     return ccnum
Exemplo n.º 39
0
    def Encrypt(self):
        self.ErrorCode = '0'
        self.ErrorDescription = ''
        self.ToBeEncrypt = ''

        if not self.ShopLogin:
            self.ErrorCode = '546'
            self.ErrorDescription = 'IDshop not valid'
            return None

        if not self.Currency:
            self.ErrorCode = '552'
            self.ErrorDescription = 'Currency not valid'
            return None

        if not self.Amount:
            self.ErrorCode = '553'
            self.ErrorDescription = 'Amount not valid'
            return None

        if not self.ShopTransactionID:
            self.ErrorCode = '551'
            self.ErrorDescription = 'Shop Transaction ID not valid'
            return None

        self.ToEncrypt(self.CVV, 'PAY1_CVV')
        self.ToEncrypt(self.Min, 'PAY1_MIN')
        self.ToEncrypt(self.Currency, 'PAY1_UICCODE')
        self.ToEncrypt(self.Amount, 'PAY1_AMOUNT')
        self.ToEncrypt(self.ShopTransactionID, 'PAY1_SHOPTRANSACTIONID')
        self.ToEncrypt(self.CardNumber, 'PAY1_CARDNUMBER')
        self.ToEncrypt(self.ExpMonth, 'PAY1_EXPMONTH')
        self.ToEncrypt(self.ExpYear, 'PAY1_EXPYEAR')
        self.ToEncrypt(self.BuyerName, 'PAY1_CHNAME')
        self.ToEncrypt(self.BuyerEmail, 'PAY1_CHEMAIL')
        self.ToEncrypt(self.Language, 'PAY1_IDLANGUAGE')
        self.ToEncrypt(self.CustomInfo, '')

        self.ToBeEncrypt = string.replace(self.ToBeEncrypt, ' ', '§')

        uri = '%s?a=%s&b=%s' % (self.ScriptEnCrypt, self.ShopLogin,
                                self.ToBeEncrypt[len(self.separator):])

        live = config_value('PAYMENT_CREDITCARD', 'LIVE')
        if live:
            self.EncryptedString = self.HttpGetResponse(
                self.DomainName, uri, 1)
        else:
            self.EncryptedString = self.HttpGetResponse(
                self.TestDomainName, uri, 1)

        if not self.EncryptedString:
            return None

        return 1
    def process(self, order=None):
        """
        Calculate the tax and return it.
        
        Probably need to make a breakout.
        """
        if order:
            self.order = order
        else:
            order = self.order

        sub_total = Decimal('0.00')
        taxes = {}

        rates = {}
        for item in order.orderitem_set.filter(product__taxable=True):
            tc = item.product.taxClass
            if tc:
                tc_key = tc.title
            else:
                tc_key = "Default"

            if rates.has_key(tc_key):
                rate = rates[tc_key]
            else:
                rate = self.get_rate(tc, get_object=True)
                rates[tc_key] = rate
                taxes[tc_key] = Decimal("0.00")
            # XXX If this setting is true,
            # Satchmo does it wrong most of the time.
            # We MUST have tests for this!
            if config_value('TAX', 'TAX_USE_ITEMPRICE'):
                # In Europe, if there is a supplier
                # which applies discounts to products
                # you have to use full price for taxes.
                price = item.line_item_price
            else:
                # use discounted price before taxing
                price = item.sub_total

            if rate:
                t = price * rate.percentage
            else:
                t = Decimal("0.00")
            sub_total += t
            taxes[tc_key] += t

        ship = self.shipping()
        sub_total += ship
        taxes['Shipping'] = ship

        for k in taxes:
            taxes[k] = taxes[k]

        return sub_total, taxes
Exemplo n.º 41
0
def index(request):
    """
    Page shell for the client-side application.

    Bootstraps read-once data onto the page.
    """
    serializer = Serializer()
    cr = CategoryResource()

    categories = list(
        Category.objects.annotate(dataset_count=Count('datasets')))

    bundles = [cr.build_bundle(obj=c) for c in categories]
    categories_bootstrap = [cr.full_dehydrate(b) for b in bundles]

    uncategorized = Category(id=settings.PANDA_UNCATEGORIZED_ID,
                             slug=settings.PANDA_UNCATEGORIZED_SLUG,
                             name=settings.PANDA_UNCATEGORIZED_NAME)
    uncategorized.__dict__['dataset_count'] = Dataset.objects.filter(
        categories=None).count()
    uncategorized_bundle = cr.full_dehydrate(
        cr.build_bundle(obj=uncategorized))

    categories_bootstrap.append(uncategorized_bundle)

    return render_to_response(
        'index.html', {
            'settings':
            settings,
            'warn_upload_size':
            int(config_value('MISC', 'WARN_UPLOAD_SIZE')),
            'max_upload_size':
            int(config_value('MISC', 'MAX_UPLOAD_SIZE')),
            'email_enabled':
            int(config_value('EMAIL', 'EMAIL_ENABLED')),
            'demo_mode_enabled':
            int(config_value('MISC', 'DEMO_MODE_ENABLED')),
            'bootstrap_data':
            serializer.to_json({'categories': categories_bootstrap}),
            'moment_lang_code':
            settings.MOMENT_LANGUAGE_MAPPING.get(settings.LANGUAGE_CODE, None),
        })
Exemplo n.º 42
0
def recentlyviewed(recent, slug=""):
    """Build a list of recent products, skipping the current one if given."""
    if slug:
        recent = [r for r in recent if slug != r.slug]
    
    rmax = config_value('PRODUCT','RECENT_MAX')
    if len(recent) > rmax:
        recent = recent[:rmax]
    return {
        'recent_products' : recent,
    }
Exemplo n.º 43
0
 def get_shop_config(self):
     shop_config = Config.objects.get_current()
     schema = self.schema()
     config = {}
     for key in schema.keys():
         config_path, config_attribute = schema[key]
         value = config_value(*config_path)
         if not value and config_attribute is not None:
             value = getattr(shop_config, config_attribute, None)
         config[key] = value
     return config
Exemplo n.º 44
0
    def handle(self, *args, **options):  # pylint: disable=R0914
        verbosity = int(options.get('verbosity', 1))
        user = config_value('ReceiveMail', 'USERNAME')
        password = config_value('ReceiveMail', 'PASSWORD')
        server = config_value('ReceiveMail', 'SERVER')
        port = config_value('ReceiveMail', 'PORT')
        ssl = config_value('ReceiveMail', 'SSL_ENABLED')
        logger = logging.getLogger('econsensus')

        try:
            if ssl == True:
                mailbox = poplib.POP3_SSL(server, port)
            else:
                mailbox = poplib.POP3(server, port)

            mailbox.user(user)
            mailbox.pass_(password)
        except poplib.error_proto, e:
            logger.error(e)
            raise
Exemplo n.º 45
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)
Exemplo n.º 46
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.º 47
0
def gift_box(context):
    gift_category = config_value('GIFT_INFO', 'GIFT_CATEGORY')
    if gift_category:
        gifts = gift_category.active_products(include_children=True)
    else:
        gifts = []

    if gifts:
        gift = gifts[0]
    else:
        gift = None
    return {'gift': gift}
Exemplo n.º 48
0
def config_boolean(option):
    """Looks up the configuration option, returning true or false."""
    args = option.split('.')
    try:
        val = config_value(*args)
    except:
        log.warn('config_boolean tag: Tried to look up config setting "%s", got SettingNotSet, returning False', option)
        val = False
    if val:
        return "true"
    else:
        return ""
Exemplo n.º 49
0
def gift_certificate_processor(order):
    """ If an order has gift certificates, then we'll try to send emails to the recipients
    """
    from payment.modules.giftcertificate.models import GiftCertificate
    email_sent = False
    send_email = config_value('PAYMENT_GIFTCERTIFICATE', 'EMAIL_RECIPIENT')
    if send_email:
        gcs = GiftCertificate.objects.filter(order=order)
        for gc in gcs:
            if gc.recipient_email:
                send_gift_certificate_by_email(gc)
                email_sent = True
    return email_sent
Exemplo n.º 50
0
    def shipping(self, subtotal=None):
        if subtotal is None and self.order:
            subtotal = self.order.shipping_sub_total

        if subtotal:
            rate = None
            if config_value('TAX','TAX_SHIPPING'):
                try:
                    tc = TaxClass.objects.get(title=config_value('TAX', 'TAX_CLASS'))
                    rate = self.get_rate(taxclass=tc)
                except:
                    log.error("'Shipping' TaxClass doesn't exist.")

            if rate:
                t = rate * subtotal
            else:
                t = Decimal("0.00")
            
        else:
            t = Decimal("0.00")
        
        return t
Exemplo n.º 51
0
    def __init__(self, *args, **kwargs):
        template_basename = kwargs.pop('template_basename')
        context = Context(dict(kwargs.pop('context'), subject=kwargs['subject']))

        body_txt = loader.get_template(template_basename + '.txt').render(context)
        body_html = loader.get_template(template_basename + '.html').render(context)

        kwargs.update(
            body=body_txt,
            alternatives=[(body_html, "text/html")],
            from_email=kwargs.get('from_email', config_value('EmailServer', 'DEFAULT_FROM_EMAIL')))

        super(ExmoEmail, self).__init__(*args, **kwargs)
Exemplo n.º 52
0
def confirm_info(request, template="shop/checkout/reward/confirm.html"):
    checkout_url = reverse('satchmo_checkout-step1')
    try:
        order = Order.objects.from_request(request)
    except Order.DoesNotExist:
        return HttpResponseRedirect(checkout_url)

    contact = Contact.objects.from_request(request)
    reward, created = Reward.objects.get_or_create(contact=contact)
    if not reward.points:
        messages.error(
            request,
            "You do not have any points. Please select an alternate payment method."
        )
        return HttpResponseRedirect(checkout_url)

    point_modifier = config_value('PAYMENT_REWARD', 'POINTS_VALUE')
    total_point_value = point_modifier * reward.points

    needs_total = config_value('PAYMENT_REWARD', 'REWARDS_NEED_TOTAL')

    if total_point_value > order.balance:
        point_value_used = order.balance
        points_used = point_value_used / point_modifier
    else:
        points_used = reward.points
        point_value_used = total_point_value

    controller = RewardConfirmController(request, payment_module)
    controller.templates['CONFIRM'] = template
    controller.extra_context = {
        'points_used': points_used,
        'points_balance': reward.points,
        'needs_total': needs_total
    }
    controller.confirm()

    return controller.response
Exemplo n.º 53
0
Arquivo: cart.py Projeto: tcv1/satchmo
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, P:
        return _product_error(request, product, _("Invalid quantity."))
Exemplo n.º 54
0
def _get_maillist(listname):
    try:
        if not listname:
            listname = config_value('NEWSLETTER', 'NEWSLETTER_NAME')

        if listname == "":
            log.warn("NEWSLETTER_NAME not set in store settings")
            raise NameError('No NEWSLETTER_NAME in settings')

        return MailList.MailList(listname, lock=0), listname

    except Errors.MMUnknownListError:
        print >> sys.stderr, "Can't find the MailMan newsletter: %s" % listname
        raise NameError('No such newsletter, "%s"' % listname)
Exemplo n.º 55
0
def _get_prev_cart(request):
    try:
        contact = Contact.objects.from_request(request)
        saved_cart = contact.cart_set.latest('date_time_created')
        # If the latest cart has len == 0, cart is unusable.
        if len(saved_cart) and 'cart' in request.session:
            existing_cart = Cart.objects.from_request(request, create=False)
            if ((len(existing_cart) == 0)
                    or config_value('SHOP', 'PERSISTENT_CART_MERGE')):
                # Merge the two carts together
                saved_cart.merge_carts(existing_cart)
                request.session['cart'] = saved_cart.id
    except Exception, e:
        pass
Exemplo n.º 56
0
def account_balance(context):
    """docstring for accaut_balance"""
    request = context['request']
    try:
        contact = Contact.objects.from_request(request, create=False)
        balance = Balance.objects.get(accountcode=contact)
    except Contact.DoesNotExist:
        contact = None
        balance = None
    return {
        'contact': contact,
        'balance': balance,
        'c': config_value('LANGUAGE', 'CURRENCY')
    }
Exemplo n.º 57
0
def add_points_on_complete(order):
    try:
        item = RewardItem.objects.get(order=order)
    except RewardItem.DoesNotExist:
        points = math.floor(
            order.total * config_value('PAYMENT_REWARD', 'POINTS_EARNT') / 100)
        description = _('Points earned from Order #%s' % order.id)
        item = RewardItem.objects.update_or_create(order.contact, order,
                                                   points, POINTS_ADDED,
                                                   description)
    except Execption, err:
        log.debug("Can't change status of points")
        log.debug(traceback.format_exc())
        return
Exemplo n.º 58
0
def mail_feedback(request, sender_email, body):
    # Send email back to author
    send_email.delay(ExmoEmail(
        template_basename='mail/feedback_creator',
        context={'comment': body},
        subject=_("Feedback"),
        to=[sender_email]))

    # Send email to support staff
    send_email.delay(ExmoEmail(
        template_basename='mail/feedback_recipient',
        context=dict(comment=body, email=sender_email, user=request.user),
        subject=_("Feedback"),
        to=[config_value('EmailServer', 'DEFAULT_SUPPORT_EMAIL')]))
Exemplo n.º 59
0
def mail_contacts_frontpage(formdata):
    # Send email back to author
    send_email.delay(ExmoEmail(
        template_basename='mail/contacts_creator',
        context=formdata,
        subject=_("Infometer communication"),
        to=[formdata["email"]]))

    # Send email to support staff
    send_email.delay(ExmoEmail(
        template_basename='mail/contacts_recipient',
        context=formdata,
        subject=_("Infometer communication"),
        to=[config_value('EmailServer', 'DEFAULT_SUPPORT_EMAIL')]))
Exemplo n.º 60
0
 def __init__(self, request, payment_module, extra_context={}):
     self.request = request
     self.paymentModule = payment_module
     if payment_module:
         processor_module = payment_module.MODULE.load_module('processor')
         self.processor = processor_module.PaymentProcessor(self.paymentModule)
     else:
         self.processor = None
     self.viewTax = config_value('TAX', 'DEFAULT_VIEW_TAX')
     self.order = None
     self.cart = None
     self.extra_context = extra_context
     self.no_stock_checkout = config_value('PRODUCT','NO_STOCK_CHECKOUT')        
     #to override the form_handler, set this
     #otherwise it will use the built-in `_onForm`
     self.onForm = self._onForm
     
     #to override the success method, set this
     #othewise it will use the built-in `_onSuccess`
     self.onSuccess = self._onSuccess
     
     #false on any "can not continue" error
     self.valid = False
     
     #the value to be returned from the view
     #an HttpResponse or a HttpRedirect
     self.response = None
     
     self.processorMessage = ""
     self.processorReasonCode = ""
     self.processorResults = None
     
     self.templates = {
         'CONFIRM' : 'shop/checkout/confirm.html',
         'EMPTY_CART': 'shop/checkout/empty_cart.html',
         '404': 'shop/404.html',
         }