コード例 #1
0
ファイル: tests.py プロジェクト: juderino/jelly-roll
def make_test_order(country, state):
    c = Contact(first_name="Gift", last_name="Tester", 
        role="Customer", email="*****@*****.**")
    c.save()
    if not isinstance(country, Country):
        country = Country.objects.get(iso2_code__iexact = country)
    ad = AddressBook(contact=c, description="home",
        street1 = "test", state=state, city="Portland",
        country = country, is_default_shipping=True,
        is_default_billing=True)
    ad.save()
    site = Site.objects.get_current()
    o = Order(contact=c, shipping_cost=Decimal('0.00'), site=site)
    o.save()

    p = Product.objects.get(slug='GIFT10')
    price = p.unit_price
    log.debug("creating with price: %s", price)
    item1 = OrderItem(order=o, product=p, quantity=2,
        unit_price=price, line_item_price=price*2)
    item1.save()

    detail = OrderItemDetail(name = 'email', value='*****@*****.**', sort_order=0, item=item1)
    detail.save()
    detail = OrderItemDetail(name = 'message', value='hello there', sort_order=0, item=item1)
    detail.save()

    return o
コード例 #2
0
ファイル: tests.py プロジェクト: sankroh/satchmo
def make_test_order(country, state, include_non_taxed=False, site=None):
    if not site:
        site = Site.objects.get_current()
    c = Contact(first_name="Tax", last_name="Tester", role="Customer", email="*****@*****.**")
    c.save()
    if not isinstance(country, Country):
        country = Country.objects.get(iso2_code__iexact=country)

    ad = AddressBook(
        contact=c,
        description="home",
        street1="test",
        state=state,
        city="Portland",
        country=country,
        is_default_shipping=True,
        is_default_billing=True,
    )
    ad.save()
    o = Order(contact=c, shipping_cost=Decimal("10.00"), site=site)
    o.save()

    p = Product.objects.get(slug="dj-rocks-s-b")
    price = p.unit_price
    item1 = OrderItem(order=o, product=p, quantity=5, unit_price=price, line_item_price=price * 5)
    item1.save()

    if include_non_taxed:
        p = Product.objects.get(slug="neat-book-hard")
        price = p.unit_price
        item2 = OrderItem(order=o, product=p, quantity=1, unit_price=price, line_item_price=price)
        item2.save()

    return o
コード例 #3
0
ファイル: tests.py プロジェクト: juderino/jelly-roll
    def setUp(self):
        self.US = Country.objects.get(iso2_code__iexact = 'US')
        self.site = Site.objects.get_current()
        tax = config_get('TAX','MODULE')
        tax.update('satchmo.tax.modules.no')
        c = Contact(first_name="Jim", last_name="Tester", 
            role="Customer", email="*****@*****.**")
        c.save()
        ad = AddressBook(contact=c, description="home",
            street1 = "test", state="OR", city="Portland",
            country = self.US, is_default_shipping=True,
            is_default_billing=True)
        ad.save()
        o = Order(contact=c, shipping_cost=Decimal('6.00'), site=self.site)
        o.save()
        small = Order(contact=c, shipping_cost=Decimal('6.00'), site=self.site)
        small.save()

        p = Product.objects.get(slug='neat-book-soft')
        price = p.unit_price
        item1 = OrderItem(order=o, product=p, quantity=1,
            unit_price=price, line_item_price=price)
        item1.save()
        
        item1s = OrderItem(order=small, product=p, quantity=1,
            unit_price=price, line_item_price=price)
        item1s.save()
        
        p = Product.objects.get(slug='neat-book-hard')
        price = p.unit_price
        item2 = OrderItem(order=o, product=p, quantity=1,
            unit_price=price, line_item_price=price)
        item2.save()
        self.order = o
        self.small = small
コード例 #4
0
ファイル: views.py プロジェクト: abrar78/satchmo
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)
コード例 #5
0
ファイル: common_contact.py プロジェクト: abrar78/satchmo
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)
コード例 #6
0
    def setUp(self):
        self.US = Country.objects.get(iso2_code__iexact='US')
        self.site = Site.objects.get_current()
        tax = config_get('TAX', 'MODULE')
        tax.update('satchmo.tax.modules.no')
        c = Contact(first_name="Jim",
                    last_name="Tester",
                    role="Customer",
                    email="*****@*****.**")
        c.save()
        ad = AddressBook(contact=c,
                         description="home",
                         street1="test",
                         state="OR",
                         city="Portland",
                         country=self.US,
                         is_default_shipping=True,
                         is_default_billing=True)
        ad.save()
        o = Order(contact=c, shipping_cost=Decimal('6.00'), site=self.site)
        o.save()
        small = Order(contact=c, shipping_cost=Decimal('6.00'), site=self.site)
        small.save()

        p = Product.objects.get(slug='neat-book-soft')
        price = p.unit_price
        item1 = OrderItem(order=o,
                          product=p,
                          quantity=1,
                          unit_price=price,
                          line_item_price=price)
        item1.save()

        item1s = OrderItem(order=small,
                           product=p,
                           quantity=1,
                           unit_price=price,
                           line_item_price=price)
        item1s.save()

        p = Product.objects.get(slug='neat-book-hard')
        price = p.unit_price
        item2 = OrderItem(order=o,
                          product=p,
                          quantity=1,
                          unit_price=price,
                          line_item_price=price)
        item2.save()
        self.order = o
        self.small = small
コード例 #7
0
ファイル: forms.py プロジェクト: jimmcgaw/levicci
    def save_contact(self, request):
        log.debug("Saving contact")
        data = self.cleaned_data
        password = data['password1']
        email = data['email']
        first_name = data['first_name']
        last_name = data['last_name']
        username = generate_id(first_name, last_name, email)

        verify = (config_value('SHOP', 'ACCOUNT_VERIFICATION') == 'EMAIL')

        if verify:
            from registration.models import RegistrationProfile
            user = RegistrationProfile.objects.create_inactive_user(
                username, password, email, send_email=True)
        else:
            user = User.objects.create_user(username, email, password)

        user.first_name = first_name
        user.last_name = last_name
        user.save()

        # If the user already has a contact, retrieve it.
        # Otherwise, create a new one.
        try:
            contact = Contact.objects.from_request(request, create=False)

        except Contact.DoesNotExist:
            contact = Contact()

        contact.user = user
        contact.first_name = first_name
        contact.last_name = last_name
        contact.email = email
        contact.role = 'Customer'
        contact.title = data.get('title', '')
        contact.save()

        if 'newsletter' not in data:
            subscribed = False
        else:
            subscribed = data['newsletter']

        signals.satchmo_registration.send(self, contact=contact, subscribed=subscribed, data=data)

        if not verify:
            user = authenticate(username=username, password=password)
            login(request, user)
            send_welcome_email(email, first_name, last_name)
            signals.satchmo_registration_verified.send(self, contact=contact)

        self.contact = contact

        return contact
コード例 #8
0
    def save_contact(self, request):
        log.debug("Saving contact")
        data = self.cleaned_data
        password = data['password1']
        email = data['email']
        first_name = data['first_name']
        last_name = data['last_name']
        username = data['username']

        verify = (config_value('SHOP', 'ACCOUNT_VERIFICATION') == 'EMAIL')

        if verify:
            from registration.models import RegistrationProfile
            user = RegistrationProfile.objects.create_inactive_user(
                username, password, email, send_email=True)
        else:
            user = User.objects.create_user(username, email, password)

        user.first_name = first_name
        user.last_name = last_name
        user.save()

        # If the user already has a contact, retrieve it.
        # Otherwise, create a new one.
        try:
            contact = Contact.objects.from_request(request, create=False)

        except Contact.DoesNotExist:
            contact = Contact()

        contact.user = user
        contact.first_name = first_name
        contact.last_name = last_name
        contact.email = email
        contact.role = 'Customer'
        contact.title = data.get('title', '')
        contact.save()

        signals.satchmo_registration.send(self, contact=contact, data=data)

        if not verify:
            user = authenticate(username=username, password=password)
            login(request, user)
            send_welcome_email(email, first_name, last_name)
            signals.satchmo_registration_verified.send(self, contact=contact)

        self.contact = contact

        return contact
