Beispiel #1
0
def update(request):
    """Update contact info"""

    init_data = {}
    areas, countries, only_country = get_area_country_options(request)

    contact = Contact.from_request(request, create=False)

    if request.POST:
        new_data = request.POST.copy()
        form = ExtendedContactInfoForm(countries, areas, new_data,
            initial=init_data)

        if form.is_valid():
            if contact is None and request.user:
                contact = Contact(user=request.user)
            custID = form.save(contact=contact)
            request.session['custID'] = custID
            url = urlresolvers.reverse('satchmo_account_info')
            return http.HttpResponseRedirect(url)
        else:
            if config_get_group('NEWSLETTER'):
                show_newsletter = True
            else:
                show_newsletter = False

    else:
        if contact:
            #If a person has their contact info, make sure we populate it in the form
            for item in contact.__dict__.keys():
                init_data[item] = getattr(contact,item)
            if contact.shipping_address:
                for item in contact.shipping_address.__dict__.keys():
                    init_data["ship_"+item] = getattr(contact.shipping_address,item)
            if contact.billing_address:
                for item in contact.billing_address.__dict__.keys():
                    init_data[item] = getattr(contact.billing_address,item)
            if contact.primary_phone:
                init_data['phone'] = contact.primary_phone.phone
            
        show_newsletter = False
        current_subscriber = False
        if config_get_group('NEWSLETTER'):
            show_newsletter = True
            if contact:
                from satchmo.newsletter import is_subscribed
                current_subscriber = is_subscribed(contact)

        init_data['newsletter'] = current_subscriber
            
        form = ExtendedContactInfoForm(countries, areas, initial=init_data)

    context = RequestContext(request, {
        'form': form,
        'country': only_country,
        'show_newsletter': show_newsletter})
    return render_to_response('contact/update_form.html', context)
Beispiel #2
0
    def inner_func(request):
        class Collection:
            pass

        checkout_data = Collection()
        payment_module = config_get_group('PAYMENT_BANKPASSWEB')
        checkout_data.payment_module = payment_module
        checkout_data.processor = processing_module.PaymentProcessor(
            payment_module)

        # Are we really processing an order?
        try:
            order = Order.objects.from_request(request)
        except Order.DoesNotExist:
            url = lookup_url(payment_module, 'satchmo_checkout-step1')
            return HttpResponseRedirect(url)

        # Does our order have items in its cart?
        tempCart = Cart.objects.from_request(request)
        if tempCart.numItems == 0:
            template = lookup_template(payment_module,
                                       'checkout/empty_cart.html')
            return render_to_response(template, RequestContext(request))

        # Is our order still valid?
        if not order.validate(request):
            context = RequestContext(
                request, {'message': _('Your order is no longer valid.')})
            return render_to_response('shop_404.html', context)

        # Finally call the view
        checkout_data.order = order
        checkout_data.cart = tempCart
        return func(request, checkout_data)
Beispiel #3
0
def pay_ship_info(request):
    # Check that items are in stock
    cart = Cart.objects.from_request(request)
    if cart.not_enough_stock():
        return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart"))

    return payship.credit_pay_ship_info(request, config_get_group('PAYMENT_TRUSTCOMMERCE'))
Beispiel #4
0
def google_checkout_image_url(parser, token):
    """
    Render the url for a google checkout image.

    Sample usage::

      {% google_checkout_image_url [imagesize] ['transparent'] ['disabled'] %}

    """
    args = token.split_contents()
    payment_module = config_get_group('PAYMENT_GOOGLE')
    merchid = payment_module.MERCHANT_ID
    sizes = CHECKOUT_BUTTON_SIZES.keys()

    imgsize = "MEDIUM"
    transparent = False
    disabled = False
    locale = None

    for arg in args[1:]:
        k = arg.upper()
        if k == 'TRANSPARENT':
            transparent = True
        elif k == 'DISABLED':
            disabled = True
        else:
            if k in sizes:
                imgsize = k
            else:
                raise template.TemplateSyntaxError(
                    "%r tag got an unexpected argument.  Perhaps a bad size?  Didn't know: %s"
                    % (args[0], arg))

    return GoogleCheckoutImageUrlNode(merchid, imgsize, transparent, disabled)
Beispiel #5
0
def pay_ship_info(request):
    # Check that items are in stock
    cart = Cart.objects.from_request(request)
    if cart.not_enough_stock():
        return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart"))

    return payship.simple_pay_ship_info(request, config_get_group('PAYMENT_COD'), 'checkout/cod/pay_ship.html')
def google_checkout_image_url(parser, token):
    """
    Render the url for a google checkout image.

    Sample usage::

      {% google_checkout_image_url [imagesize] ['transparent'] ['disabled'] %}

    """
    args = token.split_contents()
    payment_module = config_get_group('PAYMENT_GOOGLE')
    merchid = payment_module.MERCHANT_ID
    sizes = CHECKOUT_BUTTON_SIZES.keys()

    imgsize = "MEDIUM"
    transparent = False
    disabled = False
    locale = None

    for arg in args[1:]:
        k = arg.upper()
        if k == 'TRANSPARENT':
            transparent = True
        elif k == 'DISABLED':
            disabled = True
        else:
            if k in sizes:
                imgsize = k
            else:
                raise template.TemplateSyntaxError("%r tag got an unexpected argument.  Perhaps a bad size?  Didn't know: %s" % (args[0], arg))
                
    return GoogleCheckoutImageUrlNode(merchid, imgsize, transparent, disabled)
Beispiel #7
0
def one_step(request):
    # Check that items are in stock
    cart = Cart.objects.from_request(request)
    if cart.not_enough_stock():
        return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart"))

    payment_module = config_get_group('PAYMENT_AUTOSUCCESS')

    #First verify that the customer exists
    try:
        contact = Contact.objects.from_request(request, create=False)
    except Contact.DoesNotExist:
        url = lookup_url(payment_module, 'satchmo_checkout-step1')
        return HttpResponseRedirect(url)
    #Verify we still have items in the cart
    if cart.numItems == 0:
        template = lookup_template(payment_module, 'checkout/empty_cart.html')
        return render_to_response(template, RequestContext(request))

    # Create a new order
    newOrder = Order(contact=contact)
    pay_ship_save(newOrder, cart, contact, shipping="", discount="")

    request.session['orderID'] = newOrder.id

    newOrder.add_status(status='Pending', notes="Order successfully submitted")

    record_payment(newOrder, payment_module, amount=newOrder.balance)

    tempCart.empty()
    success = lookup_url(payment_module, 'satchmo_checkout-success')
    return HttpResponseRedirect(success)
Beispiel #8
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
        }

        if extra_context:
            ctx.update(extra_context)

        context = RequestContext(request, ctx)
        return render_to_response(template, context)
Beispiel #9
0
def pay_ship_info(request):
    # Check that items are in stock
    cart = Cart.objects.from_request(request)
    if cart.not_enough_stock():
        return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart"))

    return payship.credit_pay_ship_info(request, config_get_group('PAYMENT_AUTHORIZENET'))
Beispiel #10
0
def confirm_info(request):
    # Check that items are in stock
    cart = Cart.objects.from_request(request)
    if cart.not_enough_stock():
        return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart"))

    return confirm.credit_confirm_info(request, config_get_group('PAYMENT_CYBERSOURCE'))
