示例#1
0
def send_quote_email (req, user, notes=""):
  ses = req.session
  seshelp = SessionHelper (ses)
  seshelp.update (req, called_from_cart=True)
  prod = Prod(ses.get ('prod', None))
  dear = user.first_name or user.email
  notes = notes + (('\n\n' + prod.notes) if prod.notes else "")

  text = quote_product_request_email_template.format (dear=dear, u=user, s=settings, p=prod, notes=notes)

  # these lines add to cart before sending it - use with other template above, call from cart page:
  #html = '<html><body>%s</body></html>' % render_to_string ('_final_cart.html', context_instance=ctx)
  #ses ['cart'] = ses.get ('cart', []) + [prod]
  #ses ['prod'] = {}
  #html = seshelp.cart_details()
  #print 'SESHELP', seshelp.cart_summary(), seshelp.cart_details()

  quote_email_list = [user.email] + settings.ORDER_EMAIL
  msg = EmailMultiAlternatives ('Your %s eracks quote request' % settings.HNN[0],
      text,  # nope: '',  # let's try attaching the text,
      settings.ORDER_FROM_EMAIL,
      quote_email_list
  )

  #msg.attach_alternative (html, "text/html")
  msg.send()
示例#2
0
def product (request, category, sku):
    products = Product.objects.filter (sku__iexact=sku)

    if products:
        product = products [0]
        if product.sku != sku:
            return HttpResponseRedirect (product.url)
        if product.category.slug != category:
            return HttpResponseRedirect (product.url)
    else:
        raise Http404, "Unknown Product"

    edit = request.GET.get ('edit', None)

    ses_helper = SessionHelper (request.session)

    if not edit:
        ses_helper.fill (product)
    else:
        assert request.session.get ('prod', None)

    post = request.POST #.copy()  # make it mutable to add sku

    if post:  # only for small subform(s) like email quote and future wishlist
        if post.get ('quote', None):     # send quote request to admin & user both, save in quotes
          print 'POST', post
          emailform=emailForm(request)(post)
          if emailform.is_valid():
            messages.success (request, 'Your quote request has been sent')

        elif post.get ('wishlist', None):     # Add reference to this product in user's wishlist
            raise Exception ('Implement Wishlist!')
        else:
          add_to_cart (request)
          return HttpResponseRedirect('/cart/')

    else:
      emailform = emailForm(request)()

    breadcrumbs = (
        product_breadcrumb,
        product.category,
        product,
    )

    photos_list = [str(t) for t in product_photos (product)]
    photos = mark_safe ('\n'.join (photos_list))

    return render_to_response ('product.html', dict (
            title=product.title or product.name,
            product=product,
            breadcrumbs=breadcrumbs,
            meta_title=product.meta_title,
            meta_keywords=product.meta_keywords,
            meta_description=product.meta_description,
            photos=photos,
            photos_list=photos_list,
            emailform=emailform,
            js_bottom=mark_safe (tags.script (config_grid_js, type='text/javascript')),
        ), context_instance=RequestContext(request))
示例#3
0
def ordered(request):
    ses = request.session
    seshelp = SessionHelper(ses)
    totqty, grandtot = seshelp.cart_totals(
    )  # TODO: convert these legacy references to use the dict retruned from cart_summary
    order = ses.get('order')
    payment = ses.get('payment')
    gtts = ses.get('gtts')

    if not order:
        return HttpResponseRedirect('/cart/')

    #ses ['cart'] = []
    ##del ses ['order']

    return render_to_response('ordered.html',
                              dict(
                                  breadcrumbs=(
                                      Breadcrumb('Checkout', 'Checkout',
                                                 '/checkout/'),
                                      Breadcrumb('Order', 'Order',
                                                 '/checkout/order/'),
                                  ),
                                  ses=ses,
                                  totqty=totqty,
                                  grandtot=grandtot,
                                  tax=order.tax,
                                  shipping=order.shipping,
                                  gtts=gtts,
                                  order=order,
                                  payment=payment,
                              ),
                              context_instance=RequestContext(request))