コード例 #9
0
def make_test_order(country, state, include_non_taxed=False):
    warnings.warn(
        "make_test_order is deprecated - Use TestOrderFactory instead",
        DeprecationWarning,
    )
    c = Contact(first_name="Tax",
                last_name="Tester",
                role="Customer",
                email="*****@*****.**")
    c.save()
    if not isinstance(country, Country):
        country = Country.objects.get(iso2_code__iexact=country)

    ad = AddressBook(
        contact=c,
        description="home",
        street1="test",
        state=state,
        city="Portland",
        country=country,
        is_default_shipping=True,
        is_default_billing=True,
    )
    ad.save()
    o = Order(contact=c, shipping_cost=Decimal("10.00"))
    o.save()

    p = Product.objects.get(slug="dj-rocks-s-b")
    price = p.unit_price
    item1 = OrderItem(order=o,
                      product=p,
                      quantity=5,
                      unit_price=price,
                      line_item_price=price * 5)
    item1.save()

    if include_non_taxed:
        p = Product.objects.get(slug="neat-book-hard")
        price = p.unit_price
        item2 = OrderItem(order=o,
                          product=p,
                          quantity=1,
                          unit_price=price,
                          line_item_price=price)
        item2.save()

    return o
コード例 #10
0
def google_track_signup(context):
    """
    Output a a new user signup in the format that Google Analytics needs.
    """
    request = context['request']
    contact = Contact.from_request(request, create=False)

    return ({'contact': contact})
コード例 #11
0
ファイル: forms.py プロジェクト: davemerwin/satchmo
    def __init__(self, request, paymentmodule, *args, **kwargs):
        super(SimplePayShipForm, self).__init__(*args, **kwargs)

        self.tempCart = Cart.objects.get(id=request.session['cart'])
        self.tempContact = Contact.from_request(request)
        shipping_choices, shipping_dict = _get_shipping_choices(paymentmodule, self.tempCart, self.tempContact)
        self.fields['shipping'].choices = shipping_choices
        self.shipping_dict = shipping_dict
コード例 #12
0
ファイル: satchmo_google.py プロジェクト: davemerwin/satchmo
def google_track_signup(context):
    """
    Output a a new user signup in the format that Google Analytics needs.
    """
    request = context['request']
    contact = Contact.from_request(request, create=False)
    
    return({'contact' : contact})
コード例 #13
0
ファイル: forms.py プロジェクト: abrar78/satchmo
    def __init__(self, request, paymentmodule, *args, **kwargs):
        super(SimplePayShipForm, self).__init__(*args, **kwargs)

        self.tempCart = Cart.objects.get(id=request.session['cart'])
        self.tempContact = Contact.from_request(request)
        shipping_choices, shipping_dict = _get_shipping_choices(
            paymentmodule, self.tempCart, self.tempContact)
        self.fields['shipping'].choices = shipping_choices
        self.shipping_dict = shipping_dict
コード例 #14
0
ファイル: tests.py プロジェクト: ToeKnee/jelly-roll
def make_test_order(country, state):
    c = Contact(first_name="Gift",
                last_name="Tester",
                role="Customer",
                email="*****@*****.**")
    c.save()
    if not isinstance(country, Country):
        country = Country.objects.get(iso2_code__iexact=country)
    ad = AddressBook(
        contact=c,
        description="home",
        street1="test",
        state=state,
        city="Portland",
        country=country,
        is_default_shipping=True,
        is_default_billing=True,
    )
    ad.save()
    o = Order(contact=c, shipping_cost=Decimal("0.00"))
    o.save()

    p = Product.objects.get(slug="GIFT10")
    price = p.unit_price
    log.debug("creating with price: %s", price)
    item1 = OrderItem(order=o,
                      product=p,
                      quantity=2,
                      unit_price=price,
                      line_item_price=price * 2)
    item1.save()

    detail = OrderItemDetail(name="email",
                             value="*****@*****.**",
                             sort_order=0,
                             item=item1)
    detail.save()
    detail = OrderItemDetail(name="message",
                             value="hello there",
                             sort_order=0,
                             item=item1)
    detail.save()

    return o
コード例 #15
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.'
                )
コード例 #16
0
ファイル: common_contact.py プロジェクト: yusufbs/satchmo
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)
コード例 #17
0
ファイル: views.py プロジェクト: abrar78/satchmo
def order_history(request):
    orders = None
    contact = Contact.from_request(request, create=False)
    if contact is not None:
        orders = Order.objects.filter(contact=contact).order_by('-timestamp')

    ctx = RequestContext(request, {
        'contact' : contact,
        'orders' : orders})

    return render_to_response('contact/order_history.html', ctx)
コード例 #18
0
ファイル: views.py プロジェクト: davemerwin/satchmo
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.')    
コード例 #19
0
def credit_pay_ship_info(request, payment_module):
    #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:
        return render_to_response('checkout/empty_cart.html', RequestContext(request))
    #Verify order info is here
    if request.POST:
        new_data = request.POST.copy()
        form = CreditPayShipForm(request, payment_module, new_data)
        if form.is_valid():
            data = form.cleaned_data

            # Create a new order
            newOrder = Order(contact=contact)
            pay_ship_save(newOrder, tempCart, contact,
                shipping=data['shipping'], discount=data['discount'])
            request.session['orderID'] = newOrder.id

            #TODO: allow partial-pay here, which will mean that not all payments are on new orders.
            orderpayment = OrderPayment(order=newOrder, amount=newOrder.balance,
                payment=unicode(payment_module.KEY.value))
            orderpayment.save()
            # Save the credit card information
            cc = CreditCardDetail(orderpayment=orderpayment, ccv=data['ccv'],
                expireMonth=data['month_expires'],
                expireYear=data['year_expires'],
                creditType=data['credit_type'])
            cc.storeCC(data['credit_number'])
            cc.save()

            url = lookup_url(payment_module, 'satchmo_checkout-step3')
            return http.HttpResponseRedirect(url)
    else:
        form = CreditPayShipForm(request, payment_module)

    template = lookup_template(payment_module, 'checkout/pay_ship.html')
    ctx = {
        'form' : form,
        'PAYMENT_LIVE' : payment_live(payment_module)
    }
    return render_to_response(template, ctx, RequestContext(request))
コード例 #20
0
ファイル: forms.py プロジェクト: davemerwin/satchmo
    def __init__(self, request, paymentmodule, *args, **kwargs):
        creditchoices = paymentmodule.CREDITCHOICES.choice_values
        super(CreditPayShipForm, self).__init__(*args, **kwargs)

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

        year_now = datetime.date.today().year
        self.fields['year_expires'].choices = [(year, year) for year in range(year_now, year_now+6)]

        self.tempCart = Cart.objects.get(id=request.session['cart'])
        self.tempContact = Contact.from_request(request)

        shipping_choices, shipping_dict = _get_shipping_choices(paymentmodule, self.tempCart, self.tempContact)
        self.fields['shipping'].choices = shipping_choices
        self.shipping_dict = shipping_dict
コード例 #21
0
ファイル: views.py プロジェクト: abrar78/satchmo
def order_tracking(request, order_id):
    order = None
    contact = Contact.from_request(request, create=False)
    if contact is not None:
        try:
            order = Order.objects.get(id__exact=order_id, contact=contact)
        except Order.DoesNotExist:
            pass

    if order is None:
        return bad_or_missing(request, _("The order you have requested doesn't exist, or you don't have access to it."))

    ctx = RequestContext(request, {
        'contact' : contact,
        'order' : order})

    return render_to_response('contact/order_tracking.html', ctx)
コード例 #22
0
def simple_pay_ship_info(request, payment_module, template):
    """A pay_ship view which doesn't require a credit card"""
    #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))

    #Verify order info is here
    if request.POST:
        new_data = request.POST.copy()
        form = SimplePayShipForm(request, payment_module, new_data)
        if form.is_valid():
            data = form.cleaned_data

            # Create a new order
            newOrder = Order(contact=contact)
            pay_ship_save(newOrder, tempCart, contact,
                shipping=data['shipping'], discount=data['discount'])
            request.session['orderID'] = newOrder.id

            #TODO: allow partial-pay here, which will mean that not all payments are on new orders.
            orderpayment = OrderPayment(order=newOrder, amount=newOrder.balance, payment=payment_module.KEY.value)
            orderpayment.save()

            url = lookup_url(payment_module, 'satchmo_checkout-step3')
            return http.HttpResponseRedirect(url)
    else:
        form = SimplePayShipForm(request, payment_module)

    template = lookup_template(payment_module, template)
    ctx = {
        'form' : form,
        'PAYMENT_LIVE' : payment_live(payment_module)
    }
    return render_to_response(template, ctx, RequestContext(request))
