Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: add support for discounts #321

Open
wants to merge 2 commits into
base: original
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 28 additions & 8 deletions pinax/stripe/actions/customers.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ def can_charge(customer):
return False


def create(user, card=None, plan=settings.PINAX_STRIPE_DEFAULT_PLAN, charge_immediately=True, quantity=None):
default_plan = settings.PINAX_STRIPE_DEFAULT_PLAN


def create(user, card=None, plan=default_plan, charge_immediately=True, quantity=None, coupon=None):
"""
Creates a Stripe customer.

Expand All @@ -46,13 +49,15 @@ def create(user, card=None, plan=settings.PINAX_STRIPE_DEFAULT_PLAN, charge_imme
"""
trial_end = hooks.hookset.trial_period(user, plan)

stripe_customer = stripe.Customer.create(
email=user.email,
source=card,
plan=plan,
quantity=quantity,
trial_end=trial_end
)
kwargs = {
'email': user.email,
'source': card,
'plan': plan,
'trial_end': trial_end,
}
if coupon:
kwargs.update({'coupon': coupon})
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is similar to a change I've got in my PR.

Perhaps we'd both benefit from all kwargs from this function being passed into stripe.Customer.create...

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agreed, although the main purpose of the PR is to support discount syncing on customer and subscription models.

stripe_customer = stripe.Customer.create(**kwargs)
try:
with transaction.atomic():
cus = models.Customer.objects.create(
Expand Down Expand Up @@ -158,6 +163,21 @@ def sync_customer(customer, cu=None):
customer.delinquent = cu["delinquent"]
customer.default_source = cu["default_source"] or ""
customer.save()
if cu.get("discount", None):
try:
coupon = models.Coupon.objects.get(stripe_id=cu["discount"]["coupon"]["id"])
except models.Coupon.DoesNotExist:
raise models.Coupon.DoesNotExist("Sync coupons before syncing customers.")
start = utils.convert_tstamp(cu["discount"]["start"])
end = utils.convert_tstamp(cu["discount"]["end"])
if models.Discount.objects.filter(customer=customer).exists():
discount = models.Discount.objects.get(customer=customer)
discount.coupon = coupon
discount.start = start
discount.end = end
discount.save()
else:
models.Discount.objects.create(customer=customer, coupon=coupon, start=start, end=end)
for source in cu["sources"]["data"]:
sources.sync_payment_source_from_stripe_data(customer, source)
for subscription in cu["subscriptions"]["data"]:
Expand Down
23 changes: 21 additions & 2 deletions pinax/stripe/actions/subscriptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,17 +161,33 @@ def sync_subscription_from_stripe_data(customer, subscription):
start=utils.convert_tstamp(subscription["start"]),
status=subscription["status"],
trial_start=utils.convert_tstamp(subscription["trial_start"]) if subscription["trial_start"] else None,
trial_end=utils.convert_tstamp(subscription["trial_end"]) if subscription["trial_end"] else None
trial_end=utils.convert_tstamp(subscription["trial_end"]) if subscription["trial_end"] else None,
)
sub, created = models.Subscription.objects.get_or_create(
stripe_id=subscription["id"],
defaults=defaults
)
sub = utils.update_with_defaults(sub, defaults, created)
if subscription.get("discount", None):
start = utils.convert_tstamp(subscription["discount"]["start"])
end = utils.convert_tstamp(subscription["discount"]["end"]) if subscription["discount"]["end"] else None
try:
coupon = models.Coupon.objects.get(stripe_id=subscription["discount"]["coupon"]["id"])
except models.Coupon.DoesNotExist:
raise models.Coupon.DoesNotExist("Sync coupons before syncing subscriptions.")
if models.Discount.objects.filter(subscription=sub).exists():
discount = models.Discount.objects.get(subscription=sub)
discount.coupon = coupon
discount.start = start
discount.end = end
discount.save()
else:
models.Discount.objects.create(subscription=sub, coupon=coupon, start=start, end=end)
return sub


