Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Remove some fixme comments. improve tax interface

Maciej Korycinski28601ccbff2d
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 59adc0ac9a..b26641f911 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -16,13 +16,13 @@ from ..account.models import Address, User
from ..account.utils import store_user_address
from ..core.exceptions import InsufficientStock
from ..core.taxes import ZERO_MONEY
-from ..core.taxes.avatax.interface import postprocess_order_creation_with_taxes # FIXME
from ..core.taxes.interface import (
get_line_total_gross,
- get_lines_with_taxes,
get_shipping_gross,
get_subtotal_gross,
get_total_gross,
+ postprocess_order_creation,
+ show_taxes_on_storefront,
)
from ..core.utils import to_local_currency
from ..discount import VoucherType
@@ -655,7 +655,7 @@ def get_checkout_context(checkout, discounts, currency=None, shipping_range=None
context = {
"checkout": checkout,
- "checkout_are_taxes_handled": True, # bool(taxes), #FIXME
+ "checkout_are_taxes_handled": show_taxes_on_storefront(),
"checkout_lines": [
(line, get_line_total_gross(line, discounts)) for line in checkout
],
@@ -943,17 +943,15 @@ def create_order(checkout: Checkout, tracking_code: str, discounts, user: User):
order = Order.objects.create(**order_data, checkout_token=checkout.token)
- lines_with_taxes = get_lines_with_taxes(checkout, discounts)
+ lines = checkout.lines.prefetch_related("variant__product__product_type")
# create order lines from checkout lines
- for line, tax in lines_with_taxes:
- add_variant_to_order(
- order, line.variant, line.quantity, discounts, unit_tax=tax
- )
+ for line in lines:
+ add_variant_to_order(order, line.variant, line.quantity, discounts)
# assign checkout payments to the order
checkout.payments.update(order=order)
- postprocess_order_creation_with_taxes(order)
+ postprocess_order_creation(order)
# remove checkout after order is created
checkout.delete()
diff --git a/saleor/checkout/views/__init__.py b/saleor/checkout/views/__init__.py
index f4bf3f8c94..1c6386ca3b 100644
--- a/saleor/checkout/views/__init__.py
+++ b/saleor/checkout/views/__init__.py
@@ -135,15 +135,13 @@ def checkout_index(request, checkout):
initial=initial,
discounts=discounts,
)
- variant_price = line.variant.get_price(discounts)
-
+ total_line = tax_interface.get_line_total_gross(line, discounts)
+ variant_price = total_line / line.quantity
checkout_lines.append(
{
"variant": line.variant,
- "get_price": tax_interface.apply_taxes_to_variant(
- line.variant, variant_price, request.country
- ),
- "get_total": tax_interface.get_line_total_gross(line, discounts),
+ "get_price": variant_price,
+ "get_total": total_line,
"form": form,
}
)
diff --git a/saleor/core/middleware.py b/saleor/core/middleware.py
index 320c7f86b9..b001567371 100644
--- a/saleor/core/middleware.py
+++ b/saleor/core/middleware.py
@@ -167,7 +167,16 @@ def taxes(get_response):
"""Assign tax rates for default country to `request.taxes`."""
def middleware(request):
- request.taxes = None # FIXME
+ if settings.VATLAYER_ACCESS_KEY:
+ # FIXME this should be disabled after we will introduce plugin architecure.
+ # For now, a lot of templates use tax_rate function.
+ from .taxes.vatlayer import get_taxes_for_country
+
+ request.taxes = SimpleLazyObject(
+ lambda: get_taxes_for_country(request.country)
+ )
+ else:
+ request.taxes = None
return get_response(request)
return middleware
diff --git a/saleor/core/taxes/avatax/__init__.py b/saleor/core/taxes/avatax/__init__.py
index 61240d4220..096c943947 100644
--- a/saleor/core/taxes/avatax/__init__.py
+++ b/saleor/core/taxes/avatax/__init__.py
@@ -53,6 +53,22 @@ def api_get_request(
return requests.get(url, auth=HTTPBasicAuth(username, password))
+def validate_order(order: "Order") -> bool:
+ """Validate if checkout object contains enough information to generate a request to
+ avatax"""
+ if not order.lines.count():
+ return False
+ shipping_address = order.shipping_address
+ is_shipping_required = order.is_shipping_required()
+ address = shipping_address or order.billing_address
+
+ if not is_shipping_required and not address:
+ return False
+ if not shipping_address:
+ return False
+ return True
+
+
def validate_checkout(checkout: "Checkout") -> bool:
"""Validate if checkout object contains enough information to generate a request to
avatax"""
@@ -110,7 +126,7 @@ def append_line_to_data(
data.append(
{
"quantity": quantity,
- "amount": amount,
+ "amount": str(amount),
"taxCode": tax_code,
# FIXME Should fetch taxcode from somewhere and save inside variant/product
"itemCode": item_code,
@@ -129,6 +145,8 @@ def get_checkout_lines_data(
"variant__product__product_type",
)
for line in lines:
+ if not line.variant.product.charge_taxes:
+ continue
description = line.variant.product.description
append_line_to_data(
data=data,
@@ -151,7 +169,7 @@ def get_checkout_lines_data(
return data
-def get_order_lines_data(order: "Order", discounts=None) -> List[Dict[str, str]]:
+def get_order_lines_data(order: "Order") -> List[Dict[str, str]]:
data = []
lines = order.lines.prefetch_related(
"variant__product__category",
@@ -159,19 +177,21 @@ def get_order_lines_data(order: "Order", discounts=None) -> List[Dict[str, str]]
"variant__product__product_type",
)
for line in lines:
+ if not line.variant.product.charge_taxes:
+ continue
append_line_to_data(
data=data,
quantity=line.quantity,
- amount=line.variant.get_price(discounts),
+ amount=line.unit_price_net.amount * line.quantity,
tax_code="PC040156",
item_code=line.variant.sku,
description=line.variant.product.description,
)
- if order.is_shipping_required():
+ if charge_taxes_on_shipping() and order.shipping_method:
append_line_to_data(
data,
quantity=1,
- amount=str(order.shipping_method.price.amount),
+ amount=order.shipping_method.price.amount,
tax_code=common_carrier_code,
item_code="Shipping",
)
@@ -274,11 +294,14 @@ def get_checkout_tax_data(checkout: "Checkout", discounts) -> Dict[str, Any]:
return get_cached_response_or_fetch(data, str(checkout.token))
-def get_order_tax_data(order: "Order", discounts, commit=False) -> Dict[str, Any]:
+def get_order_tax_data(order: "Order", commit=False) -> Dict[str, Any]:
address = order.shipping_address or order.billing_address
- lines = get_order_lines_data(order, discounts=discounts)
+ lines = get_order_lines_data(order)
+ transaction = (
+ TransactionType.INVOICE if not order.is_draft() else TransactionType.ORDER
+ )
data = generate_request_data(
- transaction_type=TransactionType.INVOICE,
+ transaction_type=transaction,
lines=lines,
transaction_token=order.token,
address=address.as_data(),
diff --git a/saleor/core/taxes/avatax/interface.py b/saleor/core/taxes/avatax/interface.py
index 6574c189ad..558f0419fe 100644
--- a/saleor/core/taxes/avatax/interface.py
+++ b/saleor/core/taxes/avatax/interface.py
@@ -8,6 +8,7 @@ from prices import Money, TaxedMoney
from ....checkout import models as checkout_models
from ....discount.models import Sale
+from .. import ZERO_TAXED_MONEY
from ..errors import TaxError
from . import (
TransactionType,
@@ -17,6 +18,7 @@ from . import (
get_checkout_tax_data,
get_order_tax_data,
validate_checkout,
+ validate_order,
)
if TYPE_CHECKING:
@@ -69,7 +71,7 @@ def get_shipping_gross(checkout: "checkout_models.Checkout", discounts):
return shipping_total
-def get_lines_with_taxes(checkout: "checkout_models.Checkout", discounts):
+def get_lines_with_unit_tax(checkout: "checkout_models.Checkout", discounts):
"""Calculate and return tuple (line, unit_tax)"""
lines_taxes = defaultdict(lambda: Decimal("0.0"))
@@ -92,6 +94,7 @@ def postprocess_order_creation_with_taxes(order: "Order"):
# FIXME this can be a celery task (?)
# FIXME maybe we can figure out better name
+ # Fixme we can generate data directly from order
checkout = checkout_models.Checkout.objects.get(token=order.checkout_token)
discounts = Sale.objects.active(date.today()).prefetch_related(
"products", "categories", "collections"
@@ -122,14 +125,30 @@ def get_line_total_gross(checkout_line: "checkout_models.CheckoutLine", discount
return checkout_line.get_total(discounts).gross
-def refresh_order_line_unit_price(order_line: "OrderLine", discounts):
+def apply_taxes_to_order_line_unit_price(order_line: "OrderLine", price: Money):
order = order_line.order
- taxes_data = get_order_tax_data(order, discounts)
+ if validate_order(order):
+ taxes_data = get_order_tax_data(order)
+ for line in taxes_data.get("lines", []):
+ if line.get("itemCode") == order_line.variant.sku:
+ tax = Decimal(line.get("tax", "0.0"))
+ net = price
+ gross = Money(amount=net.amount + tax, currency=net.currency)
+ return TaxedMoney(net=net, gross=gross)
+ return TaxedMoney(net=price, gross=price)
+
+
+def calculate_order_shipping(order: "Order"):
+ if not validate_order(order) or not order.shipping_method:
+ return ZERO_TAXED_MONEY
+
+ taxes_data = get_order_tax_data(order, None)
for line in taxes_data.get("lines", []):
- if line.get("itemCode") == order_line.variant.sku:
+ if line["itemCode"] == "Shipping":
tax = Decimal(line.get("tax", "0.0"))
- net = order_line.variant.get_price(discounts)
+ net = order.shipping_method.price
gross = Money(amount=net.amount + tax, currency=net.currency)
return TaxedMoney(net=net, gross=gross)
- price = order_line.variant.get_price(discounts)
- return TaxedMoney(net=price, gross=price)
+ return TaxedMoney(
+ net=order.shipping_method.price, gross=order.shipping_method.price
+ )
diff --git a/saleor/core/taxes/interface.py b/saleor/core/taxes/interface.py
index 7f2f37d0c3..60fd1cc4e0 100644
--- a/saleor/core/taxes/interface.py
+++ b/saleor/core/taxes/interface.py
@@ -16,7 +16,7 @@ if TYPE_CHECKING:
from ...checkout.models import Checkout, CheckoutLine
from ...product.models import Product, ProductVariant
from ...account.models import Address
- from ...order.models import OrderLine
+ from ...order.models import OrderLine, Order
def get_total_gross(checkout: "Checkout", discounts: "SaleQueryset") -> TaxedMoney:
@@ -55,13 +55,23 @@ def get_shipping_gross(checkout: "Checkout", discounts: "SaleQueryset") -> Taxed
return TaxedMoney(net=total, gross=total)
-def get_lines_with_taxes(checkout: "Checkout", discounts):
+def calculate_order_shipping(order: "Order") -> TaxedMoney:
+ if settings.VATLAYER_ACCESS_KEY:
+ # FIXME
+ pass
+ elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
+ return avatax_interface.calculate_order_shipping(order)
+ price = order.shipping_method.price
+ return TaxedMoney(net=price, gross=price)
+
+
+def get_lines_with_unit_tax(checkout: "Checkout", discounts):
lines_taxes = defaultdict(lambda: Decimal("0.0"))
if settings.VATLAYER_ACCESS_KEY:
- return vatlayer_interface.get_lines_with_taxes(checkout, discounts)
+ return vatlayer_interface.get_lines_with_unit_tax(checkout, discounts)
elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- return avatax_interface.get_lines_with_taxes(checkout, discounts)
+ return avatax_interface.get_lines_with_unit_tax(checkout, discounts)
return [(line, lines_taxes[line.variant.sku]) for line in checkout.lines.all()]
@@ -72,7 +82,9 @@ def apply_taxes_to_shipping(price: Money, shipping_address: "Address") -> TaxedM
if settings.VATLAYER_ACCESS_KEY:
return vatlayer_interface.apply_taxes_to_shipping(price, shipping_address)
if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- # FIXME
+ # For now we can't calculate product/shipping prices that are not directly
+ # assigned to order. Avatax has api only to calculate prices based on
+ # checkout/order data
pass
return TaxedMoney(net=price, gross=price)
@@ -87,25 +99,23 @@ def get_tax_rate_type_choices():
def get_line_total_gross(checkout_line: "CheckoutLine", discounts: "SaleQueryset"):
if settings.VATLAYER_ACCESS_KEY:
- return checkout_line.get_total(discounts) # FIXME
+ return vatlayer_interface.get_line_total_gross(checkout_line, discounts)
if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
return avatax_interface.get_line_total_gross(checkout_line, discounts)
total = checkout_line.get_total(discounts)
return TaxedMoney(net=total, gross=total)
-def refresh_order_line_unit_price(order_line: "OrderLine", discounts: "SaleQueryset"):
+def apply_taxes_to_order_line_unit_price(order_line: "OrderLine", price: Money):
"""It updates unit_price for a given order line based on current price of variant"""
if settings.VATLAYER_ACCESS_KEY:
+ # FIXME Should be inside vatlayer module
address = order_line.order.shipping_address or order_line.order.billing_address
country = address.country if address else None
variant = order_line.variant
- return vatlayer_interface.apply_taxes_to_variant(
- variant, variant.get_price(discounts), country
- )
+ return vatlayer_interface.apply_taxes_to_variant(variant, price, country)
if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- return avatax_interface.refresh_order_line_unit_price(order_line, discounts)
- price = order_line.variant.get_price(discounts)
+ return avatax_interface.apply_taxes_to_order_line_unit_price(order_line, price)
return TaxedMoney(net=price, gross=price)
@@ -147,3 +157,10 @@ def apply_taxes_to_shipping_price_range(prices: MoneyRange, country: Country):
start = TaxedMoney(net=prices.start, gross=prices.start)
stop = TaxedMoney(net=prices.stop, gross=prices.stop)
return TaxedMoneyRange(start=start, stop=stop)
+
+
+# FIXME this should be converted to the plugin action after we introduce plugin
+# architecture
+def postprocess_order_creation(order: "Order"):
+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
+ avatax_interface.postprocess_order_creation_with_taxes(order)
diff --git a/saleor/core/taxes/vatlayer/interface.py b/saleor/core/taxes/vatlayer/interface.py
index e05a9184f1..d4b7bf1225 100644
--- a/saleor/core/taxes/vatlayer/interface.py
+++ b/saleor/core/taxes/vatlayer/interface.py
@@ -7,7 +7,6 @@ from django_prices_vatlayer.utils import get_tax_rate, get_tax_rate_types
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
from ....core import TaxRateType # FIXME this should be placed in VatLayer module
-from ....discount.utils import calculate_discounted_price
from .. import ZERO_TAXED_MONEY
from . import (
DEFAULT_TAX_RATE_NAME,
@@ -19,7 +18,7 @@ from . import (
if TYPE_CHECKING:
from ....discount.models import SaleQueryset
- from ....checkout.models import Checkout
+ from ....checkout.models import Checkout, CheckoutLine
from ....product.models import Product, ProductVariant
from ....account.models import Address
@@ -53,15 +52,16 @@ def get_shipping_gross(checkout: "Checkout", _: "SaleQueryset") -> TaxedMoney:
return get_taxed_shipping_price(checkout.shipping_method.price, taxes)
-def get_lines_with_taxes(checkout: "Checkout", discounts: "SaleQueryset"):
+def get_lines_with_unit_tax(checkout: "Checkout", discounts: "SaleQueryset"):
lines_taxes = defaultdict(lambda: Decimal("0.0"))
address = checkout.shipping_address or checkout.billing_address
taxes = get_taxes_for_address(address)
- for line in checkout.lines.all():
- price = calculate_discounted_price(
- line.variant.product, line.variant.base_price, discounts
- )
+ lines = checkout.lines.prefetch_related("variant__product__product_type")
+ for line in lines:
+ price = line.variant.get_price(discounts)
+
+ # FIXME tax_rate belongs to vatlayer. We should transfer it to metadata somehow
tax_rate_name = (
line.variant.product.tax_rate or line.variant.product.product_type.tax_rate
)
@@ -74,6 +74,15 @@ def get_lines_with_taxes(checkout: "Checkout", discounts: "SaleQueryset"):
return [(line, lines_taxes[line.variant.sku]) for line in checkout.lines.all()]
+def get_line_total_gross(checkout_line: "CheckoutLine", discounts: "SaleQueryset"):
+ address = (
+ checkout_line.checkout.shipping_address
+ or checkout_line.checkout.billing_address
+ )
+ price = checkout_line.variant.get_price(discounts) * checkout_line.quantity
+ return apply_taxes_to_variant(checkout_line.variant, price, address.country)
+
+
def apply_taxes_to_shipping(price: Money, shipping_address: "Address"):
taxes = get_taxes_for_country(shipping_address.country)
return get_taxed_shipping_price(price, taxes)
diff --git a/saleor/core/templatetags/taxed_prices.py b/saleor/core/templatetags/taxed_prices.py
index a64dba00ea..afce80c9f6 100644
--- a/saleor/core/templatetags/taxed_prices.py
+++ b/saleor/core/templatetags/taxed_prices.py
@@ -1,8 +1,10 @@
from django import template
-from django.conf import settings
from prices import MoneyRange, TaxedMoney, TaxedMoneyRange
-from ...core.taxes.vatlayer import DEFAULT_TAX_RATE_NAME # FIXME
+# FIXME This const variable belongs to vatlayer, we shouldn't take it directly from
+# vatlayer module. This should be moved to plugin after we will introduce plugin
+# architecture
+from ...core.taxes.vatlayer import DEFAULT_TAX_RATE_NAME
register = template.Library()
@@ -16,7 +18,7 @@ def price_range(context, price_range):
@register.simple_tag
def tax_rate(taxes, rate_name):
"""Return tax rate value for given tax rate type in current country."""
- if not taxes or not settings.VATLAYER_ACCESS_KEY: # FIXME
+ if not taxes:
return 0
tax = taxes.get(rate_name) or taxes.get(DEFAULT_TAX_RATE_NAME)
return tax["value"]
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index d9ce2553e5..119a17e6e0 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -11,7 +11,7 @@ from ...account.i18n import (
from ...account.models import User
from ...checkout.forms import QuantityField
from ...core.exceptions import InsufficientStock
-from ...core.taxes import ZERO_TAXED_MONEY
+from ...core.taxes import ZERO_TAXED_MONEY, interface as tax_interface
from ...discount.models import Voucher
from ...discount.utils import decrease_voucher_usage, increase_voucher_usage
from ...order import OrderStatus, events
@@ -189,7 +189,6 @@ class OrderShippingForm(forms.ModelForm):
fields = ["shipping_method"]
def __init__(self, *args, **kwargs):
- self.taxes = kwargs.pop("taxes") # FIXME
super().__init__(*args, **kwargs)
method_field = self.fields["shipping_method"]
fetch_data_url = reverse(
@@ -212,7 +211,9 @@ class OrderShippingForm(forms.ModelForm):
def save(self, commit=True):
method = self.instance.shipping_method
self.instance.shipping_method_name = method.name
- self.instance.shipping_price = method.get_total(self.taxes) # FIXME
+ self.instance.shipping_price = tax_interface.calculate_order_shipping(
+ self.instance
+ )
recalculate_order(self.instance)
return super().save(commit)
@@ -632,9 +633,7 @@ class AddVariantToOrderForm(forms.Form):
"""
variant = self.cleaned_data.get("variant")
quantity = self.cleaned_data.get("quantity")
- line = add_variant_to_order(
- self.order, variant, quantity, self.discounts, self.taxes # FIXME
- )
+ line = add_variant_to_order(self.order, variant, quantity, self.discounts)
events.draft_order_added_products_event(
order=self.order, user=user, order_lines=[(line.quantity, line)]
)
diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.py
index e78c32fe21..3e9ba3b3be 100644
--- a/saleor/dashboard/order/views.py
+++ b/saleor/dashboard/order/views.py
@@ -432,8 +432,7 @@ def order_customer_remove(request, order_pk):
@permission_required("order.manage_orders")
def order_shipping_edit(request, order_pk):
order = get_object_or_404(Order.objects.drafts(), pk=order_pk)
- taxes = None # FIXME
- form = OrderShippingForm(request.POST or None, instance=order, taxes=taxes)
+ form = OrderShippingForm(request.POST or None, instance=order)
status = 200
if form.is_valid():
form.save()
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index a270d47983..12a779e15b 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -243,9 +243,7 @@ class CheckoutLinesAdd(BaseMutation):
for variant, quantity in zip(variants, quantities):
add_variant_to_checkout(checkout, variant, quantity, replace=replace)
- recalculate_checkout_discount(
- checkout, info.context.discounts, info.context.taxes # FIXME
- )
+ recalculate_checkout_discount(checkout, info.context.discounts)
return CheckoutLinesAdd(checkout=checkout)
@@ -290,9 +288,7 @@ class CheckoutLineDelete(BaseMutation):
discounts=info.context.discounts,
)
- recalculate_checkout_discount(
- checkout, info.context.discounts, info.context.taxes # FIXME
- )
+ recalculate_checkout_discount(checkout, info.context.discounts)
return CheckoutLineDelete(checkout=checkout)
@@ -371,9 +367,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
with transaction.atomic():
shipping_address.save()
change_shipping_address_in_checkout(checkout, shipping_address)
- recalculate_checkout_discount(
- checkout, info.context.discounts, info.context.taxes # FIXME
- )
+ recalculate_checkout_discount(checkout, info.context.discounts)
return CheckoutShippingAddressUpdate(checkout=checkout)
@@ -461,9 +455,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):
checkout.shipping_method = shipping_method
checkout.save(update_fields=["shipping_method"])
- recalculate_checkout_discount(
- checkout, info.context.discounts, info.context.taxes # FIXME
- )
+ recalculate_checkout_discount(checkout, info.context.discounts)
return CheckoutShippingMethodUpdate(checkout=checkout)
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index ad52874f02..f6dd38a2fa 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -12,6 +12,7 @@ from ....order.utils import (
change_order_line_quantity,
delete_order_line,
recalculate_order,
+ update_order_prices,
)
from ...account.i18n import I18nMixin
from ...account.types import AddressInput
@@ -107,16 +108,20 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
return cleaned_input
@staticmethod
- def _save_addresses(instance, cleaned_input):
+ def _save_addresses(info, instance: models.Order, cleaned_input):
# Create the draft creation event
shipping_address = cleaned_input.get("shipping_address")
if shipping_address:
shipping_address.save()
instance.shipping_address = shipping_address.get_copy()
+ if instance.is_shipping_required():
+ update_order_prices(instance, info.context.discounts)
billing_address = cleaned_input.get("billing_address")
if billing_address:
billing_address.save()
instance.billing_address = billing_address.get_copy()
+ if not instance.is_shipping_required():
+ update_order_prices(instance, info.context.discounts)
@staticmethod
def _save_lines(info, instance, quantities, variants):
@@ -151,7 +156,7 @@ class DraftOrderCreate(ModelMutation, I18nMixin):
@classmethod
def save(cls, info, instance, cleaned_input):
# Process addresses
- cls._save_addresses(instance, cleaned_input)
+ cls._save_addresses(info, instance, cleaned_input)
# Save any changes create/update the draft
cls._commit_changes(info, instance, cleaned_input)
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index d72984cd32..9674a7344f 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -2,7 +2,7 @@ import graphene
from django.core.exceptions import ValidationError
from ....account.models import User
-from ....core.taxes import ZERO_TAXED_MONEY
+from ....core.taxes import ZERO_TAXED_MONEY, interface as tax_interface
from ....order import events, models
from ....order.utils import cancel_order
from ....payment import CustomPaymentChoices, PaymentError
@@ -172,7 +172,7 @@ class OrderUpdateShipping(BaseMutation):
clean_order_update_shipping(order, method)
order.shipping_method = method
- order.shipping_price = method.get_total(info.context.taxes) # FIXME
+ order.shipping_price = tax_interface.calculate_order_shipping(order)
order.shipping_method_name = method.name
order.save(
update_fields=[
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 8640571236..9e241eb833 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -1,4 +1,3 @@
-from decimal import Decimal
from functools import wraps
from django.conf import settings
@@ -9,7 +8,7 @@ from prices import Money, TaxedMoney
from ..account.utils import store_user_address
from ..checkout import AddressType
from ..core.taxes import ZERO_MONEY
-from ..core.taxes.interface import refresh_order_line_unit_price
+from ..core.taxes.interface import apply_taxes_to_order_line_unit_price
from ..core.weight import zero_weight
from ..dashboard.order.utils import get_voucher_discount_for_order
from ..discount.models import NotApplicable
@@ -156,7 +155,8 @@ def update_order_prices(order, discounts):
"""Update prices in order with given discounts and proper taxes."""
for line in order:
if line.variant:
- price = refresh_order_line_unit_price(line, discounts)
+ unit_net_price = line.variant.get_price(discounts)
+ price = apply_taxes_to_order_line_unit_price(line, unit_net_price)
line.unit_price = price
line.tax_rate = 0 # Fixme we can calulcate tax_rate based on prices
line.save()
@@ -252,10 +252,8 @@ def add_variant_to_order(
variant,
quantity,
discounts=None,
- taxes=None,
allow_overselling=False,
track_inventory=True,
- unit_tax=Decimal("0.0"),
):
"""Add total_quantity of variant to order.
@@ -267,17 +265,12 @@ def add_variant_to_order(
if not allow_overselling:
variant.check_quantity(quantity)
- # FIXME maybe something more prettier ?
- unit_price_net = variant.get_price(discounts)
- unit_price_gross = Money(
- amount=unit_price_net.amount + unit_tax, currency=unit_price_net.currency
- )
- unit_price = TaxedMoney(net=unit_price_net, gross=unit_price_gross)
try:
line = order.lines.get(variant=variant)
line.quantity += quantity
line.save(update_fields=["quantity"])
except OrderLine.DoesNotExist:
+ unit_price_net = variant.get_price(discounts)
product_name = variant.display_product()
translated_product_name = variant.display_product(translated=True)
if translated_product_name == product_name:
@@ -288,11 +281,17 @@ def add_variant_to_order(
product_sku=variant.sku,
is_shipping_required=variant.is_shipping_required(),
quantity=quantity,
+ unit_price_net=unit_price_net,
+ unit_price_gross=unit_price_net,
variant=variant,
- unit_price=unit_price,
- tax_rate=0,
)
+ unit_price = apply_taxes_to_order_line_unit_price(line, unit_price_net)
+ line.unit_price_net = unit_price.net
+ line.unit_price_gross = unit_price.gross
+ line.tax_rate = unit_price.tax / unit_price.net
+ line.save(update_fields=["unit_price_net", "unit_price_gross", "tax_rate"])
+
if variant.track_inventory and track_inventory:
allocate_stock(variant, quantity)
return line
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 500b94c54d..00ec1045ab 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -318,7 +318,7 @@ class ProductVariant(models.Model):
return images[0] if images else self.product.get_first_image()
def get_ajax_label(self, discounts=None):
- price = self.get_price(discounts).gross
+ price = self.get_price(discounts)
return "%s, %s, %s" % (
self.sku,
self.display_product(),