Beispiel #11
0
def one_step(request):
    # Check that items are in stock
    cart = Cart.objects.from_request(request)
    if cart.not_enough_stock():
        return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart"))

    payment_module = config_get_group('PAYMENT_AUTOSUCCESS')

    #First verify that the customer exists
    try:
        contact = Contact.objects.from_request(request, create=False)
    except Contact.DoesNotExist:
        url = lookup_url(payment_module, 'satchmo_checkout-step1')
        return HttpResponseRedirect(url)
    #Verify we still have items in the cart
    if cart.numItems == 0:
        template = lookup_template(payment_module, 'checkout/empty_cart.html')
        return render_to_response(template, RequestContext(request))
            
    # Create a new order
    newOrder = Order(contact=contact)
    pay_ship_save(newOrder, cart, contact,
        shipping="", discount="")
        
    request.session['orderID'] = newOrder.id
        
    newOrder.add_status(status='Pending', notes = "Order successfully submitted")

    record_payment(newOrder, payment_module, amount=newOrder.balance)
    
    tempCart.empty()
    success = lookup_url(payment_module, 'satchmo_checkout-success')
    return HttpResponseRedirect(success)
Beispiel #12
0
	def inner_func(request):
		class Collection:
			pass
		checkout_data = Collection()
		payment_module = config_get_group('PAYMENT_BANKPASSWEB')
		checkout_data.payment_module = payment_module
		checkout_data.processor = processing_module.PaymentProcessor(payment_module)

		# Are we really processing an order?
		try:
			order = Order.objects.from_request(request)
		except Order.DoesNotExist:
			url = lookup_url(payment_module, 'satchmo_checkout-step1')
			return HttpResponseRedirect(url)

		# Does our order have items in its cart?
		tempCart = Cart.objects.from_request(request)
		if tempCart.numItems == 0:
			template = lookup_template(payment_module, 'checkout/empty_cart.html')
			return render_to_response(template, RequestContext(request))

		# Is our order still valid?
		if not order.validate(request):
			context = RequestContext(request,
				{'message': _('Your order is no longer valid.')})
			return render_to_response('shop_404.html', context)
			
		# Finally call the view
		checkout_data.order = order
		checkout_data.cart = tempCart
		return func(request, checkout_data)
Beispiel #13
0
def confirm_info(request, template='checkout/protx/confirm.html', extra_context={}):
    payment_module = config_get_group('PAYMENT_PROTX')
    controller = confirm.ConfirmController(request, payment_module)
    controller.templates['CONFIRM'] = template
    controller.extra_context = extra_context
    controller.onForm = secure3d_form_handler
    controller.confirm()
    return controller.response
Beispiel #14
0
 def cost(self):
     """
     Complex calculations can be done here as long as the return value is a decimal figure
     """
     assert(self._calculated)
     settings =  config_get_group('satchmo.shipping.modules.usps')
     if settings.HANDLING_FEE and float(str(settings.HANDLING_FEE)) > 0.0:
         self.charges = Decimal(self.charges) + Decimal(str(settings.HANDLING_FEE))
     return Decimal(str(self.charges))
Beispiel #15
0
def payment_label(value):
    """convert a payment key into its translated text"""
    
    payments = config_get("PAYMENT", "MODULES")
    for mod in payments.value:
        config = config_get_group(mod)
        if config.KEY.value == value:
            return translation.ugettext(config.LABEL)
    return value.capitalize()
Beispiel #16
0
def payment_label(value):
    """convert a payment key into its translated text"""

    payments = config_get("PAYMENT", "MODULES")
    for mod in payments.value:
        config = config_get_group(mod)
        if config.KEY.value == value:
            return translation.ugettext(unicode(config.LABEL))
    return value.capitalize()
Beispiel #17
0
def contact_info(request):
    """View which collects demographic information from customer."""

    #First verify that the cart exists and has items
    if request.session.get('cart'):
        tempCart = Cart.objects.get(id=request.session['cart'])
        if tempCart.numItems == 0:
            return render_to_response('checkout/empty_cart.html', RequestContext(request))
    else:
        return render_to_response('checkout/empty_cart.html', RequestContext(request))

    init_data = {}
    areas, countries, only_country = get_area_country_options(request)

    contact = Contact.from_request(request, create=False)

    if request.POST:
        new_data = request.POST.copy()
        if not tempCart.is_shippable:
            new_data['copy_address'] = True
        form = PaymentContactInfoForm(countries, areas, new_data,
            initial=init_data)

        if form.is_valid():
            if contact is None and request.user:
                contact = Contact(user=request.user)
            custID = form.save(contact=contact, update_newsletter=False)
            request.session['custID'] = custID
            #TODO - Create an order here and associate it with a session
            modulename = 'PAYMENT_' + new_data['paymentmethod']
            paymentmodule = config_get_group(modulename)
            url = lookup_url(paymentmodule, 'satchmo_checkout-step2')
            return http.HttpResponseRedirect(url)
    else:
        if contact:
            #If a person has their contact info, make sure we populate it in the form
            for item in contact.__dict__.keys():
                init_data[item] = getattr(contact,item)
            if contact.shipping_address:
                for item in contact.shipping_address.__dict__.keys():
                    init_data["ship_"+item] = getattr(contact.shipping_address,item)
            if contact.billing_address:
                for item in contact.billing_address.__dict__.keys():
                    init_data[item] = getattr(contact.billing_address,item)
            if contact.primary_phone:
                init_data['phone'] = contact.primary_phone.phone
        else:
            # Allow them to login from this page.
            request.session.set_test_cookie()
        form = PaymentContactInfoForm(countries, areas, initial=init_data)

    context = RequestContext(request, {
        'form': form,
        'country': only_country,
        'paymentmethod_ct': len(config_value('PAYMENT', 'MODULES'))
        })
    return render_to_response('checkout/form.html', context)
Beispiel #18
0
def one_step(request):
    payment_module = config_get_group('PAYMENT_AUTOSUCCESS')

    #First verify that the customer exists
    contact = Contact.from_request(request, create=False)
    if contact is None:
        url = lookup_url(payment_module, 'satchmo_checkout-step1')
        return http.HttpResponseRedirect(url)
    #Verify we still have items in the cart
    if request.session.get('cart', False):
        tempCart = Cart.objects.get(id=request.session['cart'])
        if tempCart.numItems == 0:
            template = lookup_template(payment_module,
                                       'checkout/empty_cart.html')
            return render_to_response(template, RequestContext(request))
    else:
        template = lookup_template(payment_module, 'checkout/empty_cart.html')
        return render_to_response(template, RequestContext(request))

    # Create a new order
    newOrder = Order(contact=contact)
    pay_ship_save(newOrder, tempCart, contact, shipping="", discount="")

    request.session['orderID'] = newOrder.id

    newOrder.add_status(status='Pending', notes="Order successfully submitted")

    orderpayment = OrderPayment(order=newOrder,
                                amount=newOrder.balance,
                                payment=payment_module.KEY.value)
    orderpayment.save()

    #Now, send a confirmation email
    if payment_module['EMAIL'].value:
        shop_config = Config.get_shop_config()
        shop_email = shop_config.store_email
        shop_name = shop_config.store_name
        t = loader.get_template('email/order_complete.txt')
        c = Context({'order': newOrder, 'shop_name': shop_name})
        subject = "Thank you for your order from %s" % shop_name

        try:
            email = orderToProcess.contact.email
            body = t.render(c)
            send_mail(subject, body, shop_email, [email], fail_silently=False)
        except SocketError, e:
            if settings.DEBUG:
                log.error('Error sending mail: %s' % e)
                log.warn(
                    'Ignoring email error, since you are running in DEBUG mode.  Email was:\nTo:%s\nSubject: %s\n---\n%s',
                    email, subject, body)
            else:
                log.fatal('Error sending mail: %s' % e)
                raise IOError(
                    'Could not send email, please check to make sure your email settings are correct, and that you are not being blocked by your ISP.'
                )
