Skip to content

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

Init draft version

Maciej Korycinski269996a4fe8b
diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.py
index 760275c1b6..483efd74ca 100644
--- a/saleor/checkout/forms.py
+++ b/saleor/checkout/forms.py
@@ -9,10 +9,11 @@ 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 TaxedMoney
from ..core.exceptions import InsufficientStock
+from ..core.taxes import display_gross_prices
from ..core.utils import format_money
-from ..core.utils.taxes import display_gross_prices, get_taxed_shipping_price
from ..discount.models import NotApplicable, Voucher
from ..shipping.models import ShippingMethod, ShippingZone
from ..shipping.utils import get_shipping_price_estimate
@@ -295,7 +296,7 @@ class ShippingMethodChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
"""Return a friendly label for the shipping method."""
- price = get_taxed_shipping_price(obj.price, self.taxes)
+ price = TaxedMoney(net=obj.price, gross=obj.price)
if display_gross_prices():
price = price.gross
else:
diff --git a/saleor/checkout/migrations/0015_auto_20181017_1346.py b/saleor/checkout/migrations/0015_auto_20181017_1346.py
index d98911e4d7..bbec093e15 100644
--- a/saleor/checkout/migrations/0015_auto_20181017_1346.py
+++ b/saleor/checkout/migrations/0015_auto_20181017_1346.py
@@ -1,8 +1,9 @@
# Generated by Django 2.1.2 on 2018-10-17 18:46
+import django_prices.models
from django.conf import settings
from django.db import migrations
-import django_prices.models
+
import saleor.core
@@ -17,7 +18,7 @@ class Migration(migrations.Migration):
field=django_prices.models.MoneyField(
currency=settings.DEFAULT_CURRENCY,
decimal_places=2,
- default=saleor.core.utils.taxes.zero_money,
+ default=saleor.core.taxes.zero_money,
max_digits=12,
),
)
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 303a2c2163..b12880c840 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.utils.taxes import ZERO_TAXED_MONEY, zero_money
+from ..core.taxes import ZERO_TAXED_MONEY, zero_money
from ..core.weight import zero_weight
from ..shipping.models import ShippingMethod
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 421761e2e3..6553f9875a 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -1,5 +1,6 @@
"""Checkout-related utility functions."""
from datetime import date, timedelta
+from decimal import Decimal
from functools import wraps
from uuid import UUID
@@ -10,14 +11,22 @@ 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 TaxedMoneyRange
+from prices import TaxedMoney, TaxedMoneyRange
from ..account.forms import get_address_form
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_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 ..core.utils.taxes import ZERO_MONEY, get_taxes_for_country
from ..discount import VoucherType
from ..discount.models import NotApplicable, Voucher
from ..discount.utils import (
@@ -637,22 +646,24 @@ def get_checkout_context(
checkout, discounts, taxes, currency=None, shipping_range=None
):
"""Data shared between views in checkout process."""
- checkout_total = checkout.get_total(discounts, taxes)
+ checkout_total = get_total_gross(checkout, discounts)
+ checkout_subtotal = get_subtotal_gross(checkout, discounts)
+ shipping_price = get_shipping_gross(checkout, discounts)
+
shipping_required = checkout.is_shipping_required()
- checkout_subtotal = checkout.get_subtotal(discounts, taxes)
total_with_shipping = TaxedMoneyRange(
start=checkout_subtotal, stop=checkout_subtotal
)
if shipping_required and shipping_range:
- total_with_shipping = shipping_range + checkout_subtotal
+ total_with_shipping = shipping_range + checkout_subtotal.net
context = {
"checkout": checkout,
- "checkout_are_taxes_handled": bool(taxes),
+ "checkout_are_taxes_handled": True, # bool(taxes),
"checkout_lines": [
(line, line.get_total(discounts, taxes)) for line in checkout
],
- "checkout_shipping_price": checkout.get_shipping_price(taxes),
+ "checkout_shipping_price": shipping_price, # checkout.get_shipping_price(taxes),
"checkout_subtotal": checkout_subtotal,
"checkout_total": checkout_total,
"shipping_required": checkout.is_shipping_required(),
@@ -874,7 +885,7 @@ def _process_voucher_data_for_order(checkout):
}
-def _process_shipping_data_for_order(checkout, taxes):
+def _process_shipping_data_for_order(checkout, shipping_price):
"""Fetch, process and return shipping data from checkout."""
if not checkout.is_shipping_required():
return {}
@@ -890,7 +901,7 @@ def _process_shipping_data_for_order(checkout, taxes):
"shipping_address": shipping_address,
"shipping_method": checkout.shipping_method,
"shipping_method_name": smart_text(checkout.shipping_method),
- "shipping_price": checkout.get_shipping_price(taxes),
+ "shipping_price": shipping_price, # checkout.get_shipping_price(taxes),
"weight": checkout.get_total_weight(),
}
@@ -931,27 +942,34 @@ def create_order(checkout: Checkout, tracking_code: str, discounts, taxes, user:
if order is not None:
return order
+ total = get_total_gross(checkout, discounts)
+ shipping_total = get_shipping_gross(checkout, discounts)
order_data = {}
order_data.update(_process_voucher_data_for_order(checkout))
- order_data.update(_process_shipping_data_for_order(checkout, taxes))
+ order_data.update(_process_shipping_data_for_order(checkout, shipping_total))
order_data.update(_process_user_data_for_order(checkout))
order_data.update(
{
"language_code": get_language(),
"tracking_client_id": tracking_code,
- "total": checkout.get_total(discounts, taxes),
+ "total": total,
}
)
order = Order.objects.create(**order_data, checkout_token=checkout.token)
+ lines_with_taxes = get_lines_with_taxes(checkout, discounts)
# create order lines from checkout lines
- for line in checkout:
- add_variant_to_order(order, line.variant, line.quantity, discounts, taxes)
+ for line, tax in lines_with_taxes:
+ add_variant_to_order(
+ order, line.variant, line.quantity, discounts, unit_tax=tax
+ )
# assign checkout payments to the order
checkout.payments.update(order=order)
+ postprocess_order_creation_with_taxes(order)
+
# remove checkout after order is created
checkout.delete()
diff --git a/saleor/checkout/views/shipping.py b/saleor/checkout/views/shipping.py
index 0f2dcd4c8e..af89c1f1e6 100644
--- a/saleor/checkout/views/shipping.py
+++ b/saleor/checkout/views/shipping.py
@@ -37,7 +37,6 @@ def user_shipping_address_view(request, checkout):
addresses_form, address_form, updated = update_shipping_address_in_checkout(
checkout, user_addresses, request.POST or None, request.country
)
-
if updated:
return redirect("checkout:shipping-method")
diff --git a/saleor/checkout/views/summary.py b/saleor/checkout/views/summary.py
index d340725175..e85e5a97dc 100644
--- a/saleor/checkout/views/summary.py
+++ b/saleor/checkout/views/summary.py
@@ -6,6 +6,9 @@ from django.utils.translation import pgettext
from ...account.models import Address
from ...core import analytics
from ...core.exceptions import InsufficientStock
+
+# FIXME This should be taken from taxes module
+from ...core.taxes.errors import TaxError
from ...discount.models import NotApplicable
from ..forms import CheckoutNoteForm
from ..utils import (
@@ -40,6 +43,14 @@ def _handle_order_placement(request, checkout):
request, pgettext("Checkout warning", "Please review your checkout.")
)
return redirect("checkout:summary")
+ except TaxError as tax_error:
+ messages.warning(
+ request,
+ pgettext(
+ "Checkout warning", "Unable to calculate taxes - %s" % str(tax_error)
+ ),
+ )
+ return redirect("checkout:summary")
# Redirect the user to the payment page
return redirect("order:payment", token=order.token)
diff --git a/saleor/core/middleware.py b/saleor/core/middleware.py
index af378482e9..e35d4db23e 100644
--- a/saleor/core/middleware.py
+++ b/saleor/core/middleware.py
@@ -24,7 +24,6 @@ from django_countries.fields import Country
from ..discount.models import Sale
from . import analytics
from .utils import get_client_ip, get_country_by_ip, get_currency_for_country
-from .utils.taxes import get_taxes_for_country
logger = logging.getLogger(__name__)
@@ -168,12 +167,7 @@ def taxes(get_response):
"""Assign tax rates for default country to `request.taxes`."""
def middleware(request):
- if settings.VATLAYER_ACCESS_KEY:
- request.taxes = SimpleLazyObject(
- lambda: get_taxes_for_country(request.country)
- )
- else:
- request.taxes = None
+ request.taxes = None
return get_response(request)
return middleware
diff --git a/saleor/core/taxes/__init__.py b/saleor/core/taxes/__init__.py
new file mode 100644
index 0000000000..1f27598c2d
--- /dev/null
+++ b/saleor/core/taxes/__init__.py
@@ -0,0 +1,24 @@
+from django.conf import settings
+from django.contrib.sites.models import Site
+from prices import Money, TaxedMoney
+
+ZERO_MONEY = Money(0, settings.DEFAULT_CURRENCY)
+
+ZERO_TAXED_MONEY = TaxedMoney(net=ZERO_MONEY, gross=ZERO_MONEY)
+
+
+def zero_money():
+ """Function used as a model's default."""
+ return ZERO_MONEY
+
+
+def include_taxes_in_prices():
+ return Site.objects.get_current().settings.include_taxes_in_prices
+
+
+def display_gross_prices():
+ return Site.objects.get_current().settings.display_gross_prices
+
+
+def charge_taxes_on_shipping():
+ return Site.objects.get_current().settings.charge_taxes_on_shipping
diff --git a/saleor/core/taxes/avatax/__init__.py b/saleor/core/taxes/avatax/__init__.py
new file mode 100644
index 0000000000..910265d501
--- /dev/null
+++ b/saleor/core/taxes/avatax/__init__.py
@@ -0,0 +1,187 @@
+import json
+from datetime import date
+from typing import Any, Dict, List
+from urllib.parse import urljoin
+
+import requests
+from django.conf import settings
+from django.core.cache import cache
+from requests.auth import HTTPBasicAuth
+
+from .. import charge_taxes_on_shipping
+
+common_carrier_code = "FR020100" # FIXME
+cache_key = "avatax_checkout_id"
+
+
+class TransactionType:
+ INVOICE = "SalesInvoice"
+ ORDER = "SalesOrder"
+
+
+def get_api_url() -> str:
+ """Based on settings return sanbox or production url"""
+ if settings.AVATAX_USE_SANDBOX:
+ return "https://sandbox-rest.avatax.com/api/v2/"
+ return "https://rest.avatax.com/api/v2/"
+
+
+def api_post_request(
+ url: str,
+ data: Dict[str, Any],
+ username: str = settings.AVATAX_USERNAME_OR_ACCOUNT,
+ password: str = settings.AVATAX_PASSWORD_OR_LICENSE,
+) -> Dict[str, Any]:
+ try:
+ auth = HTTPBasicAuth(username, password)
+ response = requests.post(url, auth=auth, data=json.dumps(data))
+ print(auth)
+ print(response.content)
+ except requests.exceptions.RequestException:
+ return {}
+ return response.json()
+
+
+def api_get_request(
+ url,
+ username=settings.AVATAX_USERNAME_OR_ACCOUNT,
+ password=settings.AVATAX_PASSWORD_OR_LICENSE,
+):
+ return requests.get(url, auth=HTTPBasicAuth(username, password))
+
+
+def validate_checkout(checkout: "Checkout") -> bool:
+ """Validate if checkout object contains enough information to generate a request to
+ avatax"""
+ if not checkout.lines.count():
+ return False
+
+ shipping_address = checkout.shipping_address
+ is_shipping_required = checkout.is_shipping_required
+ address = shipping_address or checkout.billing_address
+ if not is_shipping_required and not address:
+ return False
+ if not shipping_address:
+ return False
+ return True
+
+
+def checkout_needs_new_fetch(data, checkout_token: str) -> bool:
+ """We store the response from avatax for checkout object for given time. If object
+ doesn't exist in cache or something has changed, then we fetch data from avatax."""
+ checkout_cache_key = cache_key + checkout_token
+ cached_checkout = cache.get(checkout_cache_key)
+
+ if not cached_checkout:
+ return True
+
+ cached_request_data, cached_response = cached_checkout
+ if data != cached_request_data:
+ return True
+ return False
+
+
+def get_lines_data(checkout: "Checkout", discounts=None) -> List[Dict[str, str]]:
+ data = []
+ lines = checkout.lines.prefetch_related(
+ "variant__product__category",
+ "variant__product__collections",
+ "variant__product__product_type",
+ )
+ for line in lines:
+ description = line.variant.product.description
+
+ data.append(
+ {
+ "quantity": line.quantity,
+ "amount": str(line.get_total(discounts).net.amount),
+ "taxCode": "PC040156", # FIXME Should fetch taxcode from somewhere and save inside variant/product
+ "itemCode": line.variant.sku,
+ "description": description[:2000] if description else None,
+ }
+ )
+
+ if charge_taxes_on_shipping() and checkout.shipping_method:
+ data.append(
+ {
+ "quantity": 1,
+ "amount": str(checkout.shipping_method.price.amount),
+ "taxCode": common_carrier_code,
+ "itemCode": "Shipping",
+ }
+ )
+ return data
+
+
+def generate_request_data(
+ checkout: "Checkout",
+ transaction_token=None,
+ transaction_type=TransactionType.ORDER,
+ commit=False,
+ discounts=None,
+):
+
+ address = checkout.shipping_address or checkout.billing_address
+ lines = get_lines_data(checkout, discounts)
+
+ data = {
+ "companyCode": settings.AVATAX_COMPANY_NAME,
+ "type": transaction_type,
+ "lines": lines,
+ "code": transaction_token or str(checkout.token),
+ "date": str(date.today()),
+ "customerCode": checkout.user.id if checkout.user else None,
+ # 'salespersonCode'
+ # 'customerUsageType'
+ # 'entityUseCode'
+ # 'discount'
+ # 'purchaseOrderNo'
+ # 'exemptionNo'
+ "addresses": {
+ # FIXME we should put company address here
+ "shipFrom": { # warehouse
+ "line1": "2000 Main Street",
+ "city": "Irvine",
+ "region": "CA",
+ "country": "US",
+ "postalCode": "92614",
+ },
+ "shipTo": {
+ "line1": address.street_address_1,
+ "line2": address.street_address_2,
+ "city": address.city,
+ "region": address.country_area,
+ "country": address.country.code,
+ "postalCode": address.postal_code,
+ },
+ },
+ # parameters
+ # referenceCode
+ # reportingLocationCode
+ # isSellerImporterOfRecord
+ # businessIdentificationNo
+ "commit": commit,
+ # batchCode
+ "currencyCode": settings.DEFAULT_CURRENCY,
+ "email": checkout.email,
+ }
+ return data
+
+
+def get_checkout_tax_data(checkout: "Checkout", discounts) -> Dict[str, Any]:
+ checkout_cache_key = cache_key + str(checkout.token)
+ data = generate_request_data(checkout, discounts=discounts)
+ if checkout_needs_new_fetch(data, str(checkout.token)):
+ transaction_url = urljoin(get_api_url(), "transactions/create")
+ print("HIT TO API")
+ response = api_post_request(transaction_url, data)
+ if response and "error" not in response:
+ cache.set(
+ checkout_cache_key,
+ (data, response),
+ settings.AVATAX_CHECKOUT_CACHE_TIME,
+ )
+ else:
+ _, response = cache.get(checkout_cache_key)
+
+ return response
diff --git a/saleor/core/taxes/avatax/interface.py b/saleor/core/taxes/avatax/interface.py
new file mode 100644
index 0000000000..62b5039108
--- /dev/null
+++ b/saleor/core/taxes/avatax/interface.py
@@ -0,0 +1,105 @@
+from collections import defaultdict
+from datetime import date
+from decimal import Decimal
+from urllib.parse import urljoin
+
+from prices import Money, TaxedMoney
+
+from ....checkout.models import Checkout
+from ....discount.models import Sale
+from ....order.models import Order
+from ..errors import TaxError
+from . import (
+ TransactionType,
+ api_post_request,
+ generate_request_data,
+ get_api_url,
+ get_checkout_tax_data,
+ validate_checkout,
+)
+
+
+def get_total_gross(checkout: "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_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):
+ if not validate_checkout(checkout):
+ return checkout.get_subtotal(discounts)
+ response = get_checkout_tax_data(checkout, discounts)
+
+ sub_tax = Decimal(0.0)
+ for line in response.get("lines", []):
+ if line["itemCode"] == "Shipping":
+ continue
+ sub_tax += Decimal(line["tax"])
+ sub_total_net = checkout.get_subtotal(discounts).net
+ 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):
+ if not validate_checkout(checkout):
+ return checkout.get_shipping_price(None)
+ response = get_checkout_tax_data(checkout, discounts)
+
+ shipping_tax = Decimal(0.0)
+ for line in response.get("lines", []):
+ if line["itemCode"] == "Shipping":
+ shipping_tax = Decimal(line["tax"])
+ break
+
+ shipping_net = checkout.get_shipping_price(None).net
+ 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):
+ """Calculate and return tuple (line, unit_tax)"""
+ lines_taxes = defaultdict(lambda: Decimal("0.0"))
+
+ if validate_checkout(checkout):
+ response = get_checkout_tax_data(checkout, discounts)
+
+ for line in response.get("lines", []):
+ if line["itemCode"] == "Shipping":
+ continue
+ tax = line.get("tax")
+ quantity = line.get("quantity")
+ if tax and quantity:
+ tax = Decimal(tax / int(quantity))
+ lines_taxes[line["itemCode"]] = tax
+
+ return [(line, lines_taxes[line.variant.sku]) for line in checkout.lines.all()]
+
+
+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)
+ discounts = Sale.objects.active(date.today()).prefetch_related(
+ "products", "categories", "collections"
+ )
+ data = generate_request_data(
+ checkout,
+ transaction_token=str(order.token),
+ transaction_type=TransactionType.INVOICE,
+ discounts=discounts,
+ )
+ transaction_url = urljoin(get_api_url(), "transactions/create")
+ 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", ""))
diff --git a/saleor/core/taxes/errors.py b/saleor/core/taxes/errors.py
new file mode 100644
index 0000000000..4a216d9bb5
--- /dev/null
+++ b/saleor/core/taxes/errors.py
@@ -0,0 +1,2 @@
+class TaxError(Exception):
+ """Default tax error"""
diff --git a/saleor/core/taxes/interface.py b/saleor/core/taxes/interface.py
new file mode 100644
index 0000000000..b5c403084c
--- /dev/null
+++ b/saleor/core/taxes/interface.py
@@ -0,0 +1,56 @@
+from collections import defaultdict
+from decimal import Decimal
+
+from django.conf import settings
+from prices import TaxedMoney
+
+from . import ZERO_TAXED_MONEY
+from .vatlayer import interface as vatlayer_interface
+from .avatax import interface as avatax_interface
+
+from ...checkout.models import Checkout
+from ...discount.models import SaleQueryset
+
+
+def get_total_gross(checkout: Checkout, discounts: SaleQueryset) -> TaxedMoney:
+ """Calculate total gross for checkout"""
+
+ if settings.VATLAYER_ACCESS_KEY:
+ return vatlayer_interface.get_total_gross(checkout, discounts)
+ 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)
+
+
+def get_subtotal_gross(checkout: Checkout, discounts: SaleQueryset) -> TaxedMoney:
+ """Calculate subtotal gross for checkout"""
+
+ if settings.VATLAYER_ACCESS_KEY:
+ return vatlayer_interface.get_subtotal_gross(checkout, discounts)
+ 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)
+
+
+def get_shipping_gross(checkout: Checkout, discounts: SaleQueryset) -> TaxedMoney:
+ """Calculate shipping gross for checkout"""
+ if not checkout.shipping_method:
+ return ZERO_TAXED_MONEY
+ if settings.VATLAYER_ACCESS_KEY:
+ 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()
+
+
+def get_lines_with_taxes(checkout: Checkout, discounts):
+ lines_taxes = defaultdict(lambda: Decimal("0.0"))
+
+ if settings.VATLAYER_ACCESS_KEY:
+ return vatlayer_interface.get_lines_with_taxes(checkout, discounts)
+ elif settings.AVATAX_USERNAME_OR_ACCOUNT and settings.AVATAX_PASSWORD_OR_LICENSE:
+ return avatax_interface.get_lines_with_taxes(checkout, discounts)
+
+ return [(line, lines_taxes[line.variant.sku]) for line in checkout.lines.all()]
diff --git a/saleor/core/utils/taxes.py b/saleor/core/taxes/vatlayer/__init__.py
similarity index 82%
rename from saleor/core/utils/taxes.py
rename to saleor/core/taxes/vatlayer/__init__.py
index b4499cc56e..2af1ce8147 100644
--- a/saleor/core/utils/taxes.py
+++ b/saleor/core/taxes/vatlayer/__init__.py
@@ -1,21 +1,13 @@
from django.conf import settings
-from django.contrib.sites.models import Site
from django_countries.fields import Country
from django_prices_vatlayer.utils import get_tax_for_rate, get_tax_rates_for_country
from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
-from ...core import TaxRateType
+from ... import TaxRateType
+from .. import charge_taxes_on_shipping, include_taxes_in_prices
DEFAULT_TAX_RATE_NAME = TaxRateType.STANDARD
-ZERO_MONEY = Money(0, settings.DEFAULT_CURRENCY)
-ZERO_TAXED_MONEY = TaxedMoney(net=ZERO_MONEY, gross=ZERO_MONEY)
-
-
-def zero_money():
- """Function used as a model's default."""
- return ZERO_MONEY
-
def apply_tax_to_price(taxes, rate_name, base):
if not taxes or not rate_name:
@@ -87,18 +79,6 @@ def get_tax_rate_by_name(rate_name, taxes=None):
return tax_rate
-def include_taxes_in_prices():
- return Site.objects.get_current().settings.include_taxes_in_prices
-
-
-def display_gross_prices():
- return Site.objects.get_current().settings.display_gross_prices
-
-
-def charge_taxes_on_shipping():
- return Site.objects.get_current().settings.charge_taxes_on_shipping
-
-
def get_taxed_shipping_price(shipping_price, taxes):
"""Calculate shipping price based on settings and taxes."""
if not charge_taxes_on_shipping():
diff --git a/saleor/core/taxes/vatlayer/interface.py b/saleor/core/taxes/vatlayer/interface.py
new file mode 100644
index 0000000000..9bf1aa3e91
--- /dev/null
+++ b/saleor/core/taxes/vatlayer/interface.py
@@ -0,0 +1,51 @@
+from collections import defaultdict
+from decimal import Decimal
+
+from django_prices_vatlayer.utils import get_tax_rate
+from prices import TaxedMoney
+
+from ....discount.models import SaleQueryset
+from ....discount.utils import calculate_discounted_price
+from . import get_taxed_shipping_price, get_taxes_for_address
+
+
+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)
+
+
+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)
+
+
+def get_shipping_gross(checkout: "Checkout", discounts: 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):
+ 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
+ )
+ tax_rate_name = (
+ line.variant.product.tax_rate or line.variant.product.product_type.tax_rate
+ )
+ tax_rate = get_tax_rate(taxes, tax_rate_name)
+ if not tax_rate:
+ continue
+ tax_rate = Decimal(tax_rate / 100)
+ lines_taxes[line.variant.sku] = price.amount * tax_rate
+
+ return [(line, lines_taxes[line.variant.sku]) for line in checkout.lines.all()]
diff --git a/saleor/core/templatetags/taxed_prices.py b/saleor/core/templatetags/taxed_prices.py
index 4ef49ca8d1..a64dba00ea 100644
--- a/saleor/core/templatetags/taxed_prices.py
+++ b/saleor/core/templatetags/taxed_prices.py
@@ -1,7 +1,8 @@
from django import template
+from django.conf import settings
from prices import MoneyRange, TaxedMoney, TaxedMoneyRange
-from ...core.utils.taxes import DEFAULT_TAX_RATE_NAME
+from ...core.taxes.vatlayer import DEFAULT_TAX_RATE_NAME # FIXME
register = template.Library()
@@ -15,9 +16,8 @@ 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:
+ if not taxes or not settings.VATLAYER_ACCESS_KEY: # FIXME
return 0
-
tax = taxes.get(rate_name) or taxes.get(DEFAULT_TAX_RATE_NAME)
return tax["value"]
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 85116d8fbc..ce9af47999 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -20,7 +20,6 @@ from ...account.models import Address, User
from ...account.utils import store_user_address
from ...checkout import AddressType
from ...core.utils.json_serializer import object_hook
-from ...core.utils.taxes import get_tax_rate_by_name, get_taxes_for_country
from ...core.weight import zero_weight
from ...dashboard.menu.utils import update_menu
from ...discount import DiscountValueType, VoucherType
@@ -52,7 +51,6 @@ from ...product.thumbnails import (
create_product_thumbnails,
)
from ...shipping.models import ShippingMethod, ShippingMethodType, ShippingZone
-from ...shipping.utils import get_taxed_shipping_price
fake = Factory.create()
@@ -362,7 +360,7 @@ def create_order_line(order, discounts, taxes):
quantity=quantity,
variant=variant,
unit_price=variant.get_price(discounts=discounts, taxes=taxes),
- tax_rate=get_tax_rate_by_name(variant.product.tax_rate, taxes),
+ tax_rate=0,
)
@@ -403,7 +401,6 @@ def create_fake_order(discounts, taxes):
shipping_method = ShippingMethod.objects.order_by("?").first()
shipping_price = shipping_method.price
- shipping_price = get_taxed_shipping_price(shipping_price, taxes)
order_data.update(
{"shipping_method_name": shipping_method.name, "shipping_price": shipping_price}
)
@@ -442,7 +439,7 @@ def create_users(how_many=10):
def create_orders(how_many=10):
- taxes = get_taxes_for_country(Country(settings.DEFAULT_COUNTRY))
+ taxes = None
discounts = Sale.objects.active(date.today()).prefetch_related(
"products", "categories", "collections"
)
diff --git a/saleor/dashboard/discount/forms.py b/saleor/dashboard/discount/forms.py
index c2809a5d70..edf6a7cba2 100644
--- a/saleor/dashboard/discount/forms.py
+++ b/saleor/dashboard/discount/forms.py
@@ -6,7 +6,7 @@ from django_countries import countries
from django_prices.forms import MoneyField
from mptt.forms import TreeNodeMultipleChoiceField
-from ...core.utils.taxes import ZERO_MONEY
+from ...core.taxes import ZERO_MONEY
from ...discount import DiscountValueType
from ...discount.models import Sale, Voucher
from ...discount.utils import generate_voucher_code
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 5fe9884a5a..3ade133564 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.utils.taxes import ZERO_TAXED_MONEY
+from ...core.taxes import ZERO_TAXED_MONEY
from ...discount.models import Voucher
from ...discount.utils import decrease_voucher_usage, increase_voucher_usage
from ...order import OrderStatus, events
diff --git a/saleor/dashboard/order/utils.py b/saleor/dashboard/order/utils.py
index 1d0331cf6f..fd299734b0 100644
--- a/saleor/dashboard/order/utils.py
+++ b/saleor/dashboard/order/utils.py
@@ -5,7 +5,7 @@ from django.template.loader import get_template
from ...checkout import AddressType
from ...checkout.utils import _get_products_voucher_discount
-from ...core.utils.taxes import ZERO_MONEY
+from ...core.taxes import ZERO_MONEY
from ...discount import VoucherType
from ...discount.utils import get_shipping_voucher_discount, get_value_voucher_discount
diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.py
index 1a4f3efcdc..501d0b71f0 100644
--- a/saleor/dashboard/order/views.py
+++ b/saleor/dashboard/order/views.py
@@ -14,7 +14,6 @@ from django_prices.templatetags import prices_i18n
from ...core.exceptions import InsufficientStock
from ...core.utils import get_paginator_items
-from ...core.utils.taxes import get_taxes_for_address
from ...order import OrderStatus, events
from ...order.emails import (
send_fulfillment_confirmation_to_customer,
@@ -315,7 +314,7 @@ def orderline_cancel(request, order_pk, line_pk):
def add_variant_to_order(request, order_pk):
"""Add variant in given quantity to an order."""
order = get_object_or_404(Order.objects.drafts(), pk=order_pk)
- taxes = get_taxes_for_address(order.shipping_address)
+ taxes = None
form = AddVariantToOrderForm(
request.POST or None, order=order, discounts=request.discounts, taxes=taxes
)
@@ -433,7 +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 = get_taxes_for_address(order.shipping_address)
+ taxes = None
form = OrderShippingForm(request.POST or None, instance=order, taxes=taxes)
status = 200
if form.is_valid():
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.py
index a890a4733a..22689d1713 100644
--- a/saleor/dashboard/product/forms.py
+++ b/saleor/dashboard/product/forms.py
@@ -11,7 +11,8 @@ from django_prices_vatlayer.utils import get_tax_rate_types
from mptt.forms import TreeNodeChoiceField
from ...core import TaxRateType
-from ...core.utils.taxes import DEFAULT_TAX_RATE_NAME, include_taxes_in_prices
+from ...core.taxes import include_taxes_in_prices
+from ...core.taxes.vatlayer import DEFAULT_TAX_RATE_NAME # FIXME
from ...core.weight import WeightField
from ...product.models import (
Attribute,
diff --git a/saleor/dashboard/taxes/views.py b/saleor/dashboard/taxes/views.py
index efb5f03478..cf3f3519fd 100644
--- a/saleor/dashboard/taxes/views.py
+++ b/saleor/dashboard/taxes/views.py
@@ -13,8 +13,8 @@ from django_countries.fields import Country
from django_prices_vatlayer.models import VAT
from ...core import TaxRateType
+from ...core.taxes.vatlayer import get_taxes_for_country # FIXME
from ...core.utils import get_paginator_items
-from ...core.utils.taxes import get_taxes_for_country
from ...dashboard.taxes.filters import TaxFilter
from ...dashboard.taxes.forms import TaxesConfigurationForm
from ...dashboard.views import staff_member_required
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 74088eeecb..c9ce721b1f 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -3,7 +3,7 @@ import uuid
from django.db.models import F
from django.utils.translation import pgettext
-from ..core.utils.taxes import ZERO_MONEY, ZERO_TAXED_MONEY
+from ..core.taxes import ZERO_MONEY, ZERO_TAXED_MONEY
from .models import NotApplicable
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 47ae9fb761..96b2e64611 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -21,7 +21,7 @@ from ...checkout.utils import (
)
from ...core import analytics
from ...core.exceptions import InsufficientStock
-from ...core.utils.taxes import get_taxes_for_address
+from ...core.taxes.errors import TaxError
from ...discount import models as voucher_model
from ...payment import PaymentError
from ...payment.utils import gateway_process_payment
@@ -239,7 +239,7 @@ class CheckoutLinesAdd(BaseMutation):
checkout=checkout,
method=checkout.shipping_method,
discounts=info.context.discounts,
- taxes=get_taxes_for_address(checkout.shipping_address),
+ taxes=None,
)
if variants and quantities:
@@ -291,7 +291,7 @@ class CheckoutLineDelete(BaseMutation):
checkout=checkout,
method=checkout.shipping_method,
discounts=info.context.discounts,
- taxes=get_taxes_for_address(checkout.shipping_address),
+ taxes=None,
)
recalculate_checkout_discount(
@@ -370,7 +370,7 @@ class CheckoutShippingAddressUpdate(BaseMutation, I18nMixin):
checkout=checkout,
method=checkout.shipping_method,
discounts=info.context.discounts,
- taxes=get_taxes_for_address(shipping_address),
+ taxes=None,
)
with transaction.atomic():
@@ -510,6 +510,8 @@ class CheckoutComplete(BaseMutation):
raise ValidationError("Insufficient product stock.")
except voucher_model.NotApplicable:
raise ValidationError("Voucher not applicable")
+ except TaxError as tax_error:
+ return ValidationError("Unable to calculate taxes - %s" % str(tax_error))
payment.order = order
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 7baad335dc..60220e9331 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -3,7 +3,6 @@ import graphene_django_optimizer as gql_optimizer
from django.conf import settings
from ...checkout import models
-from ...core.utils.taxes import get_taxes_for_address
from ..core.connection import CountableDjangoObjectType
from ..core.types.money import TaxedMoney
from ..order.utils import applicable_shipping_methods
@@ -28,7 +27,7 @@ class CheckoutLine(CountableDjangoObjectType):
filter_fields = ["id"]
def resolve_total_price(self, info):
- taxes = get_taxes_for_address(self.checkout.shipping_address)
+ taxes = None # FIXME
return self.get_total(discounts=info.context.discounts, taxes=taxes)
def resolve_requires_shipping(self, *_args):
@@ -99,22 +98,22 @@ class Checkout(CountableDjangoObjectType):
filter_fields = ["token"]
def resolve_total_price(self, info):
- taxes = get_taxes_for_address(self.shipping_address)
+ taxes = None # FIXME
return self.get_total(discounts=info.context.discounts, taxes=taxes)
def resolve_subtotal_price(self, *_args):
- taxes = get_taxes_for_address(self.shipping_address)
+ taxes = None
return self.get_subtotal(taxes=taxes)
def resolve_shipping_price(self, *_args):
- taxes = get_taxes_for_address(self.shipping_address)
+ taxes = None
return self.get_shipping_price(taxes=taxes)
def resolve_lines(self, *_args):
return self.lines.prefetch_related("variant")
def resolve_available_shipping_methods(self, info):
- taxes = get_taxes_for_address(self.shipping_address)
+ taxes = None
price = self.get_subtotal(taxes=taxes, discounts=info.context.discounts)
return applicable_shipping_methods(self, price.gross.amount)
diff --git a/saleor/graphql/order/mutations/draft_orders.py b/saleor/graphql/order/mutations/draft_orders.py
index e52598f206..ad52874f02 100644
--- a/saleor/graphql/order/mutations/draft_orders.py
+++ b/saleor/graphql/order/mutations/draft_orders.py
@@ -4,7 +4,7 @@ from graphene.types import InputObjectType
from ....account.models import User
from ....core.exceptions import InsufficientStock
-from ....core.utils.taxes import ZERO_TAXED_MONEY
+from ....core.taxes import ZERO_TAXED_MONEY
from ....order import OrderStatus, events, models
from ....order.utils import (
add_variant_to_order,
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index ad1260f308..34c5cc127f 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.utils.taxes import ZERO_TAXED_MONEY
+from ....core.taxes import ZERO_TAXED_MONEY
from ....order import events, models
from ....order.utils import cancel_order
from ....payment import CustomPaymentChoices, PaymentError
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 2956a2bc4c..c2d74f8a5d 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -3,7 +3,6 @@ from django.conf import settings
from django.core.exceptions import ValidationError
from ...core.utils import get_client_ip
-from ...core.utils.taxes import get_taxes_for_address
from ...payment import PaymentError, models
from ...payment.utils import (
create_payment,
@@ -80,8 +79,7 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
)
checkout_total = checkout.get_total(
- discounts=info.context.discounts,
- taxes=get_taxes_for_address(checkout.billing_address),
+ discounts=info.context.discounts, taxes=None
)
amount = data.get("amount", checkout_total)
if amount < checkout_total.gross.amount:
diff --git a/saleor/order/migrations/0065_auto_20181017_1346.py b/saleor/order/migrations/0065_auto_20181017_1346.py
index f668097ac8..511316384b 100644
--- a/saleor/order/migrations/0065_auto_20181017_1346.py
+++ b/saleor/order/migrations/0065_auto_20181017_1346.py
@@ -1,10 +1,12 @@
# Generated by Django 2.1.2 on 2018-10-17 18:46
+from decimal import Decimal
+
+import django_prices.models
from django.conf import settings
from django.db import migrations, models
-import django_prices.models
+
import saleor.core
-from decimal import Decimal
class Migration(migrations.Migration):
@@ -21,7 +23,7 @@ class Migration(migrations.Migration):
field=django_prices.models.MoneyField(
currency=settings.DEFAULT_CURRENCY,
decimal_places=2,
- default=saleor.core.utils.taxes.zero_money,
+ default=saleor.core.taxes.zero_money,
max_digits=12,
),
),
@@ -31,7 +33,7 @@ class Migration(migrations.Migration):
field=django_prices.models.MoneyField(
currency=settings.DEFAULT_CURRENCY,
decimal_places=2,
- default=saleor.core.utils.taxes.zero_money,
+ default=saleor.core.taxes.zero_money,
max_digits=12,
),
),
@@ -41,7 +43,7 @@ class Migration(migrations.Migration):
field=django_prices.models.MoneyField(
currency=settings.DEFAULT_CURRENCY,
decimal_places=2,
- default=saleor.core.utils.taxes.zero_money,
+ default=saleor.core.taxes.zero_money,
max_digits=12,
),
),
diff --git a/saleor/order/models.py b/saleor/order/models.py
index cbd716c54f..3edce3ee9a 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -16,8 +16,8 @@ from measurement.measures import Weight
from prices import Money
from ..account.models import Address
+from ..core.taxes import ZERO_TAXED_MONEY, zero_money
from ..core.utils.json_serializer import CustomJsonEncoder
-from ..core.utils.taxes import ZERO_TAXED_MONEY, zero_money
from ..core.weight import WeightUnits, zero_weight
from ..discount.models import Voucher
from ..payment import ChargeStatus, TransactionKind
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 64b3849c9e..d890c86e39 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -1,3 +1,4 @@
+from decimal import Decimal
from functools import wraps
from django.conf import settings
@@ -7,7 +8,7 @@ from prices import Money, TaxedMoney
from ..account.utils import store_user_address
from ..checkout import AddressType
-from ..core.utils.taxes import ZERO_MONEY, get_tax_rate_by_name, get_taxes_for_address
+from ..core.taxes import ZERO_MONEY
from ..core.weight import zero_weight
from ..dashboard.order.utils import get_voucher_discount_for_order
from ..discount.models import NotApplicable
@@ -152,12 +153,12 @@ def recalculate_order_weight(order):
def update_order_prices(order, discounts):
"""Update prices in order with given discounts and proper taxes."""
- taxes = get_taxes_for_address(order.shipping_address)
+ taxes = None
for line in order:
if line.variant:
line.unit_price = line.variant.get_price(discounts, taxes)
- line.tax_rate = get_tax_rate_by_name(line.variant.product.tax_rate, taxes)
+ line.tax_rate = 0
line.save()
if order.shipping_method:
@@ -254,6 +255,7 @@ def add_variant_to_order(
taxes=None,
allow_overselling=False,
track_inventory=True,
+ unit_tax=Decimal("0.0"),
):
"""Add total_quantity of variant to order.
@@ -265,6 +267,11 @@ def add_variant_to_order(
if not allow_overselling:
variant.check_quantity(quantity)
+ unit_price_net = variant.get_price(discounts).net
+ 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
@@ -281,8 +288,8 @@ def add_variant_to_order(
is_shipping_required=variant.is_shipping_required(),
quantity=quantity,
variant=variant,
- unit_price=variant.get_price(discounts, taxes),
- tax_rate=get_tax_rate_by_name(variant.product.tax_rate, taxes),
+ unit_price=unit_price,
+ tax_rate=0,
)
if variant.track_inventory and track_inventory:
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 1d6f96af63..5370ce4999 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -9,7 +9,7 @@ from django.db import models
from prices import Money
from ..checkout.models import Checkout
-from ..core.utils.taxes import zero_money
+from ..core.taxes import zero_money
from ..order.models import Order
from . import (
ChargeStatus,
diff --git a/saleor/product/forms.py b/saleor/product/forms.py
index 1ddb7b618c..9a995944a4 100644
--- a/saleor/product/forms.py
+++ b/saleor/product/forms.py
@@ -6,7 +6,7 @@ from django.utils.translation import pgettext_lazy
from django_prices.templatetags.prices_i18n import amount
from ..checkout.forms import AddToCheckoutForm
-from ..core.utils.taxes import display_gross_prices
+from ..core.taxes import display_gross_prices
class VariantChoiceField(forms.ModelChoiceField):
diff --git a/saleor/product/migrations/0079_default_tax_rate_instead_of_empty_field.py b/saleor/product/migrations/0079_default_tax_rate_instead_of_empty_field.py
index 31abb6fc5d..d1cd6116d7 100644
--- a/saleor/product/migrations/0079_default_tax_rate_instead_of_empty_field.py
+++ b/saleor/product/migrations/0079_default_tax_rate_instead_of_empty_field.py
@@ -2,7 +2,7 @@
from django.db import migrations, models
-from ...core.utils.taxes import DEFAULT_TAX_RATE_NAME
+from ...core.taxes.vatlayer import DEFAULT_TAX_RATE_NAME
def add_default_tax_rate_instead_of_empty_field(apps, schema_editor):
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 8dc7423d39..e6bd498f88 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 TaxedMoneyRange
+from prices import TaxedMoney, TaxedMoneyRange
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.utils.taxes import apply_tax_to_price
from ..core.utils.translations import TranslationProxy
from ..core.weight import WeightUnits, zero_weight
from ..discount.utils import calculate_discounted_price
@@ -189,7 +188,7 @@ class Product(SeoModel, PublishableModel):
if not self.charge_taxes:
taxes = None
tax_rate = self.tax_rate or self.product_type.tax_rate
- price = apply_tax_to_price(taxes, tax_rate, price)
+ price = TaxedMoney(net=price, gross=price)
return TaxedMoneyRange(start=price, stop=price)
@@ -290,7 +289,7 @@ class ProductVariant(models.Model):
if not self.product.charge_taxes:
taxes = None
tax_rate = self.product.tax_rate or self.product.product_type.tax_rate
- return apply_tax_to_price(taxes, tax_rate, price)
+ return TaxedMoney(net=price, gross=price)
def get_weight(self):
return self.weight or self.product.weight or self.product.product_type.weight
diff --git a/saleor/product/utils/__init__.py b/saleor/product/utils/__init__.py
index 2b18a27539..d6d414a90a 100644
--- a/saleor/product/utils/__init__.py
+++ b/saleor/product/utils/__init__.py
@@ -7,9 +7,9 @@ from ...checkout.utils import (
get_checkout_from_request,
get_or_create_checkout_from_request,
)
+from ...core.taxes import ZERO_TAXED_MONEY, TaxedMoney
from ...core.utils import get_paginator_items
from ...core.utils.filters import get_now_sorted_by
-from ...core.utils.taxes import ZERO_TAXED_MONEY, TaxedMoney
from ..forms import ProductForm
from .availability import products_with_availability
diff --git a/saleor/product/utils/costs.py b/saleor/product/utils/costs.py
index 79350bde14..fa9c9e4426 100644
--- a/saleor/product/utils/costs.py
+++ b/saleor/product/utils/costs.py
@@ -1,6 +1,6 @@
from prices import MoneyRange
-from ...core.utils.taxes import ZERO_MONEY
+from ...core.taxes import ZERO_MONEY
def get_product_costs_data(product):
diff --git a/saleor/product/utils/variants_picker.py b/saleor/product/utils/variants_picker.py
index 97d69c67e9..256a52b8f7 100644
--- a/saleor/product/utils/variants_picker.py
+++ b/saleor/product/utils/variants_picker.py
@@ -2,8 +2,8 @@ from collections import defaultdict
from django_prices.templatetags import prices_i18n
+from ...core.taxes import display_gross_prices
from ...core.utils import to_local_currency
-from ...core.utils.taxes import display_gross_prices, get_tax_rate_by_name
from ...seo.schema.product import variant_json_ld
from .availability import get_product_availability
@@ -65,7 +65,7 @@ def get_variant_picker_data(product, discounts=None, taxes=None, local_currency=
data["availability"] = {
"discount": price_as_dict(availability.discount),
- "taxRate": get_tax_rate_by_name(product.tax_rate, taxes),
+ "taxRate": 0,
"priceRange": price_range_as_dict(availability.price_range),
"priceRangeUndiscounted": price_range_as_dict(
availability.price_range_undiscounted
diff --git a/saleor/settings.py b/saleor/settings.py
index b47717ac0f..e6ff4e3c04 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -352,6 +352,15 @@ OPENEXCHANGERATES_API_KEY = os.environ.get("OPENEXCHANGERATES_API_KEY")
VATLAYER_ACCESS_KEY = os.environ.get("VATLAYER_ACCESS_KEY")
VATLAYER_USE_HTTPS = get_bool_from_env("VATLAYER_USE_HTTPS", False)
+# Avatax supports two ways of log in - username:password or account:license
+AVATAX_USERNAME_OR_ACCOUNT = os.environ.get("AVATAX_USERNAME_OR_ACCOUNT")
+AVATAX_PASSWORD_OR_LICENSE = os.environ.get("AVATAX_PASSWORD_OR_LICENSE")
+AVATAX_USE_SANDBOX = os.environ.get("AVATAX_USE_SANDBOX", True)
+AVATAX_COMPANY_NAME = os.environ.get("AVATAX_COMPANY_NAME", "DEFAULT")
+AVATAX_CHECKOUT_CACHE_TIME = os.environ.get("AVATAX_CHECKOUT_CACHE_TIME", 60 * 60)
+AVATAX_TAX_CODE_CACHE_TIME = os.environ.get("AVATAX_TAX_CODE_CACHE_TIME", 24 * 60 * 60)
+
+
ACCOUNT_ACTIVATION_DAYS = 3
LOGIN_REDIRECT_URL = "home"
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index b7c6a6a3c9..a23b46c22f 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -6,10 +6,9 @@ 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
+from prices import MoneyRange, TaxedMoney
from ..core.utils import format_money
-from ..core.utils.taxes import get_taxed_shipping_price
from ..core.utils.translations import TranslationProxy
from ..core.weight import WeightUnits, zero_weight
from . import ShippingMethodType
@@ -161,7 +160,7 @@ class ShippingMethod(models.Model):
)
def get_total(self, taxes=None):
- return get_taxed_shipping_price(self.price, taxes)
+ return TaxedMoney(net=self.price, gross=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 d9dbe89929..1adbd418fb 100644
--- a/saleor/shipping/utils.py
+++ b/saleor/shipping/utils.py
@@ -2,7 +2,7 @@ from django.db.models import Q
from django.utils.translation import pgettext_lazy
from prices import MoneyRange
-from ..core.utils.taxes import get_taxed_shipping_price
+from ..core.taxes.vatlayer import get_taxed_shipping_price # FIXME
from ..core.weight import convert_weight, get_default_weight_unit