Esempio n. 1
0
    def send_gear_email(self):
        """Send email for Cristmas calendars."""

        from_email = self.EMAIL_SUMMARY_FROM_FIRST_BAG
        subject = self.EMAIL_SUMMARY_SUBJECT_FIRST_BAG
        template_name = self.EMAIL_SUMMARY_CALENDARS_2017

        now = self.now
        today = '{} {}'.format(
            ordinal(now.day),
            datetime.strftime(now, '%B %Y')
            )

        send_email_async.delay(
            subject=subject,
            template=template_name,
            to_email=self.customer.get_email(),
            from_email=from_email,
            merge_vars={
                'USERNAME': self.customer.first_name,
                'COFFEE': self.order.gear.name,
                'SHIPPING_DATE': today,
                'PACKAGE': '',
                'ADDRESS_NAME': self.order.shipping_address['name'],
                'LINE1': self.order.shipping_address['line1'],
                'COUNTRY_POSTCODE': self.order.shipping_address['postcode'],
                'ESTIMATED_DELIVERY': get_estimated_date(now, 1, 1),
                'ROADBULL_TRACKING_NUMBER': "http://{server}/Order/Tracking/{tracking_number}".format(
                    server=settings.ROADBULL_SERVER, tracking_number=self.order.tracking_number),
                'DOMAIN_NAME': self.request.META.get('HTTP_HOST'),
            },
        )
Esempio n. 2
0
def send_replacement_email(request, order):
    send_email_async.delay(
        subject='Hold on tight! It is coming!',
        template='Your replacement order is on its way to you!',
        to_email=order.customer.get_email(),
        merge_vars={
            'USERNAME': order.customer.first_name,
            'DOMAIN_NAME': request.META.get('HTTP_HOST'),
        })
Esempio n. 3
0
 def form_valid(self, form):
     new_date = datetime.strftime(self.object.shipping_date, '%d of %B, %Y')
     if self.object.is_paused:  # status already updated
         reminder, _ = Reminder.objects.update_or_create(
             order=self.object,
             defaults={
                 'username':
                 self.object.customer.first_name,
                 'email':
                 self.object.customer.user.email,
                 'order':
                 self.object,
                 'from_email':
                 'Hook Coffee <*****@*****.**>',
                 'subject': ('Welcome back! Your paused subscription '
                             'is to be resumed.'),
                 'template_name':
                 'Paused subscription to be resumed',
                 'resumed':
                 self.object.shipping_date,
                 'scheduled':
                 self.object.shipping_date - timedelta(days=3),
                 'completed':
                 False,
             })
         send_email_async.delay(subject='Your subscription has been paused',
                                template='Paused Subscription (done)',
                                to_email=self.object.customer.get_email(),
                                merge_vars={
                                    'USERNAME':
                                    self.object.customer.first_name,
                                    'SHIPPING_DATE':
                                    new_date,
                                    'DOMAIN_NAME':
                                    self.request.META.get('HTTP_HOST'),
                                })
     else:
         (Reminder.objects.filter(email=self.object.customer.get_email(),
                                  order=self.object).update(completed=True))
     return super(PauseOrResumeOrder, self).form_valid(form,
                                                       new_date=new_date)
Esempio n. 4
0
 def _send_email(self, customer, recipient_name, recipient_email, ref_link):
     voucher = ReferralVoucher.objects.create(
         sender=customer,
         recipient_email=recipient_email,
         discount_sgd=12,
         code=ReferralVoucher.get_random_code(size=8),
     )
     send_email_async.delay(
         subject=self.EMAIL_SUBJECT % customer.first_name,
         template=self.EMAIL_TEMPLATE,
         to_email=recipient_email,
         from_email='Sam from Hook Coffee <*****@*****.**>',
         merge_vars={
             'REFNAME': recipient_name or 'there',
             'USERNAME': customer.get_full_name(),
             'LINK': ref_link,
             'VOUCHER': voucher.code,
             'DOMAIN_NAME': self.request.META.get('HTTP_HOST'),
         },
         metadata={'by_customer': customer.get_lower_email()},
     )
Esempio n. 5
0
    def form_valid(self, form):
        if isinstance(self.object, Order) and self.object.recurrent:
            # Mark related to the order reminders as completed
            Reminder.objects.filter(order=self.object).update(completed=True)
            ReminderSkipDelivery.objects.filter(order=self.object).update(
                completed=True)

            sync_cancel_reason.apply_async((
                self.object.customer.id,
                self.object.id,
            ),
                                           countdown=180)  # run in 3 minutes

            send_email_async.delay(subject='We are sorry to see you leave',
                                   template='Cancelled Subscription (done)',
                                   to_email=self.object.customer.get_email(),
                                   merge_vars={
                                       'USERNAME':
                                       self.object.customer.first_name,
                                       'DOMAIN_NAME':
                                       self.request.META.get('HTTP_HOST'),
                                   })
        return super(CancelOrder, self).form_valid(form)
