Skip to content

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

Use Money, instead of TaxedMoney in internal operations

Maciej Korycinskif12315274633
diff --git a/.isort.cfg b/.isort.cfg
index 1a53a79fc4..5b10bef763 100644
--- a/.isort.cfg
+++ b/.isort.cfg
@@ -1,2 +1,2 @@
[settings]
-known_third_party = PIL,babel,bleach,bootstrap4,braintree,captcha,celery,dj_database_url,dj_email_url,django,django_babel,django_cache_url,django_countries,django_elasticsearch_dsl,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,elasticsearch_dsl,faker,freezegun,geolite2,google_measurement_protocol,graphene,graphene_django,graphene_django_optimizer,graphql,graphql_jwt,graphql_relay,html5lib,i18naddress,impersonate,markdown,measurement,mptt,phonenumber_field,phonenumbers,prices,promise,pytest,razorpay,six,social_core,social_django,storages,stripe,templated_email,text_unidecode,versatileimagefield
+known_third_party = PIL,babel,bleach,bootstrap4,braintree,captcha,celery,dj_database_url,dj_email_url,django,django_babel,django_cache_url,django_countries,django_elasticsearch_dsl,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,elasticsearch_dsl,faker,freezegun,geolite2,google_measurement_protocol,graphene,graphene_django,graphene_django_optimizer,graphql,graphql_jwt,graphql_relay,html5lib,i18naddress,impersonate,markdown,measurement,mptt,phonenumber_field,phonenumbers,prices,promise,pytest,razorpay,requests,six,social_core,social_django,storages,stripe,templated_email,text_unidecode,versatileimagefield
diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.py
index 0c6cc6d377..bcc5aa71f6 100644
--- a/saleor/checkout/forms.py
+++ b/saleor/checkout/forms.py
@@ -1,6 +1,5 @@
"""Checkout-related forms and fields."""
from datetime import date
-from decimal import Decimal
from typing import Any
from django import forms
@@ -10,12 +9,10 @@ from django.utils.encoding import smart_text
from django.utils.safestring import mark_safe
from django.utils.translation import npgettext_lazy, pgettext_lazy
from django_countries.fields import LazyTypedChoiceField
-from prices import Money, TaxedMoney
-
-from saleor.core.taxes.interface import apply_taxes_to_shipping, get_subtotal_gross
from ..core.exceptions import InsufficientStock
from ..core.taxes import display_gross_prices
+from ..core.taxes.interface import apply_taxes_to_shipping, get_subtotal_gross
from ..core.utils import format_money
from ..discount.models import NotApplicable, Voucher
from ..shipping.models import ShippingMethod, ShippingZone
@@ -73,7 +70,7 @@ class AddToCheckoutForm(forms.Form):
self.checkout = kwargs.pop("checkout")
self.product = kwargs.pop("product")
self.discounts = kwargs.pop("discounts", ())
- self.taxes = kwargs.pop("taxes", {})
+ self.country = kwargs.pop("country", {})
super().__init__(*args, **kwargs)
def add_error_i18n(self, field, error_name, fmt: Any = tuple()):
@@ -193,7 +190,6 @@ class CountryForm(forms.Form):
)
def __init__(self, *args, **kwargs):
- self.taxes = kwargs.pop("taxes", {})
super().__init__(*args, **kwargs)
available_countries = {
(country.code, country.name)
@@ -208,8 +204,8 @@ class CountryForm(forms.Form):
"""Return a shipping price range for given order for the selected
country.
"""
- code = self.cleaned_data["country"]
- return get_shipping_price_estimate(price, weight, code, self.taxes)
+ country = self.cleaned_data["country"]
+ return get_shipping_price_estimate(price, weight, country)
class AnonymousUserShippingForm(forms.ModelForm):
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index b12880c840..bc34fd58b3 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -11,7 +11,7 @@ from django.utils.encoding import smart_str
from django_prices.models import MoneyField
from ..account.models import Address
-from ..core.taxes import ZERO_TAXED_MONEY, zero_money
+from ..core.taxes import zero_money
from ..core.weight import zero_weight
from ..shipping.models import ShippingMethod
@@ -92,23 +92,23 @@ class Checkout(models.Model):
"""Return `True` if any of the lines requires shipping."""
return any(line.is_shipping_required() for line in self)
- def get_shipping_price(self, taxes):
+ def get_shipping_price(self):
return (
- self.shipping_method.get_total(taxes)
+ self.shipping_method.get_total()
if self.shipping_method and self.is_shipping_required()
- else ZERO_TAXED_MONEY
+ else zero_money()
)
- def get_subtotal(self, discounts=None, taxes=None):
+ def get_subtotal(self, discounts=None):
"""Return the total cost of the checkout prior to shipping."""
- subtotals = (line.get_total(discounts, taxes) for line in self)
- return sum(subtotals, ZERO_TAXED_MONEY)
+ subtotals = (line.get_total(discounts) for line in self)
+ return sum(subtotals, zero_money())
- def get_total(self, discounts=None, taxes=None):
+ def get_total(self, discounts=None):
"""Return the total cost of the checkout."""
return (
- self.get_subtotal(discounts, taxes)
- + self.get_shipping_price(taxes)
+ self.get_subtotal(discounts)
+ + self.get_shipping_price()
- self.discount_amount
)
@@ -172,9 +172,9 @@ class CheckoutLine(models.Model):
def __setstate__(self, data):
self.variant, self.quantity = data
- def get_total(self, discounts=None, taxes=None):
+ def get_total(self, discounts=None):
"""Return the total price of this line."""
- amount = self.quantity * self.variant.get_price(discounts, taxes)
+ amount = self.quantity * self.variant.get_price(discounts)
return amount.quantize(CENTS)
def is_shipping_required(self):
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index c5321b3beb..59adc0ac9a 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -1,17 +1,15 @@
"""Checkout-related utility functions."""
from datetime import date, timedelta
-from decimal import Decimal
from functools import wraps
from uuid import UUID
-from django.conf import settings
from django.contrib import messages
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Sum
from django.utils.encoding import smart_text
from django.utils.translation import get_language, pgettext, pgettext_lazy
-from prices import TaxedMoney, TaxedMoneyRange
+from prices import TaxedMoneyRange
from ..account.forms import get_address_form
from ..account.models import Address, User
@@ -20,12 +18,12 @@ 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,
)
-from ..core.taxes.vatlayer import get_taxes_for_country # FIXME
from ..core.utils import to_local_currency
from ..discount import VoucherType
from ..discount.models import NotApplicable, Voucher
@@ -642,9 +640,7 @@ def change_shipping_address_in_checkout(checkout, address):
checkout.save(update_fields=["shipping_address"])
-def get_checkout_context(
- checkout, discounts, taxes, currency=None, shipping_range=None
-):
+def get_checkout_context(checkout, discounts, currency=None, shipping_range=None):
"""Data shared between views in checkout process."""
checkout_total = get_total_gross(checkout, discounts)
checkout_subtotal = get_subtotal_gross(checkout, discounts)
@@ -661,7 +657,7 @@ def get_checkout_context(
"checkout": checkout,
"checkout_are_taxes_handled": True, # bool(taxes), #FIXME
"checkout_lines": [
- (line, line.get_total(discounts, taxes)) for line in checkout
+ (line, get_line_total_gross(line, discounts)) for line in checkout
],
"checkout_shipping_price": shipping_price,
"checkout_subtotal": checkout_subtotal,
@@ -760,7 +756,7 @@ def get_voucher_for_checkout(checkout, vouchers=None):
return None
-def recalculate_checkout_discount(checkout, discounts, taxes):
+def recalculate_checkout_discount(checkout, discounts):
"""Recalculate `checkout.discount` based on the voucher.
Will clear both voucher and discount if the discount is no longer
@@ -773,7 +769,7 @@ def recalculate_checkout_discount(checkout, discounts, taxes):
except NotApplicable:
remove_voucher_from_checkout(checkout)
else:
- subtotal = checkout.get_subtotal(discounts, taxes).gross
+ subtotal = get_subtotal_gross(checkout, discounts).gross
checkout.discount_amount = min(discount, subtotal)
checkout.discount_name = str(voucher)
checkout.translated_discount_name = (
@@ -829,17 +825,6 @@ def remove_voucher_from_checkout(checkout):
)
-def get_taxes_for_checkout(checkout, default_taxes):
- """Return taxes (if handled) due to shipping address or default one."""
- if not settings.VATLAYER_ACCESS_KEY:
- return None
-
- if checkout.shipping_address:
- return get_taxes_for_country(checkout.shipping_address.country)
-
- return default_taxes
-
-
def is_valid_shipping_method(checkout, discounts):
"""Check if shipping method is valid and remove (if not)."""
if not checkout.shipping_method:
@@ -924,7 +909,7 @@ def _process_user_data_for_order(checkout):
@transaction.atomic
-def create_order(checkout: Checkout, tracking_code: str, discounts, taxes, user: User):
+def create_order(checkout: Checkout, tracking_code: str, discounts, user: User):
"""Create an order from the checkout.
Each order will get a private copy of both the billing and the shipping
@@ -981,16 +966,16 @@ def create_order(checkout: Checkout, tracking_code: str, discounts, taxes, user:
return order
-def is_fully_paid(checkout: Checkout, taxes, discounts):
+def is_fully_paid(checkout: Checkout, discounts):
"""Check if provided payment methods cover the checkout's total amount.
Note that these payments may not be captured or charged at all."""
payments = [payment for payment in checkout.payments.all() if payment.is_active]
total_paid = sum([p.total for p in payments])
- checkout_total = checkout.get_total(discounts=discounts, taxes=taxes).gross.amount
- return total_paid >= checkout_total
+ checkout_total = get_total_gross(checkout, discounts=discounts).gross
+ return total_paid >= checkout_total.amount
-def clean_checkout(checkout: Checkout, taxes, discounts):
+def clean_checkout(checkout: Checkout, discounts):
"""Check if checkout can be completed."""
if checkout.is_shipping_required():
if not checkout.shipping_method:
@@ -1005,7 +990,7 @@ def clean_checkout(checkout: Checkout, taxes, discounts):
if not checkout.billing_address:
raise ValidationError("Billing address is not set")
- if not is_fully_paid(checkout, taxes, discounts):
+ if not is_fully_paid(checkout, discounts):
raise ValidationError(
"Provided payment methods can not cover the checkout's total " "amount"
)
diff --git a/saleor/checkout/views/__init__.py b/saleor/checkout/views/__init__.py
index c8d5b7b4c9..f4bf3f8c94 100644
--- a/saleor/checkout/views/__init__.py
+++ b/saleor/checkout/views/__init__.py
@@ -4,6 +4,7 @@ from django.shortcuts import get_object_or_404, redirect, render
from django.template.response import TemplateResponse
from ...account.forms import LoginForm
+from ...core.taxes import interface as tax_interface
from ...core.utils import format_money, get_user_shipping_country, to_local_currency
from ...shipping.utils import get_shipping_price_estimate
from ..forms import CheckoutShippingMethodForm, CountryForm, ReplaceCheckoutLineForm
@@ -12,7 +13,6 @@ from ..utils import (
check_product_availability_and_warn,
get_checkout_context,
get_or_empty_db_checkout,
- get_taxes_for_checkout,
is_valid_shipping_method,
update_checkout_quantity,
)
@@ -70,7 +70,6 @@ def checkout_shipping_address(request, checkout):
def checkout_shipping_method(request, checkout):
"""Display the shipping method selection step."""
discounts = request.discounts
- taxes = get_taxes_for_checkout(checkout, request.taxes)
is_valid_shipping_method(checkout, discounts)
form = CheckoutShippingMethodForm(
@@ -83,7 +82,7 @@ def checkout_shipping_method(request, checkout):
form.save()
return redirect("checkout:summary")
- ctx = get_checkout_context(checkout, discounts, taxes)
+ ctx = get_checkout_context(checkout, discounts)
ctx.update({"shipping_method_form": form})
return TemplateResponse(request, "checkout/shipping_method.html", ctx)
@@ -107,7 +106,6 @@ def checkout_order_summary(request, checkout):
def checkout_index(request, checkout):
"""Display checkout details."""
discounts = request.discounts
- taxes = request.taxes
checkout_lines = []
check_product_availability_and_warn(request, checkout)
@@ -136,13 +134,16 @@ def checkout_index(request, checkout):
variant=line.variant,
initial=initial,
discounts=discounts,
- taxes=taxes,
)
+ variant_price = line.variant.get_price(discounts)
+
checkout_lines.append(
{
"variant": line.variant,
- "get_price": line.variant.get_price(discounts, taxes),
- "get_total": line.get_total(discounts, taxes),
+ "get_price": tax_interface.apply_taxes_to_variant(
+ line.variant, variant_price, request.country
+ ),
+ "get_total": tax_interface.get_line_total_gross(line, discounts),
"form": form,
}
)
@@ -150,16 +151,14 @@ def checkout_index(request, checkout):
default_country = get_user_shipping_country(request)
country_form = CountryForm(initial={"country": default_country})
shipping_price_range = get_shipping_price_estimate(
- price=checkout.get_subtotal(discounts, taxes).gross,
+ price=tax_interface.get_subtotal_gross(checkout, discounts).gross,
weight=checkout.get_total_weight(),
country_code=default_country,
- taxes=taxes,
)
context = get_checkout_context(
checkout,
discounts,
- taxes,
currency=request.currency,
shipping_range=shipping_price_range,
)
@@ -177,10 +176,10 @@ def checkout_index(request, checkout):
@get_or_empty_db_checkout(checkout_queryset=Checkout.objects.for_display())
def checkout_shipping_options(request, checkout):
"""Display shipping options to get a price estimate."""
- country_form = CountryForm(request.POST or None, taxes=request.taxes)
+ country_form = CountryForm(request.POST or None)
if country_form.is_valid():
shipping_price_range = country_form.get_shipping_price_estimate(
- price=checkout.get_subtotal(request.discounts, request.taxes).gross,
+ price=tax_interface.get_subtotal_gross(checkout, request.discounts).gross,
weight=checkout.get_total_weight(),
)
else:
@@ -189,7 +188,6 @@ def checkout_shipping_options(request, checkout):
checkout_data = get_checkout_context(
checkout,
request.discounts,
- request.taxes,
currency=request.currency,
shipping_range=shipping_price_range,
)
@@ -205,25 +203,25 @@ def update_checkout_line(request, checkout, variant_id):
checkout_line = get_object_or_404(checkout.lines, variant_id=variant_id)
discounts = request.discounts
- taxes = request.taxes
status = None
form = ReplaceCheckoutLineForm(
request.POST,
checkout=checkout,
variant=checkout_line.variant,
discounts=discounts,
- taxes=taxes,
)
if form.is_valid():
form.save()
response = {
"variantId": variant_id,
- "subtotal": format_money(checkout_line.get_total(discounts, taxes).gross),
+ "subtotal": format_money(
+ tax_interface.get_line_total_gross(checkout_line, discounts).gross
+ ),
"total": 0,
"checkout": {"numItems": checkout.quantity, "numLines": len(checkout)},
}
- checkout_total = checkout.get_subtotal(discounts, taxes)
+ checkout_total = tax_interface.get_subtotal_gross(checkout, discounts)
response["total"] = format_money(checkout_total.gross)
local_checkout_total = to_local_currency(checkout_total, request.currency)
if local_checkout_total is not None:
@@ -251,7 +249,6 @@ def clear_checkout(request, checkout):
def checkout_dropdown(request, checkout):
"""Display a checkout summary suitable for displaying on all pages."""
discounts = request.discounts
- taxes = request.taxes
def prepare_line_data(line):
first_image = line.variant.get_first_image()
@@ -262,7 +259,7 @@ def checkout_dropdown(request, checkout):
"variant": line.variant,
"quantity": line.quantity,
"image": first_image,
- "line_total": line.get_total(discounts, taxes),
+ "line_total": tax_interface.get_line_total_gross(line, discounts),
"variant_url": line.variant.get_absolute_url(),
}
@@ -271,7 +268,7 @@ def checkout_dropdown(request, checkout):
else:
data = {
"quantity": checkout.quantity,
- "total": checkout.get_subtotal(discounts, taxes),
+ "total": tax_interface.get_subtotal_gross(checkout, discounts),
"lines": [prepare_line_data(line) for line in checkout],
}
diff --git a/saleor/checkout/views/discount.py b/saleor/checkout/views/discount.py
index f726b5f407..35400d5de0 100644
--- a/saleor/checkout/views/discount.py
+++ b/saleor/checkout/views/discount.py
@@ -12,7 +12,6 @@ from ..forms import CheckoutVoucherForm
from ..models import Checkout
from ..utils import (
get_or_empty_db_checkout,
- get_taxes_for_checkout,
recalculate_checkout_discount,
remove_voucher_from_checkout,
)
@@ -38,8 +37,7 @@ def add_voucher_form(view):
# if only discount form was used we clear post for other forms
request.POST = {}
else:
- taxes = get_taxes_for_checkout(checkout, request.taxes)
- recalculate_checkout_discount(checkout, request.discounts, taxes)
+ recalculate_checkout_discount(checkout, request.discounts)
response = view(request, checkout)
if isinstance(response, TemplateResponse):
response.context_data["voucher_form"] = voucher_form
diff --git a/saleor/checkout/views/shipping.py b/saleor/checkout/views/shipping.py
index af89c1f1e6..e85c63028b 100644
--- a/saleor/checkout/views/shipping.py
+++ b/saleor/checkout/views/shipping.py
@@ -3,7 +3,6 @@ from django.template.response import TemplateResponse
from ..utils import (
get_checkout_context,
- get_taxes_for_checkout,
update_shipping_address_in_anonymous_checkout,
update_shipping_address_in_checkout,
)
@@ -18,8 +17,7 @@ def anonymous_user_shipping_address_view(request, checkout):
if updated:
return redirect("checkout:shipping-method")
- taxes = get_taxes_for_checkout(checkout, request.taxes)
- ctx = get_checkout_context(checkout, request.discounts, taxes)
+ ctx = get_checkout_context(checkout, request.discounts)
ctx.update({"address_form": address_form, "user_form": user_form})
return TemplateResponse(request, "checkout/shipping_address.html", ctx)
@@ -40,8 +38,7 @@ def user_shipping_address_view(request, checkout):
if updated:
return redirect("checkout:shipping-method")
- taxes = get_taxes_for_checkout(checkout, request.taxes)
- ctx = get_checkout_context(checkout, request.discounts, taxes)
+ ctx = get_checkout_context(checkout, request.discounts)
ctx.update(
{
"additional_addresses": user_addresses,
diff --git a/saleor/checkout/views/summary.py b/saleor/checkout/views/summary.py
index 276664cf60..f51da6e16e 100644
--- a/saleor/checkout/views/summary.py
+++ b/saleor/checkout/views/summary.py
@@ -12,7 +12,6 @@ from ..forms import CheckoutNoteForm
from ..utils import (
create_order,
get_checkout_context,
- get_taxes_for_checkout,
update_billing_address_in_anonymous_checkout,
update_billing_address_in_checkout,
update_billing_address_in_checkout_with_shipping,
@@ -31,7 +30,6 @@ def _handle_order_placement(request, checkout):
checkout=checkout,
tracking_code=analytics.get_client_id(request),
discounts=request.discounts,
- taxes=get_taxes_for_checkout(checkout, request.taxes),
user=request.user,
)
except InsufficientStock:
@@ -74,8 +72,7 @@ def summary_with_shipping_view(request, checkout):
if updated:
return _handle_order_placement(request, checkout)
- taxes = get_taxes_for_checkout(checkout, request.taxes)
- ctx = get_checkout_context(checkout, request.discounts, taxes)
+ ctx = get_checkout_context(checkout, request.discounts)
ctx.update(
{
"additional_addresses": user_addresses,
@@ -103,8 +100,7 @@ def anonymous_summary_without_shipping(request, checkout):
if updated:
return _handle_order_placement(request, checkout)
- taxes = get_taxes_for_checkout(checkout, request.taxes)
- ctx = get_checkout_context(checkout, request.discounts, taxes)
+ ctx = get_checkout_context(checkout, request.discounts)
ctx.update(
{"address_form": address_form, "note_form": note_form, "user_form": user_form}
)
@@ -129,8 +125,7 @@ def summary_without_shipping(request, checkout):
if updated:
return _handle_order_placement(request, checkout)
- taxes = get_taxes_for_checkout(checkout, request.taxes)
- ctx = get_checkout_context(checkout, request.discounts, taxes)
+ ctx = get_checkout_context(checkout, request.discounts)
ctx.update(
{
"additional_addresses": user_addresses,
diff --git a/saleor/core/taxes/avatax/__init__.py b/saleor/core/taxes/avatax/__init__.py
index e6349d448f..61240d4220 100644
--- a/saleor/core/taxes/avatax/__init__.py
+++ b/saleor/core/taxes/avatax/__init__.py
@@ -1,6 +1,6 @@
import json
from datetime import date
-from typing import Any, Dict, List, Optional
+from typing import TYPE_CHECKING, Any, Dict, List, Optional
from urllib.parse import urljoin
import requests
@@ -10,6 +10,11 @@ from requests.auth import HTTPBasicAuth
from .. import charge_taxes_on_shipping
+if TYPE_CHECKING:
+ from ....checkout.models import Checkout
+ from ....order.models import Order
+
+
common_carrier_code = "FR020100" # FIXME
cache_key = "avatax_request_id_" # FIXME
@@ -128,8 +133,9 @@ def get_checkout_lines_data(
append_line_to_data(
data=data,
quantity=line.quantity,
- amount=str(line.get_total(discounts).net.amount),
- tax_code="PC040156", # FIXME Should fetch taxcode from somewhere and save inside variant/product
+ amount=str(line.get_total(discounts).amount),
+ # FIXME Should fetch taxcode from somewhere and save inside variant/product
+ tax_code="PC040156",
item_code=line.variant.sku,
description=description,
)
diff --git a/saleor/core/taxes/avatax/interface.py b/saleor/core/taxes/avatax/interface.py
index b41bb9f101..6574c189ad 100644
--- a/saleor/core/taxes/avatax/interface.py
+++ b/saleor/core/taxes/avatax/interface.py
@@ -1,41 +1,41 @@
from collections import defaultdict
from datetime import date
from decimal import Decimal
+from typing import TYPE_CHECKING
from urllib.parse import urljoin
from prices import Money, TaxedMoney
-from ....checkout.models import Checkout
+from ....checkout import models as checkout_models
from ....discount.models import Sale
-from ....order.models import Order
from ..errors import TaxError
from . import (
TransactionType,
api_post_request,
- common_carrier_code,
- generate_request_data,
generate_request_data_from_checkout,
get_api_url,
- get_cached_response_or_fetch,
get_checkout_tax_data,
get_order_tax_data,
validate_checkout,
)
+if TYPE_CHECKING:
+ from ....order.models import Order, OrderLine
-def get_total_gross(checkout: "Checkout", discounts):
+
+def get_total_gross(checkout: "checkout_models.Checkout", discounts):
if not validate_checkout(checkout):
return checkout.get_total(discounts=discounts)
response = get_checkout_tax_data(checkout, discounts)
tax = Decimal(response.get("totalTax", "0.0"))
- total_net = checkout.get_total(discounts=discounts).net
+ total_net = checkout.get_total(discounts=discounts)
total_gross = Money(amount=total_net.amount + tax, currency=total_net.currency)
total = TaxedMoney(net=total_net, gross=total_gross)
return total
-def get_subtotal_gross(checkout: "Checkout", discounts):
+def get_subtotal_gross(checkout: "checkout_models.Checkout", discounts):
if not validate_checkout(checkout):
return checkout.get_subtotal(discounts)
response = get_checkout_tax_data(checkout, discounts)
@@ -45,15 +45,15 @@ def get_subtotal_gross(checkout: "Checkout", discounts):
if line["itemCode"] == "Shipping":
continue
sub_tax += Decimal(line["tax"])
- sub_total_net = checkout.get_subtotal(discounts).net
+ sub_total_net = checkout.get_subtotal(discounts)
sub_total_gross = Money(sub_total_net.amount + sub_tax, sub_total_net.currency)
sub_total = TaxedMoney(net=sub_total_net, gross=sub_total_gross)
return sub_total
-def get_shipping_gross(checkout: "Checkout", discounts):
+def get_shipping_gross(checkout: "checkout_models.Checkout", discounts):
if not validate_checkout(checkout):
- return checkout.get_shipping_price(None)
+ return checkout.get_shipping_price()
response = get_checkout_tax_data(checkout, discounts)
shipping_tax = Decimal(0.0)
@@ -62,14 +62,14 @@ def get_shipping_gross(checkout: "Checkout", discounts):
shipping_tax = Decimal(line["tax"])
break
- shipping_net = checkout.get_shipping_price(None).net
+ shipping_net = checkout.get_shipping_price()
shipping_gross = Money(shipping_net.amount + shipping_tax, shipping_net.currency)
shipping_total = TaxedMoney(net=shipping_net, gross=shipping_gross)
return shipping_total
-def get_lines_with_taxes(checkout: "Checkout", discounts):
+def get_lines_with_taxes(checkout: "checkout_models.Checkout", discounts):
"""Calculate and return tuple (line, unit_tax)"""
lines_taxes = defaultdict(lambda: Decimal("0.0"))
@@ -92,7 +92,7 @@ def postprocess_order_creation_with_taxes(order: "Order"):
# FIXME this can be a celery task (?)
# FIXME maybe we can figure out better name
- checkout = Checkout.objects.get(token=order.checkout_token)
+ checkout = checkout_models.Checkout.objects.get(token=order.checkout_token)
discounts = Sale.objects.active(date.today()).prefetch_related(
"products", "categories", "collections"
)
@@ -102,32 +102,34 @@ def postprocess_order_creation_with_taxes(order: "Order"):
transaction_type=TransactionType.INVOICE,
discounts=discounts,
)
- transaction_url = urljoin(get_api_url(), "transactions/create")
+ transaction_url = urljoin(get_api_url(), "transactions/createoradjust")
response = api_post_request(transaction_url, data)
# FIXME errors for users (?)
if not response or "error" in response:
raise TaxError(response.get("error", {}).get("message", ""))
-def get_line_total_gross(checkout_line: "CheckoutLine", discounts):
+def get_line_total_gross(checkout_line: "checkout_models.CheckoutLine", discounts):
checkout = checkout_line.checkout
taxes_data = get_checkout_tax_data(checkout, discounts)
for line in taxes_data.get("lines", []):
if line.get("itemCode") == checkout_line.variant.sku:
tax = Decimal(line.get("tax", "0.0"))
- net = checkout_line.get_total(discounts).net
+ net = checkout_line.get_total(discounts)
return Money(amount=net.amount + tax, currency=net.currency)
return checkout_line.get_total(discounts).gross
-def get_order_line_total_gross(order_line: "OrderLine", discounts):
+def refresh_order_line_unit_price(order_line: "OrderLine", discounts):
order = order_line.order
taxes_data = get_order_tax_data(order, discounts)
for line in taxes_data.get("lines", []):
if line.get("itemCode") == order_line.variant.sku:
tax = Decimal(line.get("tax", "0.0"))
- net = order_line.variant.get_total(discounts).net
- return Money(amount=net.amount + tax, currency=net.currency)
- return order_line.variant.get_total(discounts).gross
+ net = order_line.variant.get_price(discounts)
+ 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)
diff --git a/saleor/core/taxes/interface.py b/saleor/core/taxes/interface.py
index a68bdd78c1..7f2f37d0c3 100644
--- a/saleor/core/taxes/interface.py
+++ b/saleor/core/taxes/interface.py
@@ -1,17 +1,25 @@
+# from __future__ import annotations
from collections import defaultdict
from decimal import Decimal
+from typing import TYPE_CHECKING
from django.conf import settings
-from prices import Money, TaxedMoney
+from django_countries.fields import Country
+from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
-from ...checkout.models import Checkout
-from ...discount.models import SaleQueryset
from . import ZERO_TAXED_MONEY
from .avatax import interface as avatax_interface
from .vatlayer import interface as vatlayer_interface
+if TYPE_CHECKING:
+ from ...discount.models import SaleQueryset
+ from ...checkout.models import Checkout, CheckoutLine
+ from ...product.models import Product, ProductVariant
+ from ...account.models import Address
+ from ...order.models import OrderLine
-def get_total_gross(checkout: Checkout, discounts: SaleQueryset) -> TaxedMoney:
+
+def get_total_gross(checkout: "Checkout", discounts: "SaleQueryset") -> TaxedMoney:
"""Calculate total gross for checkout"""
if settings.VATLAYER_ACCESS_KEY:
@@ -19,10 +27,11 @@ def get_total_gross(checkout: Checkout, discounts: SaleQueryset) -> TaxedMoney:
elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
return avatax_interface.get_total_gross(checkout, discounts)
- return checkout.get_total(discounts)
+ total = checkout.get_total(discounts)
+ return TaxedMoney(net=total, gross=total)
-def get_subtotal_gross(checkout: Checkout, discounts: SaleQueryset) -> TaxedMoney:
+def get_subtotal_gross(checkout: "Checkout", discounts: "SaleQueryset") -> TaxedMoney:
"""Calculate subtotal gross for checkout"""
if settings.VATLAYER_ACCESS_KEY:
@@ -30,10 +39,11 @@ def get_subtotal_gross(checkout: Checkout, discounts: SaleQueryset) -> TaxedMone
elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
return avatax_interface.get_subtotal_gross(checkout, discounts)
- return checkout.get_subtotal(discounts)
+ subtotal = checkout.get_subtotal(discounts)
+ return TaxedMoney(net=subtotal, gross=subtotal)
-def get_shipping_gross(checkout: Checkout, discounts: SaleQueryset) -> TaxedMoney:
+def get_shipping_gross(checkout: "Checkout", discounts: "SaleQueryset") -> TaxedMoney:
"""Calculate shipping gross for checkout"""
if not checkout.shipping_method:
return ZERO_TAXED_MONEY
@@ -41,10 +51,11 @@ def get_shipping_gross(checkout: Checkout, discounts: SaleQueryset) -> TaxedMone
return vatlayer_interface.get_shipping_gross(checkout, discounts)
elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
return avatax_interface.get_shipping_gross(checkout, discounts)
- return checkout.shipping_method.get_total()
+ total = checkout.shipping_method.get_total()
+ return TaxedMoney(net=total, gross=total)
-def get_lines_with_taxes(checkout: Checkout, discounts):
+def get_lines_with_taxes(checkout: "Checkout", discounts):
lines_taxes = defaultdict(lambda: Decimal("0.0"))
if settings.VATLAYER_ACCESS_KEY:
@@ -56,13 +67,13 @@ def get_lines_with_taxes(checkout: Checkout, discounts):
def apply_taxes_to_shipping(price: Money, shipping_address: "Address") -> TaxedMoney:
- """Apply taxes for shiping methods that user can use during checkout"""
-
- 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
- pass
+ """Apply taxes for shipping methods that user can use during checkout"""
+ if shipping_address:
+ 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
+ pass
return TaxedMoney(net=price, gross=price)
@@ -74,25 +85,31 @@ def get_tax_rate_type_choices():
return []
-def get_line_total_gross(checkout_line: "CheckoutLine", discounts):
+def get_line_total_gross(checkout_line: "CheckoutLine", discounts: "SaleQueryset"):
if settings.VATLAYER_ACCESS_KEY:
return checkout_line.get_total(discounts) # FIXME
if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
return avatax_interface.get_line_total_gross(checkout_line, discounts)
- return checkout_line.get_total(discounts)
+ total = checkout_line.get_total(discounts)
+ return TaxedMoney(net=total, gross=total)
-def get_order_line_total_gross(order_line: "OrderLine", discounts):
+def refresh_order_line_unit_price(order_line: "OrderLine", discounts: "SaleQueryset"):
+ """It updates unit_price for a given order line based on current price of variant"""
if settings.VATLAYER_ACCESS_KEY:
- return order_line.variant.get_price(
- discounts
- ) # FIXME unit_price or total_price ?
+ 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
+ )
if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
- return avatax_interface.get_order_line_total_gross(order_line, discounts)
- return order_line.variant.get_price(discounts) # FIXME unit_price or total_price ?
+ return avatax_interface.refresh_order_line_unit_price(order_line, discounts)
+ price = order_line.variant.get_price(discounts)
+ return TaxedMoney(net=price, gross=price)
-def apply_taxes_to_variant(variant: "ProductVariant", price: Money, country: "Country"):
+def apply_taxes_to_variant(variant: "ProductVariant", price: Money, country: Country):
if settings.VATLAYER_ACCESS_KEY:
return vatlayer_interface.apply_taxes_to_variant(variant, price, country)
if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
@@ -102,9 +119,31 @@ def apply_taxes_to_variant(variant: "ProductVariant", price: Money, country: "Co
return TaxedMoney(net=price, gross=price)
-def apply_taxes_to_product(product: "Product", price: Money, country: "Country"):
+def apply_taxes_to_product(product: "Product", price: Money, country: Country):
if settings.VATLAYER_ACCESS_KEY:
return vatlayer_interface.apply_taxes_to_product(product, price, country)
if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
return TaxedMoney(net=price, gross=price)
return TaxedMoney(net=price, gross=price)
+
+
+def show_taxes_on_storefront() -> bool:
+ """Specify if taxes are enabled"""
+ if settings.VATLAYER_ACCESS_KEY:
+ return True
+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
+ return False
+ return False
+
+
+def apply_taxes_to_shipping_price_range(prices: MoneyRange, country: Country):
+ if country:
+ if settings.VATLAYER_ACCESS_KEY:
+ return vatlayer_interface.apply_taxes_to_shipping_price_range(
+ prices, country
+ )
+ if settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
+ pass
+ start = TaxedMoney(net=prices.start, gross=prices.start)
+ stop = TaxedMoney(net=prices.stop, gross=prices.stop)
+ return TaxedMoneyRange(start=start, stop=stop)
diff --git a/saleor/core/taxes/vatlayer/interface.py b/saleor/core/taxes/vatlayer/interface.py
index 921f9dd4e3..e05a9184f1 100644
--- a/saleor/core/taxes/vatlayer/interface.py
+++ b/saleor/core/taxes/vatlayer/interface.py
@@ -1,13 +1,14 @@
from collections import defaultdict
from decimal import Decimal
+from typing import TYPE_CHECKING
from django_countries.fields import Country
from django_prices_vatlayer.utils import get_tax_rate, get_tax_rate_types
-from prices import TaxedMoney
+from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
from ....core import TaxRateType # FIXME this should be placed in VatLayer module
-from ....discount.models import SaleQueryset
from ....discount.utils import calculate_discounted_price
+from .. import ZERO_TAXED_MONEY
from . import (
DEFAULT_TAX_RATE_NAME,
apply_tax_to_price,
@@ -16,29 +17,43 @@ from . import (
get_taxes_for_country,
)
+if TYPE_CHECKING:
+ from ....discount.models import SaleQueryset
+ from ....checkout.models import Checkout
+ from ....product.models import Product, ProductVariant
+ from ....account.models import Address
-def get_total_gross(checkout: "Checkout", discounts: SaleQueryset) -> TaxedMoney:
+
+def get_total_gross(checkout: "Checkout", discounts: "SaleQueryset") -> TaxedMoney:
"""Calculate total gross for checkout by using vatlayer"""
- address = checkout.shipping_address or checkout.billing_address
- taxes = get_taxes_for_address(address)
- return checkout.get_total(discounts, taxes)
+ return (
+ get_subtotal_gross(checkout, discounts)
+ + get_shipping_gross(checkout, discounts)
+ - checkout.discount_amount
+ )
-def get_subtotal_gross(checkout: "Checkout", discounts: SaleQueryset) -> TaxedMoney:
+def get_subtotal_gross(checkout: "Checkout", discounts: "SaleQueryset") -> TaxedMoney:
"""Calculate subtotal gross for checkout"""
address = checkout.shipping_address or checkout.billing_address
- taxes = get_taxes_for_address(address)
- return checkout.get_total(discounts, taxes)
+ lines = checkout.lines.prefetch_related("variant__product__product_type")
+ lines_total = ZERO_TAXED_MONEY
+ for line in lines:
+ price = line.variant.get_price(discounts)
+ lines_total += line.quantity * apply_taxes_to_variant(
+ line.variant, price, address.country
+ )
+ return lines_total
-def get_shipping_gross(checkout: "Checkout", discounts: SaleQueryset) -> TaxedMoney:
+def get_shipping_gross(checkout: "Checkout", _: "SaleQueryset") -> TaxedMoney:
"""Calculate shipping gross for checkout"""
address = checkout.shipping_address or checkout.billing_address
taxes = get_taxes_for_address(address)
return get_taxed_shipping_price(checkout.shipping_method.price, taxes)
-def get_lines_with_taxes(checkout: "Checkout", discounts):
+def get_lines_with_taxes(checkout: "Checkout", discounts: "SaleQueryset"):
lines_taxes = defaultdict(lambda: Decimal("0.0"))
address = checkout.shipping_address or checkout.billing_address
@@ -59,7 +74,7 @@ def get_lines_with_taxes(checkout: "Checkout", discounts):
return [(line, lines_taxes[line.variant.sku]) for line in checkout.lines.all()]
-def apply_taxes_to_shipping(price: "Money", shipping_address: "Address"):
+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)
@@ -75,15 +90,30 @@ def get_tax_rate_type_choices():
return sorted(choices, key=lambda x: x[1])
-def apply_taxes_to_variant(variant: "ProductVariant", price, country: "Country"):
- taxes = get_taxes_for_country(country)
+def apply_taxes_to_variant(
+ variant: "ProductVariant", price: "Money", country: "Country"
+) -> TaxedMoney:
+ taxes = None
+ if variant.product.charge_taxes and country:
+ taxes = get_taxes_for_country(country)
tax_rate = variant.product.tax_rate or variant.product.product_type.tax_rate
return apply_tax_to_price(taxes, tax_rate, price)
-def apply_taxes_to_product(product: "Product", price: "Money", country: "Country"):
+def apply_taxes_to_product(
+ product: "Product", price: Money, country: Country
+) -> TaxedMoney:
taxes = None
- if country:
+ if product.charge_taxes and country:
taxes = get_taxes_for_country(country)
tax_rate = product.tax_rate or product.product_type.tax_rate
return apply_tax_to_price(taxes, tax_rate, price)
+
+
+def apply_taxes_to_shipping_price_range(
+ prices: MoneyRange, country: "Country"
+) -> TaxedMoneyRange:
+ taxes = None
+ if country:
+ taxes = get_taxes_for_country(country)
+ return get_taxed_shipping_price(prices, taxes)
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index bb6ae53e0b..d9ce2553e5 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -189,7 +189,7 @@ class OrderShippingForm(forms.ModelForm):
fields = ["shipping_method"]
def __init__(self, *args, **kwargs):
- self.taxes = kwargs.pop("taxes")
+ self.taxes = kwargs.pop("taxes") # FIXME
super().__init__(*args, **kwargs)
method_field = self.fields["shipping_method"]
fetch_data_url = reverse(
@@ -212,7 +212,7 @@ 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)
+ self.instance.shipping_price = method.get_total(self.taxes) # FIXME
recalculate_order(self.instance)
return super().save(commit)
@@ -602,7 +602,7 @@ class AddVariantToOrderForm(forms.Form):
def __init__(self, *args, **kwargs):
self.order = kwargs.pop("order")
self.discounts = kwargs.pop("discounts")
- self.taxes = kwargs.pop("taxes")
+ self.taxes = kwargs.pop("taxes") # FIXME
super().__init__(*args, **kwargs)
def clean(self):
diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.py
index 7ced6de9a8..29339640cf 100644
--- a/saleor/dashboard/product/views.py
+++ b/saleor/dashboard/product/views.py
@@ -10,6 +10,7 @@ from django.template.response import TemplateResponse
from django.utils.translation import npgettext_lazy, pgettext_lazy
from django.views.decorators.http import require_POST
+from ...core.taxes import interface as tax_interface
from ...core.utils import get_paginator_items
from ...discount.models import Sale
from ...product.models import (
@@ -313,8 +314,10 @@ def variant_details(request, product_pk, variant_pk):
images = variant.images.all()
margin = get_margin_for_variant(variant)
- discounted_price = variant.get_price(
- discounts=Sale.objects.active(date.today())
+ discounted_price = tax_interface.apply_taxes_to_variant(
+ variant,
+ variant.get_price(discounts=Sale.objects.active(date.today())),
+ request.country,
).gross
ctx = {
"images": images,
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 547f0c6b60..a270d47983 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -14,7 +14,6 @@ from ...checkout.utils import (
clean_checkout,
create_order,
get_or_create_user_checkout,
- get_taxes_for_checkout,
get_voucher_for_checkout,
recalculate_checkout_discount,
remove_voucher_from_checkout,
@@ -245,7 +244,7 @@ class CheckoutLinesAdd(BaseMutation):
add_variant_to_checkout(checkout, variant, quantity, replace=replace)
recalculate_checkout_discount(
- checkout, info.context.discounts, info.context.taxes
+ checkout, info.context.discounts, info.context.taxes # FIXME
)
return CheckoutLinesAdd(checkout=checkout)
@@ -292,7 +291,7 @@ class CheckoutLineDelete(BaseMutation):
)
recalculate_checkout_discount(
- checkout, info.context.discounts, info.context.taxes
+ checkout, info.context.discounts, info.context.taxes # FIXME
)
return CheckoutLineDelete(checkout=checkout)
@@ -373,7 +372,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
shipping_address.save()
change_shipping_address_in_checkout(checkout, shipping_address)
recalculate_checkout_discount(
- checkout, info.context.discounts, info.context.taxes
+ checkout, info.context.discounts, info.context.taxes # FIXME
)
return CheckoutShippingAddressUpdate(checkout=checkout)
@@ -463,7 +462,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
+ checkout, info.context.discounts, info.context.taxes # FIXME
)
return CheckoutShippingMethodUpdate(checkout=checkout)
@@ -488,8 +487,7 @@ class CheckoutComplete(BaseMutation):
info, checkout_id, only_type=Checkout, field="checkout_id"
)
- taxes = get_taxes_for_checkout(checkout, info.context.taxes)
- clean_checkout(checkout, taxes, info.context.discounts)
+ clean_checkout(checkout, info.context.discounts)
payment = checkout.get_last_active_payment()
@@ -498,7 +496,6 @@ class CheckoutComplete(BaseMutation):
checkout=checkout,
tracking_code=analytics.get_client_id(info.context),
discounts=info.context.discounts,
- taxes=get_taxes_for_checkout(checkout, info.context.taxes),
user=info.context.user,
)
except InsufficientStock:
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 87e8d7bbbd..1e8cd3ae85 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -117,8 +117,7 @@ class Checkout(CountableDjangoObjectType):
return self.lines.prefetch_related("variant")
def resolve_available_shipping_methods(self, info):
- taxes = None
- price = self.get_subtotal(taxes=taxes, discounts=info.context.discounts)
+ price = get_subtotal_gross(checkout=self, discounts=info.context.discounts)
return applicable_shipping_methods(self, price.gross.amount)
def resolve_available_payment_gateways(self, _info):
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 34c5cc127f..d72984cd32 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -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)
+ order.shipping_price = method.get_total(info.context.taxes) # FIXME
order.shipping_method_name = method.name
order.save(
update_fields=[
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index b6c61d5836..dedebb831d 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -267,7 +267,7 @@ class ProductVariant(CountableDjangoObjectType):
def resolve_pricing(self, info):
context = info.context
availability = get_variant_availability(
- self, context.discounts, context.taxes, context.currency
+ self, context.discounts, context.country, context.currency
)
return VariantPricingInfo(**availability._asdict())
@@ -461,7 +461,7 @@ class Product(CountableDjangoObjectType):
)
def resolve_price(self, info):
price_range = self.get_price_range(info.context.discounts)
- return price_range.start.net
+ return price_range.start
@gql_optimizer.resolver_hints(
prefetch_related="product_type__product_attributes__values"
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 877705ac8b..8640571236 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -9,7 +9,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 get_order_line_total_gross
+from ..core.taxes.interface import refresh_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,13 +156,13 @@ def update_order_prices(order, discounts):
"""Update prices in order with given discounts and proper taxes."""
for line in order:
if line.variant:
- price = get_order_line_total_gross(line, discounts)
+ price = refresh_order_line_unit_price(line, discounts)
line.unit_price = price
- line.tax_rate = 0
+ line.tax_rate = 0 # Fixme we can calulcate tax_rate based on prices
line.save()
if order.shipping_method:
- order.shipping_price = order.shipping_method.get_total(taxes)
+ order.shipping_price = order.shipping_method.get_total()
order.save()
recalculate_order(order)
@@ -268,7 +268,7 @@ def add_variant_to_order(
variant.check_quantity(quantity)
# FIXME maybe something more prettier ?
- unit_price_net = variant.get_price(discounts).net
+ unit_price_net = variant.get_price(discounts)
unit_price_gross = Money(
amount=unit_price_net.amount + unit_tax, currency=unit_price_net.currency
)
diff --git a/saleor/product/forms.py b/saleor/product/forms.py
index 9a995944a4..6ca1bf0730 100644
--- a/saleor/product/forms.py
+++ b/saleor/product/forms.py
@@ -7,27 +7,28 @@ from django_prices.templatetags.prices_i18n import amount
from ..checkout.forms import AddToCheckoutForm
from ..core.taxes import display_gross_prices
+from ..core.taxes.interface import apply_taxes_to_variant
class VariantChoiceField(forms.ModelChoiceField):
discounts = None
- taxes = None
+ country = None
display_gross = True
def label_from_instance(self, obj):
variant_label = smart_text(obj)
- price = obj.get_price(self.discounts, self.taxes)
+ price = apply_taxes_to_variant(obj, obj.get_price(self.discounts), self.country)
price = price.gross if self.display_gross else price.net
label = pgettext_lazy(
"Variant choice field label", "%(variant_label)s - %(price)s"
) % {"variant_label": variant_label, "price": amount(price)}
return label
- def update_field_data(self, variants, discounts, taxes):
+ def update_field_data(self, variants, discounts, country):
"""Initialize variant picker metadata."""
self.queryset = variants
self.discounts = discounts
- self.taxes = taxes
+ self.country = country
self.empty_label = None
self.display_gross = display_gross_prices()
images_map = {
@@ -46,8 +47,10 @@ class ProductForm(AddToCheckoutForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
variant_field = self.fields["variant"]
+ shipping_address = self.checkout.shipping_address
+ country = shipping_address.country if shipping_address else self.country
variant_field.update_field_data(
- self.product.variants.all(), self.discounts, self.taxes
+ self.product.variants.all(), self.discounts, country
)
def get_variant(self, cleaned_data):
diff --git a/saleor/product/models.py b/saleor/product/models.py
index efa9c15757..500b94c54d 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -15,7 +15,7 @@ from django_prices.templatetags import prices_i18n
from measurement.measures import Weight
from mptt.managers import TreeManager
from mptt.models import MPTTModel
-from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
+from prices import MoneyRange
from text_unidecode import unidecode
from versatileimagefield.fields import PPOIField, VersatileImageField
@@ -24,7 +24,6 @@ from saleor.core.utils import build_absolute_uri
from ..core import TaxRateType
from ..core.exceptions import InsufficientStock
from ..core.models import PublishableModel, SortableModel
-from ..core.taxes import interface as tax_interface
from ..core.utils.translations import TranslationProxy
from ..core.weight import WeightUnits, zero_weight
from ..discount.utils import calculate_discounted_price
@@ -179,10 +178,10 @@ class Product(SeoModel, PublishableModel):
images = list(self.images.all())
return images[0] if images else None
- def get_price_range(self, discounts=None, country=None):
+ def get_price_range(self, discounts=None):
if self.variants.all():
- prices = [variant.get_price(discounts, country) for variant in self]
- return MoneyRange(min(prices, max(prices)))
+ prices = [variant.get_price(discounts) for variant in self]
+ return MoneyRange(min(prices), max(prices))
price = calculate_discounted_price(self, self.price, discounts)
return MoneyRange(start=price, stop=price)
diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.py
index baac77000f..313b030d95 100644
--- a/saleor/product/utils/__init__.py
+++ b/saleor/product/utils/__init__.py
@@ -70,7 +70,7 @@ def handle_checkout_form(request, product, create_checkout=False):
product=product,
data=request.POST or None,
discounts=request.discounts,
- taxes=request.taxes,
+ country=request.country,
)
return form, checkout
diff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.py
index eb55f7ac1a..6172022123 100644
--- a/saleor/product/utils/availability.py
+++ b/saleor/product/utils/availability.py
@@ -7,7 +7,7 @@ from prices import TaxedMoneyRange
from saleor.graphql.core.types import MoneyRange
from saleor.product.models import Product, ProductVariant
-from ...core.taxes.interface import apply_taxes_to_product
+from ...core.taxes.interface import apply_taxes_to_product, apply_taxes_to_variant
from ...core.utils import to_local_currency
from .. import ProductAvailabilityStatus, VariantAvailabilityStatus
@@ -141,11 +141,13 @@ def get_product_availability(
def get_variant_availability(
- variant: ProductVariant, discounts=None, taxes=None, local_currency=None
+ variant: ProductVariant, discounts=None, country=None, local_currency=None
) -> VariantAvailability:
- discounted = variant.get_price(discounts=discounts, taxes=taxes)
- undiscounted = variant.get_price(taxes=taxes)
+ discounted = apply_taxes_to_variant(
+ variant, variant.get_price(discounts=discounts), country
+ )
+ undiscounted = apply_taxes_to_variant(variant, variant.get_price(), country)
discount = _get_total_discount(undiscounted, discounted)
diff --git a/saleor/product/utils/variants_picker.py b/saleor/product/utils/variants_picker.py
index 2211c5e9a7..1f49e0fd53 100644
--- a/saleor/product/utils/variants_picker.py
+++ b/saleor/product/utils/variants_picker.py
@@ -3,7 +3,7 @@ from collections import defaultdict
from django_prices.templatetags import prices_i18n
from ...core.taxes import display_gross_prices
-from ...core.taxes.interface import apply_taxes_to_variant
+from ...core.taxes.interface import apply_taxes_to_variant, show_taxes_on_storefront
from ...core.utils import to_local_currency
from ...seo.schema.product import variant_json_ld
from .availability import get_product_availability
@@ -29,7 +29,7 @@ def get_variant_picker_data(product, discounts=None, country=None, local_currenc
else:
price_local_currency = None
in_stock = variant.is_in_stock()
- schema_data = variant_json_ld(price, variant, in_stock)
+ schema_data = variant_json_ld(price.net, variant, in_stock)
variant_data = {
"id": variant.id,
"availability": in_stock,
@@ -79,7 +79,7 @@ def get_variant_picker_data(product, discounts=None, country=None, local_currenc
}
data["priceDisplay"] = {
"displayGross": display_gross_prices(),
- "handleTaxes": bool(taxes),
+ "handleTaxes": show_taxes_on_storefront(),
}
return data
diff --git a/saleor/seo/schema/product.py b/saleor/seo/schema/product.py
index 5e0fc8754d..09b8e7ebe9 100644
--- a/saleor/seo/schema/product.py
+++ b/saleor/seo/schema/product.py
@@ -48,7 +48,7 @@ def variant_json_ld(price, variant, in_stock):
"@type": "Offer",
"itemCondition": "http://schema.org/NewCondition",
"priceCurrency": price.currency,
- "price": price.net.amount,
+ "price": price.amount,
"sku": variant.sku,
}
if in_stock:
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index 0146ac90c5..93183be224 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -6,7 +6,7 @@ from django_countries.fields import CountryField
from django_measurement.models import MeasurementField
from django_prices.models import MoneyField
from measurement.measures import Weight
-from prices import MoneyRange, TaxedMoney
+from prices import MoneyRange
from ..core.utils import format_money
from ..core.utils.translations import TranslationProxy
@@ -48,7 +48,7 @@ class ShippingZone(models.Model):
for shipping_method in self.shipping_methods.all()
]
if prices:
- return MoneyRange(min(prices).net, max(prices).net)
+ return MoneyRange(min(prices), max(prices))
return None
class Meta:
@@ -159,9 +159,8 @@ class ShippingMethod(models.Model):
),
)
- def get_total(self, country=None):
-
- return TaxedMoney(net=self.price, gross=self.price)
+ def get_total(self):
+ return self.price
def get_ajax_label(self):
price_html = format_money(self.price)
diff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.py
index 1adbd418fb..73c1992918 100644
--- a/saleor/shipping/utils.py
+++ b/saleor/shipping/utils.py
@@ -2,11 +2,11 @@ from django.db.models import Q
from django.utils.translation import pgettext_lazy
from prices import MoneyRange
-from ..core.taxes.vatlayer import get_taxed_shipping_price # FIXME
+from ..core.taxes import interface as tax_interface
from ..core.weight import convert_weight, get_default_weight_unit
-def get_shipping_price_estimate(price, weight, country_code, taxes):
+def get_shipping_price_estimate(price, weight, country_code):
"""Returns estimated price range for shipping for given order."""
from .models import ShippingMethod
@@ -17,7 +17,7 @@ def get_shipping_price_estimate(price, weight, country_code, taxes):
if not shipping_methods:
return
prices = MoneyRange(start=min(shipping_methods), stop=max(shipping_methods))
- return get_taxed_shipping_price(prices, taxes)
+ return tax_interface.apply_taxes_to_shipping_price_range(prices, country_code)
def applicable_weight_based_methods(weight, qs):