feat: added customer addresses and shipping method

This commit is contained in:
2024-12-23 13:27:00 +01:00
parent b2f8febdb6
commit a1f6983148
7 changed files with 279 additions and 426 deletions
+74 -1
View File
@@ -1,6 +1,15 @@
from decimal import Decimal
from shop.models import Order, OrderLine, Product, ProductBatch
from shop.models import (
Order,
OrderLine,
Product,
ProductBatch,
Cart,
CustomerAddress,
ShippingMethod,
ProductPrice,
)
from django.contrib.auth import get_user_model
User = get_user_model()
@@ -59,3 +68,67 @@ def delete_product_batch(batch: ProductBatch):
product.stock = max(product.stock - batch.quantity, 0)
product.save()
batch.delete()
def create_order_from_cart(
cart: Cart,
billing_address: CustomerAddress,
shipping_address: CustomerAddress,
shipping_method: ShippingMethod,
):
order = Order.objects.create(
billing_address=billing_address.address,
billing_city=billing_address.address_town,
billing_state=billing_address.address_state,
billing_country=billing_address.address_country,
billing_zip=billing_address.address_zip,
shipping_address=shipping_address.address,
shipping_city=shipping_address.address_town,
shipping_state=shipping_address.address_state,
shipping_country=shipping_address.address_country,
shipping_zip=shipping_address.address_zip,
)
for item in cart.items.all():
product = item.product
price: ProductPrice = product.price
base_total = price.price * item.quantity
tax_value = price.tax.value
taxes = base_total * (tax_value / 100)
total = base_total + taxes
OrderLine.objects.create(
order=order,
product=product,
quantity=item.quantity,
price=price.price,
base_total=base_total,
tax_value=tax_value,
taxes=taxes,
total=total,
)
order.calculate_total_from_lines()
add_shipping_order_line(order, shipping_method)
return order
def add_shipping_order_line(order, shipping_method):
shipping_price: ProductPrice = shipping_method.shipping_product.price
shipping_base_total = shipping_price.price
shipping_tax_value = shipping_price.tax.value
shipping_taxes = shipping_base_total * (shipping_tax_value / 100)
shipping_total = shipping_base_total + shipping_taxes
OrderLine.objects.create(
order=order,
product=shipping_method.shipping_product,
quantity=1,
price=shipping_price.price,
base_total=shipping_base_total,
tax_value=shipping_tax_value,
taxes=shipping_taxes,
total=shipping_total,
)
order.calculate_total_from_lines()