示例#4
0
def ordered (request):
    ses     = request.session
    seshelp = SessionHelper (ses)
    totqty, grandtot = seshelp.cart_totals() # TODO: convert these legacy references to use the dict retruned from cart_summary
    order   = ses.get ('order')
    payment = ses.get ('payment')
    gtts    = ses.get ('gtts')

    if not order:
        return HttpResponseRedirect ('/cart/')

    #ses ['cart'] = []
    ##del ses ['order']

    return render_to_response ('ordered.html', dict (
            breadcrumbs     = ( Breadcrumb ('Checkout', 'Checkout', '/checkout/'),
                                Breadcrumb ('Order', 'Order', '/checkout/order/'),
                              ),
            ses             = ses,
            totqty          = totqty,
            grandtot        = grandtot,
            tax             = order.tax,
            shipping        = order.shipping,
            gtts            = gtts,
            order           = order,
            payment         = payment,
        ), context_instance=RequestContext(request))
示例#5
0
def send_quote_email(req, user):
  print 'send_quote_email'
  ses = req.session
  seshelp = SessionHelper (ses)
  seshelp.update (req, called_from_cart=True)
  prod = ses.get ('prod', None)

  text = quote_product_request_email_template.format (u=user, s=settings, p=Prod(prod))

  # these lines add to cart before sending it - use with other template above, call from cart page:
  #html = '<html><body>%s</body></html>' % render_to_string ('_final_cart.html', context_instance=ctx)
  #ses ['cart'] = ses.get ('cart', []) + [prod]
  #ses ['prod'] = {}
  #html = seshelp.cart_details()
  #print 'SESHELP', seshelp.cart_summary(), seshelp.cart_details()

  quote_email_list = [user.email] + settings.ORDER_EMAIL
  msg = EmailMultiAlternatives ('Your %s eracks quote request' % settings.HNN[0],
      text,  # nope: '',  # let's try attaching the text,
      settings.ORDER_FROM_EMAIL,
      quote_email_list
  )

  #msg.attach_alternative (html, "text/html")
  print 'send_quote_email'
  print 'haijaisjaisjak'
  print '****************settings.ORDER_FROM_EMAIL,'
  print user.email
  msg.send()
示例#6
0
def add_to_cart (request):  # called from here (deprecating) and from product view with redirect to /cart/, here
  ses = request.session
  post = request.POST #.dict()
  seshelp = SessionHelper (request.session)

  prod = ses.get ('prod', None)

  if prod:
      seshelp.update (request, called_from_cart=True)
      ses ['cart'] = ses.get ('cart', []) + [prod]
      ses ['prod'] = {}
示例#7
0
def add_to_cart (request):  # called from here (deprecating) and from product view with redirect to /cart/, here
  ses = request.session
  post = request.POST #.dict()
  seshelp = SessionHelper (request.session)

  prod = ses.get ('prod', None)

  if prod:
      seshelp.update (request, called_from_cart=True)
      ses ['cart'] = ses.get ('cart', []) + [prod]
      ses ['prod'] = {}