コード例 #23
0
ファイル: forms.py プロジェクト: abrar78/satchmo
    def __init__(self, request, paymentmodule, *args, **kwargs):
        creditchoices = paymentmodule.CREDITCHOICES.choice_values
        super(CreditPayShipForm, self).__init__(*args, **kwargs)

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

        year_now = datetime.date.today().year
        self.fields['year_expires'].choices = [
            (year, year) for year in range(year_now, year_now + 6)
        ]

        self.tempCart = Cart.objects.get(id=request.session['cart'])
        self.tempContact = Contact.from_request(request)

        shipping_choices, shipping_dict = _get_shipping_choices(
            paymentmodule, self.tempCart, self.tempContact)
        self.fields['shipping'].choices = shipping_choices
        self.shipping_dict = shipping_dict
コード例 #24
0
ファイル: forms.py プロジェクト: juderino/jelly-roll
    def save_info(self, contact=None, **kwargs):
        """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()
            log.debug('creating new contact')
        else:
            customer = contact
            log.debug('Saving contact info for %s', contact)

        data = self.cleaned_data.copy()

        country = data['country']
        if not isinstance(country, Country):
            country = Country.objects.get(pk=country)
            data['country'] = country
        data['country_id'] = country.id

        shipcountry = data['ship_country']
        if not isinstance(shipcountry, Country):
            shipcountry = Country.objects.get(pk=shipcountry)
            data['ship_country'] = shipcountry

        data['ship_country_id'] = shipcountry.id

        companyname = data.pop('company', None)
        if companyname:
            org = Organization.objects.by_name(companyname, create=True)
            customer.organization = org

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

        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)

        changed_location = False
        address_keys = bill_address.__dict__.keys()
        for field in address_keys:
            if (not changed_location) and field in ('state', 'country', 'city'):
                if getattr(bill_address, field) != data[field]:
                    changed_location = True
            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:
                if (not changed_location) and field in ('state', 'country', 'city'):
                    if getattr(ship_address, field) != data[field]:
                        changed_location = True
                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.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()

        signals.form_save.send(ContactInfoForm, object=customer, formdata=data, form=self)

        if changed_location:
            signals.satchmo_contact_location_changed.send(self, contact=customer)

        return customer.id
コード例 #25
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
コード例 #26
0
def pp_express_pay_ship_info_verify(request, payment_module):
    """Verify customer and cart.
    Returns:
    True, contact, cart on success
    False, destination of failure
    """
    # Get Customer Info from Paypal Express Checkout
    
    paypal = PayPal(payment_module)

    if 'paypal_express_token' in request.session:
        paypal_express_token = request.session['paypal_express_token']
    else:
        # If the user didn't get the authorization I redirect to the request authorization page
        return False
        
    
    response_dict = paypal.GetExpressCheckoutDetails(paypal_express_token, return_all=True)
    
    if 'SHIPTOSTREET' not in response_dict:
        # If the user didn't get the authorization I redirect to the request authorization page
        return False
        
    email = response_dict["EMAIL"][0]
    first_name = response_dict["FIRSTNAME"][0]
    last_name = response_dict["LASTNAME"][0]
    addressee = response_dict["SHIPTONAME"][0]
    street1 = response_dict["SHIPTOSTREET"][0]
    
    try:
        street2 = response_dict["SHIPTOSTREET2"][0]
    except:
        street2 = ""
        
    city = response_dict["SHIPTOCITY"][0]
    
    try:
        state = response_dict["SHIPTOSTATE"][0]
    except:
        state = " "
    postal_code = response_dict["SHIPTOZIP"][0]
    country_code = response_dict["SHIPTOCOUNTRY"][0]

    country = Country.objects.get(iso2_code__iexact=country_code)
    # I get users notes

    if request.user.is_authenticated():
        try:
            contact = Contact.objects.get(user=request.user) # If the user is authenticated I don't neet to create a new contact
            contact.email = email
            contact.first_name = first_name
            contact.last_name = last_name
            
            # I delete the user shipping address to overwrite with paypal express data
            try:
                contact.shipping_address.delete()
            except:
                pass
        
            # I delete the user phone number to overwrite with paypal express data
            try:
                contact.primary_phone.delete()
            except:
                pass

        except:
            pass
        
    elif request.session.get(CUSTOMER_ID):
            try:
                contact = Contact.objects.get(id=request.session[CUSTOMER_ID])
                contact.email = email
                contact.first_name = first_name
                contact.last_name = last_name
                
                # I delete the user shipping address to overwrite with paypal express data
                try:
                    contact.shipping_address.delete()
                except:
                    pass
        
                # I delete the user phone number to overwrite with paypal express data
                try:
                    contact.primary_phone.delete()
                except:
                    pass
                
            except Contact.DoesNotExist:
                del request.session[CUSTOMER_ID]
        
            
            
    try:
        contact    
    except NameError:
        try: # If a user with the same name, email and last name exists, I get that instead of a new contact creation
            contact = Contact.objects.filter(email__iexact=email).filter(first_name__iexact=first_name).filter(last_name__iexact=last_name)[0]
        
        except:    
            # if it doesn't exists, I create it
            contact = Contact(email=email, first_name = first_name, last_name=last_name)

    # If the user wrote a note, I save it
    try:
        #if the user exists, I overwrite his contact data
        contact.notes = contact.notes + '\n' + response_dict["NOTE"][0]
             
    except:
            pass
    
        


    # I save my contact
    contact.save()
    #request.session['CUSTOMER_ID'] = contact.id
    request.session[CUSTOMER_ID] = contact.id
    
 
    shipping_address = AddressBook(addressee=addressee, contact=contact, street1=street1, street2=street2,city = city, state=state, postal_code=postal_code,\
                                   country=country, is_default_shipping=True)
    shipping_address.save()
    
    #billing_address = AddressBook(addressee=addressee, contact=contact, street1=street1, street2=street2,city = city, state=state, postal_code=postal_code,\
    #                               country=country, is_default_shipping=True)
    #billing_address.save()
    
    try:
        phone = PhoneNumber(contact=contact, phone=response_dict["PHONENUM"][0], primary=True, type="Home")
        phone.save()
    except:
        log.debug("PayPal Error importing phone number: " + repr(response_dict))

    # Verify that we still have items in the cart.
    tempCart = Cart.objects.from_request(request)
    tempCart.customer = contact
    tempCart.save()
    
    if tempCart.numItems == 0:
        template = lookup_template(payment_module, 'checkout/empty_cart.html')
        return (False, render_to_response(template, RequestContext(request)))


    return (True, contact, tempCart)
コード例 #27
0
def load_data():
    from satchmo.contact.models import Contact, AddressBook, PhoneNumber
    from satchmo.product.models import Product, Price, ConfigurableProduct, ProductVariation, Category, OptionGroup, Option, ProductImage  #, DownloadableProduct
    from satchmo.supplier.models import Organization
    from satchmo.shop.models import Config
    from django.conf import settings
    from satchmo.l10n.models import Country
    #Load basic configuration information
    print "Creating site..."
    site = Site.objects.get(id=settings.SITE_ID)
    site.domain = settings.SITE_DOMAIN
    site.name = settings.SITE_NAME
    site.save()
    store_country = Country.objects.get(iso3_code='USA')
    config = Config(site=site,
                    store_name=settings.SITE_NAME,
                    no_stock_checkout=False,
                    country=store_country,
                    sales_country=store_country)
    config.save()
    print "Creating Customers..."
    # Import some customers
    c1 = Contact(first_name="Chris",
                 last_name="Smith",
                 email="*****@*****.**",
                 role="Customer",
                 notes="Really cool stuff")
    c1.save()
    p1 = PhoneNumber(contact=c1,
                     phone="601-555-5511",
                     type="Home",
                     primary=True)
    p1.save()
    c2 = Contact(first_name="John",
                 last_name="Smith",
                 email="*****@*****.**",
                 role="Customer",
                 notes="Second user")
    c2.save()
    p2 = PhoneNumber(contact=c2,
                     phone="999-555-5111",
                     type="Work",
                     primary=True)
    p2.save()
    # Import some addresses for these customers
    a1 = AddressBook(description="Home",
                     street1="8235 Pike Street",
                     city="Anywhere Town",
                     state="TN",
                     postal_code="38138",
                     country="US",
                     is_default_shipping=True,
                     contact=c1)
    a1.save()
    a2 = AddressBook(description="Work",
                     street1="1245 Main Street",
                     city="Stillwater",
                     state="MN",
                     postal_code="55082",
                     country="US",
                     is_default_shipping=True,
                     contact=c2)
    a2.save()
    print "Creating Suppliers..."
    #Import some suppliers
    org1 = Organization(name="Rhinestone Ronny",
                        type="Company",
                        role="Supplier")
    org1.save()
    c4 = Contact(first_name="Fred",
                 last_name="Jones",
                 email="*****@*****.**",
                 role="Supplier",
                 organization=org1)
    c4.save()
    p4 = PhoneNumber(contact=c4,
                     phone="800-188-7611",
                     type="Work",
                     primary=True)
    p4.save()
    p5 = PhoneNumber(contact=c4, phone="755-555-1111", type="Fax")
    p5.save()
    a3 = AddressBook(contact=c4,
                     description="Mailing address",
                     street1="Receiving Dept",
                     street2="918 Funky Town St",
                     city="Fishkill",
                     state="NJ",
                     postal_code="19010")
    a3.save()
    #s1 = Supplier(name="Rhinestone Ronny", address1="918 Funky Town St", address2="Suite 200",
    #              city="Fishkill", state="NJ", zip="19010", phone1="800-188-7611", fax="900-110-1909", email="*****@*****.**",
    #              notes="My main supplier")
    #s1.save()

    #s2 = Supplier(name="Shirt Sally", address1="9 ABC Lane",
    #    city="Happyville", state="MD", zip="190111", phone1="888-888-1111", fax="999-110-1909", email="*****@*****.**",
    #              notes="Shirt Supplier")
    #s2.save()

    print "Creating Categories..."
    #Create some categories
    cat1 = Category(name="Shirts", slug="shirts", description="Women's Shirts")
    cat1.save()
    cat2 = Category(name="Short Sleeve",
                    slug="shortsleeve",
                    description="Short sleeve shirts",
                    parent=cat1)
    cat2.save()
    cat3 = Category(name="Books", slug="book", description="Books")
    cat3.save()
    cat4 = Category(name="Fiction",
                    slug="fiction",
                    description="Fiction Books",
                    parent=cat3)
    cat4.save()
    cat5 = Category(name="Science Fiction",
                    slug="scifi",
                    description="Science Fiction",
                    parent=cat4)
    cat5.save()
    cat6 = Category(name="Non Fiction",
                    slug="nonfiction",
                    description="Non Fiction",
                    parent=cat3)
    cat6.save()
    cat7 = Category(name="Software", slug="software")
    cat7.save()

    print "Creating products..."
    #Create some items
    i1 = Product(name="Django Rocks shirt",
                 slug="DJ-Rocks",
                 description="Really cool shirt",
                 active=True,
                 featured=True)
    i1.save()
    p1 = Price(price="20.00", product=i1)
    p1.save()
    i1.category.add(cat1)
    i1.save()
    i2 = Product(name="Python Rocks shirt",
                 slug="PY-Rocks",
                 description="Really cool python shirt - One Size Fits All",
                 active=True,
                 featured=True)
    i2.save()
    p2 = Price(price="19.50", product=i2)
    p2.save()
    i2.category.add(cat2)
    i2.save()
    i3 = Product(name="A really neat book",
                 slug="neat-book",
                 description="A neat book.  You should buy it.",
                 active=True,
                 featured=True)
    i3.save()
    p3 = Price(price="5.00", product=i3)
    p3.save()
    i3.category.add(cat4)
    i3.save()
    i4 = Product(name="Robots Attack!",
                 slug="robot-attack",
                 description="Robots try to take over the world.",
                 active=True,
                 featured=True)
    i4.save()
    p4 = Price(price="7.99", product=i4)
    p4.save()
    i4.category.add(cat5)
    i4.save()

    #    i5 = Product(name="Really Neat Software", slug="neat-software", description="Example Configurable/Downloadable product", active=True, featured=True)
    #    i5.save()
    #    i5.category.add(cat7)
    #    i5.save()

    #Create an attribute set
    optSet1 = OptionGroup(name="sizes", sort_order=1)
    optSet2 = OptionGroup(name="colors", sort_order=2)
    optSet1.save()
    optSet2.save()

    optSet3 = OptionGroup(name="Book type", sort_order=1)
    optSet3.save()

    optSet4 = OptionGroup(name="Full/Upgrade", sort_order=5)
    optSet4.save()

    optItem1a = Option(name="Small",
                       value="S",
                       displayOrder=1,
                       optionGroup=optSet1)
    optItem1a.save()
    optItem1b = Option(name="Medium",
                       value="M",
                       displayOrder=2,
                       optionGroup=optSet1)
    optItem1b.save()
    optItem1c = Option(name="Large",
                       value="L",
                       displayOrder=3,
                       price_change=1.00,
                       optionGroup=optSet1)
    optItem1c.save()

    optItem2a = Option(name="Black",
                       value="B",
                       displayOrder=1,
                       optionGroup=optSet2)
    optItem2a.save()
    optItem2b = Option(name="White",
                       value="W",
                       displayOrder=2,
                       optionGroup=optSet2)
    optItem2b.save()
    optItem2c = Option(name="Blue",
                       value="BL",
                       displayOrder=3,
                       price_change=2.00,
                       optionGroup=optSet2)
    optItem2c.save()

    optItem3a = Option(name="Hard cover",
                       value="hard",
                       displayOrder=1,
                       optionGroup=optSet3)
    optItem3a.save()
    optItem3b = Option(name="Soft cover",
                       value="soft",
                       displayOrder=2,
                       price_change=1.00,
                       optionGroup=optSet3)
    optItem3b.save()
    optItem3c = Option(name="On tape",
                       value="tape",
                       displayOrder=3,
                       optionGroup=optSet3)
    optItem3c.save()

    optItem4a = Option(name="Full Version",
                       value="full",
                       optionGroup=optSet4,
                       displayOrder=1)
    optItem4a.save()
    optItem4b = Option(name="Upgrade Version",
                       value="upgrade",
                       optionGroup=optSet4,
                       displayOrder=2)
    optItem4b.save()

    #Add the option group to our items
    pg1 = ConfigurableProduct(product=i1)
    pg1.save()
    pg1.option_group.add(optSet1)
    pg1.save()
    pg1.option_group.add(optSet2)
    pg1.save()

    pg3 = ConfigurableProduct(product=i3)
    pg3.save()
    pg3.option_group.add(optSet3)
    pg3.save()

    pg4 = ConfigurableProduct(product=i4)
    pg4.save()
    pg4.option_group.add(optSet3)
    pg4.save()

    #    pg5 = ConfigurableProduct(product=i5)
    #    pg5.option_group.add(optSet4)
    #    pg5.save()

    print "Creating product variations..."
    #Create the required sub_items
    pg1.create_products()
    pg3.create_products()
    pg4.create_products()
    #pg5.create_products()

    #set prices for full and upgrade versions of neat-software, this is an alternative to using the price_change in options, it allows for more flexability when required.
    #    pv1 = pg5.get_product_from_options([optItem4a])
    #    Price(product=pv1, price='5.00').save()
    #    Price(product=pv1, price='2.00', quantity=50).save()
    #    DownloadableProduct(product=pv1).save()

    #    pv2 = pg5.get_product_from_options([optItem4b])
    #    Price(product=pv2, price='1.00').save()
    #    DownloadableProduct(product=pv2).save()

    print "Create a test user..."
    #First see if our test user is still there, then use or create that user
    try:
        test_user = User.objects.get(username="******")
    except:
        test_user = User.objects.create_user('csmith', '*****@*****.**',
                                             'test')
        test_user.save()
    c1.user = test_user
    c1.save()
コード例 #28
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(request, "checkout/empty_cart.html")

    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(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 list(contact.__dict__.keys()):
                init_data[item] = getattr(contact, item)
            if contact.shipping_address:
                for item in list(contact.shipping_address.__dict__.keys()):
                    init_data["ship_" + item] = getattr(
                        contact.shipping_address, item)
            if contact.billing_address:
                for item in list(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 = {
        "form": form,
        "country": only_country,
        "paymentmethod_ct": len(form.fields["paymentmethod"].choices),
    }
    return render(request, "checkout/form.html", context)
コード例 #29
0
    def save_info(self, contact=None, **kwargs):
        """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()
            log.debug('creating new contact')
        else:
            customer = contact
            log.debug('Saving contact info for %s', contact)

        data = self.cleaned_data.copy()

        country = data['country']
        if not isinstance(country, Country):
            country = Country.objects.get(pk=country)
            data['country'] = country
        data['country_id'] = country.id

        shipcountry = data['ship_country']
        if not isinstance(shipcountry, Country):
            shipcountry = Country.objects.get(pk=shipcountry)
            data['ship_country'] = shipcountry

        data['ship_country_id'] = shipcountry.id

        companyname = data.pop('company', None)
        if companyname:
            org = Organization.objects.by_name(companyname, create=True)
            customer.organization = org

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

        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)

        changed_location = False
        address_keys = bill_address.__dict__.keys()
        for field in address_keys:
            if (not changed_location) and field in ('state', 'country',
                                                    'city'):
                if getattr(bill_address, field) != data[field]:
                    changed_location = True
            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:
                if (not changed_location) and field in ('state', 'country',
                                                        'city'):
                    if getattr(ship_address, field) != data[field]:
                        changed_location = True
                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.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()

        signals.form_save.send(ContactInfoForm,
                               object=customer,
                               formdata=data,
                               form=self)

        if changed_location:
            signals.satchmo_contact_location_changed.send(self,
                                                          contact=customer)

        return customer.id
