コード例 #1
0
 def save(self, commit=True):
     coffee = self.cleaned_data['coffee']
     self.instance.recurrent = True
     self.instance.amount = coffee.amount
     self.instance.shipping_date = get_shipping_date()
     if self.instance.coffee.is_pods:
         self.request.session['active_tab'] = "active_subscriptions_pods"
     elif self.instance.coffee.is_bottled():
         self.request.session['active_tab'] = "active_subscriptions_bottled"
     else:
         self.request.session['active_tab'] = "active_subscriptions"
     return super(CreateOrderForm, self).save(commit)
コード例 #2
0
ファイル: views.py プロジェクト: ajajul/ReactJS_Python
 def get_form_kwargs(self):
     kwargs = super(PauseOrResumeOrder, self).get_form_kwargs()
     if self.object.is_paused:
         new_status = self.model.ACTIVE
         shipping_date = get_shipping_date()
     else:
         new_status = self.model.PAUSED
         shipping_date = self.object.shipping_date + timedelta(days=28)
     kwargs.update(
         {'data': {
             'status': new_status,
             'shipping_date': shipping_date,
         }})
     return kwargs
コード例 #3
0
    def redem_item(self, user, item):
        """Redem item"""

        point = Point.objects.get(user=user)
        print 'User has had ', point.points, ' points'

        redem_item = RedemItem(user=user,
                               item=item,
                               points=item.points,
                               shipping_date=get_shipping_date())
        redem_item.save()
        print 'Redeem item is ', redem_item.item

        point.points -= item.points
        point.save()

        RedemPointLog.objects.create(user=user,
                                     item=item,
                                     points=redem_item.points)

        return redem_item
コード例 #4
0
ファイル: taster.py プロジェクト: ajajul/ReactJS_Python
def taster5x(request):
    result = context = {}

    if request.method == "POST":

        if 'one-password1' in request.POST:
            rf = CustomRegistrationForm(request.POST, prefix='one')

            if rf.is_valid():
                result['success'] = True

                request.session['email'] = rf.cleaned_data['email']
                request.session['password'] = request.POST['one-password1']

                mailchimp_subscribe.delay(email=request.session.get('email'))
            else:
                errors = rf.errors
                return HttpResponse(json.dumps(errors))

        if 'two-first_name' in request.POST:
            cf = GS_CustomerForm(request.POST, prefix='two')
            pf = GS_PreferencesForm(request.POST, prefix='tri')

            if cf.is_valid():
                result['success'] = True

                request.session['first_name'] = request.POST['two-first_name']
                request.session['last_name'] = request.POST['two-last_name']
                request.session['line1'] = request.POST['two-line1']
                request.session['line2'] = request.POST['two-line2']
                request.session['postcode'] = request.POST['two-postcode']

                mailchimp_subscribe.delay(
                    email=request.session.get('email'),
                    merge_vars={
                        'FNAME': request.session.get('first_name'),
                        'LNAME': request.session.get('last_name'),
                    },
                )

            else:
                errors = cf.errors
                return HttpResponse(json.dumps(errors))

        if 'stripeToken' in request.POST:
            try:
                user = MyUser(email=request.session['email'])
                user.set_password(request.session['password'])
                user.save()
            except Exception as e:
                print e

            try:
                customer = Customer(
                    user=user,
                    first_name=request.session['first_name'],
                    last_name=request.session['last_name'],
                    line1=request.session['line1'],
                    line2=request.session['line2'],
                    postcode=request.session['postcode'],
                    stripe_id=request.session['stripe_id']
                    )
                customer.save()
                add_event.delay(
                    customer_id=customer.id,
                    event='signed-up',
                    data={'taster5x': True})

            except Exception as e:
                print e

            random_coffee = CoffeeType.objects.bags().filter(
                special=False).first()
            preferences = Preferences(
                customer=customer,
                coffee=random_coffee,
                brew=BrewMethod.objects.get(name_en='None'),
                package=Preferences.DRIP_BAGS
                )
            preferences.save()

            taster5x = CoffeeType.objects.get(name='Taster 5x')

            try:
                voucher = Voucher.objects.get(name='Taster 5x')
                voucher.count += 1
                voucher.save()
            except:
                voucher = Voucher(
                    name='Taster 5x',
                    discount=0,
                    count=1
                    )
                voucher.save()

            try:
                order = Order.objects.create(
                    customer=customer,
                    coffee=taster5x,
                    date=timezone.now(),
                    shipping_date=get_shipping_date(),
                    amount=taster5x.amount,
                    status=Order.ACTIVE,
                    brew=preferences.brew,
                    package=preferences.package,
                    interval=0,
                    voucher=voucher
                )
                add_event.delay(
                    customer_id=customer.id,
                    event='created-taster5x',
                    order_id=order.id)
            except Exception as e:
                print e

            new_user = authenticate(email=user.email,
                password=request.session['password'])
            login(request, new_user)

            context = {
                'coffee': taster5x.name,
                'image': taster5x.img.url,
            }

            # Send reminding email in a week
            ctz = timezone.get_current_timezone()
            now = ctz.normalize(timezone.now())

            # If there are other reminders (for example from Gets Started)
            # mark they as completed
            Reminder.objects.filter(email=user.email).update(completed=True)
            # Send email in a week if taster pack
            Reminder.objects.create(
                username=customer.first_name,
                email=customer.user.email,
                from_email='Hook Coffee <*****@*****.**>',
                subject='Which was your favourite?',
                template_name='Which was your favourite?',
                scheduled=now + timedelta(days=7),
            )

            # Send summary email
            send_email_async.delay(
                subject='Welcome on board!',
                template='O1 - First order on a subscription (done)',
                to_email=customer.get_email(),
                from_email='Ernest from Hook Coffee <*****@*****.**>',
                merge_vars={
                    'USERNAME': customer.first_name,
                    'DOMAIN_NAME': request.META.get('HTTP_HOST'),
                }
            )
            return render(request, 'get_started/thankyou-trial.html', context)

        return result

    else:
        rf = CustomRegistrationForm(prefix='one')
        cf = GS_CustomerForm(prefix='two')
        pf = GS_PreferencesForm(prefix='tri')

        context['reg_form'] = rf
        context['cus_form'] = cf
        context['pre_form'] = pf
        context['stripe_key'] = settings.PUBLISHABLE_KEY

    return render(request, 'taster/taster5x.html', context)