示例#8
0
def cart(request):
    ses = request.session
    post = request.POST  #.dict()
    seshelp = SessionHelper(request.session)

    if post:
        if post.get('add', None):  # check if we have smth to add to ses.cart
            add_to_cart(request)

        elif post.get('delete', None):  # delete entire cart
            ses['cart'] = []

        elif post.get('update', None):  # update quantities in shopping cart
            cart = ses['cart']
            newqties = post.getlist('updqty')

            for i, newqty in enumerate(newqties):
                if newqty.isdigit() and int(newqty) != cart[i]['qty']:
                    if trace_grid:
                        print 'changing line:', i, 'qty', cart[i][
                            'qty'], 'to', newqty
                    cart[i]['qty'] = int(newqty)
                    #cart [i] ['extprice'] = int (newqty) * cart [i] ['totprice']

            if trace:
                for num, line in enumerate(cart):
                    print 'line/qty:', num, line['qty']

            to_delete = reversed(
                [num for num, line in enumerate(cart) if line['qty'] == 0])

            for num in to_delete:
                if trace_grid: print 'deleting line:', num
                del cart[num]

            ses['cart'] = cart

    # now display cart fm session - empty cart is handled in template
    cart = ses.get('cart', None)

    if trace: print pformat(cart)

    return render_to_response('cart.html',
                              dict(
                                  breadcrumbs=(Breadcrumb(
                                      'Cart', 'Your Cart', '/cart/'), ),
                                  summary=seshelp.cart_summary_table(),
                                  content=seshelp.cart_details(),
                                  title='Your Cart',
                              ),
                              context_instance=RequestContext(request))
示例#9
0
def cart (request):
    ses = request.session
    post = request.POST #.dict()
    seshelp = SessionHelper (request.session)

    if post:
        if post.get ('add', None):          # check if we have smth to add to ses.cart
            add_to_cart (request)

        elif post.get ('delete', None):     # delete entire cart
            ses ['cart'] = []

        elif post.get ('update', None):     # update quantities in shopping cart
            cart = ses ['cart']
            newqties = post.getlist ('updqty')

            for i, newqty in enumerate (newqties):
                if newqty.isdigit() and int (newqty) != cart [i] ['qty']:
                    if trace_grid: print 'changing line:', i, 'qty', cart [i] ['qty'], 'to', newqty
                    cart [i] ['qty'] = int (newqty)
                    #cart [i] ['extprice'] = int (newqty) * cart [i] ['totprice']

            if trace:
                for num, line in enumerate (cart):
                    print 'line/qty:', num, line ['qty']

            to_delete = reversed([num for num, line in enumerate (cart) if line ['qty'] == 0])

            for num in to_delete:
                if trace_grid: print 'deleting line:', num
                del cart [num]

            ses ['cart'] = cart

    # now display cart fm session - empty cart is handled in template
    cart = ses.get ('cart', None)

    if trace: print pformat (cart)

    return render_to_response('cart.html', dict (
            breadcrumbs=(Breadcrumb ('Cart', 'Your Cart', '/cart/'),),
            summary=seshelp.cart_summary_table(),
            content=seshelp.cart_details(),
            title='Your Cart',
        ), context_instance=RequestContext(request))
示例#10
0
def update_grid (request):
    ses_helper = SessionHelper (request.session)
    results = ses_helper.update (request)
    return HttpResponse (json.dumps (results), content_type='application/json')
示例#11
0
def product (request, category, sku):
    products = Product.objects.filter (sku__iexact=sku)

    if products:
        product = products [0]
        if product.sku != sku:
            return HttpResponseRedirect (product.url)
        if product.category.slug != category:
            return HttpResponseRedirect (product.url)
    else:
        raise Http404, "Unknown Product"

    edit = request.GET.get ('edit', None)

    ses_helper = SessionHelper (request.session)
    if not edit:
        ses_helper.fill (product)
    else:
        assert request.session.get ('prod', None)

    post = request.POST #.copy()  # make it mutable to add sku

    if post:  # only for small subform(s) like email quote and future wishlist
        if post.get('quote', None):
            # send quote request to admin & user both, save in quotes
            #print 'POST', post
            #request.user.email
            emailform = emailForm (request, product) (post)
            email = request.POST.get ("email")

            if emailform.is_valid():
                #Do we need this? we already just validated it
                #emailform = emailForm (request, product)()
                if email:
                    sent_email = email
                else:  # if form is vaolid, then this is lways true: if request.user.is_authenticated():
                    sent_email = request.user.email

                messages.success (request, 'Your quote request has been sent to %s' % sent_email)

        elif post.get ('wishlist', None):     # Add reference to this product in user's wishlist
            raise Exception ('Implement Wishlist!')
        else:
            add_to_cart (request)
            return HttpResponseRedirect('/cart/')

    else:
        emailform = emailForm(request,product)()

    breadcrumbs = (
        product_breadcrumb,
        product.category,
        product,
    )

    photos_list = [str(t) for t in product_photos (product)]
    photos = mark_safe ('\n'.join (photos_list))

    return render_to_response ('product.html', dict (
            title=product.title or product.name,
            product=product,
            breadcrumbs=breadcrumbs,
            meta_title=product.meta_title,
            meta_keywords=product.meta_keywords,
            meta_description=product.meta_description,
            photos=photos,
            photos_list=photos_list,
            emailform=emailform,
            js_bottom=mark_safe (tags.script (config_grid_js, type='text/javascript')),
        ), context_instance=RequestContext(request))
