Skip to content

Commit

Permalink
Adjust length of voucher field - order models
Browse files Browse the repository at this point in the history
  • Loading branch information
tomik-z-cech committed Mar 6, 2024
1 parent cea4e9c commit 9d07b91
Show file tree
Hide file tree
Showing 7 changed files with 71 additions and 50 deletions.
17 changes: 17 additions & 0 deletions checkout/migrations/0006_alter_order_voucher.py
Original file line number Diff line number Diff line change
@@ -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),
),
]
2 changes: 1 addition & 1 deletion checkout/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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='')
Expand Down
2 changes: 2 additions & 0 deletions checkout/templates/checkout/checkout.html
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,8 @@ <h2 class="accordion-header" id="panelsStayOpen-headingFour">
{% block extra_js %}
{{ block.super }}
<script type="text/javascript">
const subtotal = {{ subtotal}};
const currentVoucher = '{{ current_voucher }}';
let standardDelivery = {{ standard_delivery_cost|floatformat:2 }};
let expressDelivery = {{ express_delivery_cost|floatformat:2 }};
</script>
Expand Down
42 changes: 23 additions & 19 deletions checkout/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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,
}
)

Expand Down Expand Up @@ -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'
Expand All @@ -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)
Expand Down Expand Up @@ -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) :')
Expand Down Expand Up @@ -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"
Expand All @@ -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,
Expand All @@ -315,15 +319,15 @@ 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
# Update stock
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:
Expand All @@ -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,
}
Expand All @@ -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:
Expand Down Expand Up @@ -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,
Expand Down
53 changes: 24 additions & 29 deletions checkout/webhook_handler.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -24,43 +25,37 @@ 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
)
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:
Expand All @@ -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:
Expand All @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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 :')
Expand Down Expand Up @@ -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,
Expand Down
3 changes: 3 additions & 0 deletions static/js/stripe_elements.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion templates/header.html
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
<br>
<span class="hide-less-991px">
{% if subtotal > 0 %}
{{ subtotal }} €
{{ subtotal|floatformat:2 }} €
{% else %}
0.00 €
{% endif %}
Expand Down

0 comments on commit 9d07b91

Please sign in to comment.