aboutsummaryrefslogtreecommitdiffstats
path: root/alphabetlearning/payments/views.py
blob: 07a0177159744682c70c1eb3b866aecf19cebb1a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.core.mail import send_mail
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import get_object_or_404, render, redirect
from django.urls import reverse, reverse_lazy
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView, DeleteView

from alphabetlearning.payments.models import EmailSignup
from alphabetlearning.resources.models import Resource
from alphabetlearning.users.models import User

from .models import CartItem, Price, Product, ShoppingCart

import stripe

# TODO get the cart integrated with Stripe
# Steps to convert our Cart into something that can be used with Stripe:
#
#    - Fix the total in the cart
#    - X Sort out the webhook
#    - Associate the purchases with the users profile page
#    - We need a profile page!
#        - Link in navbar (when logged in)
#    - Fix the email and make it nice
#    - Associate each of our resources with a Product item
#        - this should be done in the create resource page
#        - or we can do it manually for the time being
#    - X Check that we can add resources to the cart
#    - X When the user hits the cart page, each associated product is pulled from the database
#    - X prices are extracted from the products accordingly
#    - X use the form from the landingpage.html as the checkout button to call the create-checkout-session
#    - Add delete buttons the checkout page, etc


stripe.api_key = settings.STRIPE_SECRET_KEY

class SuccessEmailSignupView(TemplateView):
    template_name = "payments/success_email_signup.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['email'] = self.request.POST.get('email')
        return context

def email_signup(request):
    if request.method == 'POST':
        email = request.POST.get('email')
        if email:
            EmailSignup.objects.get_or_create(email=email)
            # Send email to user
            send_mail(
                "Thank you for signing up",
                "You have successfully signed up for our newsletter.",
                settings.DEFAULT_FROM_EMAIL,
                [email],
                fail_silently=False,
            )
            # Send email to admin
            admin_email = "admin@example.com"  # Replace with actual admin email
            send_mail(
                "New Email Signup",
                f"A new user has signed up with the email: {email}",
                settings.DEFAULT_FROM_EMAIL,
                [admin_email],
                fail_silently=False,
            )
            return redirect(reverse('payments:success_email_signup'))  # Redirect to a success page or similar
    return render(request, 'pages/home.html')  # Adjust as necessary

def create_line_items(resources):
    price_objs = [r.price_obj.first() for r in resources]
    stripe_price_ids = [p.stripe_price_id for p in price_objs]
    return [{"quantity": 1, "price": s} for s in stripe_price_ids]
    pass


class CreateCheckoutSessionView(View):
    def post(self, request, *args, **kwargs):
        # price = Price.objects.get(id=self.kwargs["pk"])
        cart = ShoppingCart.objects.get(id=self.kwargs["pk"])
        resources = [i.resource for i in cart.items.all()]
        total = sum([r.price_obj.first().price for r in resources])
        domain = "http://localhost:8000"
        checkout_session = stripe.checkout.Session.create(
            payment_method_types=["card"],
            customer_email=request.user.email,
            line_items=create_line_items(resources),
            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):
        resource = Resource.objects.get(id=91)
        prices = Price.objects.filter(resource=resource)
        context = super(ProductLandingPageView, self).get_context_data(**kwargs)
        context.update({"resource": resource, "prices": prices})
        return context


@login_required
def add_to_cart(request, resource_id):
    resource = get_object_or_404(Resource, id=resource_id)
    if not resource.price_obj.first():
        return HttpResponseBadRequest(
            "There is no price assigned to this resource. Please contact Alphabet Learning Support."
        )
    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("payments:cart_detail")


@login_required
def cart_detail(request):
    cart, created = ShoppingCart.objects.get_or_create(user=request.user)
    resources = [i.resource for i in cart.items.all()]
    total = sum([r.price_obj.first().price for r in resources]) / 1000
    context = {"cart": cart, "resources": resources, "total": total}
    return render(request, "payments/cart_detail.html", context)


# 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})


@csrf_exempt
def stripe_webhook(request):
    payload = request.body
    sig_header = request.META["HTTP_STRIPE_SIGNATURE"]
    event = None

    # verify that the request came from STRIPE
    try:
        event = stripe.Webhook.construct_event(payload, sig_header, settings.STRIPE_WEBHOOK_SECRET)
    except ValueError as e:
        return HttpResponse(status=400)
    except stripe.error.SignatureVerificationError as e:
        return HttpResponse(status=400)

    if event["type"] == "checkout.session.completed":
        session = event["data"]["object"]
        customer_email = session["customer_details"]["email"]
        payment_intent = session["payment_intent"]

        # TODO Add the items to the users profile page
        # This should be done before deleting the cart otherwise we have no record of what they bought

        # TODO clear their shopping cart - we need to obtain their user ID
        user = User.objects.get(email=customer_email)
        ShoppingCart.objects.get(user=user).delete()

        # TODO add the transaction to our local history? Or just use Stripe?

        # TODO send an email to the customer
        send_mail(
            "Thank you for your purchase",
            "You have bought something nice - enjoy it",
            settings.DEFAULT_FROM_EMAIL,
            [customer_email],
            fail_silently=False,
        )
    return HttpResponse(status=200)

class DeleteCartItem(DeleteView):
    model = CartItem
    success_url = reverse_lazy("payments:cart_detail")
	
    # delete the cart item if there is more than one
    # delete the item and the cart itself if it is the last thing in the cart
    def post(self, request, *args, **kwargs):
        cart_items = request.user.shoppingcart.items.all()
        if len(cart_items) > 1: 
            return self.delete(request, *args, **kwargs)
        else:
            request.user.shoppingcart.delete()
            return redirect("resources:resource_list")

def privacy_policy(request):
    return render(request, 'pages/privacy_policy.html')