Esempio n. 6
0
    def process_by_charge(self):
        """Charge the customer by using Stripe.

        Customer has not got enought credits to buy out the order.
        """
        try:
            with transaction.atomic():
                if self.customer.amount > 0:
                    self.order.amount -= self.customer.amount
                    self.order.save(update_fields=['amount'])
                    self.customer.amount = 0
                    self.customer.save(update_fields=['amount'])

                self.result['charge'] = stripe.Charge.create(
                    amount=int(round(self.order.amount * 100)),
                    currency='SGD',
                    customer=self.customer.stripe_id,
                    description=str(self.order.coffee),
                    metadata={'order_id': self.order.id},
                )
        except stripe.error.CardError as e:
            self.order.status = Order.DECLINED
            self.order.save(update_fields=['status'])
            self.result['error'] = e.json_body['error'].get('message')
            self.result['declined'] = True
            send_email_async.delay(
                subject=self.EMAIL_DECLINED_SUBJECT,
                template=self.EMAIL_DECLINED_TEMPLATE,
                to_email=self.customer.get_email(),
                merge_vars={
                    'USERNAME': self.customer.first_name,
                    'DOMAIN_NAME': self.request.META.get('HTTP_HOST'),
                }
            )
            self.log_error(e)
        except stripe.error.RateLimitError as e:
            self.result['error'] = (
                'Too many requests made to the API too quickly.')
            self.log_error(e)
        except stripe.error.InvalidRequestError as e:
            self.result['error'] = (
                "Invalid parameters were supplied to Stripe's API.")
            self.log_error(e)
        except stripe.error.AuthenticationError as e:
            self.result['error'] = "Authentication with Stripe's API failed."
            self.log_error(e)
        except stripe.error.APIConnectionError as e:
            self.result['error'] = 'Network communication with Stripe failed.'
            self.log_error(e)
        except stripe.error.StripeError as e:
            self.result['error'] = ('Display a very generic error to the user,'
                                    ' and maybe send yourself an email.')
            self.log_error(e)
        except Exception as e:
            self.order.status = Order.ERROR
            self.order.save(update_fields=['status'])
            self.result['error'] = 'Critical Stripe error: %r' % e
            self.log_error(e)
        else:
            self.order.status = Order.SHIPPED
            self.order.save(update_fields=['status'])
            self.result['processed_by'] = 'card'
Esempio n. 7
0
    def send_summary_email(self):
        """Send summary email.

        Send email if this is not first processed order and not resent,
        otherwise customer has already received "Welcome to hook coffee" email.
        """
        if self.order.resent:
            return

        roasted_at = link_to_skip_delivery = ''
        if self.order.coffee.roasted_on:
            roasted_at = datetime.strftime(self.order.coffee.roasted_on, '%d/%m/%y')

        now = self.now
        today = '{} {}'.format(
            ordinal(now.day),
            datetime.strftime(now, '%B %Y')
            )

        next_delivery_at = datetime.strftime(self.order.get_next_shipping_date(), '%d %B %Y')

        point_obj, _ = Point.objects.get_or_create(
            user=self.customer.user,
            defaults={'points': 0},
        )
        ref_obj, _ = Referral.objects.get_or_create(
            user=self.customer.user,
            defaults={'code': Referral.get_random_code(customer=self.customer)}
        )

        last_bag = bool(self.result.get('processed_by') == 'credits' and
                        self.customer.amount == 0)

        from_email = self.EMAIL_SUMMARY_FROM
        subject = self.EMAIL_SUMMARY_SUBJECT

        if last_bag:
            # if customer has not got credits in his account, send email
            # to inform customer that this would be his last bag of coffee
            template_name = self.EMAIL_SUMMARY_TEMPLATE_LAST_BAG
        elif self.is_first:
            template_name = self.EMAIL_SUMMARY_TEMPLATE_FIRST_BAG
            from_email = self.EMAIL_SUMMARY_FROM_FIRST_BAG
            subject = self.EMAIL_SUMMARY_SUBJECT_FIRST_BAG
        else:
            template_name = self.EMAIL_SUMMARY_TEMPLATE_NORMAL
            # create a link to skip next delivery
            # link_to_skip_delivery = self.create_link_skip_delivery()

        if self.is_shotpods:
            brew = 'Nespresso®'
            package = 'Nespresso® compatible pods'
        else:
            brew = self.order.brew.name
            package = {
                Preferences.GRINDED: "Ground for {}".format(brew),
                Preferences.WHOLEBEANS: "Wholebeans",
                Preferences.DRIP_BAGS: "Drip bags",
            }.get(self.order.package, "Drip bags")

        send_email_async.delay(
            subject=subject,
            template=template_name,
            to_email=self.customer.get_email(),
            from_email=from_email,
            merge_vars={
                'USERNAME': self.customer.first_name,
                'COFFEE': self.order.coffee.name,
                'ROASTED_ON': roasted_at,
                'BREW': brew,
                'PACKAGE': package,
                'PRICE': 'S$ %s' % self.order.amount,
                'SHIPPING_DATE': today,
                'ADDRESS_NAME': self.order.shipping_address['name'],
                'LINE1': self.order.shipping_address['line1'],
                'COUNTRY_POSTCODE': self.order.shipping_address['postcode'],
                'NEXT_DELIVERY': next_delivery_at,
                'POINTS': self.get_number_of_points_for_order(),
                'TOTAL_POINTS': point_obj.points,
                'ESTIMATED_DELIVERY': get_estimated_date(now),
                'REFERRAL_CODE': ref_obj.code,
                # 'LINK_TO_SKIP_DELIVERY': link_to_skip_delivery,
                'DOMAIN_NAME': self.request.META.get('HTTP_HOST'),
            },
        )

        if self.order.recurrent and self.order.interval >= 7:
            template_name = self.EMAIL_REMINDING_TEMPLATE_SKIP_LINK
            if ReminderSkipDelivery.objects.exists():
                if ReminderSkipDelivery.objects.latest('id').id % 2 != 0:
                    template_name = self.EMAIL_REMINDING_TEMPLATE_NO_SKIP_LINK

            ReminderSkipDelivery.objects.create(
                username=self.customer.first_name.title(),
                order=self.new_order,
                email=self.customer.get_email(),
                from_email='Hook Coffee Roastery <*****@*****.**>',
                subject='Your upcoming Hook Coffee Order',
                template_name=template_name,
                created=now,
                scheduled=self.new_order.shipping_date - timedelta(days=4),
            )