Beispiel #19
0
def pay_ship_info(request):
    # Check that items are in stock
    cart = Cart.objects.from_request(request)
    if cart.not_enough_stock():
        return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart"))

    return payship.credit_pay_ship_info(
        request,
        config_get_group('PAYMENT_PROTX'),
        template="checkout/protx/pay_ship.html")
Beispiel #20
0
 def cost(self):
     """
     Complex calculations can be done here as long as the return value is a decimal figure
     """
     assert (self._calculated)
     settings = config_get_group('satchmo.shipping.modules.usps')
     if settings.HANDLING_FEE and float(str(settings.HANDLING_FEE)) > 0.0:
         self.charges = Decimal(self.charges) + Decimal(
             str(settings.HANDLING_FEE))
     return Decimal(str(self.charges))
Beispiel #21
0
def contact_info(request):
    """View which collects demographic information from customer."""

    # First verify that the cart exists and has items
    if request.session.get("cart"):
        tempCart = Cart.objects.get(id=request.session["cart"])
        if tempCart.numItems == 0:
            return render_to_response("checkout/empty_cart.html", RequestContext(request))
    else:
        return render_to_response("checkout/empty_cart.html", RequestContext(request))

    init_data = {}
    areas, countries, only_country = get_area_country_options(request)

    contact = Contact.from_request(request, create=False)

    if request.POST:
        new_data = request.POST.copy()
        if not tempCart.is_shippable:
            new_data["copy_address"] = True
        form = PaymentContactInfoForm(countries, areas, new_data, initial=init_data)

        if form.is_valid():
            if contact is None and request.user:
                contact = Contact(user=request.user)
            custID = form.save(contact=contact, update_newsletter=False)
            request.session["custID"] = custID
            # TODO - Create an order here and associate it with a session
            modulename = "PAYMENT_" + new_data["paymentmethod"]
            paymentmodule = config_get_group(modulename)
            url = lookup_url(paymentmodule, "satchmo_checkout-step2")
            return http.HttpResponseRedirect(url)
    else:
        if contact:
            # If a person has their contact info, make sure we populate it in the form
            for item in contact.__dict__.keys():
                init_data[item] = getattr(contact, item)
            if contact.shipping_address:
                for item in contact.shipping_address.__dict__.keys():
                    init_data["ship_" + item] = getattr(contact.shipping_address, item)
            if contact.billing_address:
                for item in contact.billing_address.__dict__.keys():
                    init_data[item] = getattr(contact.billing_address, item)
            if contact.primary_phone:
                init_data["phone"] = contact.primary_phone.phone
        else:
            # Allow them to login from this page.
            request.session.set_test_cookie()
        form = PaymentContactInfoForm(countries, areas, initial=init_data)

    context = RequestContext(
        request, {"form": form, "country": only_country, "paymentmethod_ct": len(config_value("PAYMENT", "MODULES"))}
    )
    return render_to_response("checkout/form.html", context)
Beispiel #22
0
def confirm_info(request):
    # Check that items are in stock
    cart = Cart.objects.from_request(request)
    if cart.not_enough_stock():
        return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart"))

    payment_module = config_get_group('PAYMENT_GOOGLE')

    if not 'orderID' in request.session:
        url = lookup_url(payment_module, 'satchmo_checkout-step1')
        return http.HttpResponseRedirect(url)

    tempCart = Cart.objects.from_request(request)
    if tempCart.numItems == 0:
        template = lookup_template(payment_module, 'checkout/empty_cart.html')
        return render_to_response(template, RequestContext(request))

    try:
        order = Order.objects.from_request(request)

    except Order.DoesNotExist:
        order = None

    if not (order and order.validate(request)):
        context = RequestContext(
            request, {'message': _('Your order is no longer valid.')})
        return render_to_response('shop_404.html', context)

    live = payment_live(payment_module)
    gcart = GoogleCart(order, payment_module, live)
    log.debug("CART:\n%s", gcart.cart_xml)
    template = lookup_template(payment_module, 'checkout/google/confirm.html')

    if live:
        merchant_id = payment_module.MERCHANT_ID.value
        url_template = payment_module.POST_URL.value
    else:
        merchant_id = payment_module.MERCHANT_TEST_ID.value
        url_template = payment_module.POST_TEST_URL.value

    post_url = url_template % {'MERCHANT_ID': merchant_id}
    default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX')

    ctx = RequestContext(
        request, {
            'order': order,
            'post_url': post_url,
            'default_view_tax': default_view_tax,
            'google_cart': gcart.encoded_cart(),
            'google_signature': gcart.encoded_signature(),
            'PAYMENT_LIVE': live
        })

    return render_to_response(template, ctx)
def checkout_image_url(merchid, imgsize, locale, transparent=False, disabled=False):
    payment_module = config_get_group('PAYMENT_GOOGLE')
    dimensions = CHECKOUT_BUTTON_SIZES[imgsize]
    return ("%s?%s" % (
        payment_module.CHECKOUT_BUTTON_URL,
        urlencode((('merchant_id', merchid),
                  ('w', dimensions[0]),
                  ('h', dimensions[1]),
                  ('style', _truefalse(transparent, t="trans", f="white")),
                  ('variant', _truefalse(disabled, t="disabled", f="text")),
                  ('loc', locale)))))
Beispiel #24
0
    def render_template(self, template, cart=None, contact=None):
        from satchmo.shop.models import Config
        shop_details = Config.objects.get_current()
        settings = config_get_group('satchmo.shipping.modules.usps')

        if not self.is_intl:
            mail_type = CODES[self.service_type_code]
            if mail_type == 'INTL': return ''

            if mail_type == 'FIRST CLASS':
                self.api = None
            else:
                self.api = APIS[mail_type]
        else:
            mail_type = None
            self.api = None

        # calculate the weight of the entire order
        weight = Decimal('0.0')
        for item in cart.cartitem_set.all():
            if item.product.weight:
                weight += item.product.weight * item.quantity
        self.verbose_log('WEIGHT: %s' % weight)

        # I don't know why USPS made this one API different this way...
        if self.api == 'ExpressMailCommitment':
            zip_ending = 'ZIP'
        else:
            zip_ending = 'zip'

        # get the shipping country (for the international orders)
        ship_country = contact.shipping_address.country.printable_name

        configuration = {
            'userid': settings.USER_ID.value,
            'password': settings.USER_PASSWORD.value,
            'container': settings.SHIPPING_CONTAINER.value,
            'ship_type': mail_type,
            'shop_details': shop_details
        }
        c = Context({
            'config': configuration,
            'cart': cart,
            'contact': contact,
            'is_international': self.is_intl,
            'api': self.api,
            'weight': weight,
            'zip': zip_ending,
            'country': ship_country,
            'first_class_types': ['LETTER', 'FLAT', 'PARCEL']
        })
        t = loader.get_template(template)
        return t.render(c)