コード例 #5
0
ファイル: views.py プロジェクト: ajajul/ReactJS_Python
def buy_gear(request, is_worldwide):
    gear_id = request.POST.get('gear-id')
    address_id = request.POST.get('address-id')
    note = request.POST.get('note')
    chosen_date = request.POST.get('chosen_date')
    chosen_date = datetime.strptime(chosen_date, '%d/%m/%Y')

    gear_color_id = request.POST.get('gear-color-id', 0)
    quantity = request.POST.get('quantity', 1)
    packaging = request.POST.get('packaging', 0)
    brew_method_id = request.POST.get('brew-method-id', 0)
    voucher_name = (request.session.get('voucher-name')
                    or request.POST.get('voucher-name'))

    f = forms.IntegerField()
    fch = forms.CharField()

    gear_id = f.clean(gear_id)
    gear_color_id = f.clean(gear_color_id)
    quantity = f.clean(quantity)
    packaging = f.clean(packaging)
    brew_method_id = f.clean(brew_method_id)
    voucher = None
    if voucher_name:
        voucher_name = fch.clean(voucher_name)
        voucher_name = voucher_name.strip().upper()
        try:
            voucher = (Voucher.objects.filter(
                mode=True, category__name='GiftSets').get(name=voucher_name))
        except Voucher.DoesNotExist:
            pass
        else:
            request.session['gear_voucher'] = voucher.name

    details = {}
    if gear_color_id:
        color = CoffeeGearColor.objects.get(id=gear_color_id)
        details['Colour'] = color.name

    if quantity < 1:  # shit happens, right?
        quantity = 1
    details['Quantity'] = str(quantity)

    if packaging:
        packaging = 'Wholebeans' if packaging == 1 else 'Ground'
        request.session['gear_packaging'] = details['packaging'] = packaging

    if brew_method_id:
        brew_method = BrewMethod.objects.get(id=brew_method_id)
        request.session['gear_brew_method'] = details[
            'brew_method'] = brew_method.name_en

    if not request.user.is_authenticated:
        return redirect(
            'preregister_gear',
            gear_id=gear_id,
            gear_qty=quantity,
            gear_color_id=gear_color_id,
        )

    customer = Customer.objects.get(user=request.user)
    gear = CoffeeGear.objects.get(id=gear_id)

    # now = timezone.now()
    # if (now.month == 1 and now.day < 9):
    #     details['Pre-Order'] = 'True'
    #     shipping_date = datetime(
    #         2017, 1, 9,
    #         hour=12, minute=0, second=0, microsecond=0,
    #         tzinfo=timezone.get_current_timezone())
    # else:
    #     shipping_date = get_shipping_date()

    price = gear.price * quantity
    if voucher:
        price -= price * voucher.discount / 100 + voucher.discount2
        # Mark voucher as used for current customer
        customer.vouchers.add(voucher)
        customer.save()
        voucher.count += 1
        voucher.save()

    # charge global users immediately
    # context = {}
    # if is_worldwide:
    #     get_shipping_rates(request, cid=customer.country.code, gear_id=gear.id, qty=quantity)
    #     shipping_cost = request.session.get('shipping_cost', 0)
    #     total_price = float(price) + shipping_cost
    #     context = charge_client(request, customer.stripe_id, total_price)

    context = charge_client(request, customer.stripe_id, price)
    if not context.get('error'):
        order = GearOrder.objects.create(
            customer=customer,
            gear=gear,
            shipping_date=chosen_date or get_shipping_date(),
            price=price,
            details=details,
            voucher=voucher,
        )

        try:
            address = Address.objects.get(id=address_id)
        except Address.DoesNotExist:
            pass
        else:
            order.address = address
            order.save()

        if note:
            order.details['gift_note'] = note
            order.save()

        request.session['new_purchase_amount'] = float(order.price)
    else:
        # TODO: show error to user
        pass

    request.session['active_tab'] = 'active_one_offs'

    return redirect('profile')