コード例 #30
0
ファイル: load_data.py プロジェクト: jimmcgaw/true-platform
def load_data():
    from satchmo.contact.models import Contact, AddressBook, PhoneNumber
    from satchmo.product.models import Product, Price, ConfigurableProduct, ProductVariation, Category, OptionGroup, Option, ProductImage#, DownloadableProduct
    from satchmo.supplier.models import Organization
    from satchmo.shop.models import Config
    from django.conf import settings
    from satchmo.l10n.models import Country
    #Load basic configuration information
    print "Creating site..."
    site = Site.objects.get(id=settings.SITE_ID)
    site.domain = settings.SITE_DOMAIN  
    site.name = settings.SITE_NAME
    site.save()
    store_country = Country.objects.get(iso3_code='USA')
    config = Config(site=site, store_name = settings.SITE_NAME, no_stock_checkout=False, country=store_country, sales_country=store_country)
    config.save()
    config.shipping_countries.add(store_country)
    config.save()
    print "Creating Customers..."
    # Import some customers
    c1 = Contact(first_name="Chris", last_name="Smith", email="*****@*****.**", role="Customer", notes="Really cool stuff")
    c1.save()
    p1 = PhoneNumber(contact=c1, phone="601-555-5511", type="Home",primary=True)
    p1.save()
    c2 = Contact(first_name="John", last_name="Smith", email="*****@*****.**", role="Customer", notes="Second user")
    c2.save()
    p2 = PhoneNumber(contact=c2, phone="999-555-5111", type="Work",primary=True)
    p2.save()
    # Import some addresses for these customers
    a1 = AddressBook(description="Home", street1="8235 Pike Street", city="Anywhere Town", state="TN",
                 postal_code="38138", country="US", is_default_shipping=True, contact=c1)
    a1.save()
    a2 = AddressBook(description="Work", street1="1245 Main Street", city="Stillwater", state="MN",
                 postal_code="55082", country="US", is_default_shipping=True, contact=c2)
    a2.save()
    print "Creating Suppliers..."
    #Import some suppliers
    org1 = Organization(name="Rhinestone Ronny", type="Company",role="Supplier")
    org1.save()
    c4 = Contact(first_name="Fred", last_name="Jones", email="*****@*****.**", role="Supplier", organization=org1)
    c4.save()
    p4 = PhoneNumber(contact=c4,phone="800-188-7611", type="Work", primary=True)
    p4.save()
    p5 = PhoneNumber(contact=c4,phone="755-555-1111",type="Fax")
    p5.save()
    a3 = AddressBook(contact=c4, description="Mailing address", street1="Receiving Dept", street2="918 Funky Town St", city="Fishkill",
                     state="NJ", postal_code="19010")
    a3.save()
    #s1 = Supplier(name="Rhinestone Ronny", address1="918 Funky Town St", address2="Suite 200",
    #              city="Fishkill", state="NJ", zip="19010", phone1="800-188-7611", fax="900-110-1909", email="*****@*****.**",
    #              notes="My main supplier")
    #s1.save()

    #s2 = Supplier(name="Shirt Sally", address1="9 ABC Lane", 
    #    city="Happyville", state="MD", zip="190111", phone1="888-888-1111", fax="999-110-1909", email="*****@*****.**",
    #              notes="Shirt Supplier")
    #s2.save()
    
    
    print "Creating Categories..."
    #Create some categories
    cat1 = Category(name="Shirts",slug="shirts",description="Women's Shirts", site=site)
    cat1.save()
    cat2 = Category(name="Short Sleeve",slug="shortsleeve",description="Short sleeve shirts", parent=cat1, site=site)
    cat2.save()
    cat3 = Category(name="Books",slug="book",description="Books", site=site)
    cat3.save()
    cat4 = Category(name="Fiction",slug="fiction",description="Fiction Books", parent=cat3, site=site)
    cat4.save()
    cat5 = Category(name="Science Fiction",slug="scifi",description="Science Fiction",parent=cat4, site=site)
    cat5.save()
    cat6 = Category(name="Non Fiction",slug="nonfiction",description="Non Fiction",parent=cat3, site=site)
    cat6.save()
    cat7 = Category(name="Software", slug="software", site=site)
    cat7.save()
    
    
    print "Creating products..."   
    #Create some items
    i1 = Product(name="Django Rocks shirt", slug="dj-rocks", description="Really cool shirt",
             active=True, featured=True, site=site)
    i1.save()
    p1 = Price(price="20.00", product=i1)
    p1.save()
    i1.category.add(cat1)
    i1.save()
    i2 = Product(name="Python Rocks shirt", slug="PY-Rocks", description="Really cool python shirt - One Size Fits All", 
             active=True, featured=True, site=site)
    i2.save()
    p2 = Price(price="19.50", product=i2)
    p2.save()
    i2.category.add(cat2)
    i2.save()
    i3 = Product(name="A really neat book", slug="neat-book", description="A neat book.  You should buy it.", 
             active=True, featured=True, site=site)
    i3.save()
    p3 = Price(price="5.00", product=i3)
    p3.save()
    i3.category.add(cat4)
    i3.save()
    i4 = Product(name="Robots Attack!", slug="robot-attack", description="Robots try to take over the world.", 
             active=True, featured=True, site=site)
    i4.save()
    p4 = Price(price="7.99", product=i4)
    p4.save()
    i4.category.add(cat5)
    i4.save()