def update(subscription, plan=None, quantity=None, prorate=True, coupon=None, charge_immediately=False):
def update(subscription, plan=None, quantity=None, prorate=True, coupon=None, charge_immediately=False,
trial_days=None):
"""
Updates a subscription

Expand All @@ -182,8 +198,11 @@ def update(subscription, plan=None, quantity=None, prorate=True, coupon=None, ch
prorate: optionally, if the subscription should be prorated or not
coupon: optionally, a coupon to apply to the subscription
charge_immediately: optionally, whether or not to charge immediately
trial_days: optionally, number of days to pause billing
"""
stripe_subscription = subscription.stripe_subscription
if trial_days:
stripe_subscription.trial_end = datetime.datetime.utcnow() + datetime.timedelta(days=trial_days)
if plan:
stripe_subscription.plan = plan
if quantity:
Expand Down
47 changes: 47 additions & 0 deletions pinax/stripe/migrations/0009_discount.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone


class Migration(migrations.Migration):

dependencies = [
('pinax_stripe', '0008_auto_20170509_1736'),
]

operations = [
migrations.CreateModel(
name='Discount',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('start', models.DateTimeField(null=True)),
('end', models.DateTimeField(null=True)),
],
options={
'abstract': False,
},
),
migrations.AlterField(
model_name='coupon',
name='duration',
field=models.CharField(choices=[('forever', 'forever'), ('once', 'once'), ('repeating', 'repeating')], default='once', max_length=10),
),
migrations.AddField(
model_name='discount',
name='coupon',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='pinax_stripe.Coupon'),
),
migrations.AddField(
model_name='discount',
name='customer',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='pinax_stripe.Customer'),
),
migrations.AddField(
model_name='discount',
name='subscription',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='pinax_stripe.Subscription'),
),
]
34 changes: 32 additions & 2 deletions pinax/stripe/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,15 @@ def __str__(self):
@python_2_unicode_compatible
class Coupon(StripeObject):

DURATION_CHOICES = (
('forever', 'forever'),
('once', 'once'),
('repeating', 'repeating'),
)

amount_off = models.DecimalField(decimal_places=2, max_digits=9, null=True)
currency = models.CharField(max_length=10, default="usd")
duration = models.CharField(max_length=10, default="once")
duration = models.CharField(max_length=10, default="once", choices=DURATION_CHOICES)
duration_in_months = models.PositiveIntegerField(null=True)
livemode = models.BooleanField(default=False)
max_redemptions = models.PositiveIntegerField(null=True)
Expand Down Expand Up @@ -138,6 +144,27 @@ def __str__(self):
return str(self.user)


@python_2_unicode_compatible
class Discount(models.Model):

coupon = models.ForeignKey("Coupon", on_delete=models.CASCADE)
customer = models.OneToOneField("Customer", null=True, on_delete=models.CASCADE)
subscription = models.OneToOneField("Subscription", null=True, on_delete=models.CASCADE)
start = models.DateTimeField(null=True)
end = models.DateTimeField(null=True)

def __str__(self):
return "<coupon={}, customer={}, subscription={}>".format(self.coupon, self.customer, self.subscription)

def apply_discount(self, amount):
if self.end is not None and self.end > timezone.now():
return amount
if self.coupon.amount_off:
return decimal.Decimal(amount - self.coupon.amount_off)
elif self.coupon.percent_off:
return decimal.Decimal('{:.2f}'.format(amount - (decimal.Decimal(self.coupon.percent_off) / 100 * amount)))


class Card(StripeObject):

customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
Expand Down Expand Up @@ -204,7 +231,10 @@ def stripe_subscription(self):

@property
def total_amount(self):
return self.plan.amount * self.quantity
total_amount = self.plan.amount * self.quantity
if hasattr(self, 'discount'):
total_amount = self.discount.apply_discount(total_amount)
return total_amount

def plan_display(self):
return self.plan.name
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@
],
install_requires=[
"django-appconf>=1.0.1",
"jsonfield>=1.0.3,<2.0.0",
"jsonfield>=2.0.0",
"stripe>=1.7.9",
"django>=1.7",
"pytz",
Expand Down