Manage Stripe customers from the User model

This commit is contained in:
2022-07-21 13:48:14 +01:00
parent 4234669ad9
commit e0390f383c
2 changed files with 83 additions and 1 deletions

View File

@@ -1,7 +1,7 @@
from django.contrib.auth.models import AbstractUser
from django.db import models
# Create your models here.
from core.lib.customers import get_or_create, update_customer_fields
class Plan(models.Model):
@@ -24,6 +24,30 @@ class User(AbstractUser):
paid = models.BooleanField(null=True, blank=True)
plans = models.ManyToManyField(Plan, blank=True)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._original = self
def save(self, *args, **kwargs):
"""
Override the save function to create a Stripe customer.
"""
if not self.stripe_id: # stripe ID not stored
self.stripe_id = get_or_create(self.email, self.first_name, self.last_name)
to_update = {}
if self.email != self._original.email:
to_update["email"] = self.email
if self.first_name != self._original.first_name:
to_update["first_name"] = self.first_name
if self.last_name != self._original.last_name:
to_update["last_name"] = self.last_name
update_customer_fields(self.stripe_id, **to_update)
super().save(*args, **kwargs)
def has_plan(self, plan):
if not self.paid: # We can't have any plans if we haven't paid
return False