#    i5 = Product(name="Really Neat Software", slug="neat-software", description="Example Configurable/Downloadable product", active=True, featured=True)
#    i5.save()
#    i5.category.add(cat7)
#    i5.save()

    #Create an attribute set 
    optSet1 = OptionGroup(name="sizes", sort_order=1, site=site)
    optSet2 = OptionGroup(name="colors", sort_order=2, site=site)
    optSet1.save()
    optSet2.save()
    
    optSet3 = OptionGroup(name="Book type", sort_order=1, site=site)
    optSet3.save()

    optSet4 = OptionGroup(name="Full/Upgrade", sort_order=5, site=site)
    optSet4.save()
    
    optItem1a = Option(name="Small", value="S", sort_order=1, option_group=optSet1)
    optItem1a.save()
    optItem1b = Option(name="Medium", value="M", sort_order=2, option_group=optSet1)
    optItem1b.save()
    optItem1c = Option(name="Large", value="L", sort_order=3, price_change = Decimal("1.00"), option_group=optSet1)
    optItem1c.save()

    optItem2a = Option(name="Black", value="B", sort_order=1, option_group=optSet2)
    optItem2a.save()
    optItem2b = Option(name="White", value="W", sort_order=2, option_group=optSet2)
    optItem2b.save()
    optItem2c = Option(name="Blue", value="BL", sort_order=3, price_change=Decimal("2.00"), option_group=optSet2)
    optItem2c.save()

    optItem3a = Option(name="Hard cover", value="hard", sort_order=1, option_group=optSet3)
    optItem3a.save()
    optItem3b = Option(name="Soft cover", value="soft", sort_order=2, price_change=Decimal("1.00"), option_group=optSet3)
    optItem3b.save()
    optItem3c = Option(name="On tape", value="tape", sort_order=3, option_group=optSet3)
    optItem3c.save()

    optItem4a = Option(name="Full Version", value="full", option_group=optSet4, sort_order=1)
    optItem4a.save()
    optItem4b = Option(name="Upgrade Version", value="upgrade", option_group=optSet4, sort_order=2)
    optItem4b.save()


    #Add the option group to our items
    pg1 = ConfigurableProduct(product=i1)
    pg1.save()
    pg1.option_group.add(optSet1)
    pg1.save()
    pg1.option_group.add(optSet2)
    pg1.save()

    pg3 = ConfigurableProduct(product=i3)
    pg3.save()
    pg3.option_group.add(optSet3)
    pg3.save()
    
    pg4 = ConfigurableProduct(product=i4)
    pg4.save()
    pg4.option_group.add(optSet3)
    pg4.save()