示例#12
0
def order(request):
    ses = request.session

    seshelp = SessionHelper(ses)
    totqty, grandtot = seshelp.cart_totals(
    )  # TODO: convert these legacy references to use the dict retruned from cart_summary

    order = ses['order']
    payment = ses['payment']
    payment_data = ses['payment_data']
    customer = ses['customer']
    billing_address = ses['billing_address']
    shipping_address = ses['shipping_address']
    billing_name = ses['billing_name']
    gtts = ses['gtts']

    ctx = dict(
        email=customer.email,
        order=order,
        name=shipping_address.name,  #billing_name, # or customer.name(),
        payment=payment,
        form=payment_data,
        addr="%s / %s  %s" % (
            billing_address,
            shipping_address,
            customer,
        ),
        gtts=gtts,
        ses=ses,
        grandtot=grandtot,
        totqty=totqty,
        tax=order.tax,
        shipping=order.shipping,
    )

    if trace: print 'ORDER BEFORE:', order.id, customer.id, customer.user_id

    customer.save()
    shipping_address.save()

    order.ship_to_address = shipping_address
    if shipping_address.type != 'both':
        billing_address.save()
        order.bill_to_address = billing_address
    else:
        order.bill_to_address = shipping_address

    order.save()
    payment.order = order
    payment.save()

    # not sure why I need to to do this, COW semantics on save, maybe?
    ses['order'] = order
    ses['payment'] = payment

    # send secure order email to Joe

    if trace_order:
        print 'ORDER AFTER COMMIT:', order.id, customer.id, customer.user_id
        print 'Sending secure email w/order data'
        try:
            print order_email.render(Context(ctx))
        except Exception, e:
            print e
            print order_email
            print ctx
            raise e
