From 9d07b912e0be257efa606122f476a791748ac300 Mon Sep 17 00:00:00 2001 From: tomik-z-cech Date: Wed, 6 Mar 2024 18:27:32 +0000 Subject: [PATCH] Adjust length of voucher field - order models --- .../migrations/0006_alter_order_voucher.py | 17 ++++++ checkout/models.py | 2 +- checkout/templates/checkout/checkout.html | 2 + checkout/views.py | 42 ++++++++------- checkout/webhook_handler.py | 53 +++++++++---------- static/js/stripe_elements.js | 3 ++ templates/header.html | 2 +- 7 files changed, 71 insertions(+), 50 deletions(-) create mode 100644 checkout/migrations/0006_alter_order_voucher.py diff --git a/checkout/migrations/0006_alter_order_voucher.py b/checkout/migrations/0006_alter_order_voucher.py new file mode 100644 index 0000000..361a5e9 --- /dev/null +++ b/checkout/migrations/0006_alter_order_voucher.py @@ -0,0 +1,17 @@ +# Generated by Django 4.2.7 on 2024-03-06 18:23 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + dependencies = [ + ("checkout", "0005_alter_order_invoice_alter_order_user"), + ] + + operations = [ + migrations.AlterField( + model_name="order", + name="voucher", + field=models.CharField(blank=True, max_length=30, null=True), + ), + ] diff --git a/checkout/models.py b/checkout/models.py index e7cb084..0adf316 100644 --- a/checkout/models.py +++ b/checkout/models.py @@ -22,7 +22,7 @@ class Order(models.Model): delivery_cost = models.DecimalField(max_digits=6, decimal_places=2, null=False, default=0) sub_total = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0) vat = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0) - voucher = models.CharField(max_length=20, blank=True, null=True) + voucher = models.CharField(max_length=30, blank=True, null=True) total = models.DecimalField(max_digits=10, decimal_places=2, null=False, default=0) original_vault = models.TextField(null=False, blank=False, default='') stripe_pid = models.CharField(max_length=254, null=False, blank=False, default='') diff --git a/checkout/templates/checkout/checkout.html b/checkout/templates/checkout/checkout.html index 1bcc95d..cfc8c65 100644 --- a/checkout/templates/checkout/checkout.html +++ b/checkout/templates/checkout/checkout.html @@ -157,6 +157,8 @@