#    pg5 = ConfigurableProduct(product=i5)
#    pg5.option_group.add(optSet4)
#    pg5.save()

    print "Creating product variations..."
    #Create the required sub_items
    pg1.create_all_variations()
    pg3.create_all_variations()
    pg4.create_all_variations()
    #pg5.create_all_variations()

    #set prices for full and upgrade versions of neat-software, this is an alternative to using the price_change in options, it allows for more flexability when required.
#    pv1 = pg5.get_product_from_options([optItem4a])
#    Price(product=pv1, price='5.00').save()
#    Price(product=pv1, price='2.00', quantity=50).save()
#    DownloadableProduct(product=pv1).save()

#    pv2 = pg5.get_product_from_options([optItem4b])
#    Price(product=pv2, price='1.00').save()
#    DownloadableProduct(product=pv2).save()
    
    print "Create a test user..."
    #First see if our test user is still there, then use or create that user
    try:
        test_user = User.objects.get(username="******")
    except:
        test_user = User.objects.create_user('csmith', '*****@*****.**', 'test')
        test_user.save()
    c1.user = test_user
    c1.save()
コード例 #31
0
    def handle_noargs(self, **options):
        from satchmo.contact.models import Contact, AddressBook, PhoneNumber
        from satchmo.product.models import (
            Product,
            Price,
            ConfigurableProduct,
            ProductVariation,
            Category,
            OptionGroup,
            Option,
            ProductImage,
        )  # , DownloadableProduct
        from satchmo.shop.models import Config
        from django.conf import settings
        from satchmo.l10n.models import Country
        from django.contrib.sites.models import Site
        from django.contrib.auth.models import User

        # idempotency test

        print("Checking for existing sample data.")
        try:
            p = Product.objects.get(slug="dj-rocks")
            print(
                "It looks like you already have loaded the sample store data, quitting."
            )
            import sys

            sys.exit(1)
        except Product.DoesNotExist:
            pass

        print("Loading sample store data.")

        # Load basic configuration information

        print("Creating site...")
        try:
            site = Site.objects.get(id=settings.SITE_ID)
            print(("Using existing site #%i" % settings.SITE_ID))
        except Site.DoesNotExist:
            print("Creating Example Store Site")
            site = Site(domain="localhost", name="Sample Store")
        site.domain = settings.SITE_DOMAIN
        site.name = settings.SITE_NAME
        site.save()
        store_country = Country.objects.get(iso3_code="USA")
        config = Config(
            site=site,
            store_name=settings.SITE_NAME,
            no_stock_checkout=True,
            country=store_country,
            sales_country=store_country,
        )
        config.save()
        config.shipping_countries.add(store_country)
        config.save()
        print("Creating Customers...")
        # Import some customers
        c1 = Contact(
            first_name="Chris",
            last_name="Smith",
            email="*****@*****.**",
            role="Customer",
            notes="Really cool stuff",
        )
        c1.save()
        p1 = PhoneNumber(contact=c1, phone="601-555-5511", type="Home", primary=True)
        p1.save()
        c2 = Contact(
            first_name="John",
            last_name="Smith",
            email="*****@*****.**",
            role="Customer",
            notes="Second user",
        )
        c2.save()
        p2 = PhoneNumber(contact=c2, phone="999-555-5111", type="Work", primary=True)
        p2.save()
        # Import some addresses for these customers
        us = Country.objects.get(iso2_code="US")
        a1 = AddressBook(
            description="Home",
            street1="8235 Pike Street",
            city="Anywhere Town",
            state="TN",
            postal_code="38138",
            country=us,
            is_default_shipping=True,
            contact=c1,
        )
        a1.save()
        a2 = AddressBook(
            description="Work",
            street1="1245 Main Street",
            city="Stillwater",
            state="MN",
            postal_code="55082",
            country=us,
            is_default_shipping=True,
            contact=c2,
        )
        a2.save()

        print("Creating Categories...")
        # Create some categories
        cat1 = Category(name="Shirts", slug="shirts", description="Women's Shirts")
        cat1.save()
        cat2 = Category(
            name="Short Sleeve",
            slug="shortsleeve",
            description="Short sleeve shirts",
            parent=cat1,
        )
        cat2.save()
        cat3 = Category(name="Books", slug="book", description="Books")
        cat3.save()
        cat4 = Category(
            name="Fiction", slug="fiction", description="Fiction Books", parent=cat3
        )
        cat4.save()
        cat5 = Category(
            name="Science Fiction",
            slug="scifi",
            description="Science Fiction",
            parent=cat4,
        )
        cat5.save()
        cat6 = Category(
            name="Non Fiction",
            slug="nonfiction",
            description="Non Fiction",
            parent=cat3,
        )
        cat6.save()
        cat7 = Category(name="Software", slug="software")
        cat7.save()

        print("Creating products...")
        # Create some items
        i1 = Product(
            name="Django Rocks shirt",
            slug="dj-rocks",
            description="Really cool shirt",
            active=True,
            featured=True,
        )
        i1.save()
        p1 = Price(price="20.00", product=i1)
        p1.save()
        i1.category.add(cat1)
        i1.save()
        i2 = Product(
            name="Python Rocks shirt",
            slug="PY-Rocks",
            description="Really cool python shirt - One Size Fits All",
            active=True,
            featured=True,
        )
        i2.save()
        p2 = Price(price="19.50", product=i2)
        p2.save()
        i2.category.add(cat2)
        i2.save()
        i3 = Product(
            name="A really neat book",
            slug="neat-book",
            description="A neat book.  You should buy it.",
            active=True,
            featured=True,
        )
        i3.save()
        p3 = Price(price="5.00", product=i3)
        p3.save()
        i3.category.add(cat4)
        i3.save()
        i4 = Product(
            name="Robots Attack!",
            slug="robot-attack",
            description="Robots try to take over the world.",
            active=True,
            featured=True,
        )
        i4.save()
        p4 = Price(price="7.99", product=i4)
        p4.save()
        i4.category.add(cat5)
        i4.save()

        #    i5 = Product(name="Really Neat Software", slug="neat-software", description="Example Configurable/Downloadable product", active=True, featured=True)
        #    i5.save()
        #    i5.category.add(cat7)
        #    i5.save()

        # Create an attribute set
        optSet1 = OptionGroup(name="sizes", sort_order=1)
        optSet2 = OptionGroup(name="colors", sort_order=2)
        optSet1.save()
        optSet2.save()

        optSet3 = OptionGroup(name="Book type", sort_order=1)
        optSet3.save()

        optSet4 = OptionGroup(name="Full/Upgrade", sort_order=5)
        optSet4.save()

        optItem1a = Option(name="Small", value="S", sort_order=1, option_group=optSet1)
        optItem1a.save()
        optItem1b = Option(name="Medium", value="M", sort_order=2, option_group=optSet1)
        optItem1b.save()
        optItem1c = Option(
            name="Large",
            value="L",
            sort_order=3,
            price_change="1.00",
            option_group=optSet1,
        )
        optItem1c.save()

        optItem2a = Option(name="Black", value="B", sort_order=1, option_group=optSet2)
        optItem2a.save()
        optItem2b = Option(name="White", value="W", sort_order=2, option_group=optSet2)
        optItem2b.save()
        optItem2c = Option(
            name="Blue",
            value="BL",
            sort_order=3,
            price_change="2.00",
            option_group=optSet2,
        )
        optItem2c.save()

        optItem3a = Option(
            name="Hard cover", value="hard", sort_order=1, option_group=optSet3
        )
        optItem3a.save()
        optItem3b = Option(
            name="Soft cover",
            value="soft",
            sort_order=2,
            price_change="1.00",
            option_group=optSet3,
        )
        optItem3b.save()
        optItem3c = Option(
            name="On tape", value="tape", sort_order=3, option_group=optSet3
        )
        optItem3c.save()

        optItem4a = Option(
            name="Full Version", value="full", option_group=optSet4, sort_order=1
        )
        optItem4a.save()
        optItem4b = Option(
            name="Upgrade Version", value="upgrade", option_group=optSet4, sort_order=2
        )
        optItem4b.save()

        # Add the option group to our items
        pg1 = ConfigurableProduct(product=i1)
        pg1.save()
        pg1.option_group.add(optSet1)
        pg1.save()
        pg1.option_group.add(optSet2)
        pg1.save()

        pg3 = ConfigurableProduct(product=i3)
        pg3.save()
        pg3.option_group.add(optSet3)
        pg3.save()

        pg4 = ConfigurableProduct(product=i4)
        pg4.save()
        pg4.option_group.add(optSet3)
        pg4.save()

        #    pg5 = ConfigurableProduct(product=i5)
        #    pg5.option_group.add(optSet4)
        #    pg5.save()

        print("Creating product variations...")
        # Create the required sub_items
        pg1.create_all_variations()
        pg3.create_all_variations()
        pg4.create_all_variations()
        # pg5.create_all_variations()

        # set prices for full and upgrade versions of neat-software, this is an alternative to using the price_change in options, it allows for more flexability when required.
        #    pv1 = pg5.get_product_from_options([optItem4a])
        #    Price(product=pv1, price='5.00').save()
        #    Price(product=pv1, price='2.00', quantity=50).save()
        #    DownloadableProduct(product=pv1).save()

        #    pv2 = pg5.get_product_from_options([optItem4b])
        #    Price(product=pv2, price='1.00').save()
        #    DownloadableProduct(product=pv2).save()

        print("Create a test user...")
        # First see if our test user is still there, then use or create that user
        try:
            test_user = User.objects.get(username="******")
        except:
            test_user = User.objects.create_user(
                "csmith", "*****@*****.**", "test"
            )
            test_user.save()
        c1.user = test_user
        c1.save()
