aboutsummaryrefslogtreecommitdiffstats
path: root/pyblackbird_cc/payments
diff options
context:
space:
mode:
authorMatthew Lemon <y@yulqen.org>2024-09-08 13:59:10 +0100
committerMatthew Lemon <y@yulqen.org>2024-09-08 13:59:10 +0100
commitdb531eaa027d2abcfcceabfef4b8aa9dc5ca1e5d (patch)
tree47dc0044d1a50c8ffbe689ab9f09ed3bda296ae8 /pyblackbird_cc/payments
parent50c7d5b46a9e25390ab4c4ff5dcb944a12df2bef (diff)
wip: implementing checkout
- also some formatting changes
Diffstat (limited to 'pyblackbird_cc/payments')
-rw-r--r--pyblackbird_cc/payments/__init__.py0
-rw-r--r--pyblackbird_cc/payments/admin.py33
-rw-r--r--pyblackbird_cc/payments/apps.py6
-rw-r--r--pyblackbird_cc/payments/migrations/0001_initial.py103
-rw-r--r--pyblackbird_cc/payments/migrations/0002_subscriptionplan_and_more.py36
-rw-r--r--pyblackbird_cc/payments/migrations/0003_product_price.py53
-rw-r--r--pyblackbird_cc/payments/migrations/0004_rename_stripe_product_id_price_stripe_price_id.py18
-rw-r--r--pyblackbird_cc/payments/migrations/__init__.py0
-rw-r--r--pyblackbird_cc/payments/models.py61
-rw-r--r--pyblackbird_cc/payments/tests.py3
-rw-r--r--pyblackbird_cc/payments/urls.py17
-rw-r--r--pyblackbird_cc/payments/views.py85
12 files changed, 415 insertions, 0 deletions
diff --git a/pyblackbird_cc/payments/__init__.py b/pyblackbird_cc/payments/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/pyblackbird_cc/payments/__init__.py
diff --git a/pyblackbird_cc/payments/admin.py b/pyblackbird_cc/payments/admin.py
new file mode 100644
index 0000000..526a1f0
--- /dev/null
+++ b/pyblackbird_cc/payments/admin.py
@@ -0,0 +1,33 @@
+from django.contrib import admin
+
+from .models import ShoppingCart, CartItem, Subscription, SubscriptionPlan, Product, Price
+
+
+class PriceInlineAdmin(admin.TabularInline):
+ model = Price
+ extra = 0
+
+class ProductAdmin(admin.ModelAdmin):
+ inlines = [PriceInlineAdmin]
+
+class SubscriptionPlanAdmin(admin.ModelAdmin):
+ list_display = ('name', 'price', 'description', 'allowed_downloads')
+
+
+class ShoppingCartAdmin(admin.ModelAdmin):
+ list_display = ('user', 'created_at', 'updated_at')
+
+
+class CartItemAdmin(admin.ModelAdmin):
+ list_display = ('cart', 'resource', 'quantity', 'added_at')
+
+
+class SubscriptionAdmin(admin.ModelAdmin):
+ list_display = ('user', 'is_active', 'start_date', 'end_date')
+
+
+admin.site.register(Product, ProductAdmin)
+admin.site.register(SubscriptionPlan)
+admin.site.register(ShoppingCart)
+admin.site.register(CartItem)
+admin.site.register(Subscription)
diff --git a/pyblackbird_cc/payments/apps.py b/pyblackbird_cc/payments/apps.py
new file mode 100644
index 0000000..99c845f
--- /dev/null
+++ b/pyblackbird_cc/payments/apps.py
@@ -0,0 +1,6 @@
+from django.apps import AppConfig
+
+
+class PaymentsConfig(AppConfig):
+ default_auto_field = "django.db.models.BigAutoField"
+ name = "pyblackbird_cc.payments"
diff --git a/pyblackbird_cc/payments/migrations/0001_initial.py b/pyblackbird_cc/payments/migrations/0001_initial.py
new file mode 100644
index 0000000..33b7602
--- /dev/null
+++ b/pyblackbird_cc/payments/migrations/0001_initial.py
@@ -0,0 +1,103 @@
+# Generated by Django 5.0.4 on 2024-09-03 19:21
+
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ ("resources", "0019_alter_pdfpagesnapshot_options_and_more"),
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ShoppingCart",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ("updated_at", models.DateTimeField(auto_now=True)),
+ (
+ "user",
+ models.OneToOneField(
+ on_delete=django.db.models.deletion.CASCADE,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ ),
+ migrations.CreateModel(
+ name="Subscription",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("is_active", models.BooleanField(default=False)),
+ ("start_date", models.DateTimeField(blank=True, null=True)),
+ ("end_date", models.DateTimeField(blank=True, null=True)),
+ (
+ "stripe_subscription_id",
+ models.CharField(blank=True, max_length=255, null=True),
+ ),
+ (
+ "user",
+ models.OneToOneField(
+ on_delete=django.db.models.deletion.CASCADE,
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ ],
+ ),
+ migrations.CreateModel(
+ name="CartItem",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("quantity", models.PositiveIntegerField(default=1)),
+ ("added_at", models.DateTimeField(auto_now_add=True)),
+ (
+ "resource",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ to="resources.resource",
+ ),
+ ),
+ (
+ "cart",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="items",
+ to="payments.shoppingcart",
+ ),
+ ),
+ ],
+ options={
+ "unique_together": {("cart", "resource")},
+ },
+ ),
+ ]
diff --git a/pyblackbird_cc/payments/migrations/0002_subscriptionplan_and_more.py b/pyblackbird_cc/payments/migrations/0002_subscriptionplan_and_more.py
new file mode 100644
index 0000000..cab49b5
--- /dev/null
+++ b/pyblackbird_cc/payments/migrations/0002_subscriptionplan_and_more.py
@@ -0,0 +1,36 @@
+# Generated by Django 5.0.4 on 2024-09-03 19:32
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("payments", "0001_initial"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="SubscriptionPlan",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(max_length=255)),
+ ("price", models.DecimalField(decimal_places=2, max_digits=6)),
+ ("description", models.TextField()),
+ ("allowed_downloads", models.PositiveIntegerField()),
+ ("stripe_plan_id", models.CharField(max_length=255)),
+ ],
+ ),
+ migrations.RemoveField(
+ model_name="subscription",
+ name="stripe_subscription_id",
+ ),
+ ]
diff --git a/pyblackbird_cc/payments/migrations/0003_product_price.py b/pyblackbird_cc/payments/migrations/0003_product_price.py
new file mode 100644
index 0000000..b12d5dc
--- /dev/null
+++ b/pyblackbird_cc/payments/migrations/0003_product_price.py
@@ -0,0 +1,53 @@
+# Generated by Django 5.0.4 on 2024-09-04 19:01
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("payments", "0002_subscriptionplan_and_more"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="Product",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("name", models.CharField(max_length=255)),
+ ("stripe_product_id", models.CharField(max_length=100)),
+ ],
+ ),
+ migrations.CreateModel(
+ name="Price",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("price", models.IntegerField(default=0)),
+ ("stripe_product_id", models.CharField(max_length=100)),
+ (
+ "product",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ to="payments.product",
+ ),
+ ),
+ ],
+ ),
+ ]
diff --git a/pyblackbird_cc/payments/migrations/0004_rename_stripe_product_id_price_stripe_price_id.py b/pyblackbird_cc/payments/migrations/0004_rename_stripe_product_id_price_stripe_price_id.py
new file mode 100644
index 0000000..e5a339f
--- /dev/null
+++ b/pyblackbird_cc/payments/migrations/0004_rename_stripe_product_id_price_stripe_price_id.py
@@ -0,0 +1,18 @@
+# Generated by Django 5.0.4 on 2024-09-04 19:17
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("payments", "0003_product_price"),
+ ]
+
+ operations = [
+ migrations.RenameField(
+ model_name="price",
+ old_name="stripe_product_id",
+ new_name="stripe_price_id",
+ ),
+ ]
diff --git a/pyblackbird_cc/payments/migrations/__init__.py b/pyblackbird_cc/payments/migrations/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/pyblackbird_cc/payments/migrations/__init__.py
diff --git a/pyblackbird_cc/payments/models.py b/pyblackbird_cc/payments/models.py
new file mode 100644
index 0000000..2b66c14
--- /dev/null
+++ b/pyblackbird_cc/payments/models.py
@@ -0,0 +1,61 @@
+from django.conf import settings
+from django.db import models
+
+from pyblackbird_cc.resources.models import Resource
+
+
+class Product(models.Model):
+ name = models.CharField(max_length=255)
+ stripe_product_id = models.CharField(max_length=100)
+
+
+class Price(models.Model):
+ product = models.ForeignKey(Product, on_delete=models.CASCADE)
+ price = models.IntegerField(default=0)
+ stripe_price_id = models.CharField(max_length=100)
+
+ def get_display_price(self):
+ return "{0:.2f}".format(self.price / 100)
+
+
+class ShoppingCart(models.Model):
+ user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
+ created_at = models.DateTimeField(auto_now_add=True)
+ updated_at = models.DateTimeField(auto_now=True)
+
+ def __str__(self):
+ return f"Shopping Cart for {self.user.username}"
+
+
+class CartItem(models.Model):
+ cart = models.ForeignKey(ShoppingCart, on_delete=models.CASCADE, related_name="items")
+ resource = models.ForeignKey(Resource, on_delete=models.CASCADE)
+ quantity = models.PositiveIntegerField(default=1)
+ added_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ unique_together = ("cart", "resource")
+
+ def __str__(self):
+ return f"{self.quantity} of {self.resource.name} in {self.cart.user.username}'s cart"
+
+ def get_total_price(self):
+ return self.quantity * self.resource.price
+
+
+class SubscriptionPlan(models.Model):
+ name = models.CharField(max_length=255)
+ price = models.DecimalField(max_digits=6, decimal_places=2)
+ description = models.TextField()
+ allowed_downloads = models.PositiveIntegerField()
+ stripe_plan_id = models.CharField(max_length=255)
+
+
+class Subscription(models.Model):
+ user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
+ is_active = models.BooleanField(default=False)
+ start_date = models.DateTimeField(null=True, blank=True)
+ end_date = models.DateTimeField(null=True, blank=True)
+
+ def __str__(self):
+ return f"Subscription for {self.user.username}"
diff --git a/pyblackbird_cc/payments/tests.py b/pyblackbird_cc/payments/tests.py
new file mode 100644
index 0000000..7ce503c
--- /dev/null
+++ b/pyblackbird_cc/payments/tests.py
@@ -0,0 +1,3 @@
+from django.test import TestCase
+
+# Create your tests here.
diff --git a/pyblackbird_cc/payments/urls.py b/pyblackbird_cc/payments/urls.py
new file mode 100644
index 0000000..dcfe3dc
--- /dev/null
+++ b/pyblackbird_cc/payments/urls.py
@@ -0,0 +1,17 @@
+from django.urls import path
+
+from . import views
+from .views import CancelView, SuccessView
+
+app_name = "payments"
+
+urlpatterns = [
+ # path("checkout/", views.checkout, name="checkout"),
+ # path("cart/", views.cart_detail, name="cart_detail"),
+ path("success/", SuccessView.as_view(), name="success"),
+ path("cancel/", CancelView.as_view(), name="cancel"),
+ path("create-checkout-session/<int:pk>/", views.CreateCheckoutSessionView.as_view(),
+ name="create-checkout-session"),
+ path("landing/", views.ProductLandingPageView.as_view(), name="landing"),
+ # path("webhook/", views.webhook, name="webhook"),
+]
diff --git a/pyblackbird_cc/payments/views.py b/pyblackbird_cc/payments/views.py
new file mode 100644
index 0000000..2e53af8
--- /dev/null
+++ b/pyblackbird_cc/payments/views.py
@@ -0,0 +1,85 @@
+import stripe
+from django.conf import settings
+from django.contrib.auth.decorators import login_required
+from django.shortcuts import get_object_or_404
+from django.shortcuts import render, redirect
+from django.views import View
+from django.views.generic import TemplateView
+
+from pyblackbird_cc.resources.models import Resource
+from .models import ShoppingCart, CartItem, Price, Product
+
+stripe.api_key = settings.STRIPE_SECRET_KEY
+
+
+class CreateCheckoutSessionView(View):
+ def post(self, request, *args, **kwargs):
+ price = Price.objects.get(id=self.kwargs["pk"])
+ domain = "http://localhost:8000"
+ checkout_session = stripe.checkout.Session.create(
+ payment_method_types=["card"],
+ line_items=[
+ {
+ "price": price.stripe_price_id,
+ "quantity": 1,
+ },
+ ],
+ mode="payment",
+ success_url=domain + "payments/success/",
+ cancel_url=domain + "payments/cancel/",
+ )
+ return redirect(checkout_session.url, code=303)
+
+
+class SuccessView(TemplateView):
+ template_name = "payments/success.html"
+
+
+class CancelView(TemplateView):
+ template_name = "payments/cancel.html"
+
+
+class ProductLandingPageView(TemplateView):
+ template_name = "payments/landingpage.html"
+
+ def get_context_data(self, **kwargs):
+ product = Product.objects.get(name="Worksheet 1")
+ prices = Price.objects.filter(product=product)
+ context = super(ProductLandingPageView, self).get_context_data(**kwargs)
+ context.update({"product": product, "prices": prices})
+ return context
+
+
+@login_required
+def add_to_cart(request, resource_id):
+ resource = get_object_or_404(Resource, id=resource_id)
+ cart, created = ShoppingCart.objects.get_or_create(user=request.user)
+ cart_item, created = CartItem.objects.get_or_create(cart=cart, resource=resource)
+ cart_item.quantity += 1
+ cart_item.save()
+ return redirect("cart_detail")
+
+
+@login_required
+def cart_detail(request):
+ cart, created = ShoppingCart.objects.get_or_create(user=request.user)
+ return render(request, "payments/cart_detail.html", {"cart": cart})
+
+
+@login_required
+def checkout(request):
+ cart = ShoppingCart.objects.get(user=request.user)
+ total = sum(item.get_total_price() for item in cart.items.all())
+
+ if request.method == "POST":
+ # Create Stripe PaymentIntent
+ intent = stripe.PaymentIntent.create(
+ amount=int(total * 100), # Stripe amount is in cents
+ currency="usd",
+ automatic_payment_methods={"enabled": True},
+ )
+
+ # Redirect to Stripe checkout or handle payment confirmation
+ return render(request, "cart/checkout_success.html")
+
+ return render(request, "cart/checkout.html", {"cart": cart, "total": total})