Beispiel #25
0
    def apply_to_order(self, order):
        """Apply up to the full amount of the balance of this cert to the order.

        Returns new balance.
        """
        amount = min(order.balance, self.balance)
        log.info('applying %s from giftcert #%i [%s] to order #%i [%s]',
                 money_format(amount), self.id, money_format(self.balance),
                 order.id, money_format(order.balance))
        config = config_get_group('PAYMENT_GIFTCERTIFICATE')
        orderpayment = record_payment(order, config, amount)
        return self.use(amount, orderpayment=orderpayment)
Beispiel #26
0
    def render_template(self, template, cart=None, contact=None):
        from satchmo.shop.models import Config
        shop_details = Config.objects.get_current()
        settings =  config_get_group('satchmo.shipping.modules.usps')

        if not self.is_intl:
            mail_type = CODES[self.service_type_code]
            if mail_type == 'INTL': return ''
        
            if mail_type == 'FIRST CLASS':
                self.api = None
            else:
                self.api = APIS[mail_type]
        else:
            mail_type = None
            self.api = None
        
        # calculate the weight of the entire order
        weight = Decimal('0.0')
        for item in cart.cartitem_set.all():
            if item.product.weight:
                weight += item.product.weight * item.quantity
        self.verbose_log('WEIGHT: %s' % weight)

        # I don't know why USPS made this one API different this way...
        if self.api == 'ExpressMailCommitment':
            zip_ending = 'ZIP'
        else:
            zip_ending = 'zip'

        # get the shipping country (for the international orders)
        ship_country = contact.shipping_address.country.printable_name

        configuration = {
            'userid': settings.USER_ID.value,
            'password': settings.USER_PASSWORD.value,
            'container': settings.SHIPPING_CONTAINER.value,
            'ship_type': mail_type,
            'shop_details': shop_details
        }
        c = Context({
                'config': configuration,
                'cart': cart,
                'contact': contact,
                'is_international': self.is_intl,
                'api': self.api,
                'weight': weight,
                'zip': zip_ending,
                'country': ship_country,
                'first_class_types': ['LETTER', 'FLAT', 'PARCEL']
        })
        t = loader.get_template(template)
        return t.render(c)
Beispiel #27
0
def confirm_secure3d(request,
                     secure3d_template='checkout/secure3d_form.html',
                     confirm_template='checkout/confirm.html',
                     extra_context={}):
    """Handles confirming an order and processing the charges when secured by secure3d.
 
    """
    # Check that items are in stock
    cart = Cart.objects.from_request(request)
    if cart.not_enough_stock():
        return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart"))

    payment_module = config_get_group('PAYMENT_PROTX')
    controller = confirm.ConfirmController(request,
                                           payment_module,
                                           extra_context=extra_context)
    controller.template['CONFIRM'] = confirm_template
    if not controller.sanity_check():
        return controller.response

    auth3d = request.session.get('3D', None)
    if not auth3d:
        controller.processorMessage = _(
            '3D Secure transaction expired. Please try again.')

    else:
        if request.method == "POST":
            returnMD = request.POST.get('MD', None)
            if not returnMD:
                template = payment_module.lookup_template(secure3d_template)
                ctx = {'order': controller.order, 'auth': auth3d}
                return render_to_response(template, ctx,
                                          RequestContext(request))

            elif returnMD == auth3d['MD']:
                pares = request.POST.get('PaRes', None)
                controller.processor.prepareData(controller.order)
                controller.processor.prepareData3d(returnMD, pares)
                if controller.process():
                    return controller.onSuccess(controller)
                else:
                    controller.processorMessage = _(
                        '3D Secure transaction was not approved by payment gateway. Please contact us.'
                    )
        else:
            template = lookup_template(payment_module, secure3d_template)
            ctx = RequestContext(request, {
                'order': controller.order,
                'auth': auth3d
            })
            return render_to_response(template, ctx)

    return secure3d_form_handler(controller)
Beispiel #28
0
def confirm_info(request):
    # Check that items are in stock
    cart = Cart.objects.from_request(request)
    if cart.not_enough_stock():
        return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart"))

    payment_module = config_get_group('PAYMENT_GOOGLE')

    if not 'orderID' in request.session:
        url = lookup_url(payment_module, 'satchmo_checkout-step1')
        return http.HttpResponseRedirect(url)

    tempCart = Cart.objects.from_request(request)
    if tempCart.numItems == 0:
        template = lookup_template(payment_module, 'checkout/empty_cart.html')
        return render_to_response(template, RequestContext(request))
            
    try:
        order = Order.objects.from_request(request)

    except Order.DoesNotExist:
        order = None

    if not (order and order.validate(request)):
        context = RequestContext(request,
            {'message': _('Your order is no longer valid.')})
        return render_to_response('shop_404.html', context)    

    live = payment_live(payment_module)
    gcart = GoogleCart(order, payment_module, live)
    log.debug("CART:\n%s", gcart.cart_xml)
    template = lookup_template(payment_module, 'checkout/google/confirm.html')

    if live:
        merchant_id = payment_module.MERCHANT_ID.value
        url_template = payment_module.POST_URL.value
    else:
        merchant_id = payment_module.MERCHANT_TEST_ID.value
        url_template = payment_module.POST_TEST_URL.value
        
    post_url =  url_template % {'MERCHANT_ID' : merchant_id}
    default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX')
    
    ctx = RequestContext(request, {
        'order': order,
        'post_url': post_url,
        'default_view_tax': default_view_tax,
        'google_cart' : gcart.encoded_cart(),
        'google_signature' : gcart.encoded_signature(),
        'PAYMENT_LIVE' : live
    })

    return render_to_response(template, ctx)
Beispiel #29
0
def one_step(request):
    payment_module = config_get_group('PAYMENT_AUTOSUCCESS')

    #First verify that the customer exists
    contact = Contact.from_request(request, create=False)
    if contact is None:
        url = lookup_url(payment_module, 'satchmo_checkout-step1')
        return http.HttpResponseRedirect(url)
    #Verify we still have items in the cart
    if request.session.get('cart', False):
        tempCart = Cart.objects.get(id=request.session['cart'])
        if tempCart.numItems == 0:
            template = lookup_template(payment_module, 'checkout/empty_cart.html')
            return render_to_response(template, RequestContext(request))
    else:
        template = lookup_template(payment_module, 'checkout/empty_cart.html')
        return render_to_response(template, RequestContext(request))

    # Create a new order
    newOrder = Order(contact=contact)
    pay_ship_save(newOrder, tempCart, contact,
        shipping="", discount="")
        
    request.session['orderID'] = newOrder.id
        
    newOrder.add_status(status='Pending', notes = "Order successfully submitted")

    orderpayment = OrderPayment(order=newOrder, amount=newOrder.balance, payment=payment_module.KEY.value)
    orderpayment.save()

    #Now, send a confirmation email
    if payment_module['EMAIL'].value:
        shop_config = Config.get_shop_config()
        shop_email = shop_config.store_email
        shop_name = shop_config.store_name
        t = loader.get_template('email/order_complete.txt')
        c = Context({'order': newOrder,
                      'shop_name': shop_name})
        subject = "Thank you for your order from %s" % shop_name
             
        try:
            email = orderToProcess.contact.email
            body = t.render(c)
            send_mail(subject, body, shop_email,
                      [email], fail_silently=False)
        except SocketError, e:
            if settings.DEBUG:
                log.error('Error sending mail: %s' % e)
                log.warn('Ignoring email error, since you are running in DEBUG mode.  Email was:\nTo:%s\nSubject: %s\n---\n%s', email, subject, body)
            else:
                log.fatal('Error sending mail: %s' % e)
                raise IOError('Could not send email, please check to make sure your email settings are correct, and that you are not being blocked by your ISP.')    