コード例 #32
0
ファイル: views.py プロジェクト: davemerwin/satchmo
def register_handle_form(request, redirect=None):
    """
    Handle all registration logic.  This is broken out from "register" to allow easy overriding/hooks
    such as a combined login/register page.

    Returns:
    - Success flag
    - HTTPResponseRedirect (success) or form (fail)
    """

    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():

            data = form.cleaned_data
            password = data['password']
            email = data['email']
            first_name = data['first_name']
            last_name = data['last_name']
            username = generate_id(first_name, last_name)

            verify = (config_value('SHOP', 'ACCOUNT_VERIFICATION') == 'EMAIL')
            if verify:
                from registration.models import RegistrationProfile
                user = RegistrationProfile.objects.create_inactive_user(
                    username, password, email, send_email=True)
            else:
                user = User.objects.create_user(username, email, password)

            user.first_name = first_name
            user.last_name = last_name
            user.save()

            # If the user already has a contact, retrieve it.
            # Otherwise, create a new one.
            contact = Contact.from_request(request, create=False)
            if contact is None:
                contact = Contact()

            contact.user = user
            contact.first_name = first_name
            contact.last_name = last_name
            contact.email = email                
            contact.role = 'Customer'
            contact.save()
            
            if 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 verify:
                user = authenticate(username=username, password=password)
                login(request, user)
                send_welcome_email(email, first_name, last_name)

            if not redirect:
                redirect = urlresolvers.reverse('registration_complete')
            return (True, http.HttpResponseRedirect(redirect))

    else:
        initial_data = {}
        contact = Contact.from_request(request, create=False)
        if contact is not None:
            initial_data = {
                'email': contact.email,
                'first_name': contact.first_name,
                'last_name': contact.last_name}

        if contact and config_get_group('NEWSLETTER'):
            from satchmo.newsletter import is_subscribed
            current_subscriber = is_subscribed(contact)
        else:
            current_subscriber = False

        initial_data['newsletter'] = current_subscriber

        form = RegistrationForm(initial=initial_data)

    return (False, form)
