74 lines
2.3 KiB
Python
74 lines
2.3 KiB
Python
from decimal import Decimal
|
|
|
|
from shop.models import Customer, Order, OrderLine, Product, ProductBatch
|
|
from django.contrib.auth import get_user_model
|
|
|
|
User = get_user_model()
|
|
|
|
|
|
def create_order_line_for_product(product: Product, quantity: Decimal, order: Order):
|
|
price = product.prices.last()
|
|
base_total = round(price.price * quantity, 2)
|
|
tax_value = price.tax.value / Decimal("100")
|
|
taxes = round(base_total * tax_value, 2)
|
|
|
|
return OrderLine.objects.create(
|
|
order=order,
|
|
product=product,
|
|
quantity=quantity,
|
|
price=price.price,
|
|
base_total=base_total,
|
|
tax_value=tax_value,
|
|
taxes=taxes,
|
|
total=base_total + taxes,
|
|
)
|
|
|
|
|
|
def create_order(
|
|
customer: User,
|
|
billing_address: str,
|
|
billing_city: str,
|
|
billing_state: str,
|
|
billing_country: str,
|
|
billing_zip: str,
|
|
shipping_address: str = "",
|
|
shipping_city: str = "",
|
|
shipping_state: str = "",
|
|
shipping_country: str = "",
|
|
shipping_zip: str = "",
|
|
) -> Order:
|
|
billing_address = billing_address if billing_address else customer.address
|
|
billing_city = billing_city if billing_city else customer.city
|
|
billing_state = billing_state if billing_state else customer.state
|
|
billing_country = billing_country if billing_country else customer.country
|
|
billing_zip = billing_zip if billing_zip else customer.zip
|
|
|
|
shipping_address = shipping_address if shipping_address else billing_address
|
|
shipping_city = shipping_city if shipping_city else billing_city
|
|
shipping_state = shipping_state if shipping_state else billing_state
|
|
shipping_country = shipping_country if shipping_country else billing_country
|
|
shipping_zip = shipping_zip if shipping_zip else billing_zip
|
|
|
|
order = Order.objects.create(
|
|
user=customer,
|
|
billing_address=billing_address,
|
|
billing_city=billing_city,
|
|
billing_state=billing_state,
|
|
billing_country=billing_country,
|
|
billing_zip=billing_zip,
|
|
shipping_address=shipping_address,
|
|
shipping_city=shipping_city,
|
|
shipping_state=shipping_state,
|
|
shipping_country=shipping_country,
|
|
shipping_zip=shipping_zip,
|
|
)
|
|
|
|
return order
|
|
|
|
|
|
def delete_product_batch(batch: ProductBatch):
|
|
product = batch.product
|
|
product.stock = max(product.stock - batch.quantity, 0)
|
|
product.save()
|
|
batch.delete()
|