Beispiel #30
0
def confirm_info(request):
    payment_module = config_get_group('PAYMENT_GOOGLE')

    if not request.session.get('orderID'):
        url = lookup_url(payment_module, 'satchmo_checkout-step1')
        return http.HttpResponseRedirect(url)

    if request.session.get('cart'):
        tempCart = Cart.objects.get(id=request.session['cart'])
        if tempCart.numItems == 0:
            template = lookup_template(payment_module,
                                       'checkout/empty_cart.html')
            return render_to_response(template, RequestContext(request))
    else:
        template = lookup_template(payment_module, 'checkout/empty_cart.html')
        return render_to_response(template, RequestContext(request))

    order = Order.objects.get(id=request.session['orderID'])

    # Check if the order is still valid
    if not order.validate(request):
        context = RequestContext(
            request, {'message': _('Your order is no longer valid.')})
        return render_to_response('shop_404.html', context)

    live = payment_live(payment_module)
    gcart = GoogleCart(order, payment_module, live)
    log.debug("CART:\n%s", gcart.cart_xml)
    template = lookup_template(payment_module, 'checkout/google/confirm.html')

    if live:
        merchant_id = payment_module.MERCHANT_ID.value
        url_template = payment_module.POST_URL.value
    else:
        merchant_id = payment_module.MERCHANT_TEST_ID.value
        url_template = payment_module.POST_TEST_URL.value

    post_url = url_template % {'MERCHANT_ID': merchant_id}

    ctx = RequestContext(
        request, {
            'order': order,
            'post_url': post_url,
            'google_cart': gcart.encoded_cart(),
            'google_signature': gcart.encoded_signature(),
            'PAYMENT_LIVE': live
        })

    return render_to_response(template, ctx)
Beispiel #31
0
def confirm_info(request,
                 template='checkout/protx/confirm.html',
                 extra_context={}):
    # Check that items are in stock
    cart = Cart.objects.from_request(request)
    if cart.not_enough_stock():
        return HttpResponseRedirect(urlresolvers.reverse("satchmo_cart"))

    payment_module = config_get_group('PAYMENT_PROTX')
    controller = confirm.ConfirmController(request, payment_module)
    controller.templates['CONFIRM'] = template
    controller.extra_context = extra_context
    controller.onForm = secure3d_form_handler
    controller.confirm()
    return controller.response
Beispiel #32
0
    def apply_to_order(self, order):
        """Apply up to the full amount of the balance of this cert to the order.

        Returns new balance.
        """
        amount = min(order.balance, self.balance)
        log.info('applying %s from giftcert #%i [%s] to order #%i [%s]', 
            money_format(amount), 
            self.id, 
            money_format(self.balance), 
            order.id, 
            money_format(order.balance))
        config = config_get_group('PAYMENT_GIFTCERTIFICATE')
        orderpayment = record_payment(order, config, amount)
        return self.use(amount, orderpayment=orderpayment)
Beispiel #33
0
def checkout_image_url(merchid,
                       imgsize,
                       locale,
                       transparent=False,
                       disabled=False):
    payment_module = config_get_group('PAYMENT_GOOGLE')
    dimensions = CHECKOUT_BUTTON_SIZES[imgsize]
    return ("%s?%s" %
            (payment_module.CHECKOUT_BUTTON_URL,
             urlencode(
                 (('merchant_id', merchid), ('w', dimensions[0]),
                  ('h', dimensions[1]),
                  ('style', _truefalse(transparent, t="trans", f="white")),
                  ('variant', _truefalse(disabled, t="disabled", f="text")),
                  ('loc', locale)))))
Beispiel #34
0
def confirm_info(request):
    payment_module = config_get_group('PAYMENT_PAYPAL')

    if not request.session.get('orderID'):
        url = lookup_url(payment_module, 'satchmo_checkout-step1')
        return HttpResponseRedirect(url)

    if request.session.get('cart'):
        tempCart = Cart.objects.get(id=request.session['cart'])
        if tempCart.numItems == 0:
            template = lookup_template(payment_module, 'checkout/empty_cart.html')
            return render_to_response(template, RequestContext(request))
    else:
        template = lookup_template(payment_module, 'checkout/empty_cart.html')
        return render_to_response(template, RequestContext(request))

    order = Order.objects.get(id=request.session['orderID'])

    # Check if the order is still valid
    if not order.validate(request):
        context = RequestContext(request,
            {'message': _('Your order is no longer valid.')})
        return render_to_response('shop_404.html', context)

    template = lookup_template(payment_module, 'checkout/paypal/confirm.html')
    if payment_module.LIVE.value:
        log.debug("live order on %s", payment_module.KEY.value)
        url = payment_module.POST_URL.value
        account = payment_module.BUSINESS.value
    else:
        url = payment_module.POST_TEST_URL.value
        account = payment_module.BUSINESS_TEST.value
        
    try:
        address = lookup_url(payment_module, payment_module.RETURN_ADDRESS.value, include_server=True)
    except urlresolvers.NoReverseMatch:
        address = payment_module.RETURN_ADDRESS.value
        
    ctx = RequestContext(request, {'order': order,
     'post_url': url,
     'business': account,
     'currency_code': payment_module.CURRENCY_CODE.value,
     'return_address': address,
     'PAYMENT_LIVE' : payment_live(payment_module)
    })

    return render_to_response(template, ctx)
Beispiel #35
0
def confirm_info(request):
    payment_module = config_get_group('PAYMENT_GOOGLE')

    if not request.session.get('orderID'):
        url = lookup_url(payment_module, 'satchmo_checkout-step1')
        return http.HttpResponseRedirect(url)

    if request.session.get('cart'):
        tempCart = Cart.objects.get(id=request.session['cart'])
        if tempCart.numItems == 0:
            template = lookup_template(payment_module, 'checkout/empty_cart.html')
            return render_to_response(template, RequestContext(request))
    else:
        template = lookup_template(payment_module, 'checkout/empty_cart.html')
        return render_to_response(template, RequestContext(request))

    order = Order.objects.get(id=request.session['orderID'])

    # Check if the order is still valid
    if not order.validate(request):
        context = RequestContext(request,
            {'message': _('Your order is no longer valid.')})
        return render_to_response('shop_404.html', context)

    live = payment_live(payment_module)
    gcart = GoogleCart(order, payment_module, live)
    log.debug("CART:\n%s", gcart.cart_xml)
    template = lookup_template(payment_module, 'checkout/google/confirm.html')

    if live:
        merchant_id = payment_module.MERCHANT_ID.value
        url_template = payment_module.POST_URL.value
    else:
        merchant_id = payment_module.MERCHANT_TEST_ID.value
        url_template = payment_module.POST_TEST_URL.value
        
    post_url =  url_template % {'MERCHANT_ID' : merchant_id}

    ctx = RequestContext(request, {
        'order': order,
        'post_url': post_url,
        'google_cart' : gcart.encoded_cart(),
        'google_signature' : gcart.encoded_signature(),
        'PAYMENT_LIVE' : live
    })

    return render_to_response(template, ctx)