示例#13
0
def checkout(request, confirm=False):
    ses = request.session
    seshelp = SessionHelper(ses)
    totqty, grandtot = seshelp.cart_totals(
    )  # TODO: convert these legacy references to use the dict retruned from cart_summary
    post = request.POST
    get = request.GET
    user = request.user
    cart = ses.get('cart')

    if not cart:  # likely landed here from somewhere else, redirect to "Cart is empty" message
        return HttpResponseRedirect('/cart/')

    if post:
        customer = ses.get('customer')
        billing_address = ses.get('billing_address')
        shipping_address = ses.get('shipping_address')

        if trace_order:
            print 'POST', customer, billing_address, shipping_address

        user_form = UserForm(post, instance=user)
        customer_form = CustomerForm(post, instance=customer)
        order_form = OrderForm(post)
        shipping_address_form = AddressForm(post,
                                            prefix='shipping',
                                            instance=shipping_address)
        billing_address_form = BillingAddressForm(post,
                                                  prefix='billing',
                                                  instance=billing_address)
        payment_form = PaymentForm(post)

        def cross_form_fdedits():  # must be called after forms are checked
            if shipping_address_form['state'].value(
            ) == 'CA' and not order_form['california_tax'].value():
                # this fails on Dj 1.7.x
                #order_form._update_errors ({ 'california_tax': ['CA shipments must choose county'] })
                # nope, this isn't trapped
                #raise ValidationError ('CA shipments must choose county',
                #    code='CA_County_required')
                #params={ 'california_tax': 'county required' })
                order_form.add_error('california_tax',
                                     'Shipments to CA must choose county')
                return False

            return True

        if (customer_form.is_valid() and order_form.is_valid()
                and shipping_address_form.is_valid()
                and (billing_address_form.is_valid()
                     or billing_address_form.is_empty()
                     )  # has_changed nfg for choice fields like state
                and payment_form.is_valid() and cross_form_fdedits()):
            # Process the forms taking care of proper creation order for FKs
            customer = customer_form.save(commit=False)
            customer.user = user
            ses['customer'] = customer
            #customer.save()
            if trace:
                print 'POST CUSTOMER', customer.id, user.id, customer.user_id

            order = order_form.save(commit=False)

            # TODO: compute shipping based on weight, boxes, etc!
            multiplier = 1.0  # TODO: get this from table, above
            #multiplier = totqty  # no - (totqty is the # of line items)

            if order.shipping_payment == "included":
                # Note to Mani & developers: What we should do here is:
                # - ensure the totweight is calculated correctly, including the quantity of each line item
                # - (check also how quotes work too, and ensure the cart is being filled correctly)
                # - in the future, also includ # of packages in the calcualtion, as shipping of each box has a separate cost
                # We could also look into a shipping calcualtion add-on for Django
                shipping = seshelp.cart_summary()['totweight'] * multiplier
            else:
                shipping = 0.0

            if order.california_tax:
                tax = grandtot * float(order.california_tax.tax) / 100
            else:
                tax = 0.0

            order.tax = tax
            order.shipping = str(shipping)
            order.customer_id = customer.id
            order.status = 'new'
            order.cart = cart

            shipping_address = shipping_address_form.save(commit=False)
            shipping_address.customer_id = customer.id

            if billing_address_form.is_empty():  # not has_changed():
                shipping_address.type = 'both'
                ses['shipping_address'] = shipping_address
                #shipping_address.save()
                #print shipping_address.id
                order.bill_to_address_id = shipping_address.id
                billing_address = shipping_address
                billing_name = customer.name()
            else:
                shipping_address.type = 'shipping'
                ses['shipping_address'] = shipping_address
                #shipping_address.save()
                billing_address = billing_address_form.save(commit=False)
                billing_address.customer_id = customer.id
                billing_address.type = 'billing'
                ses['billing_address'] = billing_address
                #billing_address.save()
                #print billing_address.id
                order.bill_to_address_id = billing_address.id
                if not billing_address.name:
                    billing_address.name = customer.name()
                billing_name = billing_address.name

            order.ship_to_address_id = shipping_address.id
            ses['billing_name'] = billing_name
            ses['order'] = order
            #order.save()

            payment = payment_form.save(commit=False)
            payment.user = user
            #print order.id, order.customer_id
            payment.order_id = order.id
            payment.last_4 = payment_form.cleaned_data['card_number'][-4:]
            payment.payment_terms = payment.payment_method[2:]
            ses['payment'] = payment
            ses['payment_data'] = payment_form.cleaned_data
            #payment.save()

            gtts = grandtot + tax + shipping
            ses['gtts'] = gtts

            if confirm:  # display conf form
                return render_to_response(
                    'confirm.html',
                    dict(
                        breadcrumbs=(
                            Breadcrumb('Checkout', 'Checkout - Enter info',
                                       '/checkout/'),
                            Breadcrumb('Confirm', 'Confirm your order',
                                       '/checkout/confirm/'),
                        ),
                        ses=ses,
                        seshelp=seshelp,
                        summary=seshelp.cart_summary_table(
                        ),  # JJW 8/7/15 for consistency in new theme templates
                        grandtot=grandtot,
                        totqty=totqty,
                        tax=tax,
                        shipping=shipping,
                        gtts=gtts,
                        order=order,
                        payment=payment),
                    context_instance=RequestContext(request))

    else:  # it's a GET, fill in the inital form
        #customer = user.customer_set.all() [:1] or []
        customer = Customer.objects.filter(user=user)

        if customer:
            address_obj = Address.objects.filter(customer=customer)
            user_form = UserForm(instance=user)
            customer = customer[0]

            if trace: print 'CUSTOMER', customer.id, user.id, customer.user_id
            customer_form = CustomerForm(instance=customer)
            ses['customer'] = customer
            order_form = OrderForm()
            if address_obj:
                shipping_address_form = AddressForm(
                    prefix='shipping', instance=customer.default_shipping())
            else:
                shipping_address_form = AddressForm(
                    prefix='shipping',
                    instance=customer.default_shipping(),
                    initial={
                        'name':
                        customer.user.first_name + ' ' +
                        customer.user.last_name
                    })
            #shipping_address_form    = AddressForm (prefix='shipping', instance=customer.default_shipping(),initial={'name': customer.user.first_name})
            billing_address_form = BillingAddressForm(
                prefix='billing', instance=customer.default_billing())
            ses['shipping_address'] = customer.default_shipping()
            ses['billing_address'] = customer.default_billing()
            payment_form = PaymentForm()
        else:
            if trace: print 'USER', user, user.id
            user_form = UserForm()
            customer_form = CustomerForm(initial=dict(email=user.email))
            order_form = OrderForm()
            shipping_address_form = AddressForm(prefix='shipping')
            billing_address_form = BillingAddressForm(prefix='billing')
            payment_form = PaymentForm()

        user_form.header += ' (User: '******')'

    return render_to_response(
        'checkout.html',
        dict(
            breadcrumbs=(Breadcrumb('Checkout', 'Checkout', '/checkout/'), ),
            formlist=(user_form, customer_form, order_form,
                      shipping_address_form, billing_address_form,
                      payment_form),
            totqty=totqty,
            grandtot=grandtot,
            summary=seshelp.cart_summary_table(
            ),  # JJW 8/7/15 for consistency in new theme templates
        ),
        context_instance=RequestContext(request))