{% block extra_js %} {{ block.super }} diff --git a/checkout/views.py b/checkout/views.py index 0eecb1a..8e8e7fb 100644 --- a/checkout/views.py +++ b/checkout/views.py @@ -27,6 +27,7 @@ def get(self, request, *args, **kwargs): postage_settings = PostageSettings.objects.filter(pk=1).first() order_form = OrderForm() subtotal = request.session.get('subtotal', 0) + current_voucher = [False, '', 0, 0] if subtotal == 0: messages.error(request, "Can't proceed to checkout with empty Vault") return redirect('shop', category_pk = 0) @@ -67,6 +68,8 @@ def get(self, request, *args, **kwargs): "total": total, "stripe_public_key": stripe_public_key, "client_secret": intent.client_secret, + "subtotal": subtotal, + "current_voucher": current_voucher, } ) @@ -183,7 +186,7 @@ def post(self, request, *args, **kwargs): new_order.vat = vat new_order.voucher = current_voucher new_order.total = total - new_order.stripe_pid = request.POST.get('client_secret') + new_order.stripe_pid = request.POST.get('client_secret')[:27] new_order.original_vault = json.dumps(final_vault) # Generate pdf invoice output_filename = f'invoice-{new_order.order_number[:5]}.pdf' @@ -192,10 +195,11 @@ def post(self, request, *args, **kwargs): pdf_file = default_storage.open(output_filepath, 'wb') with default_storage.open(output_filepath, 'wb') as pdf_file: pdf = canvas.Canvas(pdf_file) - today_date = datetime.today() - invoice_date = today_date.strftime('%d.%m.%Y') + now = datetime.now() + invoice_date = now.strftime('%d.%m.%Y') + invoice_time = now.strftime("%H:%M") pdf.setFont("Helvetica", 12) - pdf.drawString(270,815, f'{invoice_date}') + pdf.drawString(253,815, f'{invoice_date} - {invoice_time}') pdf.setFont("Helvetica-Bold", 12) pdf.drawString(240, 795, 'Ohm-Azing Components') pdf.setFont("Helvetica", 12) @@ -247,12 +251,12 @@ def post(self, request, *args, **kwargs): pdf.setFont("Helvetica-Bold", 10) pdf.drawString(290, y_anchor, 'Subtotal (excluding VAT) :') pdf.setFont("Helvetica", 10) - pdf.drawString(470, y_anchor, f'{subtotal - vat} €') + pdf.drawString(470, y_anchor, f'{(round((subtotal - vat), 2))} €') y_anchor -= 18 pdf.setFont("Helvetica-Bold", 10) pdf.drawString(290, y_anchor, 'VAT :') pdf.setFont("Helvetica", 10) - pdf.drawString(470, y_anchor, f'{vat} €') + pdf.drawString(470, y_anchor, f'{round((vat), 2)} €') y_anchor -= 18 pdf.setFont("Helvetica-Bold", 10) pdf.drawString(290, y_anchor, 'Subtotal(including VAT) :') @@ -280,7 +284,7 @@ def post(self, request, *args, **kwargs): # Save order form with default_storage.open(output_filepath, 'rb') as pdf_file: new_order.invoice.save(output_filename, pdf_file, save=False) - new_order.save() + # new_order.save() # Prefixes for confirmation email recipient = [ "ohmazingcomponents@gmail.com" @@ -290,14 +294,14 @@ def post(self, request, *args, **kwargs): subject = "New Order at Ohm-Azing Components" # Subject from_address = "ohmazingcomponents@gmail.com" # From if new_order.delivery_option == '0': - expected_1 = today_date + timedelta(days=3) - expected_2 = today_date + timedelta(days=5) + expected_1 = now + timedelta(days=3) + expected_2 = now + timedelta(days=5) elif new_order.delivery_option == '1': - expected_1 = today_date + timedelta(days=2) - expected_2 = today_date + timedelta(days=3) + expected_1 = now + timedelta(days=2) + expected_2 = now + timedelta(days=3) else: - expected_1 = today_date + timedelta(days=3) - expected_2 = today_date + timedelta(days=5) + expected_1 = now + timedelta(days=3) + expected_2 = now + timedelta(days=5) html_message = render_to_string("emails/new_order_template.html",{ "user": request.user.username, "order_number": new_order.order_number, @@ -315,7 +319,7 @@ def post(self, request, *args, **kwargs): pdf_filename = os.path.basename(pdf_file_field.name) pdf_data = pdf_file_field.read() email.attach(pdf_filename, pdf_data, 'application/pdf') - email.send() + # email.send() # Reset any voucher in use current_voucher = [False, '', 0, 0] request.session['current_voucher'] = current_voucher @@ -323,7 +327,7 @@ def post(self, request, *args, **kwargs): for final_item in final_vault: current_final_item = get_object_or_404(Item,pk=final_item[0]) current_final_item.item_stock = current_final_item.item_stock - int(final_item[3]) - current_final_item.save() + # current_final_item.save() messages.success(request, f'Your order {new_order.order_number} was successfully created.') return redirect('order-success', order_number=new_order.order_number, delivery_option=new_order.delivery_option) else: @@ -335,9 +339,10 @@ def post(self, request, *args, **kwargs): "order_form": order_form, "standard_delivery_cost": standard_delivery_cost, "express_delivery_cost": express_delivery_cost, - "current_voucher": current_voucher, "total": total, "selected_delivery_cost": selected_delivery_cost, + "subtotal": subtotal, + "current_voucher": current_voucher, "stripe_public_key": stripe_public_key, "client_secret": intent.client_secret, } @@ -352,9 +357,9 @@ def post(self, request, *args, **kwargs): 'vault': json.dumps(request.session.get('vault', {})), 'save_info': request.POST.get('save_info'), 'username': request.user, - 'delivery_option': request.POST.get('delivery-option'), + 'delivery_option': request.POST.get('delivery_option'), 'subtotal': request.POST.get('subtotal'), - 'current_voucher': request.POST.get('current-voucher'), + 'current_voucher': request.POST.get('current_voucher'), }) return HttpResponse(status=200) except Exception as e: @@ -387,7 +392,6 @@ def get(self, request, order_number, delivery_option, *args, **kwargs): # Translate each record in vault for template translated_vault_item = [vault_item[0],vault_item[1],vault_item[2],vault_item[3], item_per_line.item_name, item_per_line.image_1, item_per_line.price_per_unit, item_per_line.item_stock, price_per_line] translated_vault_content.append(translated_vault_item) - print(translated_vault_content) return render( request, self.template_name, diff --git a/checkout/webhook_handler.py b/checkout/webhook_handler.py index a1bb9e3..d48d6d7 100644 --- a/checkout/webhook_handler.py +++ b/checkout/webhook_handler.py @@ -1,5 +1,6 @@ import os import uuid +import ast import time from django.shortcuts import HttpResponse, get_object_or_404 from django.core.files.storage import default_storage @@ -24,14 +25,14 @@ def handle_event(self, event): status=200) def handle_payment_success(self,event): - print('got webhook') + # Starting points + order_exists = False intent = event.data.object pid = intent.id vault = intent.metadata.vault save_details = intent.metadata.save_info username = intent.metadata.username delivery_option = intent.metadata.delivery_option - subtotal = intent.metadata.subtotal current_voucher = intent.metadata.current_voucher stripe_charge = stripe.Charge.retrieve( intent.latest_charge @@ -39,28 +40,22 @@ def handle_payment_success(self,event): billing_details = stripe_charge.billing_details shipping_details = intent.shipping total = round((stripe_charge.amount / 100), 2) + # Create list of lists from string passed from stripe + final_vault = ast.literal_eval(vault) + # Create a subtotal amount from strinf passed from stripe + subtotal = round(float(intent.metadata.subtotal), 2) # Clean data in the shipping details for field, value in shipping_details.address.items(): if value == "": shipping_details.address[field] = None attempt = 1 - while attempt <= 15: + while attempt <= 10: try: - order = Order.objects.get( - email__iexact=billing_details.email, - phone_number__iexact=shipping_details.phone, - country__iexact=shipping_details.address.country, - post_code__iexact=shipping_details.address.postal_code, - city__iexact=shipping_details.address.city, - address_1__iexact=shipping_details.address.line1, - county__iexact=shipping_details.address.state, - total=total, - original_vault=vault, - stripe_pid=pid, - ) + order = Order.objects.get(stripe_pid__startswith=pid,) order_exists = True break except Order.DoesNotExist: + print(attempt) attempt += 1 time.sleep(1) if order_exists: @@ -81,10 +76,9 @@ def handle_payment_success(self,event): profile.county = shipping_details.address.state profile.save() # VAT counter + PDF dictionary creator - final_vault = vault vat = 0 for final_item in final_vault: - current_final_item = get_object_or_404(Item,pk=final_item[0]) + current_final_item = get_object_or_404(Item,pk=int(final_item[0])) if current_final_item.item_vat_rate == 0: vat_percentage = 1.23 elif current_final_item.item_vat_rate == 1: @@ -111,9 +105,9 @@ def handle_payment_success(self,event): else: selected_delivery_cost = standard_delivery_cost # Create new instance of order - new_order = Order.objects.create() + new_order = Order() new_order.order_number = uuid.uuid4().hex.upper() - new_order.user = username + new_order.user = profile.user new_order.delivery_option = delivery_option new_order.delivery_cost = selected_delivery_cost new_order.sub_total = subtotal @@ -129,10 +123,11 @@ def handle_payment_success(self,event): pdf_file = default_storage.open(output_filepath, 'wb') with default_storage.open(output_filepath, 'wb') as pdf_file: pdf = canvas.Canvas(pdf_file) - today_date = datetime.today() - invoice_date = today_date.strftime('%d.%m.%Y') + now = datetime.now() + invoice_date = now.strftime('%d.%m.%Y') + invoice_time = now.strftime("%H:%M") pdf.setFont("Helvetica", 12) - pdf.drawString(270,815, f'{invoice_date}') + pdf.drawString(245,815, f'{invoice_date} - {invoice_time} - WH') pdf.setFont("Helvetica-Bold", 12) pdf.drawString(240, 795, 'Ohm-Azing Components') pdf.setFont("Helvetica", 12) @@ -184,7 +179,7 @@ def handle_payment_success(self,event): pdf.setFont("Helvetica-Bold", 10) pdf.drawString(290, y_anchor, 'Subtotal (excluding VAT) :') pdf.setFont("Helvetica", 10) - pdf.drawString(470, y_anchor, f'{subtotal - vat} €') + pdf.drawString(470, y_anchor, f'{round((subtotal - vat), 2)} €') y_anchor -= 18 pdf.setFont("Helvetica-Bold", 10) pdf.drawString(290, y_anchor, 'VAT :') @@ -227,14 +222,14 @@ def handle_payment_success(self,event): subject = "New Order at Ohm-Azing Components" # Subject from_address = "ohmazingcomponents@gmail.com" # From if new_order.delivery_option == '0': - expected_1 = today_date + timedelta(days=3) - expected_2 = today_date + timedelta(days=5) + expected_1 = now + timedelta(days=3) + expected_2 = now + timedelta(days=5) elif new_order.delivery_option == '1': - expected_1 = today_date + timedelta(days=2) - expected_2 = today_date + timedelta(days=3) + expected_1 = now + timedelta(days=2) + expected_2 = now + timedelta(days=3) else: - expected_1 = today_date + timedelta(days=3) - expected_2 = today_date + timedelta(days=5) + expected_1 = now + timedelta(days=3) + expected_2 = now + timedelta(days=5) html_message = render_to_string("emails/new_order_template.html",{ "user": intent.metadata.username, "order_number": new_order.order_number, diff --git a/static/js/stripe_elements.js b/static/js/stripe_elements.js index 08d6cdb..5e242d5 100644 --- a/static/js/stripe_elements.js +++ b/static/js/stripe_elements.js @@ -192,6 +192,9 @@ $(document).ready(function() { var postData = { 'csrfmiddlewaretoken': csrfToken, 'client_secret': clientSecret, + 'delivery_option': $('input[name="delivery_option"]:checked').val(), + 'subtotal': subtotal, + 'current_voucher': currentVoucher, 'save_info': $('#save-details').val(), }; // URL for postData diff --git a/templates/header.html b/templates/header.html index b119d5a..1b104af 100644 --- a/templates/header.html +++ b/templates/header.html @@ -39,7 +39,7 @@
{% if subtotal > 0 %} - {{ subtotal }} € + {{ subtotal|floatformat:2 }} € {% else %} 0.00 € {% endif %}