Beispiel #36
0
def register(request, redirect=None, template='registration/registration_form.html'):
    """
    Allows a new user to register an account.
    """

    success, todo = register_handle_form(request, redirect=redirect)
    if success:
        return todo
    else:
        if config_get_group('NEWSLETTER'):
            show_newsletter = True
        else:
            show_newsletter = False
                
        context = RequestContext(request, {
            'form': todo, 
            'title' : _('Registration Form'),
            'show_newsletter' : show_newsletter
            })
        return render_to_response(template, context)
Beispiel #37
0
def config_tax():
    TAX_MODULE = config_get('TAX', 'MODULE')
    TAX_MODULE.add_choice(('satchmo.tax.modules.area', _('By Country/Area')))
    TAX_GROUP = config_get_group('TAX')

    _tax_classes = []
    ship_default = ""

    try:
        for tax in TaxClass.objects.all():
            _tax_classes.append((tax.title, tax))
            if "ship" in tax.title.lower():
                ship_default = tax.title
    except:
        log.warn("Ignoring database error retrieving tax classes - OK if you are in syncdb.")

    if ship_default == "" and len(_tax_classes) > 0:
        ship_default = _tax_classes[0][0]

    config_register(
        BooleanValue(
            TAX_GROUP,
            'TAX_SHIPPING',
            description=_("Tax Shipping?"),
            requires=TAX_MODULE,
            requiresvalue='satchmo.tax.modules.area',
            default=False
        )
    )

    config_register(
        StringValue(
            TAX_GROUP,
            'TAX_CLASS',
            description=_("TaxClass for shipping"),
            help_text=_("Select a TaxClass that should be applied for shipments."),
            default=ship_default,
            choices=_tax_classes
        )
    )
def confirm_info(request):
    """Shows the user its order details and ask confirmation to send to the real payment function"""
    
    payment_module = config_get_group('PAYMENT_PAYPAL_EXPRESS')

    try:
        order = Order.objects.from_request(request)
    except Order.DoesNotExist:
        url = lookup_url(payment_module, 'satchmo_checkout-step1')
        return HttpResponseRedirect(url)

    tempCart = Cart.objects.from_request(request)
    if tempCart.numItems == 0:
        template = lookup_template(payment_module, 'checkout/empty_cart.html')
        return render_to_response(template, RequestContext(request))

    # Check if the order is still valid
    if not order.validate(request):
        context = RequestContext(request,
            {'message': _('Your order is no longer valid.')})
        return render_to_response('shop_404.html', context)

    template = lookup_template(payment_module, 'checkout/paypal_express/confirm.html')

        
    create_pending_payment(order, payment_module)
    default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX') 
  
    recurring = None
    order_items = order.orderitem_set.all()
  
    ctx = RequestContext(request, {'order': order,
     'post_url': urlresolvers.reverse("PAYPAL_EXPRESS_satchmo_checkout-step4"),
     'default_view_tax': default_view_tax, 
     'currency_code': payment_module.CURRENCY_CODE.value,
     'invoice': order.id,

    })

    return render_to_response(template, ctx)
Beispiel #39
0
def confirm_secure3d(request, secure3d_template='checkout/secure3d_form.html', 
    confirm_template='checkout/confirm.html', extra_context={}):
    """Handles confirming an order and processing the charges when secured by secure3d.
 
    """
    payment_module = config_get_group('PAYMENT_PROTX')
    controller = confirm.ConfirmController(request, payment_module, extra_context=extra_context)
    controller.template['CONFIRM'] = confirm_template
    if not controller.sanity_check():
        return controller.response
    
    auth3d = request.session.get('3D', None)
    if not auth3d:
        controller.processorMessage = _('3D Secure transaction expired. Please try again.')

    else:
        if request.method == "POST":
            returnMD = request.POST.get('MD', None)
            if not returnMD:
                template = payment_module.lookup_template(secure3d_template)
                ctx ={'order': controller.order, 'auth': auth3d }
                return render_to_response(template, ctx, RequestContext(request))
            
            elif returnMD == auth3d['MD']:
                pares = request.POST.get('PaRes', None)
                controller.processor.prepareData(controller.order)
                controller.processor.prepareData3d(returnMD, pares)
                if controller.process():
                    return controller.onSuccess(controller)
                else:
                    controller.processorMessage = _('3D Secure transaction was not approved by payment gateway. Please contact us.')
        else:
            template = lookup_template(payment_module, secure3d_template)
            ctx =RequestContext(request, {
                'order': controller.order, 'auth': auth3d 
                })
            return render_to_response(template, ctx)                
                    
    return secure3d_form_handler(controller)
Beispiel #40
0
def view(request):
    """View contact info."""
    try:
        user_data = Contact.objects.get(user=request.user.id)
    except Contact.DoesNotExist:
        user_data = None

    show_newsletter = False
    newsletter = False

    if config_get_group('NEWSLETTER'):
        show_newsletter = True
        from satchmo.newsletter import is_subscribed
        if user_data:
            newsletter = is_subscribed(user_data)
        
    context = RequestContext(request, {
        'user_data': user_data, 
        'show_newsletter' : show_newsletter, 
        'newsletter' : newsletter })
    
    return render_to_response('contact/view_profile.html', context)
Beispiel #41
0
def balance_remaining(request):
    """Allow the user to pay the remaining balance."""
    order = None
    orderid = request.session.get('orderID')
    if orderid:
        try:
            order = Order.objects.get(pk=orderid)
        except Order.DoesNotExist:
            # TODO: verify user against current user
            pass

    if not order:
        url = urlresolvers.reverse('satchmo_checkout-step1')
        return HttpResponseRedirect(url)

    if request.method == "POST":
        new_data = request.POST.copy()
        form = PaymentMethodForm(new_data, order=order)
        if form.is_valid():
            data = form.cleaned_data
            modulename = data['paymentmethod']
            if not modulename.startswith('PAYMENT_'):
                modulename = 'PAYMENT_' + modulename

            paymentmodule = config_get_group(modulename)
            url = lookup_url(paymentmodule, 'satchmo_checkout-step2')
            return HttpResponseRedirect(url)

    else:
        form = PaymentMethodForm(order=order)

    ctx = RequestContext(
        request, {
            'form': form,
            'order': order,
            'paymentmethod_ct': len(config_value('PAYMENT', 'MODULES'))
        })
    return render_to_response('checkout/balance_remaining.html', ctx)