示例#14
0
def order (request):
    ses = request.session

    seshelp = SessionHelper (ses)
    totqty, grandtot = seshelp.cart_totals() # TODO: convert these legacy references to use the dict retruned from cart_summary

    order           = ses ['order']
    payment         = ses ['payment']
    payment_data    = ses ['payment_data']
    customer        = ses ['customer']
    billing_address = ses ['billing_address']
    shipping_address = ses ['shipping_address']
    billing_name    = ses ['billing_name']
    gtts            = ses ['gtts']

    ctx = dict (
            email = customer.email,
            order   = order,
            name    =  shipping_address.name,#billing_name, # or customer.name(),
            payment = payment,
            form    = payment_data,
            addr    = "%s / %s  %s" % (billing_address, shipping_address,customer,),
            gtts    = gtts,
            ses         = ses,
            grandtot    = grandtot,
            totqty      = totqty,
            tax         = order.tax,
            shipping    = order.shipping,
        )

    if trace: print 'ORDER BEFORE:', order.id, customer.id, customer.user_id

    customer.save()
    shipping_address.save()

    order.ship_to_address = shipping_address
    if shipping_address.type != 'both':
        billing_address.save()
        order.bill_to_address = billing_address
    else:
        order.bill_to_address = shipping_address

    order.save()
    payment.order = order
    payment.save()

    # not sure why I need to to do this, COW semantics on save, maybe?
    ses ['order'] = order
    ses ['payment'] = payment


    # send secure order email to Joe

    if trace_order:
        print 'ORDER AFTER COMMIT:', order.id, customer.id, customer.user_id
        print 'Sending secure email w/order data'
        try:
            print order_email.render (Context (ctx))
        except Exception, e:
            print e
            print order_email
            print ctx
            raise e