コード例 #33
0
def update(request):
    """Update contact info"""

    init_data = {}
    shop = Config.objects.get_current()

    try:
        contact = Contact.objects.from_request(request, create=False)
    except Contact.DoesNotExist:
        contact = None

    if request.method == "POST":
        new_data = request.POST.copy()
        form = ExtendedContactInfoForm(new_data,
                                       shop=shop,
                                       contact=contact,
                                       shippable=True,
                                       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[CUSTOMER_ID] = custID
            redirect_to = request.REQUEST.get(REDIRECT_FIELD_NAME, '')
            if not redirect_to or '//' in redirect_to or ' ' in redirect_to:
                redirect_to = urlresolvers.reverse('satchmo_account_info')

            return http.HttpResponseRedirect(redirect_to)
        else:
            signals.satchmo_contact_view.send(contact,
                                              contact=contact,
                                              contact_dict=init_data)

    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

        signals.satchmo_contact_view.send(contact,
                                          contact=contact,
                                          contact_dict=init_data)
        form = ExtendedContactInfoForm(shop=shop,
                                       contact=contact,
                                       shippable=True,
                                       initial=init_data)

    init_data['form'] = form
    if shop.in_country_only:
        init_data['country'] = shop.sales_country
    else:
        countries = shop.countries()
        if countries and countries.count() == 1:
            init_data['country'] = countries[0]

    context = RequestContext(request, init_data)

    return render_to_response('contact/update_form.html', context)
コード例 #34
0
ファイル: views.py プロジェクト: abrar78/satchmo
def register_handle_form(request, redirect=None):
    """
    Handle all registration logic.  This is broken out from "register" to allow easy overriding/hooks
    such as a combined login/register page.

    Returns:
    - Success flag
    - HTTPResponseRedirect (success) or form (fail)
    """

    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():

            data = form.cleaned_data
            password = data['password']
            email = data['email']
            first_name = data['first_name']
            last_name = data['last_name']
            username = generate_id(first_name, last_name)

            verify = (config_value('SHOP', 'ACCOUNT_VERIFICATION') == 'EMAIL')
            if verify:
                from registration.models import RegistrationProfile
                user = RegistrationProfile.objects.create_inactive_user(
                    username, password, email, send_email=True)
            else:
                user = User.objects.create_user(username, email, password)

            user.first_name = first_name
            user.last_name = last_name
            user.save()

            # If the user already has a contact, retrieve it.
            # Otherwise, create a new one.
            contact = Contact.from_request(request, create=False)
            if contact is None:
                contact = Contact()

            contact.user = user
            contact.first_name = first_name
            contact.last_name = last_name
            contact.email = email
            contact.role = 'Customer'
            contact.save()

            if 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 verify:
                user = authenticate(username=username, password=password)
                login(request, user)
                send_welcome_email(email, first_name, last_name)

            if not redirect:
                redirect = urlresolvers.reverse('registration_complete')
            return (True, http.HttpResponseRedirect(redirect))

    else:
        initial_data = {}
        contact = Contact.from_request(request, create=False)
        if contact is not None:
            initial_data = {
                'email': contact.email,
                'first_name': contact.first_name,
                'last_name': contact.last_name
            }

        if contact and config_get_group('NEWSLETTER'):
            from satchmo.newsletter import is_subscribed
            current_subscriber = is_subscribed(contact)
        else:
            current_subscriber = False

        initial_data['newsletter'] = current_subscriber

        form = RegistrationForm(initial=initial_data)

    return (False, form)
コード例 #35
0
    def handle_noargs(self, **options):
        from satchmo.contact.models import Contact, AddressBook, PhoneNumber
        from satchmo.product.models import (
            Product,
            Price,
            ConfigurableProduct,
            ProductVariation,
            Category,
            OptionGroup,
            Option,
            ProductImage,
        )  # , DownloadableProduct
        from satchmo.shop.models import Config
        from django.conf import settings
        from satchmo.l10n.models import Country
        from django.contrib.sites.models import Site
        from django.contrib.auth.models import User

        # idempotency test

        print("Checking for existing sample data.")
        try:
            p = Product.objects.get(slug="dj-rocks")
            print(
                "It looks like you already have loaded the sample store data, quitting."
            )
            import sys

            sys.exit(1)
        except Product.DoesNotExist:
            pass

        print("Loading sample store data.")

        # Load basic configuration information

        print("Creating site...")
        try:
            site = Site.objects.get(id=settings.SITE_ID)
            print(("Using existing site #%i" % settings.SITE_ID))
        except Site.DoesNotExist:
            print("Creating Example Store Site")
            site = Site(domain="localhost", name="Sample Store")
        site.domain = settings.SITE_DOMAIN
        site.name = settings.SITE_NAME
        site.save()
        store_country = Country.objects.get(iso3_code="USA")
        config = Config(
            site=site,
            store_name=settings.SITE_NAME,
            no_stock_checkout=True,
            country=store_country,
            sales_country=store_country,
        )
        config.save()
        config.shipping_countries.add(store_country)
        config.save()
        print("Creating Customers...")
        # Import some customers
        c1 = Contact(
            first_name="Chris",
            last_name="Smith",
            email="*****@*****.**",
            role="Customer",
            notes="Really cool stuff",
        )
        c1.save()
        p1 = PhoneNumber(contact=c1, phone="601-555-5511", type="Home", primary=True)
        p1.save()
        c2 = Contact(
            first_name="John",
            last_name="Smith",
            email="*****@*****.**",
            role="Customer",
            notes="Second user",
        )
        c2.save()
        p2 = PhoneNumber(contact=c2, phone="999-555-5111", type="Work", primary=True)
        p2.save()
        # Import some addresses for these customers
        us = Country.objects.get(iso2_code="US")
        a1 = AddressBook(
            description="Home",
            street1="8235 Pike Street",
            city="Anywhere Town",
            state="TN",
            postal_code="38138",
            country=us,
            is_default_shipping=True,
            contact=c1,
        )
        a1.save()
        a2 = AddressBook(
            description="Work",
            street1="1245 Main Street",
            city="Stillwater",
            state="MN",
            postal_code="55082",
            country=us,
            is_default_shipping=True,
            contact=c2,
        )
        a2.save()

        print("Creating Categories...")
        # Create some categories
        cat1 = Category(
            site=site, name="Shirts", slug="shirts", description="Women's Shirts"
        )
        cat1.save()
        cat2 = Category(
            site=site,
            name="Short Sleeve",
            slug="shortsleeve",
            description="Short sleeve shirts",
            parent=cat1,
        )
        cat2.save()
        cat3 = Category(site=site, name="Books", slug="book", description="Books")
        cat3.save()
        cat4 = Category(
            site=site,
            name="Fiction",
            slug="fiction",
            description="Fiction Books",
            parent=cat3,
        )
        cat4.save()
        cat5 = Category(
            site=site,
            name="Science Fiction",
            slug="scifi",
            description="Science Fiction",
            parent=cat4,
        )
        cat5.save()
        cat6 = Category(
            site=site,
            name="Non Fiction",
            slug="nonfiction",
            description="Non Fiction",
            parent=cat3,
        )
        cat6.save()
        cat7 = Category(site=site, name="Software", slug="software")
        cat7.save()

        print("Creating products...")
        # Create some items
        i1 = Product(
            site=site,
            name="Django Rocks shirt",
            slug="dj-rocks",
            description="Really cool shirt",
            active=True,
            featured=True,
        )
        i1.save()
        p1 = Price(price="20.00", product=i1)
        p1.save()
        i1.category.add(cat1)
        i1.save()
        i2 = Product(
            site=site,
            name="Python Rocks shirt",
            slug="PY-Rocks",
            description="Really cool python shirt - One Size Fits All",
            active=True,
            featured=True,
        )
        i2.save()
        p2 = Price(price="19.50", product=i2)
        p2.save()
        i2.category.add(cat2)
        i2.save()
        i3 = Product(
            site=site,
            name="A really neat book",
            slug="neat-book",
            description="A neat book.  You should buy it.",
            active=True,
            featured=True,
        )
        i3.save()
        p3 = Price(price="5.00", product=i3)
        p3.save()
        i3.category.add(cat4)
        i3.save()
        i4 = Product(
            site=site,
            name="Robots Attack!",
            slug="robot-attack",
            description="Robots try to take over the world.",
            active=True,
            featured=True,
        )
        i4.save()
        p4 = Price(price="7.99", product=i4)
        p4.save()
        i4.category.add(cat5)
        i4.save()

        #    i5 = Product(site=site, name="Really Neat Software", slug="neat-software", description="Example Configurable/Downloadable product", active=True, featured=True)
        #    i5.save()
        #    i5.category.add(cat7)
        #    i5.save()

        # Create an attribute set
        optSet1 = OptionGroup(site=site, name="sizes", sort_order=1)
        optSet2 = OptionGroup(site=site, name="colors", sort_order=2)
        optSet1.save()
        optSet2.save()

        optSet3 = OptionGroup(site=site, name="Book type", sort_order=1)
        optSet3.save()

        optSet4 = OptionGroup(site=site, name="Full/Upgrade", sort_order=5)
        optSet4.save()

        optItem1a = Option(name="Small", value="S", sort_order=1, option_group=optSet1)
        optItem1a.save()
        optItem1b = Option(name="Medium", value="M", sort_order=2, option_group=optSet1)
        optItem1b.save()
        optItem1c = Option(
            name="Large",
            value="L",
            sort_order=3,
            price_change="1.00",
            option_group=optSet1,
        )
        optItem1c.save()

        optItem2a = Option(name="Black", value="B", sort_order=1, option_group=optSet2)
        optItem2a.save()
        optItem2b = Option(name="White", value="W", sort_order=2, option_group=optSet2)
        optItem2b.save()
        optItem2c = Option(
            name="Blue",
            value="BL",
            sort_order=3,
            price_change="2.00",
            option_group=optSet2,
        )
        optItem2c.save()

        optItem3a = Option(
            name="Hard cover", value="hard", sort_order=1, option_group=optSet3
        )
        optItem3a.save()
        optItem3b = Option(
            name="Soft cover",
            value="soft",
            sort_order=2,
            price_change="1.00",
            option_group=optSet3,
        )
        optItem3b.save()
        optItem3c = Option(
            name="On tape", value="tape", sort_order=3, option_group=optSet3
        )
        optItem3c.save()

        optItem4a = Option(
            name="Full Version", value="full", option_group=optSet4, sort_order=1
        )
        optItem4a.save()
        optItem4b = Option(
            name="Upgrade Version", value="upgrade", option_group=optSet4, sort_order=2
        )
        optItem4b.save()

        # Add the option group to our items
        pg1 = ConfigurableProduct(product=i1)
        pg1.save()
        pg1.option_group.add(optSet1)
        pg1.save()
        pg1.option_group.add(optSet2)
        pg1.save()

        pg3 = ConfigurableProduct(product=i3)
        pg3.save()
        pg3.option_group.add(optSet3)
        pg3.save()

        pg4 = ConfigurableProduct(product=i4)
        pg4.save()
        pg4.option_group.add(optSet3)
        pg4.save()

        #    pg5 = ConfigurableProduct(product=i5)
        #    pg5.option_group.add(optSet4)
        #    pg5.save()

        print("Creating product variations...")
        # Create the required sub_items
        pg1.create_all_variations()
        pg3.create_all_variations()
        pg4.create_all_variations()
        # pg5.create_all_variations()

        # set prices for full and upgrade versions of neat-software, this is an alternative to using the price_change in options, it allows for more flexability when required.
        #    pv1 = pg5.get_product_from_options([optItem4a])
        #    Price(product=pv1, price='5.00').save()
        #    Price(product=pv1, price='2.00', quantity=50).save()
        #    DownloadableProduct(product=pv1).save()

        #    pv2 = pg5.get_product_from_options([optItem4b])
        #    Price(product=pv2, price='1.00').save()
        #    DownloadableProduct(product=pv2).save()

        print("Create a test user...")
        # First see if our test user is still there, then use or create that user
        try:
            test_user = User.objects.get(username="******")
        except:
            test_user = User.objects.create_user(
                "csmith", "*****@*****.**", "test"
            )
            test_user.save()
        c1.user = test_user
        c1.save()