Beispiel #42
0
def config_tax():
    TAX_MODULE = config_get('TAX', 'MODULE')
    TAX_MODULE.add_choice(('satchmo.tax.modules.area', _('By Country/Area')))
    TAX_GROUP = config_get_group('TAX')

    _tax_classes = []
    ship_default = ""

    try:
        for tax in TaxClass.objects.all():
            _tax_classes.append((tax.title, tax))
            if "ship" in tax.title.lower():
                ship_default = tax.title
    except:
        log.warn(
            "Ignoring database error retrieving tax classes - OK if you are in syncdb."
        )

    if ship_default == "" and len(_tax_classes) > 0:
        ship_default = _tax_classes[0][0]

    config_register(
        BooleanValue(TAX_GROUP,
                     'TAX_SHIPPING',
                     description=_("Tax Shipping?"),
                     requires=TAX_MODULE,
                     requiresvalue='satchmo.tax.modules.area',
                     default=False))

    config_register(
        StringValue(
            TAX_GROUP,
            'TAX_CLASS',
            description=_("TaxClass for shipping"),
            help_text=_(
                "Select a TaxClass that should be applied for shipments."),
            default=ship_default,
            choices=_tax_classes))
Beispiel #43
0
def register(request,
             redirect=None,
             template='registration/registration_form.html'):
    """
    Allows a new user to register an account.
    """

    success, todo = register_handle_form(request, redirect=redirect)
    if success:
        return todo
    else:
        if config_get_group('NEWSLETTER'):
            show_newsletter = True
        else:
            show_newsletter = False

        context = RequestContext(
            request, {
                'form': todo,
                'title': _('Registration Form'),
                'show_newsletter': show_newsletter
            })
        return render_to_response(template, context)
Beispiel #44
0
def balance_remaining(request):
    """Allow the user to pay the remaining balance."""
    order = None
    orderid = request.session.get('orderID')
    if orderid:
        try:
            order = Order.objects.get(pk=orderid)
        except Order.DoesNotExist:
            # TODO: verify user against current user
            pass

    if not order:
        url = urlresolvers.reverse('satchmo_checkout-step1')
        return HttpResponseRedirect(url)

    if request.method == "POST":
        new_data = request.POST.copy()
        form = PaymentMethodForm(new_data, order=order)
        if form.is_valid():
            data = form.cleaned_data
            modulename = data['paymentmethod']
            if not modulename.startswith('PAYMENT_'):
                modulename = 'PAYMENT_' + modulename

            paymentmodule = config_get_group(modulename)
            url = lookup_url(paymentmodule, 'satchmo_checkout-step2')
            return HttpResponseRedirect(url)

    else:
        form = PaymentMethodForm(order=order)

    ctx = RequestContext(request, {
        'form': form,
        'order': order,
        'paymentmethod_ct': len(config_value('PAYMENT', 'MODULES'))
    })
    return render_to_response('checkout/balance_remaining.html', ctx)
Beispiel #45
0
from django.conf.urls.defaults import *
from satchmo.configuration import config_value, config_get_group

config = config_get_group('PAYMENT_DUMMY')

urlpatterns = patterns(
    'satchmo',
    (r'^$', 'payment.modules.dummy.views.pay_ship_info', {
        'SSL': config.SSL.value
    }, 'DUMMY_satchmo_checkout-step2'),
    (r'^confirm/$', 'payment.modules.dummy.views.confirm_info', {
        'SSL': config.SSL.value
    }, 'DUMMY_satchmo_checkout-step3'),
    (r'^success/$', 'payment.common.views.checkout.success', {
        'SSL': config.SSL.value
    }, 'DUMMY_satchmo_checkout-success'),
)
Beispiel #46
0
from django.conf.urls.defaults import *
from satchmo.configuration import config_value, config_get_group

config = config_get_group('PAYMENT_AUTHORIZENET')

urlpatterns = patterns('satchmo',
     (r'^$', 'payment.modules.authorizenet.views.pay_ship_info', {'SSL':config.SSL.value}, 'AUTHORIZENET_satchmo_checkout-step2'),
     (r'^confirm/$', 'payment.modules.authorizenet.views.confirm_info', {'SSL':config.SSL.value}, 'AUTHORIZENET_satchmo_checkout-step3'),
     (r'^success/$', 'payment.common.views.checkout.success', {'SSL':config.SSL.value}, 'AUTHORIZENET_satchmo_checkout-success'),
)
Beispiel #47
0
    sampleOrder = testOrder()
    sampleOrder.contact.first_name = 'Dan'
    sampleOrder.contact.last_name = 'Lim'
    sampleOrder.contact.primary_phone = '212-353-1713'
    sampleOrder.full_bill_street = '130 West 25th St'
    sampleOrder.bill_postal_code = '10001'
    sampleOrder.bill_state = 'NY'
    sampleOrder.bill_city = 'New York'
    sampleOrder.bill_country = 'US'
    sampleOrder.total = "1.05"
    sampleOrder.balance = "1.05"
    sampleOrder.credit_card.decryptedCC = '376750290511001'
    sampleOrder.credit_card.expirationDate = "06/10"
    sampleOrder.credit_card.ccv = "9207"
    #this needed to be added -Pete
    sampleOrder.paid_in_full = False 
    sampleOrder.credit_card.display_cc = sampleOrder.credit_card.decryptedCC
    sampleOrder.id = 5


    authorize_settings = config_get_group('PAYMENT_AUTHORIZENET')
    if authorize_settings.LIVE.value:
        print "Warning.  You are submitting a live order.  AUTHORIZE.NET system is set LIVE."
        
    processor = PaymentProcessor(authorize_settings)
    processor.prepareData(sampleOrder)
    results, reason_code, msg = processor.process(testing=True)
    print results,"::", msg


Beispiel #48
0
    def save(self, contact=None, update_newsletter=True):
        """Save the contact info into the database.
        Checks to see if contact exists. If not, creates a contact
        and copies in the address and phone number."""

        if not contact:
            customer = Contact()
        else:
            customer = contact

        data = self.cleaned_data

        for field in customer.__dict__.keys():
            try:
                setattr(customer, field, data[field])
            except KeyError:
                pass

        if update_newsletter and config_get_group('NEWSLETTER'):
            from satchmo.newsletter import update_subscription
            if 'newsletter' not in data:
                subscribed = False
            else:
                subscribed = data['newsletter']
            
            update_subscription(contact, subscribed)

        if not customer.role:
            customer.role = "Customer"

        customer.save()
        
        # we need to make sure we don't blindly add new addresses
        # this isn't ideal, but until we have a way to manage addresses
        # this will force just the two addresses, shipping and billing
        # TODO: add address management like Amazon.
        
        bill_address = customer.billing_address
        if not bill_address:
            bill_address = AddressBook(contact=customer)
                
        address_keys = bill_address.__dict__.keys()
        for field in address_keys:
            try:
                setattr(bill_address, field, data[field])
            except KeyError:
                pass

        bill_address.is_default_billing = True
        
        copy_address = data['copy_address']

        ship_address = customer.shipping_address
        
        if copy_address:
            # make sure we don't have any other default shipping address
            if ship_address and ship_address.id != bill_address.id:
                ship_address.delete()
            bill_address.is_default_shipping = True

        bill_address.save()
        
        if not copy_address:
            if not ship_address or ship_address.id == bill_address.id:
                ship_address = AddressBook()
            
            for field in address_keys:
                try:
                    setattr(ship_address, field, data['ship_' + field])
                except KeyError:
                    pass
            ship_address.is_default_shipping = True
            ship_address.is_default_billing = False
            ship_address.contact = customer
            ship_address.country = bill_address.country
            ship_address.save()
            
        if not customer.primary_phone:
            phone = PhoneNumber()
            phone.primary = True
        else:
            phone = customer.primary_phone
        phone.phone = data['phone']
        phone.contact = customer
        phone.save()
        
        return customer.id