示例#15
0
def checkout (request, confirm=False):
    ses = request.session
    seshelp = SessionHelper (ses)
    totqty, grandtot = seshelp.cart_totals() # TODO: convert these legacy references to use the dict retruned from cart_summary
    post = request.POST
    get = request.GET
    user = request.user
    cart = ses.get ('cart')

    if not cart:  # likely landed here from somewhere else, redirect to "Cart is empty" message
        return HttpResponseRedirect ('/cart/')

    if post:
        customer                = ses.get ('customer')
        billing_address         = ses.get ('billing_address')
        shipping_address        = ses.get ('shipping_address')

        if trace_order: print 'POST', customer, billing_address, shipping_address

        user_form               = UserForm (post, instance=user)
        customer_form           = CustomerForm (post, instance=customer)
        order_form              = OrderForm (post)
        shipping_address_form   = AddressForm (post, prefix='shipping', instance=shipping_address)
        billing_address_form    = BillingAddressForm (post, prefix='billing', instance=billing_address)
        payment_form            = PaymentForm (post)

        def cross_form_fdedits():  # must be called after forms are checked
            if shipping_address_form['state'].value() == 'CA' and not order_form['california_tax'].value():
                # this fails on Dj 1.7.x
                #order_form._update_errors ({ 'california_tax': ['CA shipments must choose county'] })
                # nope, this isn't trapped
                #raise ValidationError ('CA shipments must choose county',
                #    code='CA_County_required')
                    #params={ 'california_tax': 'county required' })
                order_form.add_error ( 'california_tax', 'Shipments to CA must choose county')
                return False

            return True

        if (customer_form.is_valid()
                and order_form.is_valid()
                and shipping_address_form.is_valid()
                and (billing_address_form.is_valid() or billing_address_form.is_empty())  # has_changed nfg for choice fields like state
                and payment_form.is_valid()
                and cross_form_fdedits()
            ):
            # Process the forms taking care of proper creation order for FKs
            customer = customer_form.save (commit=False)
            customer.user = user
            ses ['customer'] = customer
            #customer.save()
            if trace: print 'POST CUSTOMER', customer.id, user.id, customer.user_id

            order = order_form.save (commit=False)


            # TODO: compute shipping based on weight, boxes, etc!
            multiplier = 1.0      # TODO: get this from table, above
            #multiplier = totqty  # no - (totqty is the # of line items)

            if order.shipping_payment == "included":
                # Note to Mani & developers: What we should do here is:
                # - ensure the totweight is calculated correctly, including the quantity of each line item
                # - (check also how quotes work too, and ensure the cart is being filled correctly)
                # - in the future, also includ # of packages in the calcualtion, as shipping of each box has a separate cost
                # We could also look into a shipping calcualtion add-on for Django
                shipping = seshelp.cart_summary() ['totweight'] * multiplier
            else:
                shipping = 0.0

            if order.california_tax:
                tax = grandtot * float (order.california_tax.tax)/100
            else:
                tax = 0.0

            order.tax = tax
            order.shipping = str(shipping)
            order.customer_id = customer.id
            order.status = 'new'
            order.cart = cart

            shipping_address = shipping_address_form.save (commit=False)
            shipping_address.customer_id = customer.id

            if billing_address_form.is_empty():  # not has_changed():
                shipping_address.type = 'both'
                ses ['shipping_address'] = shipping_address
                #shipping_address.save()
                #print shipping_address.id
                order.bill_to_address_id = shipping_address.id
                billing_address = shipping_address
                billing_name = customer.name()
            else:
                shipping_address.type = 'shipping'
                ses ['shipping_address'] = shipping_address
                #shipping_address.save()
                billing_address = billing_address_form.save (commit=False)
                billing_address.customer_id = customer.id
                billing_address.type = 'billing'
                ses ['billing_address'] = billing_address
                #billing_address.save()
                #print billing_address.id
                order.bill_to_address_id = billing_address.id
                if not billing_address.name:
                    billing_address.name = customer.name()
                billing_name = billing_address.name

            order.ship_to_address_id = shipping_address.id
            ses ['billing_name'] = billing_name
            ses ['order'] = order
            #order.save()

            payment = payment_form.save(commit=False)
            payment.user = user
            #print order.id, order.customer_id
            payment.order_id = order.id
            payment.last_4 = payment_form.cleaned_data ['card_number'] [-4:]
            payment.payment_terms = payment.payment_method [2:]
            ses ['payment'] = payment
            ses ['payment_data'] = payment_form.cleaned_data
            #payment.save()

            gtts = grandtot + tax + shipping
            ses ['gtts'] = gtts

            if confirm:  # display conf form
                return render_to_response ('confirm.html', dict (
                    breadcrumbs     = ( Breadcrumb ('Checkout', 'Checkout - Enter info', '/checkout/'),
                                        Breadcrumb ('Confirm', 'Confirm your order', '/checkout/confirm/'),
                                      ),
                    ses         = ses,
                    seshelp     = seshelp,
                    summary     = seshelp.cart_summary_table(), # JJW 8/7/15 for consistency in new theme templates
                    grandtot    = grandtot,
                    totqty      = totqty,
                    tax         = tax,
                    shipping    = shipping,
                    gtts        = gtts,
                    order       = order,
                    payment     = payment
                ), context_instance=RequestContext(request))

    else:  # it's a GET, fill in the inital form
        #customer = user.customer_set.all() [:1] or []
        customer = Customer.objects.filter(user=user)

        if customer:
            address_obj = Address.objects.filter(customer=customer)
            user_form                = UserForm (instance=user)
            customer                 = customer [0]

            if trace: print 'CUSTOMER', customer.id, user.id, customer.user_id
            customer_form            = CustomerForm (instance=customer)
            ses ['customer']         = customer
            order_form               = OrderForm()
            if address_obj:
                shipping_address_form    = AddressForm (prefix='shipping', instance=customer.default_shipping())
            else:
                shipping_address_form    = AddressForm (prefix='shipping', instance=customer.default_shipping(),initial={'name': customer.user.first_name + ' ' + customer.user.last_name})
            #shipping_address_form    = AddressForm (prefix='shipping', instance=customer.default_shipping(),initial={'name': customer.user.first_name})
            billing_address_form     = BillingAddressForm (prefix='billing', instance=customer.default_billing())
            ses ['shipping_address'] = customer.default_shipping()
            ses ['billing_address']  = customer.default_billing()
            payment_form             = PaymentForm ()
        else:
            if trace: print 'USER', user, user.id
            user_form               = UserForm()
            customer_form           = CustomerForm (initial = dict (email=user.email))
            order_form              = OrderForm()
            shipping_address_form   = AddressForm (prefix='shipping')
            billing_address_form    = BillingAddressForm (prefix='billing')
            payment_form            = PaymentForm()

        user_form.header += ' (User: '******')'

    return render_to_response ('checkout.html', dict (
            breadcrumbs     = (Breadcrumb ('Checkout', 'Checkout', '/checkout/'),),
            formlist        = (user_form, customer_form, order_form, shipping_address_form, billing_address_form, payment_form),
            totqty          = totqty,
            grandtot        = grandtot,
            summary         = seshelp.cart_summary_table(), # JJW 8/7/15 for consistency in new theme templates
        ), context_instance=RequestContext(request))
示例#16
0
def update_grid (request):
    ses_helper = SessionHelper (request.session)
    results = ses_helper.update (request)
    return HttpResponse (json.dumps (results), content_type='application/json')