コード例 #6
0
ファイル: views.py プロジェクト: ajajul/ReactJS_Python
def detail(request, coffee_id):
    if request.method == 'POST':
        print 'detail, POST =', request.POST.items()
        coffee_id = request.POST.get('coffee-id')

        try:
            coffee = CoffeeType.objects.get(id=coffee_id)
            customer = request.user.customer
            preferences = customer.preferences
        except:
            coffee = customer = preferences = None

        if 'one-off' in request.POST:
            if coffee:

                if not request.POST.get('isNespresso'):
                    selected_brew = BrewMethod.objects.get(
                        id=request.POST.get('brew-method'))
                    selected_package = request.POST.get('package-method', )
                else:
                    selected_brew = BrewMethod.objects.get(name_en='Nespresso')
                    selected_package = Preferences.DRIP_BAGS

                order = Order.objects.create(
                    customer=customer,
                    coffee=coffee,
                    date=timezone.now(),
                    shipping_date=get_shipping_date(),
                    amount=coffee.amount_one_off,
                    interval=0,
                    recurrent=False,
                    status=Order.ACTIVE,
                    brew=selected_brew,
                    package=selected_package,
                )

                mailing_list.update_mailchimp_tracking(
                    request, order, MailchimpCampaignStats.PURCHASED)

                request.session['active_tab'] = 'active_one_offs'

                new_purchase_amount = float(order.amount)
                request.session['new_purchase_amount'] = new_purchase_amount

                add_event.delay(customer_id=order.customer.id,
                                event='created-one-off',
                                order_id=order.id)

        if 'subscription' in request.POST:
            if preferences and coffee:
                if request.POST.get('isNespresso') == 'False':
                    request.session['active_tab'] = 'active_subscriptions'
                    brew = preferences.brew or BrewMethod.objects.get(
                        name_en='Espresso')
                else:
                    request.session['active_tab'] = 'active_subscriptions_pods'
                    brew = BrewMethod.objects.get(name_en='Nespresso')

                order = Order.objects.create(
                    customer=customer,
                    coffee=coffee,
                    date=timezone.now(),
                    shipping_date=get_shipping_date(),
                    amount=coffee.amount,
                    interval=get_interval(preferences.interval),
                    recurrent=True,
                    status=Order.ACTIVE,
                    brew=brew,
                    package=preferences.package,
                    different=preferences.different,
                )

                mailing_list.update_mailchimp_tracking(
                    request, order, MailchimpCampaignStats.PURCHASED)

                add_event.delay(customer_id=order.customer.id,
                                event='created-subscription',
                                order_id=order.id)

                Reminder.objects.filter(email=customer.user.email,
                                        resumed=None).update(completed=True)

        return redirect('profile')

    else:
        customer = Customer.objects.get(user=request.user)
        preferences = customer.preferences

        subscribe = True
        if request.GET.get('subscribe'):
            if request.GET['subscribe'] == '0':
                subscribe = False

        isNespresso = True
        if request.GET.get('isNespresso'):
            if request.GET['isNespresso'] == '0':
                isNespresso = False

        context = {
            'key': settings.PUBLISHABLE_KEY,
            'coffee': CoffeeType.objects.get(id=coffee_id),
            'subscribe': subscribe,
            'isNespresso': isNespresso,
        }

        context['brew_methods'] = BrewMethod.objects.sorted(~Q(
            name_en='Nespresso'))
        context['preferences_form'] = PreferencesForm()

        # Need to clean up
        context['current_brew'] = preferences.brew or BrewMethod.objects.get(
            name_en="None")
        context['current_package'] = preferences.package

        return render(request, 'coffees/detail.html', context)