Beispiel #49
0
from django.conf.urls import patterns, url
from satchmo.configuration import config_get_group, config_get, config_value

import logging
log = logging.getLogger(__name__)

config = config_get_group('PAYMENT')

urlpatterns = patterns(
    'satchmo.payment.views',
    (r'^$', 'contact.contact_info_view', {}, 'satchmo_checkout-step1'),
    (r'custom/charge/(?P<orderitem_id>\d+)/$', 'balance.charge_remaining', {},
     'satchmo_charge_remaining'),
    (r'custom/charge/$', 'balance.charge_remaining_post', {},
     'satchmo_charge_remaining_post'),
    (r'^balance/(?P<order_id>\d+)/$', 'balance.balance_remaining_order', {},
     'satchmo_balance_remaining_order'),
    (r'^balance/$', 'balance.balance_remaining', {},
     'satchmo_balance_remaining'),
    (r'^cron/$', 'cron.cron_rebill', {}, 'satchmo_cron_rebill'),
    (r'^mustlogin/$', 'contact.authentication_required', {},
     'satchmo_checkout_auth_required'),
)


# Now add all enabled module payment settings
def make_urlpatterns():
    patterns = []
    for key in config_value('PAYMENT', 'MODULES'):
        cfg = config_get(key, 'MODULE')
        modulename = cfg.editor_value
Beispiel #50
0
from django.conf.urls import *
from satchmo.configuration import config_get_group

config = config_get_group('PAYMENT_PURCHASEORDER')

urlpatterns = patterns(
    'satchmo.payment',
    (r'^$', 'modules.purchaseorder.views.pay_ship_info', {},
     'PURCHASEORDER_satchmo_checkout-step2'),
    (r'^confirm/$', 'modules.purchaseorder.views.confirm_info', {},
     'PURCHASEORDER_satchmo_checkout-step3'),
    (r'^success/$', 'views.checkout.success', {},
     'PURCHASEORDER_satchmo_checkout-success'),
)
Beispiel #51
0
from django.conf.urls.defaults import *
from satchmo.configuration import config_get_group

config = config_get_group('PAYMENT_GIFTCERTIFICATE')

urlpatterns = patterns('satchmo',
     (r'^$', 'giftcertificate.views.pay_ship_info', {'SSL':config.SSL.value}, 'GIFTCERTIFICATE_satchmo_checkout-step2'),
     (r'^confirm/$', 'giftcertificate.views.confirm_info', {'SSL':config.SSL.value}, 'GIFTCERTIFICATE_satchmo_checkout-step3'),
     (r'^success/$', 'payment.views.checkout.success', {'SSL':config.SSL.value}, 'GIFTCERTIFICATE_satchmo_checkout-success'),
     (r'^balance/$', 'giftcertificate.views.check_balance', {}, 'satchmo_giftcertificate_balance'),
)
Beispiel #52
0
def contact_info(request, **kwargs):
    """View which collects demographic information from customer."""

    #First verify that the cart exists and has items
    tempCart = Cart.objects.from_request(request)
    if tempCart.numItems == 0:
        return render_to_response('checkout/empty_cart.html',
                                  RequestContext(request))

    init_data = {}
    shop = Config.objects.get_current()
    if request.user.email:
        init_data['email'] = request.user.email
    if request.user.first_name:
        init_data['first_name'] = request.user.first_name
    if request.user.last_name:
        init_data['last_name'] = request.user.last_name
    try:
        contact = Contact.objects.from_request(request, create=False)
    except Contact.DoesNotExist:
        contact = None

    # Check that items are in stock
    cart = Cart.objects.from_request(request)
    if cart.not_enough_stock():
        return http.HttpResponseRedirect(urlresolvers.reverse("satchmo_cart"))

    if request.method == "POST":
        new_data = request.POST.copy()
        if not tempCart.is_shippable:
            new_data['copy_address'] = True
        form = PaymentContactInfoForm(new_data,
                                      shop=shop,
                                      contact=contact,
                                      shippable=tempCart.is_shippable,
                                      initial=init_data,
                                      cart=tempCart)

        if form.is_valid():
            if contact is None and request.user and request.user.is_authenticated(
            ):
                contact = Contact(user=request.user)
            custID = form.save(contact=contact)
            request.session[CUSTOMER_ID] = custID
            #TODO - Create an order here and associate it with a session
            modulename = new_data['paymentmethod']
            if not modulename.startswith('PAYMENT_'):
                modulename = 'PAYMENT_' + modulename
            paymentmodule = config_get_group(modulename)
            url = lookup_url(paymentmodule, 'satchmo_checkout-step2')
            return http.HttpResponseRedirect(url)
        else:
            log.debug("Form errors: %s", form.errors)
    else:
        if contact:
            #If a person has their contact info, make sure we populate it in the form
            for item in contact.__dict__.keys():
                init_data[item] = getattr(contact, item)
            if contact.shipping_address:
                for item in contact.shipping_address.__dict__.keys():
                    init_data["ship_" + item] = getattr(
                        contact.shipping_address, item)
            if contact.billing_address:
                for item in contact.billing_address.__dict__.keys():
                    init_data[item] = getattr(contact.billing_address, item)
            if contact.primary_phone:
                init_data['phone'] = contact.primary_phone.phone
        else:
            # Allow them to login from this page.
            request.session.set_test_cookie()

        init_data['copy_address'] = True

        form = PaymentContactInfoForm(shop=shop,
                                      contact=contact,
                                      shippable=tempCart.is_shippable,
                                      initial=init_data,
                                      cart=tempCart)

    if shop.in_country_only:
        only_country = shop.sales_country
    else:
        only_country = None

    context = RequestContext(
        request, {
            'form': form,
            'country': only_country,
            'paymentmethod_ct': len(form.fields['paymentmethod'].choices)
        })
    return render_to_response('checkout/form.html', context)
Beispiel #53
0
from django.conf.urls.defaults import *
from satchmo.configuration import config_get_group

config = config_get_group('PAYMENT_PAYPAL')

urlpatterns = patterns('satchmo',
     (r'^$', 'payment.modules.paypal.views.pay_ship_info', {'SSL': config.SSL.value}, 'PAYPAL_satchmo_checkout-step2'),
     (r'^confirm/$', 'payment.modules.paypal.views.confirm_info', {'SSL': config.SSL.value}, 'PAYPAL_satchmo_checkout-step3'),
     (r'^success/$', 'payment.common.views.checkout.success', {'SSL': config.SSL.value}, 'PAYPAL_satchmo_checkout-success'),
)
Beispiel #54
0
def pay_ship_info(request):
    return payship.simple_pay_ship_info(request, config_get_group('PAYMENT_PAYPAL'), 'checkout/paypal/pay_ship.html')