Skip to content

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

Block when tax failed (#15292)

Krzysztof Waliczek6ee567dee3fb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6e91b27559..47ea14e250 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,13 @@ All notable, unreleased changes to this project will be documented in this file.
- Fixed validation for streetAddress1 or streetAddress2 are too long - #13973 by sonbui00
- Clear db leftovers after attribute refactor - #15372 by @IKarbowiak
+- Added possibility to break checkout/draft order completion: #15292 by @kadewu
+ - Added new field `Shop.availableTaxApps`.
+ - Added new input `taxAppId` for `TaxConfigurationUpdateInput` and `TaxConfigurationPerCountryInput`.
+ - Added new field `taxAppId` in `TaxConfiguration` and `TaxConfigurationPerCountry`.
+ - Added new input `AppInput.identifier`.
+ - Added new parameter `identifier` for `create_app` command.
+ - When `taxAppId` is provided for `TaxConfiguration` do not allow to finalize `checkoutComplete` or `draftOrderComplete` mutations if Tax App doesn't respond.
# 3.18.0
diff --git a/saleor/app/management/commands/create_app.py b/saleor/app/management/commands/create_app.py
index cd1b5226e6..093fff4f81 100644
--- a/saleor/app/management/commands/create_app.py
+++ b/saleor/app/management/commands/create_app.py
@@ -82,7 +82,7 @@ class Command(BaseCommand):
app = App.objects.create(name=name, is_active=is_active, identifier=identifier)
if not identifier:
app.identifier = graphene.Node.to_global_id("App", app.pk)
- app.save()
+ app.save(update_fields=["identifier"])
app.permissions.set(permissions)
_, auth_token = app.tokens.create() # type: ignore[call-arg] # method of a related manager # noqa: E501
data = {
diff --git a/saleor/app/migrations/0029_alter_app_identifier.py b/saleor/app/migrations/0029_alter_app_identifier.py
new file mode 100644
index 0000000000..4201f66491
--- /dev/null
+++ b/saleor/app/migrations/0029_alter_app_identifier.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("app", "0028_set_identifier"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="app",
+ name="identifier",
+ field=models.CharField(max_length=256, blank=True),
+ ),
+ ]
diff --git a/saleor/app/models.py b/saleor/app/models.py
index 5bc9208eef..251bcf530e 100644
--- a/saleor/app/models.py
+++ b/saleor/app/models.py
@@ -44,7 +44,7 @@ class App(ModelWithMetadata):
type = models.CharField(
choices=AppType.CHOICES, default=AppType.LOCAL, max_length=60
)
- identifier = models.CharField(blank=True, null=True, max_length=256)
+ identifier = models.CharField(max_length=256, blank=True)
permissions = models.ManyToManyField(
Permission,
blank=True,
diff --git a/saleor/app/tests/test_utils.py b/saleor/app/tests/test_utils.py
new file mode 100644
index 0000000000..c6a36d935e
--- /dev/null
+++ b/saleor/app/tests/test_utils.py
@@ -0,0 +1,54 @@
+from ...app.utils import get_active_tax_apps
+from ...core.tests.test_taxes import app_factory, tax_app_factory # noqa: F401
+from ...webhook.event_types import WebhookEventSyncType
+
+
+def test_get_active_tax_apps(app_factory, tax_app_factory): # noqa: F811
+ # given
+ app = app_factory(
+ name="app1",
+ is_active=True,
+ webhook_event_types=[],
+ permissions=[],
+ )
+ tax_app1 = tax_app_factory(name="app2", is_active=True)
+ tax_app2 = tax_app_factory(name="app3", is_active=False)
+
+ # when
+ tax_apps = get_active_tax_apps()
+
+ # then
+ assert len(tax_apps) == 1
+ assert tax_app1 in tax_apps
+ assert tax_app2 not in tax_apps
+ assert app not in tax_apps
+
+
+def test_get_active_tax_app_no_permission(tax_app_factory): # noqa: F811
+ # given
+ tax_app_factory(
+ name="app1",
+ is_active=True,
+ permissions=[],
+ )
+
+ # when
+ tax_apps = get_active_tax_apps()
+
+ # then
+ assert len(tax_apps) == 0
+
+
+def test_get_active_tax_app_only_one_webhook(tax_app_factory): # noqa: F811
+ # given
+ tax_app_factory(
+ name="app1",
+ is_active=True,
+ webhook_event_types=[WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES],
+ )
+
+ # when
+ tax_apps = get_active_tax_apps()
+
+ # then
+ assert len(tax_apps) == 1
diff --git a/saleor/app/utils.py b/saleor/app/utils.py
new file mode 100644
index 0000000000..e00b9eac5e
--- /dev/null
+++ b/saleor/app/utils.py
@@ -0,0 +1,20 @@
+from typing import Optional
+
+from ..webhook.event_types import WebhookEventSyncType
+from ..webhook.utils import get_webhooks_for_event
+
+
+def get_active_tax_apps(identifiers: Optional[list[str]] = None):
+ checkout_webhooks = get_webhooks_for_event(
+ event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
+ apps_identifier=identifiers,
+ )
+ order_webhooks = get_webhooks_for_event(
+ event_type=WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ apps_identifier=identifiers,
+ )
+
+ checkout_apps = {webhook.app for webhook in checkout_webhooks}
+ order_apps = {webhook.app for webhook in order_webhooks}
+
+ return checkout_apps.union(order_apps)
diff --git a/saleor/checkout/calculations.py b/saleor/checkout/calculations.py
index 79b94d8842..4c1af21d0a 100644
--- a/saleor/checkout/calculations.py
+++ b/saleor/checkout/calculations.py
@@ -3,12 +3,13 @@ from decimal import Decimal
from typing import TYPE_CHECKING, Optional, cast
from django.conf import settings
+from django.core.exceptions import ValidationError
from django.utils import timezone
from prices import Money, TaxedMoney
from ..checkout import base_calculations
from ..core.prices import quantize_price
-from ..core.taxes import TaxData, zero_money, zero_taxed_money
+from ..core.taxes import EmptyTaxData, TaxData, zero_money, zero_taxed_money
from ..discount.utils import (
create_or_update_discount_objects_from_promotion_for_checkout,
)
@@ -17,9 +18,11 @@ from ..tax import TaxCalculationStrategy
from ..tax.calculations.checkout import update_checkout_prices_with_flat_rates
from ..tax.utils import (
get_charge_taxes_for_checkout,
+ get_tax_app_identifier_for_checkout,
get_tax_calculation_strategy_for_checkout,
normalize_tax_rate_for_db,
)
+from .error_codes import CheckoutErrorCode
from .fetch import find_checkout_line_info
from .models import Checkout
from .payment_utils import update_checkout_payment_statuses
@@ -36,6 +39,7 @@ def checkout_shipping_price(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
+ need_tax_calculation: bool = False,
) -> "TaxedMoney":
"""Return checkout shipping price.
@@ -47,6 +51,7 @@ def checkout_shipping_price(
manager=manager,
lines=lines,
address=address,
+ need_tax_calculation=need_tax_calculation,
)
return quantize_price(checkout_info.checkout.shipping_price, currency)
@@ -57,6 +62,7 @@ def checkout_shipping_tax_rate(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
+ need_tax_calculation: bool = False,
) -> Decimal:
"""Return checkout shipping tax rate.
@@ -67,6 +73,7 @@ def checkout_shipping_tax_rate(
manager=manager,
lines=lines,
address=address,
+ need_tax_calculation=need_tax_calculation,
)
return checkout_info.checkout.shipping_tax_rate
@@ -77,6 +84,7 @@ def checkout_subtotal(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
+ need_tax_calculation: bool = False,
) -> "TaxedMoney":
"""Return the total cost of all the checkout lines, taxes included.
@@ -88,6 +96,7 @@ def checkout_subtotal(
manager=manager,
lines=lines,
address=address,
+ need_tax_calculation=need_tax_calculation,
)
return quantize_price(checkout_info.checkout.subtotal, currency)
@@ -117,6 +126,7 @@ def checkout_total(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"],
+ need_tax_calculation: bool = False,
) -> "TaxedMoney":
"""Return the total cost of the checkout.
@@ -131,6 +141,7 @@ def checkout_total(
manager=manager,
lines=lines,
address=address,
+ need_tax_calculation=need_tax_calculation,
)
return quantize_price(checkout_info.checkout.total, currency)
@@ -141,6 +152,7 @@ def checkout_line_total(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
+ need_tax_calculation: bool = False,
) -> TaxedMoney:
"""Return the total price of provided line, taxes included.
@@ -153,6 +165,7 @@ def checkout_line_total(
manager=manager,
lines=lines,
address=address,
+ need_tax_calculation=need_tax_calculation,
)
checkout_line = find_checkout_line_info(lines, checkout_line_info.line.id).line
return quantize_price(checkout_line.total_price, currency)
@@ -164,6 +177,7 @@ def checkout_line_unit_price(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
+ need_tax_calculation: bool = False,
) -> TaxedMoney:
"""Return the unit price of provided line, taxes included.
@@ -176,6 +190,7 @@ def checkout_line_unit_price(
manager=manager,
lines=lines,
address=address,
+ need_tax_calculation=need_tax_calculation,
)
checkout_line = find_checkout_line_info(lines, checkout_line_info.line.id).line
unit_price = checkout_line.total_price / checkout_line.quantity
@@ -188,6 +203,7 @@ def checkout_line_tax_rate(
checkout_info: "CheckoutInfo",
lines: Iterable["CheckoutLineInfo"],
checkout_line_info: "CheckoutLineInfo",
+ need_tax_calculation: bool = False,
) -> Decimal:
"""Return the tax rate of provided line.
@@ -199,6 +215,7 @@ def checkout_line_tax_rate(
manager=manager,
lines=lines,
address=address,
+ need_tax_calculation=need_tax_calculation,
)
checkout_line_info = find_checkout_line_info(lines, checkout_line_info.line.id)
return checkout_line_info.line.tax_rate
@@ -210,11 +227,13 @@ def _fetch_checkout_prices_if_expired(
lines: Iterable["CheckoutLineInfo"],
address: Optional["Address"] = None,
force_update: bool = False,
+ need_tax_calculation: bool = False,
) -> tuple["CheckoutInfo", Iterable["CheckoutLineInfo"]]:
"""Fetch checkout prices with taxes.
First calculate and apply all checkout prices with taxes separately,
- then apply tax data as well if we receive one.
+ then apply tax data as well if we receive one. If need_tax_calculation is set
+ to True, we will raise error if we didn't receive tax data.
Prices can be updated only if force_update == True, or if time elapsed from the
last price update is greater than settings.CHECKOUT_PRICES_TTL.
@@ -231,22 +250,28 @@ def _fetch_checkout_prices_if_expired(
prices_entered_with_tax = tax_configuration.prices_entered_with_tax
charge_taxes = get_charge_taxes_for_checkout(checkout_info, lines)
should_charge_tax = charge_taxes and not checkout.tax_exemption
+ tax_app_identifier = get_tax_app_identifier_for_checkout(checkout_info, lines)
lines = cast(list, lines)
create_or_update_discount_objects_from_promotion_for_checkout(checkout_info, lines)
+ checkout.tax_error = None
if prices_entered_with_tax:
# If prices are entered with tax, we need to always calculate it anyway, to
# display the tax rate to the user.
- _calculate_and_add_tax(
- tax_calculation_strategy,
- checkout,
- manager,
- checkout_info,
- lines,
- prices_entered_with_tax,
- address,
- )
+ try:
+ _calculate_and_add_tax(
+ tax_calculation_strategy,
+ tax_app_identifier,
+ checkout,
+ manager,
+ checkout_info,
+ lines,
+ prices_entered_with_tax,
+ address,
+ )
+ except EmptyTaxData as e:
+ checkout.tax_error = str(e)
if not should_charge_tax:
# If charge_taxes is disabled or checkout is exempt from taxes, remove the
@@ -258,37 +283,54 @@ def _fetch_checkout_prices_if_expired(
if should_charge_tax:
# Calculate taxes if charge_taxes is enabled and checkout is not exempt
# from taxes.
- _calculate_and_add_tax(
- tax_calculation_strategy,
- checkout,
- manager,
- checkout_info,
- lines,
- prices_entered_with_tax,
- address,
- )
+ try:
+ _calculate_and_add_tax(
+ tax_calculation_strategy,
+ tax_app_identifier,
+ checkout,
+ manager,
+ checkout_info,
+ lines,
+ prices_entered_with_tax,
+ address,
+ )
+ except EmptyTaxData as e:
+ checkout.tax_error = str(e)
else:
# Calculate net prices without taxes.
_get_checkout_base_prices(checkout, checkout_info, lines)
+ # raise an error if recorded tax_error and taxes are needed for process completion
+ if checkout.tax_error and need_tax_calculation:
+ checkout.save(update_fields=["tax_error"])
+
+ raise ValidationError(
+ "Configured Tax App didn't responded.",
+ code=CheckoutErrorCode.TAX_ERROR.value,
+ )
+
+ checkout_update_fields = [
+ "voucher_code",
+ "total_net_amount",
+ "total_gross_amount",
+ "subtotal_net_amount",
+ "subtotal_gross_amount",
+ "shipping_price_net_amount",
+ "shipping_price_gross_amount",
+ "shipping_tax_rate",
+ "translated_discount_name",
+ "discount_amount",
+ "discount_name",
+ "currency",
+ "last_change",
+ "price_expiration",
+ "tax_error",
+ ]
+
checkout.price_expiration = timezone.now() + settings.CHECKOUT_PRICES_TTL
+
checkout.save(
- update_fields=[
- "voucher_code",
- "total_net_amount",
- "total_gross_amount",
- "subtotal_net_amount",
- "subtotal_gross_amount",
- "shipping_price_net_amount",
- "shipping_price_gross_amount",
- "shipping_tax_rate",
- "price_expiration",
- "translated_discount_name",
- "discount_amount",
- "discount_name",
- "currency",
- "last_change",
- ],
+ update_fields=checkout_update_fields,
using=settings.DATABASE_CONNECTION_DEFAULT_NAME,
)
checkout.lines.bulk_update(
@@ -304,6 +346,7 @@ def _fetch_checkout_prices_if_expired(
def _calculate_and_add_tax(
tax_calculation_strategy: str,
+ tax_app_identifier: Optional[str],
checkout: "Checkout",
manager: "PluginsManager",
checkout_info: "CheckoutInfo",
@@ -315,7 +358,13 @@ def _calculate_and_add_tax(
# Call the tax plugins.
_apply_tax_data_from_plugins(checkout, manager, checkout_info, lines, address)
# Get the taxes calculated with apps and apply to checkout.
- tax_data = manager.get_taxes_for_checkout(checkout_info, lines)
+ tax_data = manager.get_taxes_for_checkout(
+ checkout_info, lines, tax_app_identifier
+ )
+ # If taxAppId is not configured we will for now allow to finalize process for
+ # backward compatibility.
+ if tax_data is None and tax_app_identifier is not None:
+ raise EmptyTaxData("Empty tax data.")
_apply_tax_data(checkout, lines, tax_data)
else:
# Get taxes calculated with flat rates and apply to checkout.
@@ -475,11 +524,15 @@ def fetch_checkout_data(
force_update: bool = False,
checkout_transactions: Optional[Iterable["TransactionItem"]] = None,
force_status_update: bool = False,
+ need_tax_calculation: bool = False,
):
"""Fetch checkout data.
This function refreshes prices if they have expired. If the checkout total has
changed as a result, it will update the payment statuses accordingly.
+
+ need_tax_calculation: Set to true if fetching data should fail when received tax data
+ is invalid. Otherwise will only collect error message to checkout.tax_error field.
"""
previous_total_gross = checkout_info.checkout.total.gross
checkout_info, lines = _fetch_checkout_prices_if_expired(
@@ -488,6 +541,7 @@ def fetch_checkout_data(
lines=lines,
address=address,
force_update=force_update,
+ need_tax_calculation=need_tax_calculation,
)
current_total_gross = checkout_info.checkout.total.gross
if current_total_gross != previous_total_gross or force_status_update:
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index da8c39ab18..3530b821ba 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -231,6 +231,7 @@ def _create_line_for_order(
checkout_info=checkout_info,
lines=lines,
checkout_line_info=checkout_line_info,
+ need_tax_calculation=True,
)
# unit price after applying all discounts - sales and vouchers
unit_price = calculations.checkout_line_unit_price(
@@ -238,12 +239,14 @@ def _create_line_for_order(
checkout_info=checkout_info,
lines=lines,
checkout_line_info=checkout_line_info,
+ need_tax_calculation=True,
)
tax_rate = calculations.checkout_line_tax_rate(
manager=manager,
checkout_info=checkout_info,
lines=lines,
checkout_line_info=checkout_line_info,
+ need_tax_calculation=True,
)
# unit price before applying discounts
undiscounted_unit_price = get_taxed_undiscounted_price(
@@ -455,12 +458,14 @@ def _prepare_order_data(
checkout_info=checkout_info,
lines=lines,
address=address,
+ need_tax_calculation=True,
)
shipping_tax_rate = calculations.checkout_shipping_tax_rate(
manager=manager,
checkout_info=checkout_info,
lines=lines,
address=address,
+ need_tax_calculation=True,
)
order_data.update(
_process_shipping_data_for_order(
@@ -513,6 +518,7 @@ def _prepare_order_data(
checkout_info=checkout_info,
lines=lines,
address=address,
+ need_tax_calculation=True,
)
+ shipping_total
- checkout.discount
@@ -872,7 +878,7 @@ def complete_checkout_pre_payment_part(
if site_settings is None:
site_settings = Site.objects.get_current().settings
- fetch_checkout_data(checkout_info, manager, lines)
+ fetch_checkout_data(checkout_info, manager, lines, need_tax_calculation=True)
checkout = checkout_info.checkout
channel_slug = checkout_info.channel.slug
@@ -1171,12 +1177,14 @@ def _create_order_from_checkout(
checkout_info=checkout_info,
lines=checkout_lines_info,
address=address,
+ need_tax_calculation=True,
)
shipping_tax_rate = calculations.checkout_shipping_tax_rate(
manager=manager,
checkout_info=checkout_info,
lines=checkout_lines_info,
address=address,
+ need_tax_calculation=True,
)
# status
@@ -1406,7 +1414,15 @@ def complete_checkout(
private_metadata_list: Optional[list] = None,
) -> tuple[Optional[Order], bool, dict]:
transactions = checkout_info.checkout.payment_transactions.all()
- fetch_checkout_data(checkout_info, manager, lines)
+
+ force_update = checkout_info.checkout.tax_error is not None
+ fetch_checkout_data(
+ checkout_info,
+ manager,
+ lines,
+ force_update=force_update,
+ need_tax_calculation=True,
+ )
# When checkout is zero, we don't need any transaction to cover the checkout total.
# We check if checkout is zero, and we also check what flow for marking an order as
diff --git a/saleor/checkout/migrations/0065_checkout_tax_error.py b/saleor/checkout/migrations/0065_checkout_tax_error.py
new file mode 100644
index 0000000000..a3992b8c92
--- /dev/null
+++ b/saleor/checkout/migrations/0065_checkout_tax_error.py
@@ -0,0 +1,17 @@
+# Generated by Django 3.2.23 on 2024-02-13 13:08
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("checkout", "0064_checkoutline_is_gift"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="checkout",
+ name="tax_error",
+ field=models.CharField(blank=True, max_length=255, null=True),
+ ),
+ ]
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 664a5ca197..d330c17ce0 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -197,6 +197,7 @@ class Checkout(models.Model):
)
tax_exemption = models.BooleanField(default=False)
+ tax_error = models.CharField(max_length=255, blank=True, null=True)
class Meta:
ordering = ("-last_change", "pk")
diff --git a/saleor/core/taxes.py b/saleor/core/taxes.py
index dcd246f09b..ec8986d69d 100644
--- a/saleor/core/taxes.py
+++ b/saleor/core/taxes.py
@@ -8,6 +8,10 @@ class TaxError(Exception):
"""Default tax error."""
+class EmptyTaxData(Exception):
+ """Empty tax data received from Tax App error."""
+
+
def zero_money(currency: str) -> Money:
"""Return a money object set to zero.
diff --git a/saleor/core/tests/test_taxes.py b/saleor/core/tests/test_taxes.py
index 7a4b81251e..0389745918 100644
--- a/saleor/core/tests/test_taxes.py
+++ b/saleor/core/tests/test_taxes.py
@@ -1,3 +1,4 @@
+import graphene
import pytest
from django.utils import timezone
@@ -16,6 +17,8 @@ from ...webhook.transport.utils import get_current_tax_app
def app_factory():
def factory(name, is_active, webhook_event_types, permissions):
app = App.objects.create(name=name, is_active=is_active)
+ app.identifier = graphene.Node.to_global_id("App", app.pk)
+ app.save()
webhook = Webhook.objects.create(
name=f"{name} Webhook",
app=app,
diff --git a/saleor/graphql/app/mutations/app_create.py b/saleor/graphql/app/mutations/app_create.py
index f018a8b8ab..9e95ba943f 100644
--- a/saleor/graphql/app/mutations/app_create.py
+++ b/saleor/graphql/app/mutations/app_create.py
@@ -3,6 +3,7 @@ import graphene
from ....app import models
from ....permission.enums import AppPermission, get_permissions
from ....webhook.event_types import WebhookEventAsyncType
+from ...core.descriptions import ADDED_IN_319
from ...core.doc_category import DOC_CATEGORY_APPS
from ...core.enums import PermissionEnum
from ...core.mutations import ModelMutation
@@ -17,6 +18,12 @@ from ..utils import ensure_can_manage_permissions
class AppInput(BaseInputObjectType):
name = graphene.String(description="Name of the app.")
+ identifier = graphene.String(
+ description=(
+ "Canonical app ID. If not provided, "
+ "the identifier will be generated based on app.id." + ADDED_IN_319
+ )
+ )
permissions = NonNullList(
PermissionEnum,
description="List of permission code names to assign to this app.",
@@ -85,7 +92,8 @@ class AppCreate(ModelMutation):
@classmethod
def save(cls, info, instance, cleaned_input):
instance.save()
- instance.identifier = graphene.Node.to_global_id("App", instance.pk)
- instance.save()
+ if not instance.identifier:
+ instance.identifier = graphene.Node.to_global_id("App", instance.pk)
+ instance.save(update_fields=["identifier"])
_, auth_token = instance.tokens.create(name="Default")
return auth_token
diff --git a/saleor/graphql/app/tests/mutations/test_app_create.py b/saleor/graphql/app/tests/mutations/test_app_create.py
index 416d6234ef..cba24f9c72 100644
--- a/saleor/graphql/app/tests/mutations/test_app_create.py
+++ b/saleor/graphql/app/tests/mutations/test_app_create.py
@@ -15,9 +15,9 @@ from ....tests.utils import assert_no_permission, get_graphql_content
APP_CREATE_MUTATION = """
mutation AppCreate(
- $name: String, $permissions: [PermissionEnum!]){
+ $name: String, $permissions: [PermissionEnum!], $identifier: String){
appCreate(input:
- {name: $name, permissions: $permissions})
+ {name: $name, permissions: $permissions, identifier: $identifier})
{
authToken
app{
@@ -31,6 +31,7 @@ APP_CREATE_MUTATION = """
tokens{
authToken
}
+ identifier
}
errors{
field
@@ -55,12 +56,48 @@ def test_app_create_mutation(
variables = {
"name": "New integration",
"permissions": [PermissionEnum.MANAGE_PRODUCTS.name],
+ "identifier": "test.test",
}
response = staff_api_client.post_graphql(
query, variables=variables, permissions=(permission_manage_apps,)
)
content = get_graphql_content(response)
+ app_data = content["data"]["appCreate"]["app"]
+ default_token = content["data"]["appCreate"]["authToken"]
+ app = App.objects.get()
+ assert app_data["isActive"] == app.is_active
+ assert app_data["name"] == app.name
+ assert app_data["identifier"] == app.identifier
+ assert list(app.permissions.all()) == [permission_manage_products]
+ assert default_token
+ assert default_token[-4:] == app.tokens.get().token_last_4
+ assert app.uuid is not None
+ assert app.identifier == "test.test"
+
+
+def test_app_create_no_identifier_mutation(
+ permission_manage_apps,
+ permission_manage_products,
+ staff_api_client,
+ staff_user,
+):
+ # given
+ query = APP_CREATE_MUTATION
+ staff_user.user_permissions.add(permission_manage_products)
+
+ variables = {
+ "name": "New integration",
+ "permissions": [PermissionEnum.MANAGE_PRODUCTS.name],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables=variables, permissions=(permission_manage_apps,)
+ )
+ content = get_graphql_content(response)
+
+ # then
app_data = content["data"]["appCreate"]["app"]
default_token = content["data"]["appCreate"]["authToken"]
app = App.objects.get()
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index d112bbcf12..8b7cbf5ac8 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -413,7 +413,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(66):
+ with django_assert_num_queries(67):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 1
@@ -431,7 +431,7 @@ def test_create_checkout_with_reservations(
}
}
- with django_assert_num_queries(66):
+ with django_assert_num_queries(67):
response = api_client.post_graphql(query, variables)
assert get_graphql_content(response)["data"]["checkoutCreate"]
assert Checkout.objects.first().lines.count() == 10
@@ -562,7 +562,7 @@ def test_create_checkout_with_order_promotion(
}
# when
- with django_assert_num_queries(88):
+ with django_assert_num_queries(89):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
# then
@@ -817,7 +817,7 @@ def test_update_checkout_lines_with_reservations(
reservation_length=5,
)
- with django_assert_num_queries(81):
+ with django_assert_num_queries(82):
variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)
variables = {
"id": to_global_id_or_none(checkout),
@@ -831,7 +831,7 @@ def test_update_checkout_lines_with_reservations(
assert not data["errors"]
# Updating multiple lines in checkout has same query count as updating one
- with django_assert_num_queries(81):
+ with django_assert_num_queries(82):
variables = {
"id": to_global_id_or_none(checkout),
"lines": [],
@@ -1076,7 +1076,7 @@ def test_add_checkout_lines_with_reservations(
new_lines.append({"quantity": 2, "variantId": variant_id})
# Adding multiple lines to checkout has same query count as adding one
- with django_assert_num_queries(80):
+ with django_assert_num_queries(81):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": [new_lines[0]],
@@ -1089,7 +1089,7 @@ def test_add_checkout_lines_with_reservations(
checkout.lines.exclude(id=line.id).delete()
- with django_assert_num_queries(80):
+ with django_assert_num_queries(81):
variables = {
"id": Node.to_global_id("Checkout", checkout.pk),
"lines": new_lines,
@@ -1125,7 +1125,7 @@ def test_add_checkout_lines_order_discount_applies(
}
# when
- with django_assert_num_queries(75):
+ with django_assert_num_queries(76):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
@@ -1159,7 +1159,7 @@ def test_add_checkout_lines_gift_discount_applies(
}
# when
- with django_assert_num_queries(101):
+ with django_assert_num_queries(102):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)
# then
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
index adfb7000f9..ad398fbe27 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py
@@ -1,15 +1,27 @@
+from unittest import mock
+
import graphene
import pytest
+from django.test import override_settings
+from django.utils import timezone
+from freezegun import freeze_time
from prices import Money
from .....checkout import calculations
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
+from .....core import EventDeliveryStatus
+from .....core.models import EventDelivery
from .....order import OrderStatus
from .....order.models import Order
from .....payment.model_helpers import get_subtotal
from .....plugins.manager import get_plugins_manager
+from .....plugins.webhook.conftest import ( # noqa: F401
+ tax_data_response,
+ tax_line_data_response,
+)
+from .....webhook.event_types import WebhookEventSyncType
from ....core.utils import to_global_id_or_none
from ....tests.utils import get_graphql_content
@@ -373,3 +385,158 @@ def test_checkout_complete_0_total_value_from_giftcard(
assert not Checkout.objects.filter(
pk=checkout.pk
).exists(), "Checkout should have been deleted"
+
+
+@freeze_time()
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_checkout_complete_fails_with_invalid_tax_app(
+ mock_request,
+ user_api_client,
+ checkout_without_shipping_required,
+ channel_USD,
+ address,
+ tax_app,
+ tax_data_response, # noqa: F811
+):
+ # given
+ mock_request.return_value = tax_data_response
+
+ checkout = checkout_without_shipping_required
+ checkout.price_expiration = timezone.now()
+
+ checkout.billing_address = address
+ checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
+ checkout.metadata_storage.store_value_in_private_metadata(
+ items={"accepted": "false"}
+ )
+ checkout.metadata_storage.save()
+ checkout.save()
+
+ channel_USD.tax_configuration.tax_app_id = "invalid"
+ channel_USD.tax_configuration.save()
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+
+ # when
+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["checkoutComplete"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == CheckoutErrorCode.TAX_ERROR.name
+ assert data["errors"][0]["message"] == "Configured Tax App didn't responded."
+ assert not EventDelivery.objects.exists()
+
+ checkout.refresh_from_db()
+ assert checkout.tax_error == "Empty tax data."
+
+
+@freeze_time()
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_checkout_complete_calls_correct_tax_app(
+ mock_request,
+ user_api_client,
+ checkout_without_shipping_required,
+ channel_USD,
+ address,
+ tax_app,
+ tax_data_response, # noqa: F811
+ settings,
+):
+ # given
+ mock_request.return_value = tax_data_response
+
+ checkout = checkout_without_shipping_required
+ checkout.billing_address = address
+ checkout.price_expiration = timezone.now()
+ checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
+ checkout.metadata_storage.store_value_in_private_metadata(
+ items={"accepted": "false"}
+ )
+ checkout.metadata_storage.save()
+ checkout.save()
+
+ tax_app.identifier = "test_app"
+ tax_app.save()
+ channel_USD.tax_configuration.tax_app_id = "test_app"
+ channel_USD.tax_configuration.save()
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+
+ # when
+ user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ assert delivery.webhook.app == tax_app
+ mock_request.assert_called_once_with(delivery)
+
+ checkout.refresh_from_db()
+ assert checkout.price_expiration == timezone.now() + settings.CHECKOUT_PRICES_TTL
+ assert checkout.tax_error is None
+
+
+@freeze_time()
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
[email protected]("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_checkout_complete_calls_correct_force_tax_calculation_when_tax_error_was_saved(
+ mock_request,
+ user_api_client,
+ checkout_without_shipping_required,
+ channel_USD,
+ address,
+ tax_app,
+ tax_data_response, # noqa: F811
+ settings,
+):
+ # given
+ mock_request.return_value = tax_data_response
+
+ checkout = checkout_without_shipping_required
+ checkout.billing_address = address
+ checkout.price_expiration = (
+ timezone.now() + settings.CHECKOUT_PRICES_TTL + timezone.timedelta(hours=1)
+ )
+ checkout.tax_error = "Test error."
+
+ checkout.metadata_storage.store_value_in_metadata(items={"accepted": "true"})
+ checkout.metadata_storage.store_value_in_private_metadata(
+ items={"accepted": "false"}
+ )
+ checkout.metadata_storage.save()
+ checkout.save()
+
+ tax_app.identifier = "test_app"
+ tax_app.save()
+ channel_USD.tax_configuration.tax_app_id = "test_app"
+ channel_USD.tax_configuration.save()
+
+ variables = {
+ "id": to_global_id_or_none(checkout),
+ "redirectUrl": "https://www.example.com",
+ }
+
+ # when
+ user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ assert delivery.webhook.app == tax_app
+ mock_request.assert_called_once_with(delivery)
+
+ checkout.refresh_from_db()
+ assert checkout.price_expiration == timezone.now() + settings.CHECKOUT_PRICES_TTL
+ assert checkout.tax_error is None
diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.py
index 0decd13da8..0acdc35f9f 100644
--- a/saleor/graphql/order/mutations/draft_order_complete.py
+++ b/saleor/graphql/order/mutations/draft_order_complete.py
@@ -99,7 +99,10 @@ class DraftOrderComplete(BaseMutation):
qs=models.Order.objects.prefetch_related("lines__variant"),
)
cls.check_channel_permissions(info, [order.channel_id])
- order, _ = fetch_order_prices_if_expired(order, manager)
+ force_update = order.tax_error is not None
+ order, _ = fetch_order_prices_if_expired(
+ order, manager, force_update=force_update, need_tax_calculation=True
+ )
cls.validate_order(order)
country = get_order_country(order)
diff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
index c812e5d4d5..36de289e95 100644
--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py
@@ -4,7 +4,11 @@ from unittest.mock import patch
import graphene
import pytz
from django.db.models import Sum
+from django.test import override_settings
+from freezegun import freeze_time
+from .....core import EventDeliveryStatus
+from .....core.models import EventDelivery
from .....core.taxes import zero_taxed_money
from .....discount.models import VoucherCustomer
from .....order import OrderOrigin, OrderStatus
@@ -13,9 +17,14 @@ from .....order.error_codes import OrderErrorCode
from .....order.models import OrderEvent
from .....payment.model_helpers import get_subtotal
from .....plugins.base_plugin import ExcludedShippingMethod
+from .....plugins.webhook.conftest import ( # noqa: F401
+ tax_data_response,
+ tax_line_data_response,
+)
from .....product.models import ProductVariant
from .....warehouse.models import Allocation, PreorderAllocation, Stock
from .....warehouse.tests.utils import get_available_quantity_for_stock
+from .....webhook.event_types import WebhookEventSyncType
from ....payment.types import PaymentChargeStatusEnum
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -1001,3 +1010,134 @@ def test_draft_order_complete_display_gross_prices(
assert not content["data"]["draftOrderComplete"]["errors"]
order.refresh_from_db()
assert order.display_gross_prices == new_display_gross_prices
+
+
+@freeze_time()
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_draft_order_complete_fails_with_invalid_tax_app(
+ mock_request,
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ channel_USD,
+ tax_app,
+ tax_data_response, # noqa: F811
+):
+ # given
+ mock_request.return_value = tax_data_response
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ order = draft_order
+ order.should_refresh_prices = True
+ order.save()
+
+ channel_USD.tax_configuration.tax_app_id = "invalid"
+ channel_USD.tax_configuration.save()
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["draftOrderComplete"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["code"] == OrderErrorCode.TAX_ERROR.name
+ assert data["errors"][0]["message"] == "Configured Tax App didn't responded."
+ assert not EventDelivery.objects.exists()
+
+ order.refresh_from_db()
+ assert order.should_refresh_prices
+ assert order.tax_error == "Empty tax data."
+
+
+@freeze_time()
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_draft_order_complete_force_tax_calculation_when_tax_error_was_saved(
+ mock_request,
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ channel_USD,
+ tax_app,
+ tax_data_response, # noqa: F811
+):
+ # given
+ mock_request.return_value = tax_data_response
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ order = draft_order
+ order.should_refresh_prices = False
+ order.tax_error = "Test error."
+ order.save()
+
+ tax_app.identifier = "test_app"
+ tax_app.save()
+ channel_USD.tax_configuration.tax_app_id = "test_app"
+ channel_USD.tax_configuration.save()
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
+ get_graphql_content(response)
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ assert delivery.webhook.app == tax_app
+ mock_request.assert_called_once_with(delivery)
+
+ order.refresh_from_db()
+ assert not order.should_refresh_prices
+ assert not order.tax_error
+
+
+@freeze_time()
+@override_settings(PLUGINS=["saleor.plugins.webhook.plugin.WebhookPlugin"])
+@patch("saleor.webhook.transport.synchronous.transport.send_webhook_request_sync")
+def test_draft_order_complete_calls_correct_tax_app(
+ mock_request,
+ staff_api_client,
+ permission_group_manage_orders,
+ draft_order,
+ channel_USD,
+ tax_app,
+ tax_data_response, # noqa: F811
+):
+ # given
+ mock_request.return_value = tax_data_response
+ permission_group_manage_orders.user_set.add(staff_api_client.user)
+
+ order = draft_order
+ order.should_refresh_prices = True
+ order.save()
+
+ tax_app.identifier = "test_app"
+ tax_app.save()
+ channel_USD.tax_configuration.tax_app_id = "test_app"
+ channel_USD.tax_configuration.save()
+
+ order_id = graphene.Node.to_global_id("Order", order.id)
+ variables = {"id": order_id}
+
+ # when
+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)
+ get_graphql_content(response)
+
+ # then
+ delivery = EventDelivery.objects.get()
+ assert delivery.status == EventDeliveryStatus.PENDING
+ assert delivery.event_type == WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ assert delivery.webhook.app == tax_app
+ mock_request.assert_called_once_with(delivery)
+
+ order.refresh_from_db()
+ assert not order.should_refresh_prices
+ assert not order.tax_error
diff --git a/saleor/graphql/payment/mutations/transaction/transaction_process.py b/saleor/graphql/payment/mutations/transaction/transaction_process.py
index ed7f01c0f2..d066365cf7 100644
--- a/saleor/graphql/payment/mutations/transaction/transaction_process.py
+++ b/saleor/graphql/payment/mutations/transaction/transaction_process.py
@@ -198,7 +198,6 @@ class TransactionProcess(BaseMutation):
source_object = cls.get_source_object(transaction_item)
app = cls.clean_payment_app(transaction_item)
app_identifier = app.identifier
- app_identifier = cast(str, app_identifier)
action = cls.get_action(request_event, source_object.channel)
customer_ip_address = clean_customer_ip_address(
info,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index a8cea7b795..97b5696b86 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -9821,6 +9821,13 @@ type TaxConfiguration implements Node & ObjectWithMetadata @doc(category: "Taxes
"""List of country-specific exceptions in tax configuration."""
countries: [TaxConfigurationPerCountry!]!
+
+ """
+ The tax app id that will be used to calculate the taxes for the given channel. Empty value for `TAX_APP` set as `taxCalculationStrategy` means that Saleor will iterate over all installed tax apps. If multiple tax apps exist with provided tax app id use the `App` with newest `created` date. Will become mandatory in 4.0 for `TAX_APP` `taxCalculationStrategy`.
+
+ Added in Saleor 3.19.
+ """
+ taxAppId: String
}
enum TaxCalculationStrategy @doc(category: "Taxes") {
@@ -9849,6 +9856,13 @@ type TaxConfigurationPerCountry @doc(category: "Taxes") {
Determines whether displayed prices should include taxes for this country.
"""
displayGrossPrices: Boolean!
+
+ """
+ The tax app id that will be used to calculate the taxes for the given channel and country. If not provided, use the value from the channel's tax configuration.
+
+ Added in Saleor 3.19.
+ """
+ taxAppId: String
}
type TaxConfigurationCountableConnection @doc(category: "Taxes") {
@@ -10194,6 +10208,15 @@ type Shop implements ObjectWithMetadata {
"""
schemaVersion: String!
+ """
+ List of tax apps that can be assigned to the channel. The list will be calculated by Saleor based on the apps that are subscribed to webhooks related to tax calculations: CHECKOUT_CALCULATE_TAXES
+
+ Added in Saleor 3.19.
+
+ Requires one of the following permissions: AUTHENTICATED_STAFF_USER, MANAGE_APPS.
+ """
+ availableTaxApps: [App!]!
+
"""Include taxes in prices."""
includeTaxesInPrices: Boolean! @deprecated(reason: "This field will be removed in Saleor 4.0. Use `Channel.taxConfiguration.pricesEnteredWithTax` to determine whether prices are entered with tax.")
@@ -20856,6 +20879,13 @@ input TaxConfigurationUpdateInput @doc(category: "Taxes") {
"""List of country codes for which to remove the tax configuration."""
removeCountriesConfiguration: [CountryCode!]
+
+ """
+ The tax app id that will be used to calculate the taxes for the given channel. Empty value for `TAX_APP` set as `taxCalculationStrategy` means that Saleor will iterate over all installed tax apps. If multiple tax apps exist with provided tax app id use the `App` with newest `created` date. Will become mandatory in 4.0 for `TAX_APP` `taxCalculationStrategy`.
+
+ Added in Saleor 3.19.
+ """
+ taxAppId: String
}
input TaxConfigurationPerCountryInput @doc(category: "Taxes") {
@@ -20874,6 +20904,13 @@ input TaxConfigurationPerCountryInput @doc(category: "Taxes") {
Determines whether displayed prices should include taxes for this country.
"""
displayGrossPrices: Boolean!
+
+ """
+ The tax app identifier that will be used to calculate the taxes for the given channel and country. If not provided, use the value from the channel's tax configuration.
+
+ Added in Saleor 3.19.
+ """
+ taxAppId: String
}
"""
@@ -30459,6 +30496,13 @@ input AppInput @doc(category: "Apps") {
"""Name of the app."""
name: String
+ """
+ Canonical app ID. If not provided, the identifier will be generated based on app.id.
+
+ Added in Saleor 3.19.
+ """
+ identifier: String
+
"""List of permission code names to assign to this app."""
permissions: [PermissionEnum!]
}
diff --git a/saleor/graphql/shop/tests/queries/test_shop.py b/saleor/graphql/shop/tests/queries/test_shop.py
index a24beb80f2..2e7f676c98 100644
--- a/saleor/graphql/shop/tests/queries/test_shop.py
+++ b/saleor/graphql/shop/tests/queries/test_shop.py
@@ -5,6 +5,7 @@ import pytest
from django_countries import countries
from ..... import __version__
+from .....core.tests.test_taxes import app_factory, tax_app_factory # noqa: F401
from .....permission.enums import get_permissions_codename
from .....shipping import PostalCodeRuleInclusionType
from .....shipping.models import ShippingMethod
@@ -876,3 +877,33 @@ def test_query_allow_login_without_confirmation(
assert content["data"]["shop"]["allowLoginWithoutConfirmation"] == (
site_settings.allow_login_without_confirmation
)
+
+
+def test_query_available_tax_apps(staff_api_client, tax_app_factory): # noqa: F811
+ # given
+ query = """
+ query {
+ shop {
+ availableTaxApps{
+ id
+ name
+ }
+ }
+ }
+ """
+
+ apps = [
+ tax_app_factory(name="app1", is_active=True),
+ tax_app_factory(name="app2", is_active=True),
+ ]
+
+ # when
+ response = staff_api_client.post_graphql(query)
+ content = get_graphql_content(response)
+
+ # then
+ assert len(content["data"]["shop"]["availableTaxApps"]) == len(apps)
+
+ apps_ids = [graphene.Node.to_global_id("App", app.id) for app in apps]
+ for app in content["data"]["shop"]["availableTaxApps"]:
+ assert app["id"] in apps_ids
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index 8677984dbe..f5206ab973 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -7,13 +7,15 @@ from phonenumbers import COUNTRY_CODE_TO_REGION_CODE
from ... import __version__, schema_version
from ...account import models as account_models
+from ...app.utils import get_active_tax_apps
from ...channel import models as channel_models
from ...core.models import ModelWithMetadata
from ...core.utils import build_absolute_uri, get_domain, is_ssl_enabled
from ...permission.auth_filters import AuthorizationFilters
-from ...permission.enums import SitePermissions, get_permissions
+from ...permission.enums import AppPermission, SitePermissions, get_permissions
from ...site import models as site_models
from ..account.types import Address, AddressInput, StaffNotificationRecipient
+from ..app.types import App
from ..core import ResolveInfo
from ..core.context import get_database_connection_name
from ..core.descriptions import (
@@ -21,6 +23,7 @@ from ..core.descriptions import (
ADDED_IN_35,
ADDED_IN_314,
ADDED_IN_315,
+ ADDED_IN_319,
DEPRECATED_IN_3X_FIELD,
DEPRECATED_IN_3X_INPUT,
)
@@ -344,6 +347,20 @@ class Shop(graphene.ObjectType):
description="Minor Saleor API version." + ADDED_IN_35,
required=True,
)
+ available_tax_apps = PermissionsField(
+ NonNullList(App),
+ description=(
+ "List of tax apps that can be assigned to the channel. "
+ "The list will be calculated by Saleor based on the apps "
+ "that are subscribed to webhooks related to tax calculations: "
+ "CHECKOUT_CALCULATE_TAXES" + ADDED_IN_319
+ ),
+ required=True,
+ permissions=[
+ AuthorizationFilters.AUTHENTICATED_STAFF_USER,
+ AppPermission.MANAGE_APPS,
+ ],
+ )
# deprecated
include_taxes_in_prices = graphene.Boolean(
@@ -591,6 +608,10 @@ class Shop(graphene.ObjectType):
def resolve_schema_version(_, _info):
return schema_version
+ @staticmethod
+ def resolve_available_tax_apps(_, _info):
+ return get_active_tax_apps()
+
# deprecated
@staticmethod
diff --git a/saleor/graphql/tax/mutations/tax_configuration_update.py b/saleor/graphql/tax/mutations/tax_configuration_update.py
index 70c4ac7937..4d8fd1367e 100644
--- a/saleor/graphql/tax/mutations/tax_configuration_update.py
+++ b/saleor/graphql/tax/mutations/tax_configuration_update.py
@@ -1,11 +1,12 @@
import graphene
from django.core.exceptions import ValidationError
+from ....app.utils import get_active_tax_apps
from ....permission.enums import CheckoutPermissions
from ....tax import error_codes, models
from ...account.enums import CountryCodeEnum
from ...core import ResolveInfo
-from ...core.descriptions import ADDED_IN_39
+from ...core.descriptions import ADDED_IN_39, ADDED_IN_319
from ...core.doc_category import DOC_CATEGORY_TAXES
from ...core.mutations import ModelMutation
from ...core.types import BaseInputObjectType, Error, NonNullList
@@ -42,6 +43,13 @@ class TaxConfigurationPerCountryInput(BaseInputObjectType):
),
required=True,
)
+ tax_app_id = graphene.String(
+ description=(
+ "The tax app identifier that will be used to calculate the taxes for the "
+ "given channel and country. If not provided, use the value from the channel's "
+ "tax configuration." + ADDED_IN_319
+ ),
+ )
class Meta:
doc_category = DOC_CATEGORY_TAXES
@@ -78,6 +86,16 @@ class TaxConfigurationUpdateInput(BaseInputObjectType):
CountryCodeEnum,
description="List of country codes for which to remove the tax configuration.",
)
+ tax_app_id = graphene.String(
+ description=(
+ "The tax app id that will be used to calculate the taxes for the given channel. "
+ "Empty value for `TAX_APP` set as `taxCalculationStrategy` means that Saleor will "
+ "iterate over all installed tax apps. If multiple tax apps exist with provided "
+ "tax app id use the `App` with newest `created` date. "
+ "Will become mandatory in 4.0 for `TAX_APP` `taxCalculationStrategy`."
+ + ADDED_IN_319
+ ),
+ )
class Meta:
doc_category = DOC_CATEGORY_TAXES
@@ -112,6 +130,7 @@ class TaxConfigurationUpdate(ModelMutation):
@classmethod
def clean_input(cls, info: ResolveInfo, instance, data, **kwargs):
+ cls.clean_tax_app_id(info, data)
update_countries_configuration = data.get("update_countries_configuration", [])
update_country_codes = [
item["country_code"] for item in update_countries_configuration
@@ -133,6 +152,44 @@ class TaxConfigurationUpdate(ModelMutation):
return super().clean_input(info, instance, data, **kwargs)
+ @classmethod
+ def clean_tax_app_id(cls, info: ResolveInfo, data):
+ identifiers = []
+ if app_identifier := data.get("tax_app_id"):
+ identifiers.append(app_identifier)
+
+ update_countries_configuration = data.get("update_countries_configuration", [])
+ for country in update_countries_configuration:
+ if app_identifier := country.get("tax_app_id"):
+ identifiers.append(app_identifier)
+
+ active_tax_apps = list(get_active_tax_apps(identifiers))
+
+ if app_identifier := data.get("tax_app_id"):
+ cls.__verify_tax_app_id(info, app_identifier, active_tax_apps)
+
+ update_countries_configuration = data.get("update_countries_configuration", [])
+ for country in update_countries_configuration:
+ if app_identifier := country.get("tax_app_id"):
+ cls.__verify_tax_app_id(
+ info, app_identifier, active_tax_apps, [country["country_code"]]
+ )
+
+ @classmethod
+ def __verify_tax_app_id(
+ cls,
+ info: ResolveInfo,
+ app_identifier,
+ active_tax_apps,
+ country_codes=[],
+ ):
+ identifiers = [app.identifier for app in active_tax_apps]
+ if app_identifier not in identifiers:
+ message = "Did not found Tax App with provided taxAppId."
+ code = error_codes.TaxConfigurationUpdateErrorCode.NOT_FOUND.value
+ params = {"country_codes": country_codes}
+ raise ValidationError(message=message, code=code, params=params)
+
@classmethod
def update_countries_configuration(cls, instance, countries_configuration):
input_data_by_country = {
@@ -149,6 +206,7 @@ class TaxConfigurationUpdate(ModelMutation):
obj.charge_taxes = data["charge_taxes"]
obj.display_gross_prices = data["display_gross_prices"]
obj.tax_calculation_strategy = data.get("tax_calculation_strategy")
+ obj.tax_app_id = data.get("tax_app_id")
updated_countries.append(obj.country.code)
models.TaxConfigurationPerCountry.objects.bulk_update(
to_update,
@@ -156,6 +214,7 @@ class TaxConfigurationUpdate(ModelMutation):
"charge_taxes",
"display_gross_prices",
"tax_calculation_strategy",
+ "tax_app_id",
),
)
@@ -167,6 +226,7 @@ class TaxConfigurationUpdate(ModelMutation):
charge_taxes=item["charge_taxes"],
tax_calculation_strategy=item.get("tax_calculation_strategy"),
display_gross_prices=item["display_gross_prices"],
+ tax_app_id=item.get("tax_app_id"),
)
for item in countries_configuration
if item["country_code"] not in updated_countries
diff --git a/saleor/graphql/tax/tests/fragments.py b/saleor/graphql/tax/tests/fragments.py
index 9dbc50e4ba..27858a3905 100644
--- a/saleor/graphql/tax/tests/fragments.py
+++ b/saleor/graphql/tax/tests/fragments.py
@@ -17,7 +17,9 @@ TAX_CONFIGURATION_FRAGMENT = """
chargeTaxes
taxCalculationStrategy
displayGrossPrices
+ taxAppId
}
+ taxAppId
metadata {
key
value
diff --git a/saleor/graphql/tax/tests/mutations/test_tax_configuration_update.py b/saleor/graphql/tax/tests/mutations/test_tax_configuration_update.py
index f5544382b4..17d15555ca 100644
--- a/saleor/graphql/tax/tests/mutations/test_tax_configuration_update.py
+++ b/saleor/graphql/tax/tests/mutations/test_tax_configuration_update.py
@@ -1,6 +1,7 @@
import graphene
import pytest
+from .....core.tests.test_taxes import app_factory, tax_app_factory # noqa: F401
from .....tax.error_codes import TaxConfigurationUpdateErrorCode
from .....tax.models import TaxConfiguration
from ....tests.utils import assert_no_permission, get_graphql_content
@@ -206,6 +207,9 @@ def test_create_and_update_country_configurations(
new_item.pop("country")
response_data.append(new_item)
+ update_PL_data["taxAppId"] = None
+ create_DE_data["taxAppId"] = None
+
assert update_PL_data in response_data
assert create_DE_data in response_data
@@ -256,7 +260,9 @@ def test_create_and_update_country_configurations_no_tax_calculation_strategy(
response_data.append(new_item)
update_PL_data["taxCalculationStrategy"] = None
+ update_PL_data["taxAppId"] = None
create_PT_data["taxCalculationStrategy"] = None
+ create_PT_data["taxAppId"] = None
assert update_PL_data in response_data
assert create_PT_data in response_data
@@ -282,3 +288,102 @@ def test_remove_country_configurations(
content = get_graphql_content(response)
data = content["data"]["taxConfigurationUpdate"]["taxConfiguration"]
assert data["countries"] == []
+
+
+def test_tax_configuration_update_tax_app_id(
+ example_tax_configuration,
+ staff_api_client,
+ permission_manage_taxes,
+ tax_app_factory, # noqa: F811
+):
+ # given
+ tax_app = tax_app_factory(name="app", is_active=True)
+ country_tax_app = tax_app_factory(name="app2", is_active=True)
+
+ id = graphene.Node.to_global_id("TaxConfiguration", example_tax_configuration.pk)
+ variables = {
+ "id": id,
+ "input": {
+ "taxAppId": tax_app.identifier,
+ "updateCountriesConfiguration": [
+ {
+ "countryCode": "PL",
+ "taxAppId": country_tax_app.identifier,
+ "chargeTaxes": False,
+ "displayGrossPrices": False,
+ }
+ ],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION, variables, permissions=[permission_manage_taxes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["taxConfigurationUpdate"]["taxConfiguration"]
+ assert not content["data"]["taxConfigurationUpdate"]["errors"]
+ assert data["taxAppId"] == tax_app.identifier
+ assert data["countries"][0]["taxAppId"] == country_tax_app.identifier
+
+
+def test_tax_configuration_update_tax_app_id_with_no_tax_app(
+ example_tax_configuration,
+ staff_api_client,
+ permission_manage_taxes,
+ app_factory, # noqa: F811
+):
+ # given
+ app = app_factory(
+ name="app",
+ is_active=True,
+ permissions=[],
+ webhook_event_types=[],
+ )
+
+ id = graphene.Node.to_global_id("TaxConfiguration", example_tax_configuration.pk)
+ variables = {
+ "id": id,
+ "input": {
+ "taxAppId": app.identifier,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION, variables, permissions=[permission_manage_taxes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["taxConfigurationUpdate"]["errors"]
+ assert errors
+ assert errors[0]["message"] == "Did not found Tax App with provided taxAppId."
+ assert errors[0]["code"] == TaxConfigurationUpdateErrorCode.NOT_FOUND.name
+
+
+def test_tax_configuration_update_tax_app_id_with_non_existent_app(
+ example_tax_configuration, staff_api_client, permission_manage_taxes
+):
+ # given
+ id = graphene.Node.to_global_id("TaxConfiguration", example_tax_configuration.pk)
+ variables = {
+ "id": id,
+ "input": {
+ "taxAppId": "invalid",
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION, variables, permissions=[permission_manage_taxes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["taxConfigurationUpdate"]["errors"]
+ assert errors
+ assert errors[0]["message"] == "Did not found Tax App with provided taxAppId."
+ assert errors[0]["code"] == TaxConfigurationUpdateErrorCode.NOT_FOUND.name
diff --git a/saleor/graphql/tax/tests/queries/test_tax_configuration.py b/saleor/graphql/tax/tests/queries/test_tax_configuration.py
index 73297b2699..f27f3baac5 100644
--- a/saleor/graphql/tax/tests/queries/test_tax_configuration.py
+++ b/saleor/graphql/tax/tests/queries/test_tax_configuration.py
@@ -26,6 +26,7 @@ def _test_field_resolvers(tax_configuration: TaxConfiguration, data: dict):
assert data["chargeTaxes"] == tax_configuration.charge_taxes
assert data["displayGrossPrices"] == tax_configuration.display_gross_prices
assert data["pricesEnteredWithTax"] == tax_configuration.prices_entered_with_tax
+ assert data["taxAppId"] == tax_configuration.tax_app_id
assert len(data["countries"]) == len(country_exceptions)
assert data["countries"][0]["country"]["code"] == country_exception.country.code
assert data["countries"][0]["chargeTaxes"] == country_exception.charge_taxes
@@ -33,6 +34,7 @@ def _test_field_resolvers(tax_configuration: TaxConfiguration, data: dict):
data["countries"][0]["displayGrossPrices"]
== country_exception.display_gross_prices
)
+ assert data["countries"][0]["taxAppId"] == country_exception.tax_app_id
def test_tax_configuration_query_no_permissions(channel_USD, user_api_client):
diff --git a/saleor/graphql/tax/types.py b/saleor/graphql/tax/types.py
index d401e64f55..057b91405b 100644
--- a/saleor/graphql/tax/types.py
+++ b/saleor/graphql/tax/types.py
@@ -5,7 +5,7 @@ from ..channel.dataloaders import ChannelByIdLoader
from ..channel.types import Channel
from ..core import ResolveInfo
from ..core.connection import CountableConnection
-from ..core.descriptions import ADDED_IN_39
+from ..core.descriptions import ADDED_IN_39, ADDED_IN_319
from ..core.doc_category import DOC_CATEGORY_TAXES
from ..core.types import BaseObjectType, CountryDisplay, ModelObjectType, NonNullList
from ..meta.types import ObjectWithMetadata
@@ -50,6 +50,17 @@ class TaxConfiguration(ModelObjectType[models.TaxConfiguration]):
required=True,
description="List of country-specific exceptions in tax configuration.",
)
+ tax_app_id = graphene.String(
+ description=(
+ "The tax app id that will be used to calculate the taxes for the given channel. "
+ "Empty value for `TAX_APP` set as `taxCalculationStrategy` means that Saleor will "
+ "iterate over all installed tax apps. If multiple tax apps exist with provided "
+ "tax app id use the `App` with newest `created` date. "
+ "Will become mandatory in 4.0 for `TAX_APP` `taxCalculationStrategy`."
+ + ADDED_IN_319
+ ),
+ required=False,
+ )
class Meta:
description = "Channel-specific tax configuration." + ADDED_IN_39
@@ -98,6 +109,14 @@ class TaxConfigurationPerCountry(ModelObjectType[models.TaxConfigurationPerCount
),
required=True,
)
+ tax_app_id = graphene.String(
+ description=(
+ "The tax app id that will be used to calculate the taxes for the given channel "
+ "and country. If not provided, use the value from the channel's tax configuration."
+ + ADDED_IN_319
+ ),
+ required=False,
+ )
class Meta:
description = (
diff --git a/saleor/order/calculations.py b/saleor/order/calculations.py
index c73925e912..ddad8c442a 100644
--- a/saleor/order/calculations.py
+++ b/saleor/order/calculations.py
@@ -2,12 +2,13 @@ from collections.abc import Iterable
from decimal import Decimal
from typing import Optional
+from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import prefetch_related_objects
from prices import Money, TaxedMoney
from ..core.prices import quantize_price
-from ..core.taxes import TaxData, TaxError, zero_taxed_money
+from ..core.taxes import EmptyTaxData, TaxData, TaxError, zero_taxed_money
from ..discount import DiscountType
from ..payment.model_helpers import get_subtotal
from ..plugins.manager import PluginsManager
@@ -16,6 +17,7 @@ from ..tax.calculations import get_taxed_undiscounted_price
from ..tax.calculations.order import update_order_prices_with_flat_rates
from ..tax.utils import (
get_charge_taxes_for_order,
+ get_tax_app_identifier_for_order,
get_tax_calculation_strategy_for_order,
normalize_tax_rate_for_db,
)
@@ -26,6 +28,7 @@ from .base_calculations import (
undiscounted_order_total,
update_order_discount_amounts,
)
+from .error_codes import OrderErrorCode
from .interface import OrderTaxedPricesData
from .models import Order, OrderLine
@@ -35,6 +38,7 @@ def fetch_order_prices_if_expired(
manager: PluginsManager,
lines: Optional[Iterable[OrderLine]] = None,
force_update: bool = False,
+ need_tax_calculation: bool = False,
) -> tuple[Order, Optional[Iterable[OrderLine]]]:
"""Fetch order prices with taxes.
@@ -57,7 +61,7 @@ def fetch_order_prices_if_expired(
order.should_refresh_prices = False
_update_order_discount_for_voucher(order)
- _recalculate_prices(order, manager, lines)
+ _recalculate_prices(order, manager, lines, need_tax_calculation)
order.subtotal = get_subtotal(lines, order.currency)
with transaction.atomic(savepoint=False):
@@ -130,6 +134,7 @@ def _recalculate_prices(
order: Order,
manager: PluginsManager,
lines: Iterable[OrderLine],
+ need_tax_calculation: bool = False,
):
"""Calculate prices after handling order level discounts and taxes."""
tax_configuration = order.channel.tax_configuration
@@ -137,12 +142,24 @@ def _recalculate_prices(
prices_entered_with_tax = tax_configuration.prices_entered_with_tax
charge_taxes = get_charge_taxes_for_order(order)
should_charge_tax = charge_taxes and not order.tax_exemption
+ tax_app_identifier = get_tax_app_identifier_for_order(order)
+
+ order.tax_error = None
if prices_entered_with_tax:
# If prices are entered with tax, we need to always calculate it anyway, to
# display the tax rate to the user.
- _calculate_and_add_tax(
- tax_calculation_strategy, order, lines, manager, prices_entered_with_tax
- )
+ try:
+ _calculate_and_add_tax(
+ tax_calculation_strategy,
+ tax_app_identifier,
+ order,
+ lines,
+ manager,
+ prices_entered_with_tax,
+ )
+ except EmptyTaxData as e:
+ order.tax_error = str(e)
+
if not should_charge_tax:
# If charge_taxes is disabled or order is exempt from taxes, remove the
# tax from the original gross prices.
@@ -153,16 +170,33 @@ def _recalculate_prices(
if should_charge_tax:
# Calculate taxes if charge_taxes is enabled and order is not exempt
# from taxes.
- _calculate_and_add_tax(
- tax_calculation_strategy, order, lines, manager, prices_entered_with_tax
- )
+ try:
+ _calculate_and_add_tax(
+ tax_calculation_strategy,
+ tax_app_identifier,
+ order,
+ lines,
+ manager,
+ prices_entered_with_tax,
+ )
+ except EmptyTaxData as e:
+ order.tax_error = str(e)
else:
apply_order_discounts(order, lines, assign_prices=True)
_remove_tax(order, lines)
+ order.save(update_fields=["tax_error"])
+ # raise an error if recorded tax_error and taxes are needed for process completion
+ if order.tax_error and need_tax_calculation:
+ raise ValidationError(
+ "Configured Tax App didn't responded.",
+ code=OrderErrorCode.TAX_ERROR.value,
+ )
+
def _calculate_and_add_tax(
tax_calculation_strategy: str,
+ tax_app_identifier: Optional[str],
order: "Order",
lines: Iterable["OrderLine"],
manager: "PluginsManager",
@@ -172,7 +206,11 @@ def _calculate_and_add_tax(
# Get the taxes calculated with plugins.
_recalculate_with_plugins(manager, order, lines, prices_entered_with_tax)
# Get the taxes calculated with apps and apply to order.
- tax_data = manager.get_taxes_for_order(order)
+ tax_data = manager.get_taxes_for_order(order, tax_app_identifier)
+ # If taxAppId is not configured we will for now allow to finalize process for
+ # backward compatibility.
+ if tax_data is None and tax_app_identifier is not None:
+ raise EmptyTaxData("Empty tax data.")
_apply_tax_data(order, lines, tax_data)
# TODO: If tax data is empty, order level discounts are not propagated
# to its lines and not reflected in line total prices.
diff --git a/saleor/order/migrations/0183_order_tax_error.py b/saleor/order/migrations/0183_order_tax_error.py
new file mode 100644
index 0000000000..1609caeb38
--- /dev/null
+++ b/saleor/order/migrations/0183_order_tax_error.py
@@ -0,0 +1,17 @@
+# Generated by Django 3.2.23 on 2024-02-13 14:39
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("order", "0182_orderline_is_gift"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="order",
+ name="tax_error",
+ field=models.CharField(blank=True, max_length=255, null=True),
+ ),
+ ]
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 21831264b3..79ce62b9a0 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -338,6 +338,7 @@ class Order(ModelWithMetadata, ModelWithExternalReference):
# this field is used only for draft/unconfirmed orders
should_refresh_prices = models.BooleanField(default=True)
tax_exemption = models.BooleanField(default=False)
+ tax_error = models.CharField(max_length=255, null=True, blank=True)
objects = OrderManager()
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 80a7123532..9fa29eb73c 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -601,11 +601,11 @@ class BasePlugin:
]
get_taxes_for_checkout: Callable[
- ["CheckoutInfo", Iterable["CheckoutLineInfo"], Any],
+ ["CheckoutInfo", Iterable["CheckoutLineInfo"], str, Any],
Optional["TaxData"],
]
- get_taxes_for_order: Callable[["Order", Any], Optional["TaxData"]]
+ get_taxes_for_order: Callable[["Order", str, Any], Optional["TaxData"]]
get_client_token: Callable[[Any, Any], Any]
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index c30ca19099..0320317636 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -560,17 +560,23 @@ class PluginsManager(PaymentInterface):
default_value = False
return self.__run_method_on_plugins("show_taxes_on_storefront", default_value)
- def get_taxes_for_checkout(self, checkout_info, lines) -> Optional[TaxData]:
+ def get_taxes_for_checkout(
+ self, checkout_info, lines, app_identifier
+ ) -> Optional[TaxData]:
return self.__run_plugin_method_until_first_success(
"get_taxes_for_checkout",
checkout_info,
lines,
+ app_identifier,
channel_slug=checkout_info.channel.slug,
)
- def get_taxes_for_order(self, order: "Order") -> Optional[TaxData]:
+ def get_taxes_for_order(self, order: "Order", app_identifier) -> Optional[TaxData]:
return self.__run_plugin_method_until_first_success(
- "get_taxes_for_order", order, channel_slug=order.channel.slug
+ "get_taxes_for_order",
+ order,
+ app_identifier,
+ channel_slug=order.channel.slug,
)
def preprocess_order_creation(
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index 52cc8440c6..ba777550be 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -296,12 +296,12 @@ class PluginSample(BasePlugin):
return Decimal("0.080").quantize(Decimal(".01"))
def get_taxes_for_checkout(
- self, checkout_info: "CheckoutInfo", lines, previous_value
+ self, checkout_info: "CheckoutInfo", lines, app_identifier, previous_value
) -> Optional["TaxData"]:
return sample_tax_data(checkout_info.checkout)
def get_taxes_for_order(
- self, order: "Order", previous_value
+ self, order: "Order", app_identifier, previous_value
) -> Optional["TaxData"]:
return sample_tax_data(order)
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 78da2ae804..4dd790de97 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -557,8 +557,9 @@ def test_manager_get_taxes_for_checkout(
lines, _ = fetch_checkout_lines(checkout)
manager = get_plugins_manager(allow_replica=False)
checkout_info = fetch_checkout_info(checkout, lines, manager)
+ app_identifier = None
assert PluginsManager(plugins=plugins).get_taxes_for_checkout(
- checkout_info, lines
+ checkout_info, lines, app_identifier
) == expected_tax_data(checkout)
@@ -574,8 +575,9 @@ def test_manager_get_taxes_for_order(
plugins,
expected_tax_data,
):
+ app_identifier = None
assert PluginsManager(plugins=plugins).get_taxes_for_order(
- order
+ order, app_identifier
) == expected_tax_data(order)
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 77292afd63..510fd6d557 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -7,6 +7,7 @@ from functools import partial
from typing import (
TYPE_CHECKING,
Any,
+ Callable,
Final,
Optional,
Union,
@@ -2995,30 +2996,91 @@ class WebhookPlugin(BasePlugin):
**kwargs,
)
- def get_taxes_for_checkout(
- self, checkout_info, lines, previous_value
- ) -> Optional["TaxData"]:
- return trigger_all_webhooks_sync(
- WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES,
- lambda: generate_checkout_payload_for_tax_calculation(
- checkout_info,
- lines,
- ),
- parse_tax_data,
- checkout_info.checkout,
+ def __run_tax_webhook(
+ self,
+ event_type: str,
+ app_identifier: str,
+ payload_gen: Callable,
+ subscriptable_object=None,
+ ):
+ app = (
+ App.objects.filter(
+ identifier=app_identifier,
+ is_active=True,
+ )
+ .order_by("-created_at")
+ .first()
+ )
+ if app is None:
+ logger.warning("Configured tax app doesn't exists.")
+ return None
+ webhook = get_webhooks_for_event(event_type, apps_ids=[app.id]).first()
+ if webhook is None:
+ logger.warning(
+ "Configured tax app's webhook for checkout taxes doesn't exists."
+ )
+ return None
+
+ request_context = initialize_request(
self.requestor,
+ event_type in WebhookEventSyncType.ALL,
+ allow_replica=False,
+ event_type=event_type,
)
+ response = trigger_webhook_sync(
+ event_type=event_type,
+ webhook=webhook,
+ payload=payload_gen(),
+ allow_replica=False,
+ subscribable_object=subscriptable_object,
+ request=request_context,
+ )
+ return parse_tax_data(response)
+
+ def get_taxes_for_checkout(
+ self, checkout_info, lines, app_identifier, previous_value
+ ) -> Optional["TaxData"]:
+ event_type = WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES
+ if app_identifier:
+ return self.__run_tax_webhook(
+ event_type,
+ app_identifier,
+ lambda: generate_checkout_payload_for_tax_calculation(
+ checkout_info, lines
+ ),
+ checkout_info.checkout,
+ )
+ else:
+ return trigger_all_webhooks_sync(
+ event_type,
+ lambda: generate_checkout_payload_for_tax_calculation(
+ checkout_info,
+ lines,
+ ),
+ parse_tax_data,
+ checkout_info.checkout,
+ self.requestor,
+ )
def get_taxes_for_order(
- self, order: "Order", previous_value
+ self, order: "Order", app_identifier, previous_value
) -> Optional["TaxData"]:
- return trigger_all_webhooks_sync(
- WebhookEventSyncType.ORDER_CALCULATE_TAXES,
- lambda: generate_order_payload_for_tax_calculation(order),
- parse_tax_data,
- order,
- self.requestor,
- )
+ event_type = WebhookEventSyncType.ORDER_CALCULATE_TAXES
+ if app_identifier:
+ return self.__run_tax_webhook(
+ event_type,
+ app_identifier,
+ lambda: generate_order_payload_for_tax_calculation(order),
+ order,
+ )
+ else:
+ return trigger_all_webhooks_sync(
+ WebhookEventSyncType.ORDER_CALCULATE_TAXES,
+ lambda: generate_order_payload_for_tax_calculation(order),
+ parse_tax_data,
+ order,
+ self.requestor,
+ )
def get_shipping_methods_for_checkout(
self, checkout: "Checkout", previous_value: Any
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.py
index 912f11f42f..182e8a2a93 100644
--- a/saleor/plugins/webhook/tests/test_payment_webhook.py
+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py
@@ -358,7 +358,7 @@ def test_get_payment_gateways_with_transactions_and_app_without_identifier(
):
# given
app_name = "Payment App 2"
- app_identifier = None
+ app_identifier = ""
app = App.objects.create(name=app_name, is_active=True, identifier=app_identifier)
app.permissions.add(permission_manage_payments)
webhook = Webhook.objects.create(
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook_utils.py b/saleor/plugins/webhook/tests/test_payment_webhook_utils.py
index 8b92917c3e..6f0d98335b 100644
--- a/saleor/plugins/webhook/tests/test_payment_webhook_utils.py
+++ b/saleor/plugins/webhook/tests/test_payment_webhook_utils.py
@@ -26,7 +26,7 @@ def test_to_payment_app_id_app_identifier_used(app):
def test_to_payment_app_id_app_id_used(app):
# given
- app.identifier = None
+ app.identifier = ""
app.save(update_fields=["identifier"])
gateway_id = "example-gateway"
@@ -92,7 +92,7 @@ def test_parse_list_payment_gateways_response_app_identifier(app):
def test_parse_list_payment_gateways_response_app_id(app):
# given
- app.identifier = None
+ app.identifier = ""
app.save(update_fields=["identifier"])
response_data = [
diff --git a/saleor/plugins/webhook/tests/test_tax_webhook.py b/saleor/plugins/webhook/tests/test_tax_webhook.py
index 2be9ca732f..ae14d26619 100644
--- a/saleor/plugins/webhook/tests/test_tax_webhook.py
+++ b/saleor/plugins/webhook/tests/test_tax_webhook.py
@@ -30,9 +30,10 @@ def test_get_taxes_for_checkout_no_permission(
plugin = webhook_plugin()
lines, _ = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(checkout, lines, plugin)
+ app_identifier = None
# when
- tax_data = plugin.get_taxes_for_checkout(checkout_info, lines, None)
+ tax_data = plugin.get_taxes_for_checkout(checkout_info, lines, app_identifier, None)
# then
assert mock_request.call_count == 0
@@ -55,9 +56,10 @@ def test_get_taxes_for_order(
# given
mock_request.return_value = tax_data_response
plugin = webhook_plugin()
+ app_identifier = None
# when
- tax_data = plugin.get_taxes_for_order(order, None)
+ tax_data = plugin.get_taxes_for_order(order, app_identifier, None)
# then
payload = EventPayload.objects.get()
@@ -80,9 +82,10 @@ def test_get_taxes_for_order_no_permission(
):
# given
plugin = webhook_plugin()
+ app_identifier = None
# when
- tax_data = plugin.get_taxes_for_order(order, None)
+ tax_data = plugin.get_taxes_for_order(order, app_identifier, None)
# then
assert mock_request.call_count == 0
@@ -173,9 +176,10 @@ def test_get_taxes_for_order_with_sync_subscription(
),
)
webhook.events.create(event_type=WebhookEventSyncType.ORDER_CALCULATE_TAXES)
+ app_identifier = None
# when
- tax_data = plugin.get_taxes_for_order(order, None)
+ tax_data = plugin.get_taxes_for_order(order, app_identifier, None)
# then
payload = EventPayload.objects.get()
@@ -216,9 +220,10 @@ def test_get_taxes_for_checkout_with_sync_subscription(
),
)
webhook.events.create(event_type=WebhookEventSyncType.CHECKOUT_CALCULATE_TAXES)
+ app_identifier = None
# when
- tax_data = plugin.get_taxes_for_checkout(checkout_info, [], None)
+ tax_data = plugin.get_taxes_for_checkout(checkout_info, [], app_identifier, None)
# then
payload = EventPayload.objects.get()
diff --git a/saleor/tax/migrations/0008_auto_20240122_1353.py b/saleor/tax/migrations/0008_auto_20240122_1353.py
new file mode 100644
index 0000000000..579fa47976
--- /dev/null
+++ b/saleor/tax/migrations/0008_auto_20240122_1353.py
@@ -0,0 +1,22 @@
+# Generated by Django 3.2.23 on 2024-01-22 13:53
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("tax", "0007_auto_20230217_0837"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="taxconfiguration",
+ name="tax_app_id",
+ field=models.CharField(blank=True, max_length=256, null=True),
+ ),
+ migrations.AddField(
+ model_name="taxconfigurationpercountry",
+ name="tax_app_id",
+ field=models.CharField(blank=True, max_length=256, null=True),
+ ),
+ ]
diff --git a/saleor/tax/models.py b/saleor/tax/models.py
index d695dc8339..dc90e37953 100644
--- a/saleor/tax/models.py
+++ b/saleor/tax/models.py
@@ -62,6 +62,7 @@ class TaxConfiguration(ModelWithMetadata):
)
display_gross_prices = models.BooleanField(default=True)
prices_entered_with_tax = models.BooleanField(default=True)
+ tax_app_id = models.CharField(blank=True, null=True, max_length=256)
class Meta:
ordering = ("pk",)
@@ -77,6 +78,7 @@ class TaxConfigurationPerCountry(models.Model):
max_length=20, choices=TaxCalculationStrategy.CHOICES, blank=True, null=True
)
display_gross_prices = models.BooleanField(default=True)
+ tax_app_id = models.CharField(blank=True, null=True, max_length=256)
class Meta:
ordering = ("country", "pk")
diff --git a/saleor/tax/tests/test_utils.py b/saleor/tax/tests/test_utils.py
index 1806a2cfcd..3c9330d934 100644
--- a/saleor/tax/tests/test_utils.py
+++ b/saleor/tax/tests/test_utils.py
@@ -1,5 +1,7 @@
+import pytest
+
from ...core.utils.country import get_active_country
-from ..utils import get_charge_taxes, get_display_gross_prices
+from ..utils import get_charge_taxes, get_display_gross_prices, get_tax_app_id
def test_get_display_gross_prices(channel_USD):
@@ -39,6 +41,33 @@ def test_get_charge_taxes(channel_USD):
)
+def test_get_tax_app_id(channel_USD):
+ # given
+ tax_configuration = channel_USD.tax_configuration
+ tax_configuration.tax_app_id = "tax-app-1"
+ tax_configuration.save(update_fields=["tax_app_id"])
+
+ # then
+ assert get_tax_app_id(tax_configuration, None) == tax_configuration.tax_app_id
+
+
+ ("country_tax_app", "expected_tax_app"),
+ [(None, "tax-app-1"), ("tax-app-2", "tax-app-2")],
+)
+def test_get_tax_app_id_country(country_tax_app, expected_tax_app, channel_USD):
+ # given
+ tax_configuration = channel_USD.tax_configuration
+ tax_configuration.tax_app_id = "tax-app-1"
+ tax_configuration.save(update_fields=["tax_app_id"])
+ country_exception = tax_configuration.country_exceptions.first()
+ country_exception.tax_app_id = country_tax_app
+ country_exception.save(update_fields=["tax_app_id"])
+
+ # then
+ assert get_tax_app_id(tax_configuration, country_exception) == expected_tax_app
+
+
def test_get_tax_country_use_shipping_address(
channel_USD, address_usa, address_other_country
):
diff --git a/saleor/tax/utils.py b/saleor/tax/utils.py
index 905998d565..66283df9a2 100644
--- a/saleor/tax/utils.py
+++ b/saleor/tax/utils.py
@@ -65,8 +65,26 @@ def get_tax_calculation_strategy(
) or TaxCalculationStrategy.FLAT_RATES
-def get_charge_taxes_for_order(order: "Order") -> bool:
- """Get charge_taxes value for order."""
+def get_tax_app_id(
+ channel_tax_configuration: "TaxConfiguration",
+ country_tax_configuration: Optional["TaxConfigurationPerCountry"],
+) -> Optional[str]:
+ """Get tax_app_id value for tax channel configuration.
+
+ :param channel_tax_configuration: Channel-specific tax configuration.
+ :param country_tax_configuration: Country-specific tax configuration for the given
+ channel.
+ """
+ return (
+ country_tax_configuration.tax_app_id
+ if country_tax_configuration and country_tax_configuration.tax_app_id
+ else channel_tax_configuration.tax_app_id
+ )
+
+
+def _get_tax_configuration_for_order(
+ order: "Order",
+) -> tuple["TaxConfiguration", Optional["TaxConfigurationPerCountry"]]:
channel = order.channel
tax_configuration = channel.tax_configuration
country_code = get_active_country(
@@ -82,29 +100,33 @@ def get_charge_taxes_for_order(order: "Order") -> bool:
),
None,
)
+ return tax_configuration, country_tax_configuration
+
+
+def get_charge_taxes_for_order(order: "Order") -> bool:
+ """Get charge_taxes value for order."""
+ tax_configuration, country_tax_configuration = _get_tax_configuration_for_order(
+ order
+ )
return get_charge_taxes(tax_configuration, country_tax_configuration)
def get_tax_calculation_strategy_for_order(order: "Order"):
"""Get tax_calculation_strategy value for order."""
- channel = order.channel
- tax_configuration = channel.tax_configuration
- country_code = get_active_country(
- channel,
- order.shipping_address,
- order.billing_address,
- )
- country_tax_configuration = next(
- (
- tc
- for tc in tax_configuration.country_exceptions.all()
- if tc.country.code == country_code
- ),
- None,
+ tax_configuration, country_tax_configuration = _get_tax_configuration_for_order(
+ order
)
return get_tax_calculation_strategy(tax_configuration, country_tax_configuration)
+def get_tax_app_identifier_for_order(order: "Order"):
+ """Get tax_app_id value for order."""
+ tax_configuration, country_tax_configuration = _get_tax_configuration_for_order(
+ order
+ )
+ return get_tax_app_id(tax_configuration, country_tax_configuration)
+
+
def _get_tax_configuration_for_checkout(
checkout_info: "CheckoutInfo", lines: Iterable["CheckoutLineInfo"]
) -> tuple["TaxConfiguration", Optional["TaxConfigurationPerCountry"]]:
@@ -145,6 +167,16 @@ def get_tax_calculation_strategy_for_checkout(
return get_tax_calculation_strategy(tax_configuration, country_tax_configuration)
+def get_tax_app_identifier_for_checkout(
+ checkout_info: "CheckoutInfo", lines: Iterable["CheckoutLineInfo"]
+):
+ """Get tax_app_id value for checkout."""
+ tax_configuration, country_tax_configuration = _get_tax_configuration_for_checkout(
+ checkout_info, lines
+ )
+ return get_tax_app_id(tax_configuration, country_tax_configuration)
+
+
def normalize_tax_rate_for_db(tax_rate: Decimal) -> Decimal:
# Percentage values are used to represent tax rates in tax apps and flat rates, but
# in the database rates are stored as fractional values. Example: tax app returns
diff --git a/saleor/webhook/transport/list_stored_payment_methods.py b/saleor/webhook/transport/list_stored_payment_methods.py
index 9799077372..05d7bd83f4 100644
--- a/saleor/webhook/transport/list_stored_payment_methods.py
+++ b/saleor/webhook/transport/list_stored_payment_methods.py
@@ -1,5 +1,5 @@
import logging
-from typing import Optional, cast
+from typing import Optional
import graphene
from django.core.cache import cache
@@ -116,7 +116,7 @@ def get_payment_method_from_response(
app.id,
)
return None
- app_identifier = cast(str, app.identifier)
+ app_identifier = app.identifier
credit_card_info = payment_method.get("creditCardInfo")
name = payment_method.get("name")
return PaymentMethodData(