Esempio n. 8
0
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)
Esempio n. 9
0
def stripe_send_friend(request):
    context = {
        'success': False,
    }
    token = request.POST['stripeToken']
    recipient = request.POST.get('recipient_name')
    sender_email = request.POST.get('email')
    first_name = request.POST.get('first_name')
    last_name = request.POST.get('last_name')
    credits_amount = request.POST.get('post_credits')
    voucher_code = ReferralVoucher.get_random_code(size=8)

    try:
        charge = stripe.Charge.create(
            amount=int(credits_amount) * 100,
            currency='SGD',
            source=token,
            description='Gift voucher from {} to {}'.format(
                sender_email, recipient))
    except Exception as e:
        raise e
    else:
        GiftVoucher.objects.create(sender_email=sender_email,
                                   sender_fname=first_name,
                                   sender_lname=last_name,
                                   recipient=recipient,
                                   amount=credits_amount,
                                   code=voucher_code)

        # Create a voucher pdf
        static_path = settings.STATIC_PATH
        media_root = settings.MEDIA_ROOT

        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=voucher.pdf'

        font_src = os.path.join(static_path, 'fonts/amatic/Amatic-Bold.ttf')
        pdfmetrics.registerFont(TTFont('Amatic-Bold', font_src))

        font_src = os.path.join(static_path,
                                'fonts/brusher/Brusher-Regular.ttf')
        pdfmetrics.registerFont(TTFont('Brusher-Regular', font_src))

        buffer = StringIO()
        buffer2 = StringIO()

        outfilename = 'voucher_{}.pdf'.format(sender_email)
        outfiledir = os.path.join(media_root, 'gift_vouchers')
        outfilepath = os.path.join(outfiledir, outfilename)

        if not os.path.exists(outfiledir):
            os.makedirs(outfiledir)

        c = canvas.Canvas(buffer)
        c2 = canvas.Canvas(buffer2)

        # c.setLineWidth(.3)
        c.setFont('Amatic-Bold', 60)
        c.drawString(365, 157, '$' + credits_amount)

        c2.setFont('Amatic-Bold', 24)
        c2.drawString(150, 288, voucher_code)

        f_recipient = '{:^12}'.format(recipient)
        if len(recipient) < 9:
            c.setFont('Brusher-Regular', 35)
            c.drawString(75, 250, f_recipient)
        else:
            c.setFont('Brusher-Regular', 28)
            c.drawString(65, 250, f_recipient)

        c.showPage()
        c2.showPage()
        c.save()
        c2.save()

        template_src = os.path.join(static_path, 'vouchers/gift_voucher.pdf')

        page = PdfFileReader(file(template_src, "rb")).getPage(0)
        page2 = PdfFileReader(file(template_src, "rb")).getPage(1)
        overlay = PdfFileReader(StringIO(buffer.getvalue())).getPage(0)
        overlay2 = PdfFileReader(StringIO(buffer2.getvalue())).getPage(0)
        page.mergePage(overlay)
        page2.mergePage(overlay2)

        output = PdfFileWriter()
        output.addPage(page)
        output.addPage(page2)

        output.write(open(outfilepath, 'wb'))

        # Send notification
        send_email_async.delay(
            subject='A Lovely Gift Voucher Within',
            template='Gift Vouchers (done)',
            to_email=sender_email,
            merge_vars={
                'SENDER': first_name,
                'RECEPIENT': recipient,
                'AMOUNT': credits_amount,
                'DOMAIN_NAME': request.META.get('HTTP_HOST'),
            },
            attachments=[(outfilename, outfilepath, 'application/pdf')],
        )

        context = {
            'success': True,
        }

    return context