Skip to content

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

Feature/plugins per channel (#7198)

Maciej Korycinskic807abd30049
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ac76ec2250..b5698216a4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -118,6 +118,25 @@ All notable, unreleased changes to this project will be documented in this file.
- Make `order` property of invoice webhook payload contain order instead of order lines - #7081 by @pdblaszczyk
- Affected webhook events: `INVOICE_REQUESTED`, `INVOICE_SENT`, `INVOICE_DELETED`
- Make quantity field on `StockInput` required - #7082 by @IKarbowiak
+- Extend plugins manager to configure plugins for each plugins - #7198 by @korycins:
+ - Introduce changes in API:
+ - `paymentInitialize` - add `channel` parameter. Optional when only one channel exists.
+ - `pluginUpdate` - add `channel` parameter.
+ - `availablePaymentGateways` - add `channel` parameter.
+ - `storedPaymentSources` - add `channel` parameter.
+ - `requestPasswordReset` - add `channel` parameter.
+ - `requestEmailChange` - add `channel` parameter.
+ - `confirmEmailChange` - add `channel` parameter.
+ - `accountRequestDeletion` - add `channel` parameter.
+ - change structure of type `Plugin`:
+ - add `globalConfiguration` field for storing configuration when a plugin is globally configured
+ - add `channelConfigurations` field for storing plugin configuration for each channel
+ - removed `configuration` field, use `globalConfiguration` and `channelConfigurations` instead
+ - change structure of input `PluginFilterInput`:
+ - add `statusInChannels` field
+ - add `type` field
+ - removed `active` field. Use `statusInChannels` instead
+
- Add description to shipping method - #7116 by @IKarbowiak
- `ShippingMethod` was extended with `description` field.
- `ShippingPriceInput` was extended with `description` field
diff --git a/saleor/account/error_codes.py b/saleor/account/error_codes.py
index 7e833f1e18..c89ecd752b 100644
--- a/saleor/account/error_codes.py
+++ b/saleor/account/error_codes.py
@@ -32,6 +32,8 @@ class AccountErrorCode(Enum):
JWT_DECODE_ERROR = "decode_error"
JWT_MISSING_TOKEN = "missing_token"
JWT_INVALID_CSRF_TOKEN = "invalid_csrf_token"
+ CHANNEL_INACTIVE = "channel_inactive"
+ MISSING_CHANNEL_SLUG = "missing_channel_slug"
class PermissionGroupErrorCode(Enum):
diff --git a/saleor/account/migrations/0045_auto_20200427_0425.py b/saleor/account/migrations/0045_auto_20200427_0425.py
index df5bf23fc5..17129c887d 100644
--- a/saleor/account/migrations/0045_auto_20200427_0425.py
+++ b/saleor/account/migrations/0045_auto_20200427_0425.py
@@ -1,13 +1,15 @@
# Generated by Django 3.0.5 on 2020-04-27 09:25
from copy import deepcopy
+from django.conf import settings
from django.db import migrations
-
-from saleor.plugins.manager import get_plugins_manager
+from django.utils.module_loading import import_string
def create_payments_customer_ids():
- plugins = get_plugins_manager().plugins
+ plugins = []
+ for plugin_path in settings.PLUGINS:
+ plugins.append(import_string(plugin_path))
return {
f"{plugin.PLUGIN_NAME.strip().upper()}.customer_id": (
diff --git a/saleor/account/notifications.py b/saleor/account/notifications.py
index 26d7221251..739860c31a 100644
--- a/saleor/account/notifications.py
+++ b/saleor/account/notifications.py
@@ -1,3 +1,4 @@
+from typing import Optional
from urllib.parse import urlencode
from django.contrib.auth.tokens import default_token_generator
@@ -22,7 +23,9 @@ def get_default_user_payload(user: User):
}
-def send_password_reset_notification(redirect_url, user, manager, staff=False):
+def send_password_reset_notification(
+ redirect_url, user, manager, channel_slug: Optional[str], staff=False
+):
"""Trigger sending a password reset notification for the given customer/staff."""
token = default_token_generator.make_token(user)
params = urlencode({"email": user.email, "token": token})
@@ -33,6 +36,7 @@ def send_password_reset_notification(redirect_url, user, manager, staff=False):
"recipient_email": user.email,
"token": token,
"reset_url": reset_url,
+ "channel_slug": channel_slug,
**get_site_context(),
}
@@ -41,10 +45,10 @@ def send_password_reset_notification(redirect_url, user, manager, staff=False):
if staff
else NotifyEventType.ACCOUNT_PASSWORD_RESET
)
- manager.notify(event, payload=payload)
+ manager.notify(event, payload=payload, channel_slug=channel_slug)
-def send_account_confirmation(user, redirect_url, manager):
+def send_account_confirmation(user, redirect_url, manager, channel_slug):
"""Trigger sending an account confirmation notification for the given user."""
token = default_token_generator.make_token(user)
params = urlencode({"email": user.email, "token": token})
@@ -54,13 +58,16 @@ def send_account_confirmation(user, redirect_url, manager):
"recipient_email": user.email,
"token": token,
"confirm_url": confirm_url,
+ "channel_slug": channel_slug,
**get_site_context(),
}
- manager.notify(NotifyEventType.ACCOUNT_CONFIRMATION, payload=payload)
+ manager.notify(
+ NotifyEventType.ACCOUNT_CONFIRMATION, payload=payload, channel_slug=channel_slug
+ )
def send_request_user_change_email_notification(
- redirect_url, user, new_email, token, manager
+ redirect_url, user, new_email, token, manager, channel_slug
):
"""Trigger sending a notification change email for the given user."""
params = urlencode({"token": token})
@@ -72,22 +79,34 @@ def send_request_user_change_email_notification(
"new_email": new_email,
"token": token,
"redirect_url": redirect_url,
+ "channel_slug": channel_slug,
**get_site_context(),
}
- manager.notify(NotifyEventType.ACCOUNT_CHANGE_EMAIL_REQUEST, payload=payload)
+ manager.notify(
+ NotifyEventType.ACCOUNT_CHANGE_EMAIL_REQUEST,
+ payload=payload,
+ channel_slug=channel_slug,
+ )
-def send_user_change_email_notification(recipient_email, user, manager):
+def send_user_change_email_notification(recipient_email, user, manager, channel_slug):
"""Trigger sending a email change notification for the given user."""
payload = {
"user": get_default_user_payload(user),
"recipient_email": recipient_email,
+ "channel_slug": channel_slug,
**get_site_context(),
}
- manager.notify(NotifyEventType.ACCOUNT_CHANGE_EMAIL_CONFIRM, payload=payload)
+ manager.notify(
+ NotifyEventType.ACCOUNT_CHANGE_EMAIL_CONFIRM,
+ payload=payload,
+ channel_slug=channel_slug,
+ )
-def send_account_delete_confirmation_notification(redirect_url, user, manager):
+def send_account_delete_confirmation_notification(
+ redirect_url, user, manager, channel_slug
+):
"""Trigger sending a account delete notification for the given user."""
token = default_token_generator.make_token(user)
params = urlencode({"token": token})
@@ -97,12 +116,17 @@ def send_account_delete_confirmation_notification(redirect_url, user, manager):
"recipient_email": user.email,
"token": token,
"delete_url": delete_url,
+ "channel_slug": channel_slug,
**get_site_context(),
}
- manager.notify(NotifyEventType.ACCOUNT_DELETE, payload=payload)
+ manager.notify(
+ NotifyEventType.ACCOUNT_DELETE, payload=payload, channel_slug=channel_slug
+ )
-def send_set_password_notification(redirect_url, user, manager, staff=False):
+def send_set_password_notification(
+ redirect_url, user, manager, channel_slug, staff=False
+):
"""Trigger sending a set password notification for the given customer/staff."""
token = default_token_generator.make_token(user)
params = urlencode({"email": user.email, "token": token})
@@ -112,10 +136,11 @@ def send_set_password_notification(redirect_url, user, manager, staff=False):
"token": default_token_generator.make_token(user),
"recipient_email": user.email,
"password_set_url": password_set_url,
+ "channel_slug": channel_slug,
**get_site_context(),
}
if staff:
event = NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD
else:
event = NotifyEventType.ACCOUNT_SET_CUSTOMER_PASSWORD
- manager.notify(event, payload=payload)
+ manager.notify(event, payload=payload, channel_slug=channel_slug)
diff --git a/saleor/account/tests/test_notifications.py b/saleor/account/tests/test_notifications.py
index 43eb80afce..2119abd751 100644
--- a/saleor/account/tests/test_notifications.py
+++ b/saleor/account/tests/test_notifications.py
@@ -27,14 +27,21 @@ def test_get_default_user_payload(customer_user):
@freeze_time("2018-05-31 12:00:01")
@mock.patch("saleor.plugins.manager.PluginsManager.notify")
-def test_send_email_request_change(mocked_notify, site_settings, customer_user):
+def test_send_email_request_change(
+ mocked_notify, site_settings, customer_user, channel_PLN
+):
new_email = "[email protected]"
redirect_url = "http://localhost:8000/redirect"
token = "token_example"
manager = get_plugins_manager()
notifications.send_request_user_change_email_notification(
- redirect_url, customer_user, new_email, token, manager
+ redirect_url,
+ customer_user,
+ new_email,
+ token,
+ manager,
+ channel_slug=channel_PLN.slug,
)
expected_payload = {
@@ -46,19 +53,24 @@ def test_send_email_request_change(mocked_notify, site_settings, customer_user):
"new_email": new_email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": channel_PLN.slug,
}
mocked_notify.assert_called_once_with(
- UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_REQUEST, payload=expected_payload
+ UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_REQUEST,
+ payload=expected_payload,
+ channel_slug=channel_PLN.slug,
)
@mock.patch("saleor.plugins.manager.PluginsManager.notify")
-def test_send_email_changed_notification(mocked_notify, site_settings, customer_user):
+def test_send_email_changed_notification(
+ mocked_notify, site_settings, customer_user, channel_PLN
+):
old_email = "[email protected]"
notifications.send_user_change_email_notification(
- old_email, customer_user, get_plugins_manager()
+ old_email, customer_user, get_plugins_manager(), channel_slug=channel_PLN.slug
)
expected_payload = {
@@ -66,10 +78,13 @@ def test_send_email_changed_notification(mocked_notify, site_settings, customer_
"recipient_email": old_email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": channel_PLN.slug,
}
mocked_notify.assert_called_once_with(
- UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_CONFIRM, payload=expected_payload
+ UserNotifyEvent.ACCOUNT_CHANGE_EMAIL_CONFIRM,
+ payload=expected_payload,
+ channel_slug=channel_PLN.slug,
)
@@ -77,7 +92,7 @@ def test_send_email_changed_notification(mocked_notify, site_settings, customer_
@mock.patch("saleor.account.notifications.default_token_generator.make_token")
@mock.patch("saleor.plugins.manager.PluginsManager.notify")
def test_send_password_reset_notification(
- mocked_notify, mocked_generator, is_staff, site_settings, customer_user
+ mocked_notify, mocked_generator, is_staff, site_settings, customer_user, channel_PLN
):
token = "token_example"
mocked_generator.return_value = token
@@ -86,7 +101,11 @@ def test_send_password_reset_notification(
reset_url = prepare_url(params, redirect_url)
notifications.send_password_reset_notification(
- redirect_url, customer_user, get_plugins_manager(), staff=is_staff
+ redirect_url,
+ customer_user,
+ get_plugins_manager(),
+ channel_slug=channel_PLN.slug,
+ staff=is_staff,
)
expected_payload = {
@@ -96,10 +115,13 @@ def test_send_password_reset_notification(
"reset_url": reset_url,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": channel_PLN.slug,
}
expected_event = (
NotifyEventType.ACCOUNT_STAFF_RESET_PASSWORD
if is_staff
else NotifyEventType.ACCOUNT_PASSWORD_RESET
)
- mocked_notify.assert_called_once_with(expected_event, payload=expected_payload)
+ mocked_notify.assert_called_once_with(
+ expected_event, payload=expected_payload, channel_slug=channel_PLN.slug
+ )
diff --git a/saleor/checkout/checkout_cleaner.py b/saleor/checkout/checkout_cleaner.py
index 8ae2206263..ff68153870 100644
--- a/saleor/checkout/checkout_cleaner.py
+++ b/saleor/checkout/checkout_cleaner.py
@@ -74,7 +74,9 @@ def clean_checkout_payment(
):
clean_billing_address(checkout_info, error_code)
if not is_fully_paid(manager, checkout_info, lines, discounts):
- gateway.payment_refund_or_void(last_payment, manager)
+ gateway.payment_refund_or_void(
+ last_payment, manager, channel_slug=checkout_info.channel.slug
+ )
raise ValidationError(
"Provided payment methods can not cover the checkout's total amount",
code=error_code.CHECKOUT_NOT_FULLY_PAID.value,
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index d91f2106a1..e1d2875e93 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -515,11 +515,17 @@ def _process_payment(
payment_data: Optional[dict],
order_data: dict,
manager: "PluginsManager",
+ channel_slug: str,
) -> Transaction:
"""Process the payment assigned to checkout."""
try:
if payment.to_confirm:
- txn = gateway.confirm(payment, manager, additional_data=payment_data)
+ txn = gateway.confirm(
+ payment,
+ manager,
+ additional_data=payment_data,
+ channel_slug=channel_slug,
+ )
else:
txn = gateway.process_payment(
payment=payment,
@@ -527,6 +533,7 @@ def _process_payment(
manager=manager,
store_source=store_source,
additional_data=payment_data,
+ channel_slug=channel_slug,
)
payment.refresh_from_db()
if not txn.is_success:
@@ -556,6 +563,7 @@ def complete_checkout(
:raises ValidationError
"""
checkout = checkout_info.checkout
+ channel_slug = checkout_info.channel.slug
payment = checkout.get_last_active_payment()
_prepare_checkout(
manager=manager,
@@ -570,7 +578,7 @@ def complete_checkout(
try:
order_data = _get_order_data(manager, checkout_info, lines, discounts)
except ValidationError as exc:
- gateway.payment_refund_or_void(payment, manager)
+ gateway.payment_refund_or_void(payment, manager, channel_slug=channel_slug)
raise exc
txn = _process_payment(
@@ -579,6 +587,7 @@ def complete_checkout(
payment_data=payment_data,
order_data=order_data,
manager=manager,
+ channel_slug=channel_slug,
)
if txn.customer_id and user.is_authenticated:
@@ -601,7 +610,7 @@ def complete_checkout(
checkout.delete()
except InsufficientStock as e:
release_voucher_usage(order_data)
- gateway.payment_refund_or_void(payment, manager)
+ gateway.payment_refund_or_void(payment, manager, channel_slug=channel_slug)
error = prepare_insufficient_stock_checkout_validation_error(e)
raise error
return order, action_required, action_data
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index ca9a52106d..3e6a2fcc6d 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -28,6 +28,7 @@ def test_create_order_captured_payment_creates_expected_events(
customer_user,
shipping_method,
payment_txn_captured,
+ channel_USD,
):
checkout = checkout_with_item
checkout_user = customer_user
@@ -143,9 +144,15 @@ def test_create_order_captured_payment_creates_expected_events(
mock_notify.assert_has_calls(
[
- mock.call(NotifyEventType.ORDER_CONFIRMATION, expected_order_payload),
mock.call(
- NotifyEventType.ORDER_PAYMENT_CONFIRMATION, expected_payment_payload
+ NotifyEventType.ORDER_CONFIRMATION,
+ expected_order_payload,
+ channel_slug=channel_USD.slug,
+ ),
+ mock.call(
+ NotifyEventType.ORDER_PAYMENT_CONFIRMATION,
+ expected_payment_payload,
+ channel_slug=channel_USD.slug,
),
],
any_order=True,
@@ -167,6 +174,7 @@ def test_create_order_captured_payment_creates_expected_events_anonymous_user(
customer_user,
shipping_method,
payment_txn_captured,
+ channel_USD,
):
checkout = checkout_with_item
checkout_user = None
@@ -284,9 +292,15 @@ def test_create_order_captured_payment_creates_expected_events_anonymous_user(
mock_notify.assert_has_calls(
[
- mock.call(NotifyEventType.ORDER_CONFIRMATION, expected_order_payload),
mock.call(
- NotifyEventType.ORDER_PAYMENT_CONFIRMATION, expected_payment_payload
+ NotifyEventType.ORDER_CONFIRMATION,
+ expected_order_payload,
+ channel_slug=channel_USD.slug,
+ ),
+ mock.call(
+ NotifyEventType.ORDER_PAYMENT_CONFIRMATION,
+ expected_payment_payload,
+ channel_slug=channel_USD.slug,
),
],
any_order=True,
@@ -303,6 +317,7 @@ def test_create_order_preauth_payment_creates_expected_events(
customer_user,
shipping_method,
payment_txn_preauth,
+ channel_USD,
):
checkout = checkout_with_item
checkout_user = customer_user
@@ -390,7 +405,9 @@ def test_create_order_preauth_payment_creates_expected_events(
assert order_confirmed_event.parameters == {}
mock_notify.assert_called_once_with(
- NotifyEventType.ORDER_CONFIRMATION, expected_payload
+ NotifyEventType.ORDER_CONFIRMATION,
+ expected_payload,
+ channel_slug=channel_USD.slug,
)
# Ensure the correct customer event was created if the user was not anonymous
@@ -409,6 +426,7 @@ def test_create_order_preauth_payment_creates_expected_events_anonymous_user(
customer_user,
shipping_method,
payment_txn_preauth,
+ channel_USD,
):
checkout = checkout_with_item
checkout_user = None
@@ -496,7 +514,9 @@ def test_create_order_preauth_payment_creates_expected_events_anonymous_user(
assert order_confirmed_event.parameters == {}
mock_notify.assert_called_once_with(
- NotifyEventType.ORDER_CONFIRMATION, expected_payload
+ NotifyEventType.ORDER_CONFIRMATION,
+ expected_payload,
+ channel_slug=channel_USD.slug,
)
# Check no event was created if the user was anonymous
diff --git a/saleor/core/payments.py b/saleor/core/payments.py
index acf3b689ad..78caab7df3 100644
--- a/saleor/core/payments.py
+++ b/saleor/core/payments.py
@@ -19,56 +19,61 @@ class PaymentInterface(ABC):
self,
currency: Optional[str] = None,
checkout: Optional["Checkout"] = None,
+ channel_slug: Optional[str] = None,
active_only: bool = True,
) -> List["PaymentGateway"]:
pass
@abstractmethod
def authorize_payment(
- self, gateway: str, payment_information: "PaymentData"
+ self, gateway: str, payment_information: "PaymentData", channel_slug: str
) -> "GatewayResponse":
pass
@abstractmethod
def capture_payment(
- self, gateway: str, payment_information: "PaymentData"
+ self, gateway: str, payment_information: "PaymentData", channel_slug: str
) -> "GatewayResponse":
pass
@abstractmethod
def refund_payment(
- self, gateway: str, payment_information: "PaymentData"
+ self, gateway: str, payment_information: "PaymentData", channel_slug: str
) -> "GatewayResponse":
pass
@abstractmethod
def void_payment(
- self, gateway: str, payment_information: "PaymentData"
+ self, gateway: str, payment_information: "PaymentData", channel_slug: str
) -> "GatewayResponse":
pass
@abstractmethod
def confirm_payment(
- self, gateway: str, payment_information: "PaymentData"
+ self, gateway: str, payment_information: "PaymentData", channel_slug: str
) -> "GatewayResponse":
pass
@abstractmethod
- def token_is_required_as_payment_input(self, gateway) -> bool:
+ def token_is_required_as_payment_input(
+ self, gateway: str, channel_slug: str
+ ) -> bool:
pass
@abstractmethod
def process_payment(
- self, gateway: str, payment_information: "PaymentData"
+ self, gateway: str, payment_information: "PaymentData", channel_slug: str
) -> "GatewayResponse":
pass
@abstractmethod
- def get_client_token(self, gateway: str, token_config: "TokenConfig") -> str:
+ def get_client_token(
+ self, gateway: str, token_config: "TokenConfig", channel_slug: str
+ ) -> str:
pass
@abstractmethod
def list_payment_sources(
- self, gateway: str, customer_id: str
+ self, gateway: str, customer_id: str, channel_slug: str
) -> List["CustomerSource"]:
pass
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index d82ecb5322..aecdc2cc65 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -549,19 +549,19 @@ def create_fake_payment(mock_notify, order):
manager = get_plugins_manager()
# Create authorization transaction
- gateway.authorize(payment, payment.token, manager)
+ gateway.authorize(payment, payment.token, manager, order.channel.slug)
# 20% chance to void the transaction at this stage
if random.choice([0, 0, 0, 0, 1]):
- gateway.void(payment, manager)
+ gateway.void(payment, manager, order.channel.slug)
return payment
# 25% to end the payment at the authorization stage
if not random.choice([1, 1, 1, 0]):
return payment
# Create capture transaction
- gateway.capture(payment, manager)
+ gateway.capture(payment, manager, order.channel.slug)
# 25% to refund the payment
if random.choice([0, 0, 0, 1]):
- gateway.refund(payment, manager)
+ gateway.refund(payment, manager, order.channel.slug)
return payment
@@ -681,7 +681,9 @@ def create_fake_order(discounts, max_order_lines=5):
)
shipping_method = shipping_method_chanel_listing.shipping_method
shipping_price = shipping_method_chanel_listing.price
- shipping_price = manager.apply_taxes_to_shipping(shipping_price, address)
+ shipping_price = manager.apply_taxes_to_shipping(
+ shipping_price, address, channel_slug=channel.slug
+ )
order_data.update(
{
"channel": channel,
diff --git a/saleor/demo/management/commands/populatedb.py b/saleor/demo/management/commands/populatedb.py
index 50ee9ba218..c01041aa3f 100644
--- a/saleor/demo/management/commands/populatedb.py
+++ b/saleor/demo/management/commands/populatedb.py
@@ -1,5 +1,6 @@
from django.conf import settings
+from ....channel.models import Channel
from ....core.management.commands.populatedb import Command as PopulateDBCommand
from ....payment.gateways.braintree.plugin import BraintreeGatewayPlugin
from ....plugins.manager import get_plugins_manager
@@ -13,19 +14,22 @@ def configure_braintree():
if not (braintree_api_key and braintree_merchant_id and braintree_secret):
return False
+ channels = Channel.objects.all()
manager = get_plugins_manager()
- manager.save_plugin_configuration(
- BraintreeGatewayPlugin.PLUGIN_ID,
- {
- "active": True,
- "configuration": [
- {"name": "Public API key", "value": braintree_api_key},
- {"name": "Merchant ID", "value": braintree_merchant_id},
- {"name": "Secret API key", "value": braintree_secret},
- {"name": "Use sandbox", "value": True},
- ],
- },
- )
+ for channel in channels:
+ manager.save_plugin_configuration(
+ BraintreeGatewayPlugin.PLUGIN_ID,
+ channel.slug,
+ {
+ "active": True,
+ "configuration": [
+ {"name": "Public API key", "value": braintree_api_key},
+ {"name": "Merchant ID", "value": braintree_merchant_id},
+ {"name": "Secret API key", "value": braintree_secret},
+ {"name": "Use sandbox", "value": True},
+ ],
+ },
+ )
return True
diff --git a/saleor/graphql/account/mutations/account.py b/saleor/graphql/account/mutations/account.py
index 4edfa79b7b..01bbc3d11a 100644
--- a/saleor/graphql/account/mutations/account.py
+++ b/saleor/graphql/account/mutations/account.py
@@ -14,6 +14,7 @@ from ....core.utils.url import validate_storefront_url
from ....settings import JWT_TTL_REQUEST_EMAIL_CHANGE
from ...account.enums import AddressTypeEnum
from ...account.types import Address, AddressInput, User
+from ...channel.utils import clean_channel
from ...core.enums import LanguageCodeEnum
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ...core.types.common import AccountError
@@ -44,6 +45,12 @@ class AccountRegisterInput(graphene.InputObjectType):
description="User public metadata.",
required=False,
)
+ channel = graphene.String(
+ description=(
+ "Slug of a channel which will be used to notify users. Optional when "
+ "only one channel exists."
+ )
+ )
class AccountRegister(ModelMutation):
@@ -96,11 +103,16 @@ class AccountRegister(ModelMutation):
}
)
+ data["channel"] = clean_channel(
+ data.get("channel"), error_class=AccountErrorCode
+ ).slug
+
password = data["password"]
try:
password_validation.validate_password(password, instance)
except ValidationError as error:
raise ValidationError({"password": error})
+
data["language_code"] = data.get("language_code", settings.LANGUAGE_CODE)
return super().clean_input(info, instance, data, input_cls=None)
@@ -112,7 +124,10 @@ class AccountRegister(ModelMutation):
user.is_active = False
user.save()
notifications.send_account_confirmation(
- user, cleaned_input["redirect_url"], info.context.plugins
+ user,
+ cleaned_input["redirect_url"],
+ info.context.plugins,
+ channel_slug=cleaned_input["channel"],
)
else:
user.save()
@@ -168,6 +183,12 @@ class AccountRequestDeletion(BaseMutation):
"delete their account. URL in RFC 1808 format."
),
)
+ channel = graphene.String(
+ description=(
+ "Slug of a channel which will be used to notify users. Optional when "
+ "only one channel exists."
+ )
+ )
class Meta:
description = (
@@ -190,8 +211,11 @@ class AccountRequestDeletion(BaseMutation):
raise ValidationError(
{"redirect_url": error}, code=AccountErrorCode.INVALID
)
+ channel_slug = clean_channel(
+ data.get("channel"), error_class=AccountErrorCode
+ ).slug
notifications.send_account_delete_confirmation_notification(
- redirect_url, user, info.context.plugins
+ redirect_url, user, info.context.plugins, channel_slug=channel_slug
)
return AccountRequestDeletion()
@@ -372,6 +396,12 @@ class RequestEmailChange(BaseMutation):
"update the email address. URL in RFC 1808 format."
),
)
+ channel = graphene.String(
+ description=(
+ "Slug of a channel which will be used to notify users. Optional when "
+ "only one channel exists."
+ )
+ )
class Meta:
description = "Request email change of the logged in user."
@@ -412,6 +442,11 @@ class RequestEmailChange(BaseMutation):
raise ValidationError(
{"redirect_url": error}, code=AccountErrorCode.INVALID
)
+ channel_slug = clean_channel(
+ data.get("channel"),
+ error_class=AccountErrorCode,
+ ).slug
+
token_payload = {
"old_email": user.email,
"new_email": new_email,
@@ -419,7 +454,12 @@ class RequestEmailChange(BaseMutation):
}
token = create_token(token_payload, JWT_TTL_REQUEST_EMAIL_CHANGE)
notifications.send_request_user_change_email_notification(
- redirect_url, user, new_email, token, info.context.plugins
+ redirect_url,
+ user,
+ new_email,
+ token,
+ info.context.plugins,
+ channel_slug=channel_slug,
)
return RequestEmailChange(user=user)
@@ -431,6 +471,12 @@ class ConfirmEmailChange(BaseMutation):
token = graphene.String(
description="A one-time token required to change the email.", required=True
)
+ channel = graphene.String(
+ description=(
+ "Slug of a channel which will be used to notify users. Optional when "
+ "only one channel exists."
+ )
+ )
class Meta:
description = "Confirm the email change of the logged-in user."
@@ -476,8 +522,13 @@ class ConfirmEmailChange(BaseMutation):
user.email = new_email
user.save(update_fields=["email"])
+
+ channel_slug = clean_channel(
+ data.get("channel"), error_class=AccountErrorCode
+ ).slug
+
notifications.send_user_change_email_notification(
- old_email, user, info.context.plugins
+ old_email, user, info.context.plugins, channel_slug=channel_slug
)
info.context.plugins.customer_updated(user)
return ConfirmEmailChange(user=user)
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index ae502f8e27..42cb9a23b7 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -18,6 +18,7 @@ from ....core.utils.url import validate_storefront_url
from ....order.utils import match_orders_with_new_user
from ...account.i18n import I18nMixin
from ...account.types import Address, AddressInput, User
+from ...channel.utils import clean_channel, validate_channel
from ...core.enums import LanguageCodeEnum
from ...core.mutations import (
BaseMutation,
@@ -113,6 +114,12 @@ class RequestPasswordReset(BaseMutation):
"reset the password. URL in RFC 1808 format."
),
)
+ channel = graphene.String(
+ description=(
+ "Slug of a channel which will be used for notify user. Optional when "
+ "only one channel exists."
+ )
+ )
class Meta:
description = "Sends an email with the account password modification link."
@@ -120,9 +127,8 @@ class RequestPasswordReset(BaseMutation):
error_type_field = "account_errors"
@classmethod
- def perform_mutation(cls, _root, info, **data):
- email = data["email"]
- redirect_url = data["redirect_url"]
+ def clean_user(cls, email, redirect_url):
+
try:
validate_storefront_url(redirect_url)
except ValidationError as error:
@@ -150,8 +156,30 @@ class RequestPasswordReset(BaseMutation):
)
}
)
+ return user
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ email = data["email"]
+ redirect_url = data["redirect_url"]
+ channel_slug = data.get("channel_slug")
+ user = cls.clean_user(email, redirect_url)
+
+ if not user.is_staff:
+ channel_slug = clean_channel(
+ channel_slug, error_class=AccountErrorCode
+ ).slug
+ elif channel_slug is not None:
+ channel_slug = validate_channel(
+ channel_slug, error_class=AccountErrorCode
+ ).slug
+
send_password_reset_notification(
- redirect_url, user, info.context.plugins, staff=user.is_staff
+ redirect_url,
+ user,
+ info.context.plugins,
+ channel_slug=channel_slug,
+ staff=user.is_staff,
)
return RequestPasswordReset()
@@ -372,6 +400,12 @@ class UserCreateInput(CustomerInput):
"set the password. URL in RFC 1808 format."
)
)
+ channel = graphene.String(
+ description=(
+ "Slug of a channel which will be used for notify user. Optional when "
+ "only one channel exists."
+ )
+ )
class BaseCustomerCreate(ModelMutation, I18nMixin):
@@ -449,6 +483,18 @@ class BaseCustomerCreate(ModelMutation, I18nMixin):
info.context.plugins.customer_updated(instance)
if cleaned_input.get("redirect_url"):
+ channel_slug = cleaned_input.get("channel")
+ if not instance.is_staff:
+ channel_slug = clean_channel(
+ channel_slug, error_class=AccountErrorCode
+ ).slug
+ elif channel_slug is not None:
+ channel_slug = validate_channel(
+ channel_slug, error_class=AccountErrorCode
+ ).slug
send_set_password_notification(
- cleaned_input.get("redirect_url"), instance, info.context.plugins
+ cleaned_input.get("redirect_url"),
+ instance,
+ info.context.plugins,
+ channel_slug,
)
diff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.py
index da28bbd4f2..1349ae7fb3 100644
--- a/saleor/graphql/account/mutations/staff.py
+++ b/saleor/graphql/account/mutations/staff.py
@@ -246,6 +246,7 @@ class StaffCreate(ModelMutation):
redirect_url=cleaned_input.get("redirect_url"),
user=user,
manager=info.context.plugins,
+ channel_slug=None,
staff=True,
)
diff --git a/saleor/graphql/account/resolvers.py b/saleor/graphql/account/resolvers.py
index 73c43d33cf..0ed4467032 100644
--- a/saleor/graphql/account/resolvers.py
+++ b/saleor/graphql/account/resolvers.py
@@ -118,17 +118,19 @@ def resolve_address_validation_rules(
@traced_resolver
-def resolve_payment_sources(info, user: models.User):
+def resolve_payment_sources(info, user: models.User, channel_slug: str):
manager = info.context.plugins
stored_customer_accounts = (
(gtw.id, fetch_customer_id(user, gtw.id))
- for gtw in gateway.list_gateways(manager)
+ for gtw in gateway.list_gateways(manager, channel_slug)
)
return list(
chain(
*[
prepare_graphql_payment_sources_type(
- gateway.list_payment_sources(gtw, customer_id, manager)
+ gateway.list_payment_sources(
+ gtw, customer_id, manager, channel_slug
+ )
)
for gtw, customer_id in stored_customer_accounts
if customer_id is not None
diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.py
index e060fe752b..473aa4e54b 100644
--- a/saleor/graphql/account/tests/test_account.py
+++ b/saleor/graphql/account/tests/test_account.py
@@ -949,7 +949,8 @@ ACCOUNT_REGISTER_MUTATION = """
$email: String!,
$redirectUrl: String,
$languageCode: LanguageCodeEnum
- $metadata: [MetadataInput!]
+ $metadata: [MetadataInput!],
+ $channel: String
) {
accountRegister(
input: {
@@ -957,7 +958,8 @@ ACCOUNT_REGISTER_MUTATION = """
email: $email,
redirectUrl: $redirectUrl,
languageCode: $languageCode,
- metadata: $metadata
+ metadata: $metadata,
+ channel: $channel
}
) {
errors {
@@ -978,7 +980,7 @@ ACCOUNT_REGISTER_MUTATION = """
)
@patch("saleor.account.notifications.default_token_generator.make_token")
@patch("saleor.plugins.manager.PluginsManager.notify")
-def test_customer_register(mocked_notify, mocked_generator, api_client):
+def test_customer_register(mocked_notify, mocked_generator, api_client, channel_PLN):
mocked_generator.return_value = "token"
redirect_url = "http://localhost:3000"
@@ -988,6 +990,7 @@ def test_customer_register(mocked_notify, mocked_generator, api_client):
"redirectUrl": redirect_url,
"languageCode": "PL",
"metadata": [{"key": "meta", "value": "data"}],
+ "channel": channel_PLN.slug,
}
query = ACCOUNT_REGISTER_MUTATION
mutation_name = "accountRegister"
@@ -1006,12 +1009,15 @@ def test_customer_register(mocked_notify, mocked_generator, api_client):
"recipient_email": new_user.email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": channel_PLN.slug,
}
assert new_user.metadata == {"meta": "data"}
assert new_user.language_code == "pl"
assert not data["errors"]
mocked_notify.assert_called_once_with(
- NotifyEventType.ACCOUNT_CONFIRMATION, payload=expected_payload
+ NotifyEventType.ACCOUNT_CONFIRMATION,
+ payload=expected_payload,
+ channel_slug=channel_PLN.slug,
)
response = api_client.post_graphql(query, variables)
@@ -1096,7 +1102,12 @@ CUSTOMER_CREATE_MUTATION = """
@patch("saleor.account.notifications.default_token_generator.make_token")
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_customer_create(
- mocked_notify, mocked_generator, staff_api_client, address, permission_manage_users
+ mocked_notify,
+ mocked_generator,
+ staff_api_client,
+ address,
+ permission_manage_users,
+ channel_PLN,
):
mocked_generator.return_value = "token"
@@ -1114,6 +1125,7 @@ def test_customer_create(
"billing": address_data,
"redirect_url": redirect_url,
"languageCode": "PL",
+ "channel": channel_PLN.slug,
}
response = staff_api_client.post_graphql(
@@ -1151,9 +1163,12 @@ def test_customer_create(
"recipient_email": new_user.email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": channel_PLN.slug,
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ACCOUNT_SET_CUSTOMER_PASSWORD, payload=expected_payload
+ NotifyEventType.ACCOUNT_SET_CUSTOMER_PASSWORD,
+ payload=expected_payload,
+ channel_slug=channel_PLN.slug,
)
customer_creation_event = account_events.CustomerEvent.objects.get()
@@ -1168,10 +1183,15 @@ def test_customer_create_send_password_with_url(
mocked_generator,
staff_api_client,
permission_manage_users,
+ channel_PLN,
):
mocked_generator.return_value = "token"
- variables = {"email": email, "redirect_url": "https://www.example.com"}
+ variables = {
+ "email": email,
+ "redirect_url": "https://www.example.com",
+ "channel": channel_PLN.slug,
+ }
response = staff_api_client.post_graphql(
CUSTOMER_CREATE_MUTATION, variables, permissions=[permission_manage_users]
@@ -1192,9 +1212,12 @@ def test_customer_create_send_password_with_url(
"recipient_email": new_customer.email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": channel_PLN.slug,
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ACCOUNT_SET_CUSTOMER_PASSWORD, payload=expected_payload
+ NotifyEventType.ACCOUNT_SET_CUSTOMER_PASSWORD,
+ payload=expected_payload,
+ channel_slug=channel_PLN.slug,
)
@@ -1574,8 +1597,8 @@ def test_logged_customer_update_anonymous_user(api_client):
ACCOUNT_REQUEST_DELETION_MUTATION = """
- mutation accountRequestDeletion($redirectUrl: String!) {
- accountRequestDeletion(redirectUrl: $redirectUrl) {
+ mutation accountRequestDeletion($redirectUrl: String!, $channel: String) {
+ accountRequestDeletion(redirectUrl: $redirectUrl, channel: $channel) {
errors {
field
message
@@ -1591,11 +1614,13 @@ ACCOUNT_REQUEST_DELETION_MUTATION = """
@patch("saleor.account.notifications.default_token_generator.make_token")
@patch("saleor.plugins.manager.PluginsManager.notify")
-def test_account_request_deletion(mocked_notify, mocked_token, user_api_client):
+def test_account_request_deletion(
+ mocked_notify, mocked_token, user_api_client, channel_PLN
+):
mocked_token.return_value = "token"
user = user_api_client.user
redirect_url = "https://www.example.com"
- variables = {"redirectUrl": redirect_url}
+ variables = {"redirectUrl": redirect_url, "channel": channel_PLN.slug}
response = user_api_client.post_graphql(
ACCOUNT_REQUEST_DELETION_MUTATION, variables
)
@@ -1611,20 +1636,25 @@ def test_account_request_deletion(mocked_notify, mocked_token, user_api_client):
"recipient_email": user.email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": channel_PLN.slug,
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ACCOUNT_DELETE, payload=expected_payload
+ NotifyEventType.ACCOUNT_DELETE,
+ payload=expected_payload,
+ channel_slug=channel_PLN.slug,
)
@freeze_time("2018-05-31 12:00:01")
@patch("saleor.plugins.manager.PluginsManager.notify")
-def test_account_request_deletion_token_validation(mocked_notify, user_api_client):
+def test_account_request_deletion_token_validation(
+ mocked_notify, user_api_client, channel_PLN
+):
user = user_api_client.user
token = default_token_generator.make_token(user)
redirect_url = "https://www.example.com"
- variables = {"redirectUrl": redirect_url}
+ variables = {"redirectUrl": redirect_url, "channel": channel_PLN.slug}
response = user_api_client.post_graphql(
ACCOUNT_REQUEST_DELETION_MUTATION, variables
)
@@ -1640,10 +1670,13 @@ def test_account_request_deletion_token_validation(mocked_notify, user_api_clien
"recipient_email": user.email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": channel_PLN.slug,
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ACCOUNT_DELETE, payload=expected_payload
+ NotifyEventType.ACCOUNT_DELETE,
+ payload=expected_payload,
+ channel_slug=channel_PLN.slug,
)
@@ -1677,13 +1710,13 @@ def test_account_request_deletion_storefront_hosts_not_allowed(
@freeze_time("2018-05-31 12:00:01")
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_account_request_deletion_all_storefront_hosts_allowed(
- mocked_notify, user_api_client, settings
+ mocked_notify, user_api_client, settings, channel_PLN
):
user = user_api_client.user
token = default_token_generator.make_token(user)
settings.ALLOWED_CLIENT_HOSTS = ["*"]
redirect_url = "https://www.test.com"
- variables = {"redirectUrl": redirect_url}
+ variables = {"redirectUrl": redirect_url, "channel": channel_PLN.slug}
response = user_api_client.post_graphql(
ACCOUNT_REQUEST_DELETION_MUTATION, variables
)
@@ -1700,21 +1733,26 @@ def test_account_request_deletion_all_storefront_hosts_allowed(
"recipient_email": user.email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": channel_PLN.slug,
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ACCOUNT_DELETE, payload=expected_payload
+ NotifyEventType.ACCOUNT_DELETE,
+ payload=expected_payload,
+ channel_slug=channel_PLN.slug,
)
@freeze_time("2018-05-31 12:00:01")
@patch("saleor.plugins.manager.PluginsManager.notify")
-def test_account_request_deletion_subdomain(mocked_notify, user_api_client, settings):
+def test_account_request_deletion_subdomain(
+ mocked_notify, user_api_client, settings, channel_PLN
+):
user = user_api_client.user
token = default_token_generator.make_token(user)
settings.ALLOWED_CLIENT_HOSTS = [".example.com"]
redirect_url = "https://sub.example.com"
- variables = {"redirectUrl": redirect_url}
+ variables = {"redirectUrl": redirect_url, "channel": channel_PLN.slug}
response = user_api_client.post_graphql(
ACCOUNT_REQUEST_DELETION_MUTATION, variables
)
@@ -1730,10 +1768,13 @@ def test_account_request_deletion_subdomain(mocked_notify, user_api_client, sett
"recipient_email": user.email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": channel_PLN.slug,
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ACCOUNT_DELETE, payload=expected_payload
+ NotifyEventType.ACCOUNT_DELETE,
+ payload=expected_payload,
+ channel_slug=channel_PLN.slug,
)
@@ -1921,6 +1962,7 @@ def test_staff_create(
permission_manage_products,
permission_manage_staff,
permission_manage_users,
+ channel_PLN,
):
group = permission_group_manage_users
group.permissions.add(permission_manage_products)
@@ -1968,10 +2010,13 @@ def test_staff_create(
"recipient_email": staff_user.email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": None,
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD, payload=expected_payload
+ NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD,
+ payload=expected_payload,
+ channel_slug=None,
)
@@ -2011,6 +2056,7 @@ def test_staff_create_out_of_scope_group(
permission_manage_staff,
permission_manage_users,
permission_group_manage_users,
+ channel_PLN,
):
"""Ensure user can't create staff with groups which are out of user scope.
Ensure superuser pass restrictions.
@@ -2093,10 +2139,13 @@ def test_staff_create_out_of_scope_group(
"recipient_email": staff_user.email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": None,
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD, payload=expected_payload
+ NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD,
+ payload=expected_payload,
+ channel_slug=None,
)
@@ -2132,10 +2181,13 @@ def test_staff_create_send_password_with_url(
"recipient_email": staff_user.email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": None,
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD, payload=expected_payload
+ NotifyEventType.ACCOUNT_SET_STAFF_PASSWORD,
+ payload=expected_payload,
+ channel_slug=None,
)
@@ -3433,7 +3485,9 @@ CONFIRM_ACCOUNT_MUTATION = """
@freeze_time("2018-05-31 12:00:01")
@patch("saleor.plugins.manager.PluginsManager.notify")
-def test_account_reset_password(mocked_notify, user_api_client, customer_user):
+def test_account_reset_password(
+ mocked_notify, user_api_client, customer_user, channel_PLN
+):
redirect_url = "https://www.example.com"
variables = {"email": customer_user.email, "redirectUrl": redirect_url}
response = user_api_client.post_graphql(REQUEST_PASSWORD_RESET_MUTATION, variables)
@@ -3450,10 +3504,13 @@ def test_account_reset_password(mocked_notify, user_api_client, customer_user):
"recipient_email": customer_user.email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": channel_PLN.slug,
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ACCOUNT_PASSWORD_RESET, payload=expected_payload
+ NotifyEventType.ACCOUNT_PASSWORD_RESET,
+ payload=expected_payload,
+ channel_slug=channel_PLN.slug,
)
@@ -3531,10 +3588,13 @@ def test_request_password_reset_email_for_staff(mocked_notify, staff_api_client)
"recipient_email": staff_api_client.user.email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": None,
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ACCOUNT_STAFF_RESET_PASSWORD, payload=expected_payload
+ NotifyEventType.ACCOUNT_STAFF_RESET_PASSWORD,
+ payload=expected_payload,
+ channel_slug=None,
)
@@ -3588,7 +3648,7 @@ def test_account_reset_password_storefront_hosts_not_allowed(
@freeze_time("2018-05-31 12:00:01")
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_account_reset_password_all_storefront_hosts_allowed(
- mocked_notify, user_api_client, customer_user, settings
+ mocked_notify, user_api_client, customer_user, settings, channel_PLN
):
settings.ALLOWED_CLIENT_HOSTS = ["*"]
redirect_url = "https://www.test.com"
@@ -3608,17 +3668,20 @@ def test_account_reset_password_all_storefront_hosts_allowed(
"recipient_email": customer_user.email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": channel_PLN.slug,
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ACCOUNT_PASSWORD_RESET, payload=expected_payload
+ NotifyEventType.ACCOUNT_PASSWORD_RESET,
+ payload=expected_payload,
+ channel_slug=channel_PLN.slug,
)
@freeze_time("2018-05-31 12:00:01")
@patch("saleor.plugins.manager.PluginsManager.notify")
def test_account_reset_password_subdomain(
- mocked_notify, user_api_client, customer_user, settings
+ mocked_notify, user_api_client, customer_user, settings, channel_PLN
):
settings.ALLOWED_CLIENT_HOSTS = [".example.com"]
redirect_url = "https://sub.example.com"
@@ -3638,10 +3701,13 @@ def test_account_reset_password_subdomain(
"recipient_email": customer_user.email,
"site_name": "mirumee.com",
"domain": "mirumee.com",
+ "channel_slug": channel_PLN.slug,
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ACCOUNT_PASSWORD_RESET, payload=expected_payload
+ NotifyEventType.ACCOUNT_PASSWORD_RESET,
+ payload=expected_payload,
+ channel_slug=channel_PLN.slug,
)
@@ -4530,10 +4596,13 @@ def test_address_query_as_anonymous_user(api_client, address_other_country):
REQUEST_EMAIL_CHANGE_QUERY = """
mutation requestEmailChange(
- $password: String!, $new_email: String!, $redirect_url: String!
+ $password: String!, $new_email: String!, $redirect_url: String!, $channel:String
) {
requestEmailChange(
- password: $password, newEmail: $new_email, redirectUrl: $redirect_url
+ password: $password,
+ newEmail: $new_email,
+ redirectUrl: $redirect_url,
+ channel: $channel
) {
user {
email
@@ -4548,11 +4617,12 @@ mutation requestEmailChange(
"""
-def test_request_email_change(user_api_client, customer_user):
+def test_request_email_change(user_api_client, customer_user, channel_PLN):
variables = {
"password": "password",
"new_email": "[email protected]",
"redirect_url": "http://www.example.com",
+ "channel": channel_PLN.slug,
}
response = user_api_client.post_graphql(REQUEST_EMAIL_CHANGE_QUERY, variables)
@@ -4635,7 +4705,7 @@ mutation emailUpdate($token: String!) {
"""
-def test_email_update(user_api_client, customer_user):
+def test_email_update(user_api_client, customer_user, channel_PLN):
new_email = "[email protected]"
payload = {
"old_email": customer_user.email,
diff --git a/saleor/graphql/account/types.py b/saleor/graphql/account/types.py
index 0321de9021..5e4b3a1f95 100644
--- a/saleor/graphql/account/types.py
+++ b/saleor/graphql/account/types.py
@@ -241,6 +241,9 @@ class User(CountableDjangoObjectType):
stored_payment_sources = graphene.List(
"saleor.graphql.payment.types.PaymentSource",
description="List of stored payment sources.",
+ channel=graphene.String(
+ description="Slug of a channel for which the data should be returned."
+ ),
)
language_code = graphene.Field(
LanguageCodeEnum, description="User language code.", required=True
@@ -356,11 +359,11 @@ class User(CountableDjangoObjectType):
@staticmethod
@traced_resolver
- def resolve_stored_payment_sources(root: models.User, info):
+ def resolve_stored_payment_sources(root: models.User, info, channel=None):
from .resolvers import resolve_payment_sources
if root == info.context.user:
- return resolve_payment_sources(info, root)
+ return resolve_payment_sources(info, root, channel_slug=channel)
raise PermissionDenied()
@staticmethod
diff --git a/saleor/graphql/channel/utils.py b/saleor/graphql/channel/utils.py
index 5388bb7bd3..cf8ca11dc8 100644
--- a/saleor/graphql/channel/utils.py
+++ b/saleor/graphql/channel/utils.py
@@ -1,3 +1,4 @@
+from django.core.exceptions import ValidationError
from django.utils.functional import SimpleLazyObject
from graphql.error import GraphQLError
@@ -25,3 +26,48 @@ def get_default_channel_or_graphql_error() -> Channel:
raise GraphQLError(str(e))
else:
return channel
+
+
+def validate_channel(channel_slug, error_class):
+ try:
+ channel = Channel.objects.get(slug=channel_slug)
+ except Channel.DoesNotExist:
+ raise ValidationError(
+ {
+ "channel": ValidationError(
+ f"Channel with '{channel_slug}' slug does not exist.",
+ code=error_class.NOT_FOUND.value,
+ )
+ }
+ )
+ if not channel.is_active:
+ raise ValidationError(
+ {
+ "channel": ValidationError(
+ f"Channel with '{channel_slug}' is inactive.",
+ code=error_class.CHANNEL_INACTIVE.value,
+ )
+ }
+ )
+ return channel
+
+
+def clean_channel(
+ channel_slug,
+ error_class,
+):
+ if channel_slug is not None:
+ channel = validate_channel(channel_slug, error_class)
+ else:
+ try:
+ channel = get_default_channel()
+ except ChannelNotDefined:
+ raise ValidationError(
+ {
+ "channel": ValidationError(
+ "You need to provide channel slug.",
+ code=error_class.MISSING_CHANNEL_SLUG.value,
+ )
+ }
+ )
+ return channel
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 3b44effcae..adfe64afb4 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -7,9 +7,6 @@ from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import transaction
from django.db.models import Q
-from ...channel.exceptions import ChannelNotDefined
-from ...channel.models import Channel
-from ...channel.utils import get_default_channel
from ...checkout import AddressType, models
from ...checkout.complete_checkout import complete_checkout
from ...checkout.error_codes import CheckoutErrorCode
@@ -42,6 +39,7 @@ from ...shipping import models as shipping_models
from ...warehouse.availability import check_stock_quantity_bulk
from ..account.i18n import I18nMixin
from ..account.types import AddressInput
+from ..channel.utils import clean_channel
from ..core.enums import LanguageCodeEnum
from ..core.mutations import BaseMutation, ModelMutation
from ..core.types.common import CheckoutError
@@ -295,48 +293,6 @@ class CheckoutCreate(ModelMutation, I18nMixin):
return user.default_billing_address
return None
- @classmethod
- def validate_channel(cls, channel_slug):
- try:
- channel = Channel.objects.get(slug=channel_slug)
- except Channel.DoesNotExist:
- raise ValidationError(
- {
- "channel": ValidationError(
- f"Channel with '{channel_slug}' slug does not exist.",
- code=CheckoutErrorCode.NOT_FOUND.value,
- )
- }
- )
- if not channel.is_active:
- raise ValidationError(
- {
- "channel": ValidationError(
- f"Channel with '{channel_slug}' is inactive.",
- code=CheckoutErrorCode.CHANNEL_INACTIVE.value,
- )
- }
- )
- return channel
-
- @classmethod
- def clean_channel(cls, channel_slug):
- if channel_slug is not None:
- channel = cls.validate_channel(channel_slug)
- else:
- try:
- channel = get_default_channel()
- except ChannelNotDefined:
- raise ValidationError(
- {
- "channel": ValidationError(
- "You need to provide channel slug.",
- code=CheckoutErrorCode.MISSING_CHANNEL_SLUG,
- )
- }
- )
- return channel
-
@classmethod
def clean_input(cls, info, instance: models.Checkout, data, input_cls=None):
user = info.context.user
@@ -424,7 +380,7 @@ class CheckoutCreate(ModelMutation, I18nMixin):
@classmethod
def perform_mutation(cls, _root, info, **data):
channel_input = data.get("input", {}).get("channel")
- channel = cls.clean_channel(channel_input)
+ channel = clean_channel(channel_input, error_class=CheckoutErrorCode)
if channel:
data["input"]["channel"] = channel
response = super().perform_mutation(_root, info, **data)
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 7d577395c5..48d445a5b4 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -1402,7 +1402,9 @@ def test_checkout_available_shipping_methods_with_price_displayed(
content = get_graphql_content(response)
data = content["data"]["checkout"]
- apply_taxes_to_shipping_mock.assert_called_once_with(shipping_price, mock.ANY)
+ apply_taxes_to_shipping_mock.assert_called_once_with(
+ shipping_price, mock.ANY, checkout_with_item.channel.slug
+ )
assert data["availableShippingMethods"] == [
{"name": "DHL", "price": {"amount": expected_price}}
]
diff --git a/saleor/graphql/checkout/tests/test_checkout_complete.py b/saleor/graphql/checkout/tests/test_checkout_complete.py
index 1870e65c6a..5a31dff6e4 100644
--- a/saleor/graphql/checkout/tests/test_checkout_complete.py
+++ b/saleor/graphql/checkout/tests/test_checkout_complete.py
@@ -813,7 +813,9 @@ def test_checkout_complete_insufficient_stock_payment_refunded(
assert data["errors"][0]["message"] == "Insufficient product stock: 123"
assert orders_count == Order.objects.count()
- gateway_refund_mock.assert_called_once_with(payment, ANY)
+ gateway_refund_mock.assert_called_once_with(
+ payment, ANY, channel_slug=checkout_info.channel.slug
+ )
@patch("saleor.checkout.complete_checkout.gateway.void")
@@ -868,7 +870,9 @@ def test_checkout_complete_insufficient_stock_payment_voided(
assert data["errors"][0]["message"] == "Insufficient product stock: 123"
assert orders_count == Order.objects.count()
- gateway_void_mock.assert_called_once_with(payment, ANY)
+ gateway_void_mock.assert_called_once_with(
+ payment, ANY, channel_slug=checkout_info.channel.slug
+ )
def test_checkout_complete_without_redirect_url(
@@ -987,7 +991,9 @@ def test_checkout_complete_payment_payment_total_different_than_checkout(
assert data["errors"][0]["code"] == CheckoutErrorCode.CHECKOUT_NOT_FULLY_PAID.name
assert orders_count == Order.objects.count()
- gateway_refund_or_void_mock.assert_called_with(payment, ANY)
+ gateway_refund_or_void_mock.assert_called_with(
+ payment, ANY, channel_slug=checkout_info.channel.slug
+ )
def test_order_already_exists(
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index f3c0884951..3eab2d2e3b 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -409,7 +409,7 @@ class Checkout(CountableDjangoObjectType):
for shipping in shippings:
shipping_channel_listing = channel_listing_map[shipping.id]
taxed_price = info.context.plugins.apply_taxes_to_shipping(
- shipping_channel_listing.price, address
+ shipping_channel_listing.price, address, channel_slug
)
if display_gross:
shipping.price = taxed_price.gross
@@ -457,7 +457,7 @@ class Checkout(CountableDjangoObjectType):
@traced_resolver
def resolve_available_payment_gateways(root: models.Checkout, info):
return info.context.plugins.list_payment_gateways(
- currency=root.currency, checkout=root
+ currency=root.currency, checkout=root, channel_slug=root.channel.slug
)
@staticmethod
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index 64eb886380..aa6a4ef4a5 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -484,7 +484,8 @@ class OrderCapture(BaseMutation):
gateway.capture,
payment,
info.context.plugins,
- amount,
+ amount=amount,
+ channel_slug=order.channel.slug,
)
# Confirm that we changed the status to capture. Some payment can receive
# asynchronous webhook with update status
@@ -520,6 +521,7 @@ class OrderVoid(BaseMutation):
gateway.void,
payment,
info.context.plugins,
+ channel_slug=order.channel.slug,
)
# Confirm that we changed the status to void. Some payment can receive
# asynchronous webhook with update status
@@ -566,7 +568,8 @@ class OrderRefund(BaseMutation):
gateway.refund,
payment,
info.context.plugins,
- amount,
+ amount=amount,
+ channel_slug=order.channel.slug,
)
# Confirm that we changed the status to refund. Some payment can receive
@@ -624,8 +627,16 @@ class OrderConfirm(ModelMutation):
payment = order.get_last_payment()
manager = info.context.plugins
if payment and payment.is_authorized and payment.can_capture():
- gateway.capture(payment, info.context.plugins)
- order_captured(order, info.context.user, payment.total, payment, manager)
+ gateway.capture(
+ payment, info.context.plugins, channel_slug=order.channel.slug
+ )
+ order_captured(
+ order,
+ info.context.user,
+ payment.total,
+ payment,
+ manager,
+ )
order_confirmed(order, info.context.user, manager, send_confirmation_email=True)
return OrderConfirm(order=order)
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index e7323d75ae..db706e3118 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -759,7 +759,9 @@ def test_order_available_shipping_methods_query(
order_data = content["data"]["orders"]["edges"][0]["node"]
method = order_data["availableShippingMethods"][0]
- apply_taxes_to_shipping_mock.assert_called_once_with(shipping_price, ANY)
+ apply_taxes_to_shipping_mock.assert_called_once_with(
+ shipping_price, ANY, fulfilled_order.channel.slug
+ )
assert expected_price == method["price"]["amount"]
@@ -885,7 +887,9 @@ def test_order_confirm(
parameters__amount=payment_txn_preauth.get_total().amount,
).exists()
- capture_mock.assert_called_once_with(payment_txn_preauth, ANY)
+ capture_mock.assert_called_once_with(
+ payment_txn_preauth, ANY, channel_slug=order_unconfirmed.channel.slug
+ )
expected_payload = {
"order": get_default_order_payload(order_unconfirmed, ""),
"recipient_email": order_unconfirmed.user.email,
@@ -894,7 +898,9 @@ def test_order_confirm(
"domain": "mirumee.com",
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ORDER_CONFIRMED, expected_payload
+ NotifyEventType.ORDER_CONFIRMED,
+ expected_payload,
+ channel_slug=order_unconfirmed.channel.slug,
)
@@ -3690,6 +3696,7 @@ def test_order_cancel_as_app(
@mock.patch("saleor.plugins.manager.PluginsManager.notify")
def test_order_capture(
mocked_notify,
+ channel_USD,
staff_api_client,
permission_manage_orders,
payment_txn_preauth,
@@ -3755,7 +3762,9 @@ def test_order_capture(
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ORDER_PAYMENT_CONFIRMATION, expected_payment_payload
+ NotifyEventType.ORDER_PAYMENT_CONFIRMATION,
+ expected_payment_payload,
+ channel_slug=order.channel.slug,
)
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 43a508eec3..06c23e285b 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -1020,6 +1020,7 @@ class Order(CountableDjangoObjectType):
available_shipping_methods = []
manager = info.context.plugins
display_gross = display_gross_prices()
+ channel_slug = root.channel.slug
for shipping_method in available:
# Ignore typing check because it is checked in
# get_valid_shipping_methods_for_order
@@ -1030,13 +1031,13 @@ class Order(CountableDjangoObjectType):
taxed_price = manager.apply_taxes_to_shipping(
shipping_channel_listing.price,
root.shipping_address, # type: ignore
+ channel_slug,
)
if display_gross:
shipping_method.price = taxed_price.gross
else:
shipping_method.price = taxed_price.net
available_shipping_methods.append(shipping_method)
- channel_slug = root.channel.slug
instances = [
ChannelContext(node=shipping, channel_slug=channel_slug)
for shipping in available_shipping_methods
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 7c78adce20..2231503b3a 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -1,6 +1,7 @@
import graphene
from django.core.exceptions import ValidationError
+from ...channel.models import Channel
from ...checkout.calculations import calculate_checkout_total_with_gift_cards
from ...checkout.checkout_cleaner import clean_billing_address, clean_checkout_shipping
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
@@ -91,9 +92,9 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
)
@classmethod
- def validate_token(cls, manager, gateway: str, input_data: dict):
+ def validate_token(cls, manager, gateway: str, input_data: dict, channel_slug: str):
token = input_data.get("token")
- is_required = manager.token_is_required_as_payment_input(gateway)
+ is_required = manager.token_is_required_as_payment_input(gateway, channel_slug)
if not token and is_required:
raise ValidationError(
{
@@ -126,13 +127,17 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
manager = info.context.plugins
cls.validate_gateway(manager, gateway, checkout.currency)
- cls.validate_token(manager, gateway, data)
cls.validate_return_url(data)
lines = fetch_checkout_lines(checkout)
checkout_info = fetch_checkout_info(
checkout, lines, info.context.discounts, manager
)
+
+ cls.validate_token(
+ manager, gateway, data, channel_slug=checkout_info.channel.slug
+ )
+
address = (
checkout.shipping_address or checkout.billing_address
) # FIXME: check which address we need here
@@ -186,8 +191,15 @@ class PaymentCapture(BaseMutation):
payment = cls.get_node_or_error(
info, payment_id, field="payment_id", only_type=Payment
)
+ channel_slug = (
+ payment.order.channel.slug
+ if payment.order
+ else payment.checkout.channel.slug
+ )
try:
- gateway.capture(payment, info.context.plugins, amount)
+ gateway.capture(
+ payment, info.context.plugins, amount=amount, channel_slug=channel_slug
+ )
payment.refresh_from_db()
except PaymentError as e:
raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR)
@@ -206,8 +218,15 @@ class PaymentRefund(PaymentCapture):
payment = cls.get_node_or_error(
info, payment_id, field="payment_id", only_type=Payment
)
+ channel_slug = (
+ payment.order.channel.slug
+ if payment.order
+ else payment.checkout.channel.slug
+ )
try:
- gateway.refund(payment, info.context.plugins, amount=amount)
+ gateway.refund(
+ payment, info.context.plugins, amount=amount, channel_slug=channel_slug
+ )
payment.refresh_from_db()
except PaymentError as e:
raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR)
@@ -231,8 +250,13 @@ class PaymentVoid(BaseMutation):
payment = cls.get_node_or_error(
info, payment_id, field="payment_id", only_type=Payment
)
+ channel_slug = (
+ payment.order.channel.slug
+ if payment.order
+ else payment.checkout.channel.slug
+ )
try:
- gateway.void(payment, info.context.plugins)
+ gateway.void(payment, info.context.plugins, channel_slug=channel_slug)
payment.refresh_from_db()
except PaymentError as e:
raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR)
@@ -247,6 +271,9 @@ class PaymentInitialize(BaseMutation):
description="A gateway name used to initialize the payment.",
required=True,
)
+ channel = graphene.String(
+ description="Slug of a channel for which the data should be returned.",
+ )
payment_data = graphene.JSONString(
required=False,
description=(
@@ -260,9 +287,37 @@ class PaymentInitialize(BaseMutation):
error_type_field = "payment_errors"
@classmethod
- def perform_mutation(cls, _root, info, gateway, payment_data):
+ def validate_channel(cls, channel_slug):
+ try:
+ channel = Channel.objects.get(slug=channel_slug)
+ except Channel.DoesNotExist:
+ raise ValidationError(
+ {
+ "channel": ValidationError(
+ f"Channel with '{channel_slug}' slug does not exist.",
+ code=PaymentErrorCode.NOT_FOUND.value,
+ )
+ }
+ )
+ if not channel.is_active:
+ raise ValidationError(
+ {
+ "channel": ValidationError(
+ f"Channel with '{channel_slug}' is inactive.",
+ code=PaymentErrorCode.CHANNEL_INACTIVE.value,
+ )
+ }
+ )
+ return channel
+
+ @classmethod
+ def perform_mutation(cls, _root, info, gateway, channel, payment_data):
+ cls.validate_channel(channel_slug=channel)
+
try:
- response = info.context.plugins.initialize_payment(gateway, payment_data)
+ response = info.context.plugins.initialize_payment(
+ gateway, payment_data, channel_slug=channel
+ )
except PaymentError as e:
raise ValidationError(
{
diff --git a/saleor/graphql/payment/tests/test_payment.py b/saleor/graphql/payment/tests/test_payment.py
index 455b59ddb0..849aea5d59 100644
--- a/saleor/graphql/payment/tests/test_payment.py
+++ b/saleor/graphql/payment/tests/test_payment.py
@@ -875,7 +875,7 @@ def set_dummy_customer_id(customer_user, dummy_customer_id):
def test_list_payment_sources(
- mocker, dummy_customer_id, set_dummy_customer_id, user_api_client
+ mocker, dummy_customer_id, set_dummy_customer_id, user_api_client, channel_USD
):
gateway = DUMMY_GATEWAY
query = """
@@ -899,7 +899,7 @@ def test_list_payment_sources(
)
response = user_api_client.post_graphql(query)
- mock_get_source_list.assert_called_once_with(gateway, dummy_customer_id, ANY)
+ mock_get_source_list.assert_called_once_with(gateway, dummy_customer_id, ANY, None)
content = get_graphql_content(response)["data"]["me"]["storedPaymentSources"]
assert content is not None and len(content) == 1
assert content[0] == {"gateway": gateway, "creditCardInfo": {"lastDigits": "5678"}}
@@ -937,8 +937,9 @@ def test_stored_payment_sources_restriction(
PAYMENT_INITIALIZE_MUTATION = """
-mutation PaymentInitialize($gateway: String!, $paymentData: JSONString){
- paymentInitialize(gateway: $gateway, paymentData: $paymentData)
+mutation PaymentInitialize(
+ $gateway: String!,$channel: String!, $paymentData: JSONString){
+ paymentInitialize(gateway: $gateway, channel: $channel, paymentData: $paymentData)
{
initializedPayment{
gateway
@@ -955,7 +956,7 @@ mutation PaymentInitialize($gateway: String!, $paymentData: JSONString){
@patch.object(PluginsManager, "initialize_payment")
-def test_payment_initialize(mocked_initialize_payment, api_client):
+def test_payment_initialize(mocked_initialize_payment, api_client, channel_USD):
exected_initialize_payment_response = InitializedPaymentResponse(
gateway="gateway.id",
name="PaymentPluginName",
@@ -970,6 +971,7 @@ def test_payment_initialize(mocked_initialize_payment, api_client):
query = PAYMENT_INITIALIZE_MUTATION
variables = {
"gateway": exected_initialize_payment_response.gateway,
+ "channel": channel_USD.slug,
"paymentData": json.dumps(
{"paymentMethod": "applepay", "validationUrl": "https://127.0.0.1/valid"}
),
@@ -985,10 +987,11 @@ def test_payment_initialize(mocked_initialize_payment, api_client):
)
-def test_payment_initialize_gateway_doesnt_exist(api_client):
+def test_payment_initialize_gateway_doesnt_exist(api_client, channel_USD):
query = PAYMENT_INITIALIZE_MUTATION
variables = {
"gateway": "wrong.gateway",
+ "channel": channel_USD.slug,
"paymentData": json.dumps(
{"paymentMethod": "applepay", "validationUrl": "https://127.0.0.1/valid"}
),
@@ -999,13 +1002,16 @@ def test_payment_initialize_gateway_doesnt_exist(api_client):
@patch.object(PluginsManager, "initialize_payment")
-def test_payment_initialize_plugin_raises_error(mocked_initialize_payment, api_client):
+def test_payment_initialize_plugin_raises_error(
+ mocked_initialize_payment, api_client, channel_USD
+):
error_msg = "Missing paymentMethod field."
mocked_initialize_payment.side_effect = PaymentError(error_msg)
query = PAYMENT_INITIALIZE_MUTATION
variables = {
"gateway": "gateway.id",
+ "channel": channel_USD.slug,
"paymentData": json.dumps({"validationUrl": "https://127.0.0.1/valid"}),
}
response = api_client.post_graphql(query, variables)
diff --git a/saleor/graphql/plugins/enums.py b/saleor/graphql/plugins/enums.py
index f6b2510cae..3891334004 100644
--- a/saleor/graphql/plugins/enums.py
+++ b/saleor/graphql/plugins/enums.py
@@ -1,4 +1,11 @@
+import graphene
+
from ...graphql.core.enums import to_enum
from ...plugins.base_plugin import ConfigurationTypeField
ConfigurationTypeFieldEnum = to_enum(ConfigurationTypeField)
+
+
+class PluginConfigurationType(graphene.Enum):
+ PER_CHANNEL = "per_channel"
+ GLOBAL = "global"
diff --git a/saleor/graphql/plugins/filters.py b/saleor/graphql/plugins/filters.py
index 36c57bba7f..317fa11e23 100644
--- a/saleor/graphql/plugins/filters.py
+++ b/saleor/graphql/plugins/filters.py
@@ -1,16 +1,48 @@
-from typing import TYPE_CHECKING, List, Optional
+from typing import List, Optional
import graphene
-if TYPE_CHECKING:
- # flake8: noqa
- from ...plugins.base_plugin import BasePlugin
+from ..channel.types import Channel
+from ..utils import get_nodes
+from .enums import PluginConfigurationType
+from .types import Plugin
-def filter_plugin_search(
- plugins: List["BasePlugin"], value: Optional[str]
-) -> List["BasePlugin"]:
- plugin_fields = ["PLUGIN_NAME", "PLUGIN_DESCRIPTION"]
+def filter_plugin_status_in_channels(
+ plugins: List[Plugin], status_in_channels: dict
+) -> List[Plugin]:
+ is_active = status_in_channels["active"]
+ channels_id = status_in_channels["channels"]
+ channels = get_nodes(channels_id, Channel)
+
+ filtered_plugins = []
+ for plugin in plugins:
+ if plugin.global_configuration:
+ if plugin.global_configuration.active is is_active:
+ filtered_plugins.append(plugin)
+ else:
+ for channel in channels:
+ if any(
+ [
+ (config.channel.id == channel.id and config.active is is_active)
+ for config in plugin.channel_configurations
+ ]
+ ):
+ filtered_plugins.append(plugin)
+ break
+ return filtered_plugins
+
+
+def filter_plugin_by_type(plugins: List[Plugin], type):
+ if type == PluginConfigurationType.GLOBAL:
+ plugins = [plugin for plugin in plugins if plugin.global_configuration]
+ else:
+ plugins = [plugin for plugin in plugins if not plugin.global_configuration]
+ return plugins
+
+
+def filter_plugin_search(plugins: List[Plugin], value: Optional[str]) -> List[Plugin]:
+ plugin_fields = ["name", "description"]
if value is not None:
return [
plugin
@@ -25,6 +57,14 @@ def filter_plugin_search(
return plugins
+class PluginStatusInChannelsInput(graphene.InputObjectType):
+ active = graphene.Argument(graphene.Boolean, required=True)
+ channels = graphene.Argument(
+ graphene.List(graphene.NonNull(graphene.ID)), required=True
+ )
+
+
class PluginFilterInput(graphene.InputObjectType):
- active = graphene.Argument(graphene.Boolean)
+ status_in_channels = graphene.Argument(PluginStatusInChannelsInput)
search = graphene.Argument(graphene.String)
+ type = graphene.Argument(PluginConfigurationType)
diff --git a/saleor/graphql/plugins/mutations.py b/saleor/graphql/plugins/mutations.py
index 6208561a41..524fcda012 100644
--- a/saleor/graphql/plugins/mutations.py
+++ b/saleor/graphql/plugins/mutations.py
@@ -3,8 +3,10 @@ from django.core.exceptions import ValidationError
from ...core.permissions import PluginsPermissions
from ...plugins.error_codes import PluginErrorCode
+from ..channel.types import Channel
from ..core.mutations import BaseMutation
from ..core.types.common import PluginError
+from .resolvers import resolve_plugin
from .types import Plugin
@@ -31,6 +33,10 @@ class PluginUpdate(BaseMutation):
class Arguments:
id = graphene.ID(required=True, description="ID of plugin to update.")
+ channel = graphene.ID(
+ required=False,
+ description="ID of a channel for which the data should be modified.",
+ )
input = PluginUpdateInput(
description="Fields required to update a plugin configuration.",
required=True,
@@ -43,18 +49,53 @@ class PluginUpdate(BaseMutation):
error_type_field = "plugins_errors"
@classmethod
- def perform_mutation(cls, root, info, **data):
+ def clean_input(cls, info, data):
plugin_id = data.get("id")
- data = data.get("input")
+ channel_id = data.get("channel")
+ channel = None
+ if channel_id:
+ channel = cls.get_node_or_error(info, channel_id, only_type=Channel)
+
+ channel_slug = channel.slug if channel_id else None
+ input_data = data.get("input")
+
manager = info.context.plugins
- plugin = manager.get_plugin(plugin_id)
+ plugin = manager.get_plugin(plugin_id, channel_slug)
if not plugin:
raise ValidationError(
{
"id": ValidationError(
- "Plugin doesn't exist", code=PluginErrorCode.NOT_FOUND
+ "Plugin doesn't exist.", code=PluginErrorCode.NOT_FOUND.value
+ )
+ }
+ )
+
+ if plugin in manager.global_plugins and channel_id:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Plugin doesn't support configuration per channel.",
+ code=PluginErrorCode.INVALID.value,
)
}
)
- instance = manager.save_plugin_configuration(plugin_id, data)
- return PluginUpdate(plugin=instance)
+ elif plugin not in manager.global_plugins and not channel_id:
+ raise ValidationError(
+ {
+ "id": ValidationError(
+ "Plugin requires to specify channel slug.",
+ code=PluginErrorCode.NOT_FOUND.value,
+ )
+ }
+ )
+ return {"plugin": plugin, "data": input_data, "channel_slug": channel_slug}
+
+ @classmethod
+ def perform_mutation(cls, root, info, **data):
+ cleaned_data = cls.clean_input(info, data)
+ plugin_id = cleaned_data["plugin"].PLUGIN_ID
+ channel_slug = cleaned_data["channel_slug"]
+ input_data = cleaned_data["data"]
+ manager = info.context.plugins
+ manager.save_plugin_configuration(plugin_id, channel_slug, input_data)
+ return PluginUpdate(plugin=resolve_plugin(plugin_id, manager))
diff --git a/saleor/graphql/plugins/resolvers.py b/saleor/graphql/plugins/resolvers.py
index 8413fc9ff8..82863428cc 100644
--- a/saleor/graphql/plugins/resolvers.py
+++ b/saleor/graphql/plugins/resolvers.py
@@ -1,46 +1,107 @@
-from ...core.tracing import traced_resolver
-from ...plugins.base_plugin import BasePlugin
-from ...plugins.models import PluginConfiguration
-from .filters import filter_plugin_search
+from collections import defaultdict
+from typing import Dict, List, Tuple
+
+from ...plugins.base_plugin import BasePlugin, ConfigurationTypeField
+from .filters import (
+ filter_plugin_by_type,
+ filter_plugin_search,
+ filter_plugin_status_in_channels,
+)
from .sorters import sort_plugins
+from .types import Plugin
+
+
+def hide_private_configuration_fields(configuration, config_structure):
+ if not config_structure:
+ return
+
+ for field in configuration:
+ name = field["name"]
+ value = field["value"]
+ if value is None:
+ continue
+ field_type = config_structure.get(name, {}).get("type")
+ if field_type == ConfigurationTypeField.PASSWORD:
+ field["value"] = "" if value else None
+
+ if field_type in [
+ ConfigurationTypeField.SECRET,
+ ConfigurationTypeField.SECRET_MULTILINE,
+ ]:
+ if not value:
+ field["value"] = None
+ elif len(value) > 4:
+ field["value"] = value[-4:]
+ else:
+ field["value"] = value[-1:]
-@traced_resolver
-def resolve_plugin(info, plugin_id, manager):
+def aggregate_plugins_configuration(
+ manager,
+) -> Tuple[Dict[str, BasePlugin], Dict[str, List[BasePlugin]]]:
+ plugins_per_channel: Dict[str, List[BasePlugin]] = defaultdict(list)
+ global_plugins: Dict[str, BasePlugin] = {}
+
+ for plugin in manager.all_plugins:
+ hide_private_configuration_fields(plugin.configuration, plugin.CONFIG_STRUCTURE)
+ if not getattr(plugin, "CONFIGURATION_PER_CHANNEL", False):
+ global_plugins[plugin.PLUGIN_ID] = plugin
+ else:
+ plugins_per_channel[plugin.PLUGIN_ID].append(plugin)
+ return global_plugins, plugins_per_channel
+
+
+def resolve_plugin(plugin_id, manager):
+ global_plugins, plugins_per_channel = aggregate_plugins_configuration(manager)
plugin: BasePlugin = manager.get_plugin(plugin_id)
if not plugin:
return None
- return PluginConfiguration(
+
+ return Plugin(
id=plugin.PLUGIN_ID,
- identifier=plugin.PLUGIN_ID,
- active=plugin.active,
- configuration=plugin.configuration,
+ global_configuration=global_plugins.get(plugin.PLUGIN_ID),
+ channel_configurations=plugins_per_channel.get(plugin.PLUGIN_ID),
description=plugin.PLUGIN_DESCRIPTION,
name=plugin.PLUGIN_NAME,
)
def resolve_plugins(manager, sort_by=None, **kwargs):
+ global_plugins, plugins_per_channel = aggregate_plugins_configuration(manager)
plugin_filter = kwargs.get("filter", {})
search_query = plugin_filter.get("search")
- filter_active = plugin_filter.get("active")
-
- plugins = manager.plugins
+ filter_status_in_channel = plugin_filter.get("status_in_channels")
+ filter_plugin_type = plugin_filter.get("type")
- if filter_active is not None:
- plugins = [plugin for plugin in plugins if plugin.active is filter_active]
-
- plugins = filter_plugin_search(plugins, search_query)
- plugins = sort_plugins(plugins, sort_by)
-
- return [
- PluginConfiguration(
+ plugins = [
+ Plugin(
id=plugin.PLUGIN_ID,
- identifier=plugin.PLUGIN_ID,
- active=plugin.active,
- configuration=plugin.configuration,
+ global_configuration=plugin,
+ channel_configurations=None,
description=plugin.PLUGIN_DESCRIPTION,
name=plugin.PLUGIN_NAME,
)
- for plugin in plugins
+ for plugin_id, plugin in global_plugins.items()
]
+
+ plugins.extend(
+ [
+ Plugin(
+ id=plugin_id,
+ global_configuration=None,
+ channel_configurations=plugins,
+ description=plugins[0].PLUGIN_DESCRIPTION,
+ name=plugins[0].PLUGIN_NAME,
+ )
+ for plugin_id, plugins in plugins_per_channel.items()
+ ]
+ )
+
+ if filter_status_in_channel is not None:
+ plugins = filter_plugin_status_in_channels(plugins, filter_status_in_channel)
+ if filter_plugin_type is not None:
+ plugins = filter_plugin_by_type(plugins, filter_plugin_type)
+ plugins = filter_plugin_search(plugins, search_query)
+ plugins = sort_plugins(plugins, sort_by)
+
+ return plugins
diff --git a/saleor/graphql/plugins/schema.py b/saleor/graphql/plugins/schema.py
index f9132b851f..815663afbd 100644
--- a/saleor/graphql/plugins/schema.py
+++ b/saleor/graphql/plugins/schema.py
@@ -2,13 +2,13 @@ import graphene
from ...core.permissions import PluginsPermissions
from ...core.tracing import traced_resolver
-from ..core.fields import BaseDjangoConnectionField
+from ..core.fields import BaseConnectionField
from ..decorators import permission_required
from .filters import PluginFilterInput
from .mutations import PluginUpdate
from .resolvers import resolve_plugin, resolve_plugins
from .sorters import PluginSortingInput
-from .types import Plugin
+from .types import Plugin, PluginCountableConnection
class PluginsQueries(graphene.ObjectType):
@@ -19,16 +19,18 @@ class PluginsQueries(graphene.ObjectType):
),
description="Look up a plugin by ID.",
)
- plugins = BaseDjangoConnectionField(
- Plugin,
+
+ plugins = BaseConnectionField(
+ PluginCountableConnection,
filter=PluginFilterInput(description="Filtering options for plugins."),
sort_by=PluginSortingInput(description="Sort plugins."),
description="List of plugins.",
)
@permission_required(PluginsPermissions.MANAGE_PLUGINS)
+ @traced_resolver
def resolve_plugin(self, info, **data):
- return resolve_plugin(info, data.get("id"), info.context.plugins)
+ return resolve_plugin(data.get("id"), info.context.plugins)
@permission_required(PluginsPermissions.MANAGE_PLUGINS)
@traced_resolver
diff --git a/saleor/graphql/plugins/sorters.py b/saleor/graphql/plugins/sorters.py
index 07578041a1..0e630ff319 100644
--- a/saleor/graphql/plugins/sorters.py
+++ b/saleor/graphql/plugins/sorters.py
@@ -1,30 +1,43 @@
-from typing import TYPE_CHECKING, List, Optional
+from typing import List, Optional
import graphene
+from ..core.enums import OrderDirection
from ..core.types import SortInputObjectType
+from .types import Plugin
-if TYPE_CHECKING:
- # flake8: noqa
- from ...plugins.base_plugin import BasePlugin
+
+def sort_active_key(plugin: Plugin, sort_reverse: bool):
+ if plugin.global_configuration:
+ active = plugin.global_configuration.active
+ name = plugin.name
+ else:
+ active = False
+ if any(
+ [configuration.active for configuration in plugin.channel_configurations]
+ ):
+ active = True
+ name = plugin.name
+ return not active if sort_reverse else active, name
-def sort_plugins(
- plugins: List["BasePlugin"], sort_by: Optional[dict]
-) -> List["BasePlugin"]:
- sort_reverse = sort_by.get("direction", False) if sort_by else False
+def sort_plugins(plugins: List["Plugin"], sort_by: Optional[dict]) -> List["Plugin"]:
+ sort_reverse = False
+ direction = sort_by.get("direction", OrderDirection.ASC) if sort_by else None
+ if direction == OrderDirection.DESC:
+ sort_reverse = True
+
sort_field = (
sort_by.get("field", PluginSortField.NAME) if sort_by else PluginSortField.NAME
)
+
if sort_field == PluginSortField.IS_ACTIVE:
plugins = sorted(
plugins,
- key=lambda p: (not p.active if sort_reverse else p.active, p.PLUGIN_ID),
+ key=lambda p: sort_active_key(p, sort_reverse),
)
else:
- plugins = sorted(plugins, key=lambda p: p.PLUGIN_ID)
- if sort_reverse:
- plugins = list(reversed(plugins))
+ plugins = sorted(plugins, key=lambda p: p.name, reverse=sort_reverse)
return plugins
diff --git a/saleor/graphql/plugins/tests/conftest.py b/saleor/graphql/plugins/tests/conftest.py
new file mode 100644
index 0000000000..e31f2578de
--- /dev/null
+++ b/saleor/graphql/plugins/tests/conftest.py
@@ -0,0 +1,7 @@
+import pytest
+
+
+def staff_api_client_can_manage_plugins(staff_api_client, permission_manage_plugins):
+ staff_api_client.user.user_permissions.add(permission_manage_plugins)
+ return staff_api_client
diff --git a/saleor/graphql/plugins/tests/queries/__init__.py b/saleor/graphql/plugins/tests/queries/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/plugins/tests/queries/test_plugin.py b/saleor/graphql/plugins/tests/queries/test_plugin.py
new file mode 100644
index 0000000000..678ae91288
--- /dev/null
+++ b/saleor/graphql/plugins/tests/queries/test_plugin.py
@@ -0,0 +1,251 @@
+import copy
+
+import pytest
+
+from .....plugins.manager import get_plugins_manager
+from .....plugins.tests.sample_plugins import ChannelPluginSample, PluginSample
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+PLUGIN_QUERY = """
+ query plugin($id: ID!){
+ plugin(id:$id){
+ id
+ name
+ description
+ globalConfiguration{
+ active
+ configuration{
+ name
+ value
+ helpText
+ type
+ label
+ }
+ channel{
+ id
+ slug
+ }
+ }
+ channelConfigurations{
+ active
+ channel{
+ id
+ slug
+ }
+ configuration{
+ name
+ value
+ helpText
+ type
+ label
+ }
+ }
+ }
+ }
+"""
+
+
+ "password, expected_password, api_key, expected_api_key",
+ [
+ (None, None, None, None),
+ ("ABCDEFGHIJ", "", "123456789", "6789"),
+ ("", None, "", None),
+ (None, None, "1234", "4"),
+ ],
+)
+def test_query_plugin_hides_secret_fields(
+ password,
+ expected_password,
+ api_key,
+ expected_api_key,
+ staff_api_client,
+ permission_manage_plugins,
+ settings,
+):
+
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
+ manager = get_plugins_manager()
+ plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
+ configuration = copy.deepcopy(plugin.configuration)
+ for conf_field in configuration:
+ if conf_field["name"] == "Password":
+ conf_field["value"] = password
+ if conf_field["name"] == "API private key":
+ conf_field["value"] = api_key
+ manager.save_plugin_configuration(
+ PluginSample.PLUGIN_ID,
+ None,
+ {
+ "active": True,
+ "configuration": configuration,
+ "name": PluginSample.PLUGIN_NAME,
+ },
+ )
+
+ variables = {"id": plugin.PLUGIN_ID}
+ staff_api_client.user.user_permissions.add(permission_manage_plugins)
+ response = staff_api_client.post_graphql(PLUGIN_QUERY, variables)
+ content = get_graphql_content(response)
+
+ plugin = content["data"]["plugin"]
+
+ for conf_field in plugin["globalConfiguration"]["configuration"]:
+ if conf_field["name"] == "Password":
+ assert conf_field["value"] == expected_password
+ if conf_field["name"] == "API private key":
+ assert conf_field["value"] == expected_api_key
+
+
+ "password, expected_password, api_key, expected_api_key",
+ [
+ (None, None, None, None),
+ ("ABCDEFGHIJ", "", "123456789", "6789"),
+ ("", None, "", None),
+ (None, None, "1234", "4"),
+ ],
+)
+def test_query_plugin_hides_secret_fields_for_channel_configurations(
+ password,
+ expected_password,
+ api_key,
+ expected_api_key,
+ staff_api_client,
+ permission_manage_plugins,
+ settings,
+ channel_PLN,
+):
+
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.ChannelPluginSample"]
+ manager = get_plugins_manager()
+
+ plugin = manager.get_plugin(
+ ChannelPluginSample.PLUGIN_ID, channel_slug=channel_PLN.slug
+ )
+ configuration = copy.deepcopy(plugin.configuration)
+ for conf_field in configuration:
+ if conf_field["name"] == "Password":
+ conf_field["value"] = password
+ if conf_field["name"] == "API private key":
+ conf_field["value"] = api_key
+
+ manager.save_plugin_configuration(
+ PluginSample.PLUGIN_ID,
+ channel_PLN.slug,
+ {
+ "active": True,
+ "configuration": configuration,
+ "name": PluginSample.PLUGIN_NAME,
+ },
+ )
+
+ variables = {"id": plugin.PLUGIN_ID}
+ staff_api_client.user.user_permissions.add(permission_manage_plugins)
+ response = staff_api_client.post_graphql(PLUGIN_QUERY, variables)
+ content = get_graphql_content(response)
+
+ plugin = content["data"]["plugin"]
+
+ assert not plugin["globalConfiguration"]
+ assert len(plugin["channelConfigurations"]) == 1
+ for conf_field in plugin["channelConfigurations"][0]["configuration"]:
+ if conf_field["name"] == "Password":
+ assert conf_field["value"] == expected_password
+ if conf_field["name"] == "API private key":
+ assert conf_field["value"] == expected_api_key
+
+
+def test_query_plugin_configuration(
+ staff_api_client, permission_manage_plugins, settings
+):
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
+ manager = get_plugins_manager()
+ sample_plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
+
+ variables = {"id": sample_plugin.PLUGIN_ID}
+ staff_api_client.user.user_permissions.add(permission_manage_plugins)
+ response = staff_api_client.post_graphql(PLUGIN_QUERY, variables)
+ content = get_graphql_content(response)
+ plugin = content["data"]["plugin"]
+ assert plugin["name"] == sample_plugin.PLUGIN_NAME
+ assert plugin["id"] == sample_plugin.PLUGIN_ID
+ assert plugin["description"] == sample_plugin.PLUGIN_DESCRIPTION
+
+ assert plugin["globalConfiguration"]["active"] == sample_plugin.active
+ configuration_item = plugin["globalConfiguration"]["configuration"][0]
+ assert configuration_item["name"] == sample_plugin.configuration[0]["name"]
+ assert configuration_item["value"] == sample_plugin.configuration[0]["value"]
+
+
+def test_query_plugin_configuration_for_channel_configurations(
+ staff_api_client, permission_manage_plugins, settings, channel_PLN
+):
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.ChannelPluginSample"]
+ manager = get_plugins_manager()
+ sample_plugin = manager.get_plugin(
+ ChannelPluginSample.PLUGIN_ID, channel_slug=channel_PLN.slug
+ )
+
+ variables = {"id": sample_plugin.PLUGIN_ID}
+ staff_api_client.user.user_permissions.add(permission_manage_plugins)
+ response = staff_api_client.post_graphql(PLUGIN_QUERY, variables)
+ content = get_graphql_content(response)
+ plugin = content["data"]["plugin"]
+ assert plugin["name"] == sample_plugin.PLUGIN_NAME
+ assert plugin["id"] == sample_plugin.PLUGIN_ID
+ assert plugin["description"] == sample_plugin.PLUGIN_DESCRIPTION
+
+ assert not plugin["globalConfiguration"]
+ assert len(plugin["channelConfigurations"]) == 1
+ channel_configuration = plugin["channelConfigurations"][0]
+ assert channel_configuration["active"] == sample_plugin.active
+ assert len(channel_configuration["configuration"]) == 1
+ configuration_item = channel_configuration["configuration"][0]
+ assert configuration_item["name"] == sample_plugin.configuration[0]["name"]
+ assert configuration_item["value"] == sample_plugin.configuration[0]["value"]
+
+
+def test_query_plugin_configuration_for_multiple_channels(
+ staff_api_client, permission_manage_plugins, settings, channel_PLN, channel_USD
+):
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.ChannelPluginSample"]
+
+ variables = {"id": ChannelPluginSample.PLUGIN_ID}
+ staff_api_client.user.user_permissions.add(permission_manage_plugins)
+ response = staff_api_client.post_graphql(PLUGIN_QUERY, variables)
+ content = get_graphql_content(response)
+ plugin = content["data"]["plugin"]
+ assert plugin["name"] == ChannelPluginSample.PLUGIN_NAME
+ assert plugin["id"] == ChannelPluginSample.PLUGIN_ID
+ assert plugin["description"] == ChannelPluginSample.PLUGIN_DESCRIPTION
+
+ assert not plugin["globalConfiguration"]
+ assert len(plugin["channelConfigurations"]) == 2
+ for channel_configuration in plugin["channelConfigurations"]:
+ assert channel_configuration["active"] == ChannelPluginSample.DEFAULT_ACTIVE
+ assert channel_configuration["channel"]["slug"] in [
+ channel_USD.slug,
+ channel_PLN.slug,
+ ]
+
+
+def test_query_plugin_configuration_for_invalid_plugin_name(
+ staff_api_client, permission_manage_plugins
+):
+ variables = {"id": "fake-name"}
+ staff_api_client.user.user_permissions.add(permission_manage_plugins)
+ response = staff_api_client.post_graphql(PLUGIN_QUERY, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["plugin"] is None
+
+
+def test_query_plugin_configuration_as_customer_user(user_api_client, settings):
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
+ manager = get_plugins_manager()
+ sample_plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
+
+ variables = {"id": sample_plugin.PLUGIN_ID}
+ response = user_api_client.post_graphql(PLUGIN_QUERY, variables)
+
+ assert_no_permission(response)
diff --git a/saleor/graphql/plugins/tests/queries/test_plugins.py b/saleor/graphql/plugins/tests/queries/test_plugins.py
new file mode 100644
index 0000000000..972438f63a
--- /dev/null
+++ b/saleor/graphql/plugins/tests/queries/test_plugins.py
@@ -0,0 +1,375 @@
+import copy
+
+import graphene
+import pytest
+
+from .....plugins.base_plugin import ConfigurationTypeField
+from .....plugins.manager import get_plugins_manager
+from .....plugins.tests.sample_plugins import ChannelPluginSample, PluginSample
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+PLUGINS_QUERY = """
+ {
+ plugins(first:1){
+ edges{
+ node{
+ name
+ description
+ id
+ globalConfiguration{
+ active
+ configuration{
+ name
+ value
+ helpText
+ type
+ label
+ }
+ }
+ channelConfigurations{
+ active
+ channel{
+ id
+ slug
+ }
+ configuration{
+ name
+ value
+ helpText
+ type
+ label
+ }
+ }
+ }
+ }
+ }
+ }
+"""
+
+
+def test_query_plugin_configurations(staff_api_client_can_manage_plugins, settings):
+
+ # Enable test plugin
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
+ response = staff_api_client_can_manage_plugins.post_graphql(PLUGINS_QUERY)
+ content = get_graphql_content(response)
+
+ plugins = content["data"]["plugins"]["edges"]
+
+ assert len(plugins) == 1
+ plugin = plugins[0]["node"]
+ manager = get_plugins_manager()
+ sample_plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
+ configuration_structure = PluginSample.CONFIG_STRUCTURE
+
+ assert plugin["id"] == sample_plugin.PLUGIN_ID
+ assert plugin["name"] == sample_plugin.PLUGIN_NAME
+ assert plugin["description"] == sample_plugin.PLUGIN_DESCRIPTION
+
+ assert plugin["globalConfiguration"]["active"] == sample_plugin.DEFAULT_ACTIVE
+ configuration = plugin["globalConfiguration"]["configuration"]
+ for index, configuration_item in enumerate(configuration):
+ assert configuration_item["name"] == sample_plugin.configuration[index]["name"]
+
+ if (
+ configuration_structure[configuration_item["name"]]["type"]
+ == ConfigurationTypeField.STRING
+ ):
+ assert (
+ configuration_item["value"]
+ == sample_plugin.configuration[index]["value"]
+ )
+ elif configuration_item["value"] is None:
+ assert not sample_plugin.configuration[index]["value"]
+ else:
+ assert (
+ configuration_item["value"]
+ == str(sample_plugin.configuration[index]["value"]).lower()
+ )
+
+
+def test_query_plugin_configurations_for_channel_configurations(
+ staff_api_client_can_manage_plugins, settings, channel_PLN
+):
+
+ # Enable test plugin
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.ChannelPluginSample"]
+
+ response = staff_api_client_can_manage_plugins.post_graphql(PLUGINS_QUERY)
+ content = get_graphql_content(response)
+
+ plugins = content["data"]["plugins"]["edges"]
+
+ assert len(plugins) == 1
+ plugin = plugins[0]["node"]
+ manager = get_plugins_manager()
+ sample_plugin = manager.get_plugin(
+ ChannelPluginSample.PLUGIN_ID, channel_slug=channel_PLN.slug
+ )
+ confiugration_structure = ChannelPluginSample.CONFIG_STRUCTURE
+
+ assert plugin["id"] == sample_plugin.PLUGIN_ID
+ assert plugin["name"] == sample_plugin.PLUGIN_NAME
+ assert plugin["description"] == sample_plugin.PLUGIN_DESCRIPTION
+
+ assert not plugin["globalConfiguration"]
+
+ assert len(plugin["channelConfigurations"]) == 1
+
+ assert plugin["channelConfigurations"][0]["active"] == sample_plugin.DEFAULT_ACTIVE
+ configuration = plugin["channelConfigurations"][0]["configuration"]
+ for index, configuration_item in enumerate(configuration):
+ assert configuration_item["name"] == sample_plugin.configuration[index]["name"]
+
+ if (
+ confiugration_structure[configuration_item["name"]]["type"]
+ == ConfigurationTypeField.STRING
+ ):
+ assert (
+ configuration_item["value"]
+ == sample_plugin.configuration[index]["value"]
+ )
+ elif configuration_item["value"] is None:
+ assert not sample_plugin.configuration[index]["value"]
+ else:
+ assert (
+ configuration_item["value"]
+ == str(sample_plugin.configuration[index]["value"]).lower()
+ )
+
+
+ "password, expected_password, api_key, expected_api_key, cert, expected_cert",
+ [
+ (None, None, None, None, None, None),
+ ("ABCDEFGHIJ", "", "123456789", "6789", "long text\n with new\n lines", "ines"),
+ ("", None, "", None, "", None),
+ (None, None, "1234", "4", None, None),
+ ],
+)
+def test_query_plugins_hides_secret_fields(
+ password,
+ expected_password,
+ api_key,
+ expected_api_key,
+ cert,
+ expected_cert,
+ staff_api_client,
+ permission_manage_plugins,
+ settings,
+):
+
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
+ manager = get_plugins_manager()
+ plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
+ configuration = copy.deepcopy(plugin.configuration)
+ for conf_field in configuration:
+ if conf_field["name"] == "Password":
+ conf_field["value"] = password
+ if conf_field["name"] == "API private key":
+ conf_field["value"] = api_key
+ if conf_field["name"] == "certificate":
+ conf_field["value"] = cert
+ manager.save_plugin_configuration(
+ PluginSample.PLUGIN_ID,
+ None,
+ {
+ "active": True,
+ "configuration": configuration,
+ "name": PluginSample.PLUGIN_NAME,
+ },
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_plugins)
+ response = staff_api_client.post_graphql(PLUGINS_QUERY)
+ content = get_graphql_content(response)
+
+ plugins = content["data"]["plugins"]["edges"]
+ assert len(plugins) == 1
+ plugin = plugins[0]["node"]
+
+ for conf_field in plugin["globalConfiguration"]["configuration"]:
+ if conf_field["name"] == "Password":
+ assert conf_field["value"] == expected_password
+ if conf_field["name"] == "API private key":
+ assert conf_field["value"] == expected_api_key
+
+
+ "password, expected_password, api_key, expected_api_key, cert, expected_cert",
+ [
+ (None, None, None, None, None, None),
+ ("ABCDEFGHIJ", "", "123456789", "6789", "long text\n with new\n lines", "ines"),
+ ("", None, "", None, "", None),
+ (None, None, "1234", "4", None, None),
+ ],
+)
+def test_query_plugins_hides_secret_fields_for_channel_configurations(
+ password,
+ expected_password,
+ api_key,
+ expected_api_key,
+ cert,
+ expected_cert,
+ staff_api_client,
+ permission_manage_plugins,
+ settings,
+ channel_PLN,
+):
+
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.ChannelPluginSample"]
+ manager = get_plugins_manager()
+ plugin = manager.get_plugin(
+ ChannelPluginSample.PLUGIN_ID, channel_slug=channel_PLN.slug
+ )
+ configuration = copy.deepcopy(plugin.configuration)
+ for conf_field in configuration:
+ if conf_field["name"] == "Password":
+ conf_field["value"] = password
+ if conf_field["name"] == "API private key":
+ conf_field["value"] = api_key
+ if conf_field["name"] == "certificate":
+ conf_field["value"] = cert
+ manager.save_plugin_configuration(
+ ChannelPluginSample.PLUGIN_ID,
+ channel_PLN.slug,
+ {
+ "active": True,
+ "configuration": configuration,
+ "name": PluginSample.PLUGIN_NAME,
+ },
+ )
+
+ staff_api_client.user.user_permissions.add(permission_manage_plugins)
+ response = staff_api_client.post_graphql(PLUGINS_QUERY)
+ content = get_graphql_content(response)
+
+ plugins = content["data"]["plugins"]["edges"]
+ assert len(plugins) == 1
+ plugin = plugins[0]["node"]
+
+ assert not plugin["globalConfiguration"]
+
+ assert len(plugin["channelConfigurations"]) == 1
+
+ for conf_field in plugin["channelConfigurations"][0]["configuration"]:
+ if conf_field["name"] == "Password":
+ assert conf_field["value"] == expected_password
+ if conf_field["name"] == "API private key":
+ assert conf_field["value"] == expected_api_key
+
+
+def test_query_plugin_configurations_as_customer_user(user_api_client, settings):
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
+ response = user_api_client.post_graphql(PLUGINS_QUERY)
+
+ assert_no_permission(response)
+
+
+ "plugin_filter_fields, count",
+ [
+ ({"search": "PluginSample"}, 1),
+ ({"search": "description"}, 2),
+ ({"active": True}, 3),
+ ({"search": "Plugin"}, 3),
+ ({"active": False, "search": "Plugin"}, 1),
+ ({"type": "GLOBAL"}, 3),
+ ({"active": False, "type": "GLOBAL"}, 1),
+ ({"active": True, "type": "GLOBAL"}, 2),
+ ({"type": "PER_CHANNEL"}, 1),
+ ({"active": False, "type": "PER_CHANNEL"}, 0),
+ ({"active": True, "type": "PER_CHANNEL"}, 1),
+ ],
+)
+def test_plugins_query_with_filter(
+ plugin_filter_fields,
+ count,
+ staff_api_client_can_manage_plugins,
+ settings,
+ channel_PLN,
+):
+ settings.PLUGINS = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ "saleor.plugins.tests.sample_plugins.ActivePlugin",
+ "saleor.plugins.tests.sample_plugins.ChannelPluginSample",
+ ]
+ plugin_filter = {
+ "search": plugin_filter_fields.get("search"),
+ "type": plugin_filter_fields.get("type"),
+ }
+ if plugin_filter_fields.get("active") is not None:
+ plugin_filter["statusInChannels"] = {
+ "active": plugin_filter_fields.get("active"),
+ "channels": [graphene.Node.to_global_id("Channel", channel_PLN.id)],
+ }
+ query = """
+ query ($filter: PluginFilterInput) {
+ plugins(first: 5, filter:$filter) {
+ totalCount
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+ """
+ variables = {"filter": plugin_filter}
+ response = staff_api_client_can_manage_plugins.post_graphql(query, variables)
+ content = get_graphql_content(response)
+ assert content["data"]["plugins"]["totalCount"] == count
+
+
+QUERY_PLUGIN_WITH_SORT = """
+ query ($sort_by: PluginSortingInput!) {
+ plugins(first:5, sortBy: $sort_by) {
+ edges{
+ node{
+ name
+ }
+ }
+ }
+ }
+"""
+
+
+ "plugin_sort, result_order",
+ [
+ (
+ {"field": "NAME", "direction": "ASC"},
+ ["Active", "PluginInactive", "PluginSample"],
+ ),
+ (
+ {"field": "NAME", "direction": "DESC"},
+ ["PluginSample", "PluginInactive", "Active"],
+ ),
+ (
+ {"field": "IS_ACTIVE", "direction": "ASC"},
+ ["PluginInactive", "Active", "PluginSample"],
+ ),
+ (
+ {"field": "IS_ACTIVE", "direction": "DESC"},
+ ["Active", "PluginSample", "PluginInactive"],
+ ),
+ ],
+)
+def test_query_plugins_with_sort(
+ plugin_sort, result_order, staff_api_client_can_manage_plugins, settings
+):
+ settings.PLUGINS = [
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ "saleor.plugins.tests.sample_plugins.ActivePlugin",
+ ]
+ variables = {"sort_by": plugin_sort}
+ response = staff_api_client_can_manage_plugins.post_graphql(
+ QUERY_PLUGIN_WITH_SORT, variables
+ )
+ content = get_graphql_content(response)
+ plugins = content["data"]["plugins"]["edges"]
+
+ for order, plugin_name in enumerate(result_order):
+ assert plugins[order]["node"]["name"] == plugin_name
diff --git a/saleor/graphql/plugins/tests/test_mutation_plugin_update.py b/saleor/graphql/plugins/tests/test_mutation_plugin_update.py
new file mode 100644
index 0000000000..c80a8e2787
--- /dev/null
+++ b/saleor/graphql/plugins/tests/test_mutation_plugin_update.py
@@ -0,0 +1,278 @@
+import copy
+
+import graphene
+import pytest
+
+from ....plugins.error_codes import PluginErrorCode
+from ....plugins.manager import get_plugins_manager
+from ....plugins.models import PluginConfiguration
+from ....plugins.tests.sample_plugins import ChannelPluginSample, PluginSample
+from ....plugins.tests.utils import get_config_value
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+PLUGIN_UPDATE_MUTATION = """
+ mutation pluginUpdate(
+ $id: ID!
+ $active: Boolean
+ $channel: ID
+ $configuration: [ConfigurationItemInput]
+ ) {
+ pluginUpdate(
+ id: $id
+ channel: $channel
+ input: { active: $active, configuration: $configuration }
+ ) {
+ plugin {
+ name
+ description
+ globalConfiguration{
+ active
+ configuration{
+ name
+ value
+ helpText
+ type
+ label
+ }
+ channel{
+ id
+ slug
+ }
+ }
+ channelConfigurations{
+ active
+ channel{
+ id
+ slug
+ }
+ configuration{
+ name
+ value
+ helpText
+ type
+ label
+ }
+ }
+ }
+ errors {
+ field
+ message
+ }
+ pluginsErrors {
+ field
+ code
+ }
+ }
+ }
+"""
+
+
+ "active, updated_configuration_item",
+ [
+ (True, {"name": "Username", "value": "user"}),
+ (False, {"name": "Username", "value": "[email protected]"}),
+ ],
+)
+def test_plugin_configuration_update(
+ staff_api_client_can_manage_plugins, settings, active, updated_configuration_item
+):
+
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
+ manager = get_plugins_manager()
+ plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
+ old_configuration = copy.deepcopy(plugin.configuration)
+
+ variables = {
+ "id": plugin.PLUGIN_ID,
+ "active": active,
+ "channel": None,
+ "configuration": [updated_configuration_item],
+ }
+ response = staff_api_client_can_manage_plugins.post_graphql(
+ PLUGIN_UPDATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+
+ plugin_data = content["data"]["pluginUpdate"]["plugin"]
+
+ assert plugin_data["name"] == plugin.PLUGIN_NAME
+ assert plugin_data["description"] == plugin.PLUGIN_DESCRIPTION
+
+ plugin = PluginConfiguration.objects.get(identifier=PluginSample.PLUGIN_ID)
+ assert plugin.active == active
+
+ first_configuration_item = plugin.configuration[0]
+ assert first_configuration_item["name"] == updated_configuration_item["name"]
+ assert first_configuration_item["value"] == updated_configuration_item["value"]
+
+ second_configuration_item = plugin.configuration[1]
+ assert second_configuration_item["name"] == old_configuration[1]["name"]
+ assert second_configuration_item["value"] == old_configuration[1]["value"]
+
+ configuration = plugin_data["globalConfiguration"]["configuration"]
+ assert configuration is not None
+ assert configuration[0]["name"] == updated_configuration_item["name"]
+ assert configuration[0]["value"] == updated_configuration_item["value"]
+
+
+ "active",
+ [
+ True,
+ False,
+ ],
+)
+def test_plugin_configuration_update_for_channel_configurations(
+ staff_api_client_can_manage_plugins, settings, active, channel_PLN
+):
+
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.ChannelPluginSample"]
+ manager = get_plugins_manager()
+ plugin = manager.get_plugin(
+ ChannelPluginSample.PLUGIN_ID, channel_slug=channel_PLN.slug
+ )
+
+ variables = {
+ "id": plugin.PLUGIN_ID,
+ "active": active,
+ "channel": graphene.Node.to_global_id("Channel", channel_PLN.id),
+ "configuration": [{"name": "input-per-channel", "value": "update-value"}],
+ }
+ response = staff_api_client_can_manage_plugins.post_graphql(
+ PLUGIN_UPDATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+
+ plugin_data = content["data"]["pluginUpdate"]["plugin"]
+
+ assert plugin_data["name"] == plugin.PLUGIN_NAME
+ assert plugin_data["description"] == plugin.PLUGIN_DESCRIPTION
+
+ assert len(plugin_data["channelConfigurations"]) == 1
+ api_configuration = plugin_data["channelConfigurations"][0]
+
+ plugin = PluginConfiguration.objects.get(identifier=ChannelPluginSample.PLUGIN_ID)
+ assert plugin.active == active == api_configuration["active"]
+
+ configuration_item = plugin.configuration[0]
+ assert configuration_item["name"] == "input-per-channel"
+ assert configuration_item["value"] == "update-value"
+
+ configuration = api_configuration["configuration"]
+ assert len(configuration) == 1
+ assert configuration[0]["name"] == configuration_item["name"]
+ assert configuration[0]["value"] == configuration_item["value"]
+
+
+def test_plugin_configuration_update_channel_slug_required(
+ staff_api_client_can_manage_plugins, settings, channel_PLN
+):
+
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.ChannelPluginSample"]
+ manager = get_plugins_manager()
+ plugin = manager.get_plugin(
+ ChannelPluginSample.PLUGIN_ID, channel_slug=channel_PLN.slug
+ )
+
+ variables = {
+ "id": plugin.PLUGIN_ID,
+ "active": True,
+ "channel": None,
+ "configuration": [{"name": "input-per-channel", "value": "update-value"}],
+ }
+
+ response = staff_api_client_can_manage_plugins.post_graphql(
+ PLUGIN_UPDATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+
+ assert not content["data"]["pluginUpdate"]["plugin"]
+ assert len(content["data"]["pluginUpdate"]["pluginsErrors"]) == 1
+ error = content["data"]["pluginUpdate"]["pluginsErrors"][0]
+ assert error["field"] == "id"
+ assert error["code"] == PluginErrorCode.NOT_FOUND.name
+
+
+def test_plugin_configuration_update_unneeded_channel_slug(
+ staff_api_client_can_manage_plugins, settings, channel_PLN
+):
+
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
+ manager = get_plugins_manager()
+ plugin = manager.get_plugin(PluginSample.PLUGIN_ID, channel_slug=channel_PLN.slug)
+
+ variables = {
+ "id": plugin.PLUGIN_ID,
+ "active": True,
+ "channel": graphene.Node.to_global_id("Channel", channel_PLN.id),
+ "configuration": [{"name": "input-per-channel", "value": "update-value"}],
+ }
+
+ response = staff_api_client_can_manage_plugins.post_graphql(
+ PLUGIN_UPDATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+
+ assert not content["data"]["pluginUpdate"]["plugin"]
+ assert len(content["data"]["pluginUpdate"]["pluginsErrors"]) == 1
+ error = content["data"]["pluginUpdate"]["pluginsErrors"][0]
+ assert error["field"] == "id"
+ assert error["code"] == PluginErrorCode.INVALID.name
+
+
+def test_plugin_configuration_update_containing_invalid_plugin_id(
+ staff_api_client_can_manage_plugins,
+):
+ variables = {
+ "id": "fake-id",
+ "active": True,
+ "channel": None,
+ "configuration": [{"name": "Username", "value": "user"}],
+ }
+ response = staff_api_client_can_manage_plugins.post_graphql(
+ PLUGIN_UPDATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+ assert content["data"]["pluginUpdate"]["pluginsErrors"][0] == {
+ "field": "id",
+ "code": PluginErrorCode.NOT_FOUND.name,
+ }
+
+
+def test_plugin_update_saves_boolean_as_boolean(
+ staff_api_client_can_manage_plugins, settings
+):
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
+ manager = get_plugins_manager()
+ plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
+ use_sandbox = get_config_value("Use sandbox", plugin.configuration)
+ variables = {
+ "id": plugin.PLUGIN_ID,
+ "active": plugin.active,
+ "channel": None,
+ "configuration": [{"name": "Use sandbox", "value": True}],
+ }
+ response = staff_api_client_can_manage_plugins.post_graphql(
+ PLUGIN_UPDATE_MUTATION, variables
+ )
+ content = get_graphql_content(response)
+ assert len(content["data"]["pluginUpdate"]["errors"]) == 0
+ use_sandbox_new_value = get_config_value("Use sandbox", plugin.configuration)
+ assert type(use_sandbox) == type(use_sandbox_new_value)
+
+
+def test_plugin_configuration_update_as_customer_user(user_api_client, settings):
+ settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
+ manager = get_plugins_manager()
+ plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
+
+ variables = {
+ "id": plugin.PLUGIN_ID,
+ "active": True,
+ "channel": None,
+ "configuration": [{"name": "Username", "value": "user"}],
+ }
+ response = user_api_client.post_graphql(PLUGIN_UPDATE_MUTATION, variables)
+
+ assert_no_permission(response)
diff --git a/saleor/graphql/plugins/tests/test_plugins.py b/saleor/graphql/plugins/tests/test_plugins.py
deleted file mode 100644
index 99f0effc03..0000000000
--- a/saleor/graphql/plugins/tests/test_plugins.py
+++ /dev/null
@@ -1,481 +0,0 @@
-import copy
-
-import pytest
-
-from ....plugins.base_plugin import ConfigurationTypeField
-from ....plugins.error_codes import PluginErrorCode
-from ....plugins.manager import get_plugins_manager
-from ....plugins.models import PluginConfiguration
-from ....plugins.tests.sample_plugins import PluginSample
-from ....plugins.tests.utils import get_config_value
-from ...tests.utils import assert_no_permission, get_graphql_content
-
-
-def staff_api_client_can_manage_plugins(staff_api_client, permission_manage_plugins):
- staff_api_client.user.user_permissions.add(permission_manage_plugins)
- return staff_api_client
-
-
-PLUGINS_QUERY = """
- {
- plugins(first:1){
- edges{
- node{
- name
- description
- active
- id
- configuration{
- name
- type
- value
- helpText
- label
- }
- }
- }
- }
- }
-"""
-
-
-def test_query_plugin_configurations(staff_api_client_can_manage_plugins, settings):
-
- # Enable test plugin
- settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
- response = staff_api_client_can_manage_plugins.post_graphql(PLUGINS_QUERY)
- content = get_graphql_content(response)
-
- plugins = content["data"]["plugins"]["edges"]
-
- assert len(plugins) == 1
- plugin = plugins[0]["node"]
- manager = get_plugins_manager()
- sample_plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
- confiugration_structure = PluginSample.CONFIG_STRUCTURE
-
- assert plugin["id"] == sample_plugin.PLUGIN_ID
- assert plugin["name"] == sample_plugin.PLUGIN_NAME
- assert plugin["active"] == sample_plugin.DEFAULT_ACTIVE
- assert plugin["description"] == sample_plugin.PLUGIN_DESCRIPTION
- for index, configuration_item in enumerate(plugin["configuration"]):
- assert configuration_item["name"] == sample_plugin.configuration[index]["name"]
-
- if (
- confiugration_structure[configuration_item["name"]]["type"]
- == ConfigurationTypeField.STRING
- ):
- assert (
- configuration_item["value"]
- == sample_plugin.configuration[index]["value"]
- )
- elif configuration_item["value"] is None:
- assert not sample_plugin.configuration[index]["value"]
- else:
- assert (
- configuration_item["value"]
- == str(sample_plugin.configuration[index]["value"]).lower()
- )
-
-
- "password, expected_password, api_key, expected_api_key, cert, expected_cert",
- [
- (None, None, None, None, None, None),
- ("ABCDEFGHIJ", "", "123456789", "6789", "long text\n with new\n lines", "ines"),
- ("", None, "", None, "", None),
- (None, None, "1234", "4", None, None),
- ],
-)
-def test_query_plugins_hides_secret_fields(
- password,
- expected_password,
- api_key,
- expected_api_key,
- cert,
- expected_cert,
- staff_api_client,
- permission_manage_plugins,
- settings,
-):
-
- settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
- manager = get_plugins_manager()
- plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
- configuration = copy.deepcopy(plugin.configuration)
- for conf_field in configuration:
- if conf_field["name"] == "Password":
- conf_field["value"] = password
- if conf_field["name"] == "API private key":
- conf_field["value"] = api_key
- if conf_field["name"] == "certificate":
- conf_field["value"] = cert
- manager.save_plugin_configuration(
- PluginSample.PLUGIN_ID,
- {
- "active": True,
- "configuration": configuration,
- "name": PluginSample.PLUGIN_NAME,
- },
- )
-
- staff_api_client.user.user_permissions.add(permission_manage_plugins)
- response = staff_api_client.post_graphql(PLUGINS_QUERY)
- content = get_graphql_content(response)
-
- plugins = content["data"]["plugins"]["edges"]
- assert len(plugins) == 1
- plugin = plugins[0]["node"]
-
- for conf_field in plugin["configuration"]:
- if conf_field["name"] == "Password":
- assert conf_field["value"] == expected_password
- if conf_field["name"] == "API private key":
- assert conf_field["value"] == expected_api_key
-
-
-def test_query_plugin_configurations_as_customer_user(user_api_client, settings):
- settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
- response = user_api_client.post_graphql(PLUGINS_QUERY)
-
- assert_no_permission(response)
-
-
-PLUGIN_QUERY = """
- query plugin($id: ID!){
- plugin(id:$id){
- id
- name
- description
- active
- configuration{
- name
- value
- type
- helpText
- label
- }
- }
- }
-"""
-
-
- "password, expected_password, api_key, expected_api_key",
- [
- (None, None, None, None),
- ("ABCDEFGHIJ", "", "123456789", "6789"),
- ("", None, "", None),
- (None, None, "1234", "4"),
- ],
-)
-def test_query_plugin_hides_secret_fields(
- password,
- expected_password,
- api_key,
- expected_api_key,
- staff_api_client,
- permission_manage_plugins,
- settings,
-):
-
- settings.PLUGINS = ["saleor.graphql.plugins.tests.test_plugins.PluginSample"]
- manager = get_plugins_manager()
- plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
- configuration = copy.deepcopy(plugin.configuration)
- for conf_field in configuration:
- if conf_field["name"] == "Password":
- conf_field["value"] = password
- if conf_field["name"] == "API private key":
- conf_field["value"] = api_key
- manager.save_plugin_configuration(
- PluginSample.PLUGIN_ID,
- {
- "active": True,
- "configuration": configuration,
- "name": PluginSample.PLUGIN_NAME,
- },
- )
-
- variables = {"id": plugin.PLUGIN_ID}
- staff_api_client.user.user_permissions.add(permission_manage_plugins)
- response = staff_api_client.post_graphql(PLUGIN_QUERY, variables)
- content = get_graphql_content(response)
-
- plugin = content["data"]["plugin"]
-
- for conf_field in plugin["configuration"]:
- if conf_field["name"] == "Password":
- assert conf_field["value"] == expected_password
- if conf_field["name"] == "API private key":
- assert conf_field["value"] == expected_api_key
-
-
-def test_query_plugin_configuration(
- staff_api_client, permission_manage_plugins, settings
-):
- settings.PLUGINS = ["saleor.graphql.plugins.tests.test_plugins.PluginSample"]
- manager = get_plugins_manager()
- sample_plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
-
- variables = {"id": sample_plugin.PLUGIN_ID}
- staff_api_client.user.user_permissions.add(permission_manage_plugins)
- response = staff_api_client.post_graphql(PLUGIN_QUERY, variables)
- content = get_graphql_content(response)
- plugin = content["data"]["plugin"]
- assert plugin["name"] == sample_plugin.PLUGIN_NAME
- assert plugin["id"] == sample_plugin.PLUGIN_ID
- assert plugin["active"] == sample_plugin.active
- assert plugin["description"] == sample_plugin.PLUGIN_DESCRIPTION
-
- configuration_item = plugin["configuration"][0]
- assert configuration_item["name"] == sample_plugin.configuration[0]["name"]
- assert configuration_item["value"] == sample_plugin.configuration[0]["value"]
-
-
-def test_query_plugin_configuration_for_invalid_plugin_name(
- staff_api_client, permission_manage_plugins
-):
- variables = {"id": "fake-name"}
- staff_api_client.user.user_permissions.add(permission_manage_plugins)
- response = staff_api_client.post_graphql(PLUGIN_QUERY, variables)
- content = get_graphql_content(response)
- assert content["data"]["plugin"] is None
-
-
-def test_query_plugin_configuration_as_customer_user(user_api_client, settings):
- settings.PLUGINS = ["saleor.graphql.plugins.tests.test_plugins.PluginSample"]
- manager = get_plugins_manager()
- sample_plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
-
- variables = {"id": sample_plugin.PLUGIN_ID}
- response = user_api_client.post_graphql(PLUGIN_QUERY, variables)
-
- assert_no_permission(response)
-
-
-PLUGIN_UPDATE_MUTATION = """
- mutation pluginUpdate(
- $id: ID!
- $active: Boolean
- $configuration: [ConfigurationItemInput]
- ) {
- pluginUpdate(
- id: $id
- input: { active: $active, configuration: $configuration }
- ) {
- plugin {
- name
- description
- active
- configuration {
- name
- value
- type
- helpText
- label
- }
- }
- errors {
- field
- message
- }
- pluginsErrors {
- field
- code
- }
- }
- }
-"""
-
-
- "active, updated_configuration_item",
- [
- (True, {"name": "Username", "value": "user"}),
- (False, {"name": "Username", "value": "[email protected]"}),
- ],
-)
-def test_plugin_configuration_update(
- staff_api_client_can_manage_plugins, settings, active, updated_configuration_item
-):
-
- settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
- manager = get_plugins_manager()
- plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
- old_configuration = copy.deepcopy(plugin.configuration)
-
- variables = {
- "id": plugin.PLUGIN_ID,
- "active": active,
- "configuration": [updated_configuration_item],
- }
- response = staff_api_client_can_manage_plugins.post_graphql(
- PLUGIN_UPDATE_MUTATION, variables
- )
- content = get_graphql_content(response)
-
- plugin_data = content["data"]["pluginUpdate"]["plugin"]
-
- assert plugin_data["name"] == plugin.PLUGIN_NAME
- assert plugin_data["description"] == plugin.PLUGIN_DESCRIPTION
-
- plugin = PluginConfiguration.objects.get(identifier=PluginSample.PLUGIN_ID)
- assert plugin.active == active
-
- first_configuration_item = plugin.configuration[0]
- assert first_configuration_item["name"] == updated_configuration_item["name"]
- assert first_configuration_item["value"] == updated_configuration_item["value"]
-
- second_configuration_item = plugin.configuration[1]
- assert second_configuration_item["name"] == old_configuration[1]["name"]
- assert second_configuration_item["value"] == old_configuration[1]["value"]
-
- configuration = plugin_data["configuration"]
- assert configuration is not None
- assert configuration[0]["name"] == updated_configuration_item["name"]
- assert configuration[0]["value"] == updated_configuration_item["value"]
-
-
-def test_plugin_configuration_update_containing_invalid_plugin_id(
- staff_api_client_can_manage_plugins,
-):
- variables = {
- "id": "fake-id",
- "active": True,
- "configuration": [{"name": "Username", "value": "user"}],
- }
- response = staff_api_client_can_manage_plugins.post_graphql(
- PLUGIN_UPDATE_MUTATION, variables
- )
- content = get_graphql_content(response)
- assert content["data"]["pluginUpdate"]["pluginsErrors"][0] == {
- "field": "id",
- "code": PluginErrorCode.NOT_FOUND.name,
- }
-
-
-def test_plugin_update_saves_boolean_as_boolean(
- staff_api_client_can_manage_plugins, settings
-):
- settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
- manager = get_plugins_manager()
- plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
- use_sandbox = get_config_value("Use sandbox", plugin.configuration)
- variables = {
- "id": plugin.PLUGIN_ID,
- "active": plugin.active,
- "configuration": [{"name": "Use sandbox", "value": True}],
- }
- response = staff_api_client_can_manage_plugins.post_graphql(
- PLUGIN_UPDATE_MUTATION, variables
- )
- content = get_graphql_content(response)
- assert len(content["data"]["pluginUpdate"]["errors"]) == 0
- use_sandbox_new_value = get_config_value("Use sandbox", plugin.configuration)
- assert type(use_sandbox) == type(use_sandbox_new_value)
-
-
- "plugin_filter, count",
- [
- ({"search": "PluginSample"}, 1),
- ({"search": "description"}, 2),
- ({"active": True}, 2),
- ({"search": "Plugin"}, 2),
- ({"active": "False", "search": "Plugin"}, 1),
- ],
-)
-def test_plugins_query_with_filter(
- plugin_filter, count, staff_api_client_can_manage_plugins, settings
-):
- settings.PLUGINS = [
- "saleor.plugins.tests.sample_plugins.PluginSample",
- "saleor.plugins.tests.sample_plugins.PluginInactive",
- "saleor.plugins.tests.sample_plugins.ActivePlugin",
- ]
- query = """
- query ($filter: PluginFilterInput) {
- plugins(first: 5, filter:$filter) {
- totalCount
- edges {
- node {
- id
- }
- }
- }
- }
- """
- variables = {"filter": plugin_filter}
- response = staff_api_client_can_manage_plugins.post_graphql(query, variables)
- content = get_graphql_content(response)
- assert content["data"]["plugins"]["totalCount"] == count
-
-
-def test_plugin_configuration_update_as_customer_user(user_api_client, settings):
- settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]
- manager = get_plugins_manager()
- plugin = manager.get_plugin(PluginSample.PLUGIN_ID)
-
- variables = {
- "id": plugin.PLUGIN_ID,
- "active": True,
- "configuration": [{"name": "Username", "value": "user"}],
- }
- response = user_api_client.post_graphql(PLUGIN_UPDATE_MUTATION, variables)
-
- assert_no_permission(response)
-
-
-QUERY_PLUGIN_WITH_SORT = """
- query ($sort_by: PluginSortingInput!) {
- plugins(first:5, sortBy: $sort_by) {
- edges{
- node{
- name
- }
- }
- }
- }
-"""
-
-
- "plugin_sort, result_order",
- [
- (
- {"field": "NAME", "direction": "ASC"},
- ["Active", "PluginInactive", "PluginSample"],
- ),
- (
- {"field": "NAME", "direction": "DESC"},
- ["PluginSample", "PluginInactive", "Active"],
- ),
- (
- {"field": "IS_ACTIVE", "direction": "ASC"},
- ["PluginInactive", "Active", "PluginSample"],
- ),
- (
- {"field": "IS_ACTIVE", "direction": "DESC"},
- ["Active", "PluginSample", "PluginInactive"],
- ),
- ],
-)
-def test_query_plugins_with_sort(
- plugin_sort, result_order, staff_api_client_can_manage_plugins, settings
-):
- settings.PLUGINS = [
- "saleor.plugins.tests.sample_plugins.PluginSample",
- "saleor.plugins.tests.sample_plugins.PluginInactive",
- "saleor.plugins.tests.sample_plugins.ActivePlugin",
- ]
- variables = {"sort_by": plugin_sort}
- response = staff_api_client_can_manage_plugins.post_graphql(
- QUERY_PLUGIN_WITH_SORT, variables
- )
- content = get_graphql_content(response)
- plugins = content["data"]["plugins"]["edges"]
-
- for order, plugin_name in enumerate(result_order):
- assert plugins[order]["node"]["name"] == plugin_name
diff --git a/saleor/graphql/plugins/types.py b/saleor/graphql/plugins/types.py
index b6b11d20b6..d9e806e356 100644
--- a/saleor/graphql/plugins/types.py
+++ b/saleor/graphql/plugins/types.py
@@ -1,39 +1,9 @@
-from typing import TYPE_CHECKING, Optional
-
import graphene
-from ...core.tracing import traced_resolver
-from ...plugins import models
-from ...plugins.base_plugin import ConfigurationTypeField
-from ..core.connection import CountableDjangoObjectType
+from ..channel.types import Channel
+from ..core.connection import CountableConnection
from .enums import ConfigurationTypeFieldEnum
-if TYPE_CHECKING:
- # flake8: noqa
- from ...plugins.base_plugin import PluginConfigurationType
-
-
-def hide_private_configuration_fields(configuration, config_structure):
- for field in configuration:
- name = field["name"]
- value = field["value"]
- if value is None:
- continue
- field_type = config_structure.get(name, {}).get("type")
- if field_type == ConfigurationTypeField.PASSWORD:
- field["value"] = "" if value else None
-
- if field_type in [
- ConfigurationTypeField.SECRET,
- ConfigurationTypeField.SECRET_MULTILINE,
- ]:
- if not value:
- field["value"] = None
- elif len(value) > 4:
- field["value"] = value[-4:]
- else:
- field["value"] = value[-1:]
-
class ConfigurationItem(graphene.ObjectType):
name = graphene.String(required=True, description="Name of the field.")
@@ -46,28 +16,62 @@ class ConfigurationItem(graphene.ObjectType):
description = "Stores information about a single configuration field."
-class Plugin(CountableDjangoObjectType):
- id = graphene.Field(type=graphene.ID, required=True)
- configuration = graphene.List(ConfigurationItem)
+class PluginConfiguration(graphene.ObjectType):
+ active = graphene.Boolean(
+ required=True, description="Determines if plugin is active or not."
+ )
+ channel = graphene.Field(
+ Channel,
+ description="The channel to which the plugin configuration is assigned to.",
+ )
+ configuration = graphene.List(
+ ConfigurationItem, description="Configuration of the plugin."
+ )
+
+ class Meta:
+ description = "Stores information about a configuration of plugin."
+
+
+class Plugin(graphene.ObjectType):
+ id = graphene.ID(required=True, description="Identifier of the plugin.")
+ name = graphene.String(description="Name of the plugin.", required=True)
+ description = graphene.String(
+ description="Description of the plugin.", required=True
+ )
+ global_configuration = graphene.Field(
+ PluginConfiguration,
+ description="Global configuration of the plugin (not channel-specific).",
+ )
+ channel_configurations = graphene.List(
+ graphene.NonNull(PluginConfiguration),
+ description="Channel-specific plugin configuration.",
+ required=True,
+ )
class Meta:
description = "Plugin."
- model = models.PluginConfiguration
- interfaces = [graphene.relay.Node]
- only_fields = ["id", "name", "description", "active", "configuration"]
- def resolve_id(self: models.PluginConfiguration, _info):
- return self.identifier
+ @staticmethod
+ def resolve_id(root: "Plugin", _info):
+ return root.id
+
+ @staticmethod
+ def resolve_name(root: "Plugin", _info):
+ return root.name
+
+ @staticmethod
+ def resolve_description(root: "Plugin", _info):
+ return root.description
+
+ @staticmethod
+ def resolve_global_configuration(root: "Plugin", _info):
+ return root.global_configuration
@staticmethod
- @traced_resolver
- def resolve_configuration(
- root: models.PluginConfiguration, info
- ) -> Optional["PluginConfigurationType"]:
- plugin = info.context.plugins.get_plugin(root.identifier)
- if not plugin:
- return None
- configuration = plugin.configuration
- if plugin.CONFIG_STRUCTURE and configuration:
- hide_private_configuration_fields(configuration, plugin.CONFIG_STRUCTURE)
- return configuration
+ def resolve_channel_configurations(root: "Plugin", _info):
+ return root.channel_configurations or []
+
+
+class PluginCountableConnection(CountableConnection):
+ class Meta:
+ node = Plugin
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index a33549d853..ab92033226 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -68,6 +68,8 @@ enum AccountErrorCode {
JWT_DECODE_ERROR
JWT_MISSING_TOKEN
JWT_INVALID_CSRF_TOKEN
+ CHANNEL_INACTIVE
+ MISSING_CHANNEL_SLUG
}
input AccountInput {
@@ -91,6 +93,7 @@ input AccountRegisterInput {
redirectUrl: String
languageCode: LanguageCodeEnum
metadata: [MetadataInput!]
+ channel: String
}
type AccountRequestDeletion {
@@ -2751,7 +2754,7 @@ type Mutation {
paymentCapture(amount: PositiveDecimal, paymentId: ID!): PaymentCapture
paymentRefund(amount: PositiveDecimal, paymentId: ID!): PaymentRefund
paymentVoid(paymentId: ID!): PaymentVoid
- paymentInitialize(gateway: String!, paymentData: JSONString): PaymentInitialize
+ paymentInitialize(channel: String, gateway: String!, paymentData: JSONString): PaymentInitialize
pageCreate(input: PageCreateInput!): PageCreate
pageDelete(id: ID!): PageDelete
pageBulkDelete(ids: [ID]!): PageBulkDelete
@@ -2820,7 +2823,7 @@ type Mutation {
giftCardCreate(input: GiftCardCreateInput!): GiftCardCreate
giftCardDeactivate(id: ID!): GiftCardDeactivate
giftCardUpdate(id: ID!, input: GiftCardUpdateInput!): GiftCardUpdate
- pluginUpdate(id: ID!, input: PluginUpdateInput!): PluginUpdate
+ pluginUpdate(channel: ID, id: ID!, input: PluginUpdateInput!): PluginUpdate
saleCreate(input: SaleInput!): SaleCreate
saleDelete(id: ID!): SaleDelete
saleBulkDelete(ids: [ID]!): SaleBulkDelete
@@ -2891,19 +2894,19 @@ type Mutation {
externalRefresh(input: JSONString!, pluginId: String!): ExternalRefresh
externalLogout(input: JSONString!, pluginId: String!): ExternalLogout
externalVerify(input: JSONString!, pluginId: String!): ExternalVerify
- requestPasswordReset(email: String!, redirectUrl: String!): RequestPasswordReset
+ requestPasswordReset(channel: String, email: String!, redirectUrl: String!): RequestPasswordReset
confirmAccount(email: String!, token: String!): ConfirmAccount
setPassword(email: String!, password: String!, token: String!): SetPassword
passwordChange(newPassword: String!, oldPassword: String!): PasswordChange
- requestEmailChange(newEmail: String!, password: String!, redirectUrl: String!): RequestEmailChange
- confirmEmailChange(token: String!): ConfirmEmailChange
+ requestEmailChange(channel: String, newEmail: String!, password: String!, redirectUrl: String!): RequestEmailChange
+ confirmEmailChange(channel: String, token: String!): ConfirmEmailChange
accountAddressCreate(input: AddressInput!, type: AddressTypeEnum): AccountAddressCreate
accountAddressUpdate(id: ID!, input: AddressInput!): AccountAddressUpdate
accountAddressDelete(id: ID!): AccountAddressDelete
accountSetDefaultAddress(id: ID!, type: AddressTypeEnum!): AccountSetDefaultAddress
accountRegister(input: AccountRegisterInput!): AccountRegister
accountUpdate(input: AccountInput!): AccountUpdate
- accountRequestDeletion(redirectUrl: String!): AccountRequestDeletion
+ accountRequestDeletion(channel: String, redirectUrl: String!): AccountRequestDeletion
accountDelete(token: String!): AccountDelete
addressCreate(input: AddressInput!, userId: ID!): AddressCreate
addressUpdate(id: ID!, input: AddressInput!): AddressUpdate
@@ -3813,6 +3816,7 @@ enum PaymentErrorCode {
SHIPPING_METHOD_NOT_SET
PAYMENT_ERROR
NOT_SUPPORTED_GATEWAY
+ CHANNEL_INACTIVE
}
input PaymentFilterInput {
@@ -3951,14 +3955,25 @@ input PermissionGroupUpdateInput {
removeUsers: [ID!]
}
-type Plugin implements Node {
+type Plugin {
id: ID!
name: String!
description: String!
+ globalConfiguration: PluginConfiguration
+ channelConfigurations: [PluginConfiguration!]!
+}
+
+type PluginConfiguration {
active: Boolean!
+ channel: Channel
configuration: [ConfigurationItem]
}
+enum PluginConfigurationType {
+ PER_CHANNEL
+ GLOBAL
+}
+
type PluginCountableConnection {
pageInfo: PageInfo!
edges: [PluginCountableEdge!]!
@@ -3986,8 +4001,9 @@ enum PluginErrorCode {
}
input PluginFilterInput {
- active: Boolean
+ statusInChannels: PluginStatusInChannelsInput
search: String
+ type: PluginConfigurationType
}
enum PluginSortField {
@@ -4000,6 +4016,11 @@ input PluginSortingInput {
field: PluginSortField!
}
+input PluginStatusInChannelsInput {
+ active: Boolean!
+ channels: [ID!]!
+}
+
type PluginUpdate {
plugin: Plugin
pluginsErrors: [PluginError!]! @deprecated(reason: "Use errors field instead. This field will be removed in Saleor 4.0.")
@@ -5167,7 +5188,7 @@ input ShippingZoneUpdateInput {
}
type Shop {
- availablePaymentGateways(currency: String): [PaymentGateway!]!
+ availablePaymentGateways(currency: String, channel: String): [PaymentGateway!]!
availableExternalAuthentications: [ExternalAuthentication!]!
availableShippingMethods(channel: String!, address: AddressInput): [ShippingMethod]
countries(languageCode: LanguageCodeEnum): [CountryDisplay!]!
@@ -5591,7 +5612,7 @@ type User implements Node & ObjectWithMetadata {
editableGroups: [Group]
avatar(size: Int): Image
events: [CustomerEvent]
- storedPaymentSources: [PaymentSource]
+ storedPaymentSources(channel: String): [PaymentSource]
languageCode: LanguageCodeEnum!
}
@@ -5634,6 +5655,7 @@ input UserCreateInput {
note: String
languageCode: LanguageCodeEnum
redirectUrl: String
+ channel: String
}
type UserPermission {
diff --git a/saleor/graphql/shop/resolvers.py b/saleor/graphql/shop/resolvers.py
index fefee831a7..53277fd237 100644
--- a/saleor/graphql/shop/resolvers.py
+++ b/saleor/graphql/shop/resolvers.py
@@ -29,7 +29,9 @@ def resolve_available_shipping_methods(info, channel_slug: str, address):
)
for shipping_method in available:
shipping_price = shipping_mapping[shipping_method.pk]
- taxed_price = manager.apply_taxes_to_shipping(shipping_price, address)
+ taxed_price = manager.apply_taxes_to_shipping(
+ shipping_price, address, channel_slug
+ )
if display_gross:
shipping_method.price = taxed_price.gross
else:
diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.py
index ba6268d931..db4093b354 100644
--- a/saleor/graphql/shop/tests/test_shop.py
+++ b/saleor/graphql/shop/tests/test_shop.py
@@ -606,7 +606,7 @@ AVAILABLE_PAYMENT_GATEWAYS_QUERY = """
"""
-def test_query_available_payment_gateways(user_api_client, sample_gateway):
+def test_query_available_payment_gateways(user_api_client, sample_gateway, channel_USD):
query = AVAILABLE_PAYMENT_GATEWAYS_QUERY
response = user_api_client.post_graphql(query)
content = get_graphql_content(response)
@@ -622,7 +622,7 @@ def test_query_available_payment_gateways(user_api_client, sample_gateway):
def test_query_available_payment_gateways_specified_currency_USD(
- user_api_client, sample_gateway
+ user_api_client, sample_gateway, channel_USD
):
query = AVAILABLE_PAYMENT_GATEWAYS_QUERY
response = user_api_client.post_graphql(query, {"currency": "USD"})
@@ -639,7 +639,7 @@ def test_query_available_payment_gateways_specified_currency_USD(
def test_query_available_payment_gateways_specified_currency_EUR(
- user_api_client, sample_gateway
+ user_api_client, sample_gateway, channel_USD
):
query = AVAILABLE_PAYMENT_GATEWAYS_QUERY
response = user_api_client.post_graphql(query, {"currency": "EUR"})
diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.py
index a723cf6eed..900cbe80f4 100644
--- a/saleor/graphql/shop/types.py
+++ b/saleor/graphql/shop/types.py
@@ -82,7 +82,16 @@ class Shop(graphene.ObjectType):
graphene.NonNull(PaymentGateway),
currency=graphene.Argument(
graphene.String,
- description="A currency for which gateways will be returned.",
+ description=(
+ "DEPRECATED: use `channel` argument instead. This argument will be "
+ "removed in Saleor 4.0."
+ "A currency for which gateways will be returned."
+ ),
+ required=False,
+ ),
+ channel=graphene.Argument(
+ graphene.String,
+ description="Slug of a channel for which the data should be returned.",
required=False,
),
description="List of available payment gateways.",
@@ -193,8 +202,12 @@ class Shop(graphene.ObjectType):
@staticmethod
@traced_resolver
- def resolve_available_payment_gateways(_, info, currency: Optional[str] = None):
- return info.context.plugins.list_payment_gateways(currency=currency)
+ def resolve_available_payment_gateways(
+ _, info, currency: Optional[str] = None, channel: Optional[str] = None
+ ):
+ return info.context.plugins.list_payment_gateways(
+ currency=currency, channel_slug=channel
+ )
@staticmethod
@traced_resolver
diff --git a/saleor/order/notifications.py b/saleor/order/notifications.py
index 1c29800226..d23a6ede0f 100644
--- a/saleor/order/notifications.py
+++ b/saleor/order/notifications.py
@@ -273,7 +273,9 @@ def send_order_confirmation(order, redirect_url, manager):
"recipient_email": order.get_customer_email(),
**get_site_context(),
}
- manager.notify(NotifyEventType.ORDER_CONFIRMATION, payload)
+ manager.notify(
+ NotifyEventType.ORDER_CONFIRMATION, payload, channel_slug=order.channel.slug
+ )
# Prepare staff notification for this order
staff_notifications = StaffNotificationRecipient.objects.filter(
@@ -299,18 +301,28 @@ def send_order_confirmed(order, user, manager):
"requester_user_id": user.id,
**get_site_context(),
}
- manager.notify(NotifyEventType.ORDER_CONFIRMED, payload)
+ manager.notify(
+ NotifyEventType.ORDER_CONFIRMED, payload, channel_slug=order.channel.slug
+ )
def send_fulfillment_confirmation_to_customer(order, fulfillment, user, manager):
payload = get_default_fulfillment_payload(order, fulfillment)
payload["requester_user_id"] = user.id if user else None
- manager.notify(NotifyEventType.ORDER_FULFILLMENT_CONFIRMATION, payload=payload)
+ manager.notify(
+ NotifyEventType.ORDER_FULFILLMENT_CONFIRMATION,
+ payload=payload,
+ channel_slug=order.channel.slug,
+ )
def send_fulfillment_update(order, fulfillment, manager):
payload = get_default_fulfillment_payload(order, fulfillment)
- manager.notify(NotifyEventType.ORDER_FULFILLMENT_UPDATE, payload)
+ manager.notify(
+ NotifyEventType.ORDER_FULFILLMENT_UPDATE,
+ payload,
+ channel_slug=order.channel.slug,
+ )
def send_payment_confirmation(order, manager):
@@ -329,7 +341,11 @@ def send_payment_confirmation(order, manager):
},
**get_site_context(),
}
- manager.notify(NotifyEventType.ORDER_PAYMENT_CONFIRMATION, payload)
+ manager.notify(
+ NotifyEventType.ORDER_PAYMENT_CONFIRMATION,
+ payload,
+ channel_slug=order.channel.slug,
+ )
def send_order_canceled_confirmation(order: "Order", user: Optional["User"], manager):
@@ -339,7 +355,9 @@ def send_order_canceled_confirmation(order: "Order", user: Optional["User"], man
"recipient_email": order.get_customer_email(),
**get_site_context(),
}
- manager.notify(NotifyEventType.ORDER_CANCELED, payload)
+ manager.notify(
+ NotifyEventType.ORDER_CANCELED, payload, channel_slug=order.channel.slug
+ )
def send_order_refunded_confirmation(
@@ -353,4 +371,8 @@ def send_order_refunded_confirmation(
"currency": currency,
**get_site_context(),
}
- manager.notify(NotifyEventType.ORDER_REFUND_CONFIRMATION, payload)
+ manager.notify(
+ NotifyEventType.ORDER_REFUND_CONFIRMATION,
+ payload,
+ channel_slug=order.channel.slug,
+ )
diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.py
index a8a5c39324..707293caa9 100644
--- a/saleor/order/tests/test_notifications.py
+++ b/saleor/order/tests/test_notifications.py
@@ -235,7 +235,9 @@ def test_send_email_payment_confirmation(mocked_notify, site_settings, payment_d
}
notifications.send_payment_confirmation(order, manager)
mocked_notify.assert_called_once_with(
- NotifyEventType.ORDER_PAYMENT_CONFIRMATION, expected_payload
+ NotifyEventType.ORDER_PAYMENT_CONFIRMATION,
+ expected_payload,
+ channel_slug=order.channel.slug,
)
@@ -253,7 +255,9 @@ def test_send_email_order_confirmation(mocked_notify, order, site_settings):
"domain": "mirumee.com",
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ORDER_CONFIRMATION, expected_payload
+ NotifyEventType.ORDER_CONFIRMATION,
+ expected_payload,
+ channel_slug=order.channel.slug,
)
@@ -298,7 +302,9 @@ def test_send_confirmation_emails_without_addresses_for_payment(
"domain": "mirumee.com",
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ORDER_PAYMENT_CONFIRMATION, expected_payload
+ NotifyEventType.ORDER_PAYMENT_CONFIRMATION,
+ expected_payload,
+ channel_slug=order.channel.slug,
)
@@ -335,7 +341,9 @@ def test_send_confirmation_emails_without_addresses_for_order(
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ORDER_CONFIRMATION, expected_payload
+ NotifyEventType.ORDER_CONFIRMATION,
+ expected_payload,
+ channel_slug=order.channel.slug,
)
@@ -358,7 +366,9 @@ def test_send_fulfillment_confirmation(
expected_payload = get_default_fulfillment_payload(fulfilled_order, fulfillment)
expected_payload["requester_user_id"] = staff_user.id
mocked_notify.assert_called_once_with(
- NotifyEventType.ORDER_FULFILLMENT_CONFIRMATION, payload=expected_payload
+ NotifyEventType.ORDER_FULFILLMENT_CONFIRMATION,
+ payload=expected_payload,
+ channel_slug=fulfilled_order.channel.slug,
)
@@ -376,7 +386,9 @@ def test_send_fulfillment_update(mocked_notify, fulfilled_order, site_settings):
expected_payload = get_default_fulfillment_payload(fulfilled_order, fulfillment)
mocked_notify.assert_called_once_with(
- NotifyEventType.ORDER_FULFILLMENT_UPDATE, expected_payload
+ NotifyEventType.ORDER_FULFILLMENT_UPDATE,
+ expected_payload,
+ channel_slug=fulfilled_order.channel.slug,
)
@@ -397,7 +409,9 @@ def test_send_email_order_canceled(mocked_notify, order, site_settings, staff_us
"requester_user_id": staff_user.id,
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ORDER_CANCELED, expected_payload
+ NotifyEventType.ORDER_CANCELED,
+ expected_payload,
+ channel_slug=order.channel.slug,
)
@@ -424,5 +438,7 @@ def test_send_email_order_refunded(mocked_notify, order, site_settings, staff_us
}
mocked_notify.assert_called_once_with(
- NotifyEventType.ORDER_REFUND_CONFIRMATION, expected_payload
+ NotifyEventType.ORDER_REFUND_CONFIRMATION,
+ expected_payload,
+ channel_slug=order.channel.slug,
)
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index 1a89ede8ed..7ff317f723 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -985,7 +985,9 @@ def test_send_fulfillment_order_lines_mails(
expected_payload = get_default_fulfillment_payload(order, fulfillment)
expected_payload["requester_user_id"] = staff_user.id
mocked_notify.assert_called_once_with(
- "order_fulfillment_confirmation", payload=expected_payload
+ "order_fulfillment_confirmation",
+ payload=expected_payload,
+ channel_slug=fulfilled_order.channel.slug,
)
diff --git a/saleor/payment/error_codes.py b/saleor/payment/error_codes.py
index c6cb7456aa..2549a107af 100644
--- a/saleor/payment/error_codes.py
+++ b/saleor/payment/error_codes.py
@@ -14,3 +14,4 @@ class PaymentErrorCode(Enum):
SHIPPING_METHOD_NOT_SET = "shipping_method_not_set"
PAYMENT_ERROR = "payment_error"
NOT_SUPPORTED_GATEWAY = "not_supported_gateway"
+ CHANNEL_INACTIVE = "channel_inactive"
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index 687a06e4c0..27abbb6ef9 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -75,6 +75,7 @@ def process_payment(
payment: Payment,
token: str,
manager: "PluginsManager",
+ channel_slug: str,
store_source: bool = False,
additional_data: Optional[dict] = None,
) -> Transaction:
@@ -86,7 +87,10 @@ def process_payment(
)
response, error = _fetch_gateway_response(
- manager.process_payment, payment.gateway, payment_data
+ manager.process_payment,
+ payment.gateway,
+ payment_data,
+ channel_slug=channel_slug,
)
action_required = response is not None and response.action_required
if response and response.payment_method_info:
@@ -109,14 +113,20 @@ def authorize(
payment: Payment,
token: str,
manager: "PluginsManager",
+ channel_slug: str,
store_source: bool = False,
) -> Transaction:
clean_authorize(payment)
payment_data = create_payment_information(
- payment=payment, payment_token=token, store_source=store_source
+ payment=payment,
+ payment_token=token,
+ store_source=store_source,
)
response, error = _fetch_gateway_response(
- manager.authorize_payment, payment.gateway, payment_data
+ manager.authorize_payment,
+ payment.gateway,
+ payment_data,
+ channel_slug=channel_slug,
)
if response and response.payment_method_info:
update_payment_method_details(payment, response)
@@ -137,6 +147,7 @@ def authorize(
def capture(
payment: Payment,
manager: "PluginsManager",
+ channel_slug: str,
amount: Decimal = None,
store_source: bool = False,
) -> Transaction:
@@ -148,7 +159,10 @@ def capture(
payment=payment, payment_token=token, amount=amount, store_source=store_source
)
response, error = _fetch_gateway_response(
- manager.capture_payment, payment.gateway, payment_data
+ manager.capture_payment,
+ payment.gateway,
+ payment_data,
+ channel_slug=channel_slug,
)
if response and response.payment_method_info:
update_payment_method_details(payment, response)
@@ -166,7 +180,10 @@ def capture(
@with_locked_payment
@payment_postprocess
def refund(
- payment: Payment, manager: "PluginsManager", amount: Decimal = None
+ payment: Payment,
+ manager: "PluginsManager",
+ channel_slug: str,
+ amount: Decimal = None,
) -> Transaction:
if amount is None:
amount = payment.captured_amount
@@ -190,7 +207,7 @@ def refund(
)
response, error = _fetch_gateway_response(
- manager.refund_payment, payment.gateway, payment_data
+ manager.refund_payment, payment.gateway, payment_data, channel_slug=channel_slug
)
return get_already_processed_transaction_or_create_new_transaction(
payment=payment,
@@ -205,11 +222,15 @@ def refund(
@require_active_payment
@with_locked_payment
@payment_postprocess
-def void(payment: Payment, manager: "PluginsManager") -> Transaction:
+def void(
+ payment: Payment,
+ manager: "PluginsManager",
+ channel_slug: str,
+) -> Transaction:
token = _get_past_transaction_token(payment, TransactionKind.AUTH)
payment_data = create_payment_information(payment=payment, payment_token=token)
response, error = _fetch_gateway_response(
- manager.void_payment, payment.gateway, payment_data
+ manager.void_payment, payment.gateway, payment_data, channel_slug=channel_slug
)
return get_already_processed_transaction_or_create_new_transaction(
payment=payment,
@@ -227,6 +248,7 @@ def void(payment: Payment, manager: "PluginsManager") -> Transaction:
def confirm(
payment: Payment,
manager: "PluginsManager",
+ channel_slug: str,
additional_data: Optional[dict] = None,
) -> Transaction:
txn = payment.transactions.filter(
@@ -237,7 +259,10 @@ def confirm(
payment=payment, payment_token=token, additional_data=additional_data
)
response, error = _fetch_gateway_response(
- manager.confirm_payment, payment.gateway, payment_data
+ manager.confirm_payment,
+ payment.gateway,
+ payment_data,
+ channel_slug=channel_slug,
)
action_required = response is not None and response.action_required
if response and response.payment_method_info:
@@ -253,13 +278,18 @@ def confirm(
def list_payment_sources(
- gateway: str, customer_id: str, manager: "PluginsManager"
+ gateway: str,
+ customer_id: str,
+ manager: "PluginsManager",
+ channel_slug: str,
) -> List["CustomerSource"]:
- return manager.list_payment_sources(gateway, customer_id)
+ return manager.list_payment_sources(gateway, customer_id, channel_slug=channel_slug)
-def list_gateways(manager: "PluginsManager") -> List["PaymentGateway"]:
- return manager.list_payment_gateways()
+def list_gateways(
+ manager: "PluginsManager", channel_slug: Optional[str] = None
+) -> List["PaymentGateway"]:
+ return manager.list_payment_gateways(channel_slug=channel_slug)
def _fetch_gateway_response(fn, *args, **kwargs):
@@ -294,10 +324,12 @@ def _validate_refund_amount(payment: Payment, amount: Decimal):
raise PaymentError("Cannot refund more than captured.")
-def payment_refund_or_void(payment: Optional[Payment], manager: "PluginsManager"):
+def payment_refund_or_void(
+ payment: Optional[Payment], manager: "PluginsManager", channel_slug: str
+):
if payment is None:
return
if payment.can_refund():
- refund(payment, manager)
+ refund(payment, manager, channel_slug=channel_slug)
elif payment.can_void():
- void(payment, manager)
+ void(payment, manager, channel_slug=channel_slug)
diff --git a/saleor/payment/gateways/adyen/plugin.py b/saleor/payment/gateways/adyen/plugin.py
index 1f8d709936..75ff0c70d9 100644
--- a/saleor/payment/gateways/adyen/plugin.py
+++ b/saleor/payment/gateways/adyen/plugin.py
@@ -53,6 +53,7 @@ ADDITIONAL_ACTION_PATH = "/additional-actions"
class AdyenGatewayPlugin(BasePlugin):
PLUGIN_ID = "mirumee.payments.adyen"
PLUGIN_NAME = GATEWAY_NAME
+ CONFIGURATION_PER_CHANNEL = True
DEFAULT_CONFIGURATION = [
{"name": "merchant-account", "value": None},
{"name": "api-key", "value": None},
diff --git a/saleor/payment/gateways/adyen/tests/conftest.py b/saleor/payment/gateways/adyen/tests/conftest.py
index 58eee89f89..a059361a5f 100644
--- a/saleor/payment/gateways/adyen/tests/conftest.py
+++ b/saleor/payment/gateways/adyen/tests/conftest.py
@@ -1,3 +1,4 @@
+from decimal import Decimal
from unittest import mock
import pytest
@@ -19,7 +20,7 @@ def vcr_config():
@pytest.fixture
-def adyen_plugin(settings):
+def adyen_plugin(settings, channel_USD):
def fun(
api_key=None,
merchant_account=None,
@@ -43,6 +44,7 @@ def adyen_plugin(settings):
with mock.patch("saleor.payment.gateways.adyen.utils.apple_pay.requests.post"):
manager.save_plugin_configuration(
AdyenGatewayPlugin.PLUGIN_ID,
+ channel_USD.slug,
{
"active": True,
"configuration": [
@@ -60,7 +62,7 @@ def adyen_plugin(settings):
)
manager = get_plugins_manager()
- return manager.plugins[0]
+ return manager.plugins_per_channel[channel_USD.slug][0]
return fun
@@ -91,13 +93,21 @@ def payment_adyen_for_checkout(checkout_with_items, address, shipping_method):
@pytest.fixture
-def payment_adyen_for_order(payment_adyen_for_checkout, order_with_lines):
- payment_adyen_for_checkout.checkout = None
- payment_adyen_for_checkout.order = order_with_lines
- payment_adyen_for_checkout.save()
+def payment_adyen_for_order(order_with_lines):
+ payment = create_payment(
+ gateway=AdyenGatewayPlugin.PLUGIN_ID,
+ payment_token="",
+ total=Decimal("80.00"),
+ currency=order_with_lines.currency,
+ email=order_with_lines.user_email,
+ customer_ip_address="",
+ checkout=None,
+ order=order_with_lines,
+ return_url="https://www.example.com",
+ )
Transaction.objects.create(
- payment=payment_adyen_for_checkout,
+ payment=payment,
action_required=False,
kind=TransactionKind.AUTH,
token="token",
@@ -108,7 +118,7 @@ def payment_adyen_for_order(payment_adyen_for_checkout, order_with_lines):
gateway_response={},
action_required_data={},
)
- return payment_adyen_for_checkout
+ return payment
@pytest.fixture()
diff --git a/saleor/payment/gateways/adyen/webhooks.py b/saleor/payment/gateways/adyen/webhooks.py
index 128dfe0dbf..6e731cf326 100644
--- a/saleor/payment/gateways/adyen/webhooks.py
+++ b/saleor/payment/gateways/adyen/webhooks.py
@@ -169,7 +169,7 @@ def create_order(payment, checkout, manager):
user=checkout.user or AnonymousUser(),
)
except ValidationError:
- payment_refund_or_void(payment, manager)
+ payment_refund_or_void(payment, manager, checkout_info.channel.slug)
return None
# Refresh the payment to assign the newly created order
payment.refresh_from_db()
diff --git a/saleor/payment/gateways/authorize_net/plugin.py b/saleor/payment/gateways/authorize_net/plugin.py
index d85b5ae038..71e356debd 100644
--- a/saleor/payment/gateways/authorize_net/plugin.py
+++ b/saleor/payment/gateways/authorize_net/plugin.py
@@ -32,6 +32,7 @@ if TYPE_CHECKING:
class AuthorizeNetGatewayPlugin(BasePlugin):
PLUGIN_NAME = GATEWAY_NAME
PLUGIN_ID = "mirumee.payments.authorize_net"
+ CONFIGURATION_PER_CHANNEL = True
DEFAULT_CONFIGURATION = [
{"name": "api_login_id", "value": None},
diff --git a/saleor/payment/gateways/authorize_net/tests/conftest.py b/saleor/payment/gateways/authorize_net/tests/conftest.py
index a581570049..8bb863a7fd 100644
--- a/saleor/payment/gateways/authorize_net/tests/conftest.py
+++ b/saleor/payment/gateways/authorize_net/tests/conftest.py
@@ -33,7 +33,7 @@ def authorize_net_payment(payment_dummy):
"saleor.payment.gateways.authorize_net.plugin.AuthorizeNetGatewayPlugin"
".validate_plugin_configuration"
)
-def authorize_net_plugin(_, settings, authorize_net_gateway_config):
+def authorize_net_plugin(_, settings, channel_USD, authorize_net_gateway_config):
settings.PLUGINS = [
"saleor.payment.gateways.authorize_net.plugin.AuthorizeNetGatewayPlugin"
]
@@ -43,6 +43,7 @@ def authorize_net_plugin(_, settings, authorize_net_gateway_config):
manager.save_plugin_configuration(
AuthorizeNetGatewayPlugin.PLUGIN_ID,
+ channel_USD.slug,
{
"active": True,
"configuration": [
@@ -70,4 +71,4 @@ def authorize_net_plugin(_, settings, authorize_net_gateway_config):
)
manager = get_plugins_manager()
- return manager.plugins[0]
+ return manager.plugins_per_channel[channel_USD.slug][0]
diff --git a/saleor/payment/gateways/braintree/plugin.py b/saleor/payment/gateways/braintree/plugin.py
index c19403daee..1d34e703dc 100644
--- a/saleor/payment/gateways/braintree/plugin.py
+++ b/saleor/payment/gateways/braintree/plugin.py
@@ -25,6 +25,8 @@ if TYPE_CHECKING:
class BraintreeGatewayPlugin(BasePlugin):
PLUGIN_ID = "mirumee.payments.braintree"
PLUGIN_NAME = GATEWAY_NAME
+ CONFIGURATION_PER_CHANNEL = True
+
DEFAULT_CONFIGURATION = [
{"name": "Public API key", "value": None},
{"name": "Secret API key", "value": None},
diff --git a/saleor/payment/gateways/dummy/tests/test_dummy.py b/saleor/payment/gateways/dummy/tests/test_dummy.py
index 48344220e7..4e549beead 100644
--- a/saleor/payment/gateways/dummy/tests/test_dummy.py
+++ b/saleor/payment/gateways/dummy/tests/test_dummy.py
@@ -14,7 +14,10 @@ def setup_dummy_gateway(settings):
def test_authorize_success(payment_dummy):
txn = gateway.authorize(
- payment=payment_dummy, token="Fake", manager=get_plugins_manager()
+ payment=payment_dummy,
+ token="Fake",
+ manager=get_plugins_manager(),
+ channel_slug=payment_dummy.order.channel.slug,
)
assert txn.is_success
assert txn.kind == TransactionKind.AUTH
@@ -44,7 +47,10 @@ def test_authorize_failed(is_active, charge_status, payment_dummy):
payment.save()
with pytest.raises(PaymentError):
txn = gateway.authorize(
- payment=payment, token="Fake", manager=get_plugins_manager()
+ payment=payment,
+ token="Fake",
+ manager=get_plugins_manager(),
+ channel_slug=payment.order.channel.slug,
)
assert txn is None
@@ -53,7 +59,10 @@ def test_authorize_gateway_error(payment_dummy, monkeypatch):
monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)
with pytest.raises(PaymentError):
txn = gateway.authorize(
- payment=payment_dummy, token="Fake", manager=get_plugins_manager()
+ payment=payment_dummy,
+ token="Fake",
+ manager=get_plugins_manager(),
+ channel_slug=payment_dummy.order.channel.slug,
)
assert txn.kind == TransactionKind.AUTH
assert not txn.is_success
@@ -63,7 +72,11 @@ def test_authorize_gateway_error(payment_dummy, monkeypatch):
def test_void_success(payment_txn_preauth):
assert payment_txn_preauth.is_active
assert payment_txn_preauth.charge_status == ChargeStatus.NOT_CHARGED
- txn = gateway.void(payment=payment_txn_preauth, manager=get_plugins_manager())
+ txn = gateway.void(
+ payment=payment_txn_preauth,
+ manager=get_plugins_manager(),
+ channel_slug=payment_txn_preauth.order.channel.slug,
+ )
assert txn.is_success
assert txn.kind == TransactionKind.VOID
assert txn.payment == payment_txn_preauth
@@ -92,14 +105,22 @@ def test_void_failed(is_active, charge_status, payment_dummy):
payment.charge_status = charge_status
payment.save()
with pytest.raises(PaymentError):
- txn = gateway.void(payment=payment, manager=get_plugins_manager())
+ txn = gateway.void(
+ payment=payment,
+ manager=get_plugins_manager(),
+ channel_slug=payment.order.channel.slug,
+ )
assert txn is None
def test_void_gateway_error(payment_txn_preauth, monkeypatch):
monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)
with pytest.raises(PaymentError):
- txn = gateway.void(payment=payment_txn_preauth, manager=get_plugins_manager())
+ txn = gateway.void(
+ payment=payment_txn_preauth,
+ manager=get_plugins_manager(),
+ channel_slug=payment_txn_preauth.order.channel.slug,
+ )
assert txn.kind == TransactionKind.VOID
assert not txn.is_success
assert txn.payment == payment_txn_preauth
@@ -114,6 +135,7 @@ def test_capture_success(amount, charge_status, payment_txn_preauth):
payment=payment_txn_preauth,
manager=get_plugins_manager(),
amount=Decimal(amount),
+ channel_slug=payment_txn_preauth.order.channel.slug,
)
assert txn.is_success
assert txn.payment == payment_txn_preauth
@@ -142,7 +164,10 @@ def test_capture_failed(
payment.save()
with pytest.raises(PaymentError):
txn = gateway.capture(
- payment=payment, manager=get_plugins_manager(), amount=amount
+ payment=payment,
+ manager=get_plugins_manager(),
+ amount=amount,
+ channel_slug=payment.order.channel.slug,
)
assert txn is None
@@ -151,7 +176,10 @@ def test_capture_gateway_error(payment_txn_preauth, monkeypatch):
monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)
with pytest.raises(PaymentError):
txn = gateway.capture(
- payment=payment_txn_preauth, manager=get_plugins_manager(), amount=80
+ payment=payment_txn_preauth,
+ manager=get_plugins_manager(),
+ amount=80,
+ channel_slug=payment_txn_preauth.order.channel.slug,
)
assert txn.kind == TransactionKind.CAPTURE
assert not txn.is_success
@@ -184,6 +212,7 @@ def test_refund_success(
payment=payment,
manager=get_plugins_manager(),
amount=Decimal(refund_amount),
+ channel_slug=payment.order.channel.slug,
)
payment.refresh_from_db()
@@ -217,6 +246,7 @@ def test_refund_failed(
payment=payment,
manager=get_plugins_manager(),
amount=Decimal(refund_amount),
+ channel_slug=payment.order.channel.slug,
)
assert txn is None
@@ -232,6 +262,7 @@ def test_refund_gateway_error(payment_txn_captured, monkeypatch):
payment=payment,
manager=get_plugins_manager(),
amount=Decimal("80.00"),
+ channel_slug=payment.order.channel.slug,
)
payment.refresh_from_db()
diff --git a/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.py b/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.py
index 63af452a36..f9476b4aab 100644
--- a/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.py
+++ b/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.py
@@ -39,6 +39,7 @@ def test_authorize_success(payment_dummy_credit_card):
payment=payment_dummy_credit_card,
token="Fake",
manager=get_plugins_manager(),
+ channel_slug=payment_dummy_credit_card.order.channel.slug,
)
assert txn.is_success
assert txn.kind == TransactionKind.AUTH
@@ -67,7 +68,12 @@ def test_authorize_failed(is_active, charge_status, error, payment_dummy_credit_
payment.charge_status = charge_status
payment.save()
with pytest.raises(PaymentError) as e:
- gateway.authorize(payment=payment, token="Fake", manager=get_plugins_manager())
+ gateway.authorize(
+ payment=payment,
+ token="Fake",
+ manager=get_plugins_manager(),
+ channel_slug=payment_dummy_credit_card.order.channel.slug,
+ )
assert e._excinfo[1].message == error
@@ -81,6 +87,7 @@ def test_authorize_gateway_error(payment_dummy_credit_card, monkeypatch):
payment=payment_dummy_credit_card,
token="Fake",
manager=get_plugins_manager(),
+ channel_slug=payment_dummy_credit_card.order.channel.slug,
)
assert e._excinfo[1].message == "Unable to authorize transaction"
@@ -93,7 +100,10 @@ def test_authorize_method_error(dummy_payment_data, dummy_gateway_config, monkey
)
# when
- response = authorize(dummy_payment_data, dummy_gateway_config)
+ response = authorize(
+ dummy_payment_data,
+ dummy_gateway_config,
+ )
# then
assert not response.is_success
@@ -107,7 +117,11 @@ def test_void_success(payment_txn_preauth):
assert payment_txn_preauth.is_active
assert payment_txn_preauth.charge_status == ChargeStatus.NOT_CHARGED
- txn = gateway.void(payment=payment_txn_preauth, manager=get_plugins_manager())
+ txn = gateway.void(
+ payment=payment_txn_preauth,
+ manager=get_plugins_manager(),
+ channel_slug=payment_txn_preauth.order.channel.slug,
+ )
assert txn.is_success
assert txn.kind == TransactionKind.VOID
assert txn.payment == payment_txn_preauth
@@ -136,7 +150,11 @@ def test_void_failed(is_active, charge_status, error, payment_dummy_credit_card)
payment.charge_status = charge_status
payment.save()
with pytest.raises(PaymentError) as e:
- gateway.void(payment=payment, manager=get_plugins_manager())
+ gateway.void(
+ payment=payment,
+ manager=get_plugins_manager(),
+ channel_slug=payment.order.channel.slug,
+ )
assert e._excinfo[1].message == error
@@ -149,7 +167,11 @@ def test_void_gateway_error(payment_txn_preauth, monkeypatch):
"saleor.payment.gateways.dummy_credit_card.dummy_success", lambda: False
)
with pytest.raises(PaymentError) as e:
- gateway.void(payment=payment_txn_preauth, manager=get_plugins_manager())
+ gateway.void(
+ payment=payment_txn_preauth,
+ manager=get_plugins_manager(),
+ channel_slug=payment_txn_preauth.order.channel.slug,
+ )
assert e._excinfo[1].message == "Unable to void the transaction."
@@ -188,6 +210,7 @@ def test_capture_success(amount, charge_status, token, payment_txn_preauth):
payment=payment_txn_preauth,
manager=get_plugins_manager(),
amount=Decimal(amount),
+ channel_slug=payment_txn_preauth.order.channel.slug,
)
assert txn.is_success
assert txn.payment == payment_txn_preauth
@@ -216,7 +239,12 @@ def test_capture_failed(
payment.charge_status = charge_status
payment.save()
with pytest.raises(PaymentError) as e:
- gateway.capture(payment=payment, manager=get_plugins_manager(), amount=amount)
+ gateway.capture(
+ payment=payment,
+ manager=get_plugins_manager(),
+ amount=amount,
+ channel_slug=payment.order.channel.slug,
+ )
assert e._excinfo[1].message == error
@@ -233,7 +261,11 @@ def test_capture_error_in_response(token, error, payment_txn_preauth):
# when
with pytest.raises(PaymentError) as e:
- gateway.capture(payment=payment_txn_preauth, manager=get_plugins_manager())
+ gateway.capture(
+ payment=payment_txn_preauth,
+ manager=get_plugins_manager(),
+ channel_slug=payment_txn_preauth.order.channel.slug,
+ )
assert e._excinfo[1].message == error
@@ -281,6 +313,7 @@ def test_refund_success(
payment=payment,
manager=get_plugins_manager(),
amount=Decimal(refund_amount),
+ channel_slug=payment.order.channel.slug,
)
payment.refresh_from_db()
@@ -318,6 +351,7 @@ def test_refund_failed(
payment=payment,
manager=get_plugins_manager(),
amount=Decimal(refund_amount),
+ channel_slug=payment.order.channel.slug,
)
assert e._excinfo[1].message == error
@@ -337,6 +371,7 @@ def test_refund_gateway_error(payment_txn_captured, monkeypatch):
payment=payment,
manager=get_plugins_manager(),
amount=Decimal("80.00"),
+ channel_slug=payment.order.channel.slug,
)
payment.refresh_from_db()
@@ -355,6 +390,7 @@ def test_process_payment_success(token, payment_dummy_credit_card):
payment=payment_dummy_credit_card,
token=token,
manager=get_plugins_manager(),
+ channel_slug=payment_dummy_credit_card.order.channel.slug,
)
# then
@@ -374,6 +410,7 @@ def test_process_payment_failed(token, error, payment_dummy_credit_card):
payment=payment_dummy_credit_card,
token=token,
manager=get_plugins_manager(),
+ channel_slug=payment_dummy_credit_card.order.channel.slug,
)
assert e._excinfo[1].message == error
@@ -411,6 +448,7 @@ def test_process_payment_pre_authorized(
payment=payment_dummy_credit_card,
token=token,
manager=get_plugins_manager(),
+ channel_slug=payment_dummy_credit_card.order.channel.slug,
)
# then
@@ -439,6 +477,7 @@ def test_process_payment_pre_authorized_and_capture(
payment=payment_dummy_credit_card,
token=token,
manager=get_plugins_manager(),
+ channel_slug=payment_dummy_credit_card.order.channel.slug,
)
# then
@@ -468,6 +507,7 @@ def test_process_payment_pre_authorized_and_capture_error(
payment=payment_dummy_credit_card,
token=token,
manager=get_plugins_manager(),
+ channel_slug=payment_dummy_credit_card.order.channel.slug,
)
assert e._excinfo[1].message == TOKEN_VALIDATION_MAPPING[token]
diff --git a/saleor/payment/migrations/0016_auto_20200423_0314.py b/saleor/payment/migrations/0016_auto_20200423_0314.py
index a8b4dec34c..e2eb7cc090 100644
--- a/saleor/payment/migrations/0016_auto_20200423_0314.py
+++ b/saleor/payment/migrations/0016_auto_20200423_0314.py
@@ -1,12 +1,15 @@
# Generated by Django 3.0.5 on 2020-04-23 08:14
+from django.conf import settings
from django.db import migrations
-
-from saleor.plugins.manager import get_plugins_manager
+from django.utils.module_loading import import_string
def get_plugins():
- plugins = get_plugins_manager().plugins
+ plugins = []
+ for plugin_path in settings.PLUGINS:
+ plugins.append(import_string(plugin_path))
+
return {plugin.PLUGIN_NAME: plugin.PLUGIN_ID for plugin in plugins}
diff --git a/saleor/payment/tests/test_gateway.py b/saleor/payment/tests/test_gateway.py
index e85168a381..bc9f88a71e 100644
--- a/saleor/payment/tests/test_gateway.py
+++ b/saleor/payment/tests/test_gateway.py
@@ -87,11 +87,14 @@ def test_process_payment(fake_payment_interface, payment_txn_preauth):
fake_payment_interface.process_payment.return_value = PROCESS_PAYMENT_RESPONSE
transaction = gateway.process_payment(
- payment=payment_txn_preauth, token=TOKEN, manager=fake_payment_interface
+ payment=payment_txn_preauth,
+ token=TOKEN,
+ manager=fake_payment_interface,
+ channel_slug=payment_txn_preauth.order.channel.slug,
)
fake_payment_interface.process_payment.assert_called_once_with(
- USED_GATEWAY, PAYMENT_DATA
+ USED_GATEWAY, PAYMENT_DATA, channel_slug=payment_txn_preauth.order.channel.slug
)
assert transaction.amount == PROCESS_PAYMENT_RESPONSE.amount
assert transaction.kind == TransactionKind.CAPTURE
@@ -112,10 +115,11 @@ def test_store_source_when_processing_payment(
token=TOKEN,
manager=fake_payment_interface,
store_source=True,
+ channel_slug=payment_txn_preauth.order.channel.slug,
)
fake_payment_interface.process_payment.assert_called_once_with(
- USED_GATEWAY, PAYMENT_DATA
+ USED_GATEWAY, PAYMENT_DATA, channel_slug=payment_txn_preauth.order.channel.slug
)
assert transaction.customer_id == PROCESS_PAYMENT_RESPONSE.customer_id
@@ -127,11 +131,14 @@ def test_authorize_payment(fake_payment_interface, payment_dummy):
fake_payment_interface.authorize_payment.return_value = AUTHORIZE_RESPONSE
transaction = gateway.authorize(
- payment=payment_dummy, token=TOKEN, manager=fake_payment_interface
+ payment=payment_dummy,
+ token=TOKEN,
+ manager=fake_payment_interface,
+ channel_slug=payment_dummy.order.channel.slug,
)
fake_payment_interface.authorize_payment.assert_called_once_with(
- USED_GATEWAY, PAYMENT_DATA
+ USED_GATEWAY, PAYMENT_DATA, channel_slug=payment_dummy.order.channel.slug
)
assert transaction.amount == AUTHORIZE_RESPONSE.amount
assert transaction.kind == TransactionKind.AUTH
@@ -147,11 +154,13 @@ def test_capture_payment(fake_payment_interface, payment_txn_preauth):
fake_payment_interface.capture_payment.return_value = PROCESS_PAYMENT_RESPONSE
transaction = gateway.capture(
- payment=payment_txn_preauth, manager=fake_payment_interface
+ payment=payment_txn_preauth,
+ manager=fake_payment_interface,
+ channel_slug=payment_txn_preauth.order.channel.slug,
)
fake_payment_interface.capture_payment.assert_called_once_with(
- USED_GATEWAY, PAYMENT_DATA
+ USED_GATEWAY, PAYMENT_DATA, channel_slug=payment_txn_preauth.order.channel.slug
)
assert transaction.amount == PROCESS_PAYMENT_RESPONSE.amount
assert transaction.kind == TransactionKind.CAPTURE
@@ -165,6 +174,7 @@ def test_refund_for_manual_payment(payment_txn_captured):
payment=payment_txn_captured,
manager=get_plugins_manager(),
amount=PARTIAL_REFUND_AMOUNT,
+ channel_slug=payment_txn_captured.order.channel.slug,
)
payment_txn_captured.refresh_from_db()
assert payment_txn_captured.charge_status == ChargeStatus.PARTIALLY_REFUNDED
@@ -185,9 +195,10 @@ def test_partial_refund_payment(fake_payment_interface, payment_txn_captured):
payment=payment_txn_captured,
manager=fake_payment_interface,
amount=PARTIAL_REFUND_AMOUNT,
+ channel_slug=payment_txn_captured.order.channel.slug,
)
fake_payment_interface.refund_payment.assert_called_once_with(
- USED_GATEWAY, PAYMENT_DATA
+ USED_GATEWAY, PAYMENT_DATA, channel_slug=payment_txn_captured.order.channel.slug
)
payment_txn_captured.refresh_from_db()
@@ -207,10 +218,12 @@ def test_full_refund_payment(fake_payment_interface, payment_txn_captured):
)
fake_payment_interface.refund_payment.return_value = FULL_REFUND_RESPONSE
transaction = gateway.refund(
- payment=payment_txn_captured, manager=fake_payment_interface
+ payment=payment_txn_captured,
+ manager=fake_payment_interface,
+ channel_slug=payment_txn_captured.order.channel.slug,
)
fake_payment_interface.refund_payment.assert_called_once_with(
- USED_GATEWAY, PAYMENT_DATA
+ USED_GATEWAY, PAYMENT_DATA, channel_slug=payment_txn_captured.order.channel.slug
)
payment_txn_captured.refresh_from_db()
@@ -231,11 +244,13 @@ def test_void_payment(fake_payment_interface, payment_txn_preauth):
fake_payment_interface.void_payment.return_value = VOID_RESPONSE
transaction = gateway.void(
- payment=payment_txn_preauth, manager=fake_payment_interface
+ payment=payment_txn_preauth,
+ manager=fake_payment_interface,
+ channel_slug=payment_txn_preauth.order.channel.slug,
)
fake_payment_interface.void_payment.assert_called_once_with(
- USED_GATEWAY, PAYMENT_DATA
+ USED_GATEWAY, PAYMENT_DATA, channel_slug=payment_txn_preauth.order.channel.slug
)
payment_txn_preauth.refresh_from_db()
assert not payment_txn_preauth.is_active
@@ -255,11 +270,15 @@ def test_confirm_payment(fake_payment_interface, payment_txn_to_confirm):
fake_payment_interface.confirm_payment.return_value = CONFIRM_RESPONSE
transaction = gateway.confirm(
- payment=payment_txn_to_confirm, manager=fake_payment_interface
+ payment=payment_txn_to_confirm,
+ manager=fake_payment_interface,
+ channel_slug=payment_txn_to_confirm.order.channel.slug,
)
fake_payment_interface.confirm_payment.assert_called_once_with(
- USED_GATEWAY, PAYMENT_DATA
+ USED_GATEWAY,
+ PAYMENT_DATA,
+ channel_slug=payment_txn_to_confirm.order.channel.slug,
)
assert transaction.amount == CONFIRM_RESPONSE.amount
assert transaction.kind == TransactionKind.CONFIRM
diff --git a/saleor/payment/tests/test_payment.py b/saleor/payment/tests/test_payment.py
index 9af9904e72..8539b42964 100644
--- a/saleor/payment/tests/test_payment.py
+++ b/saleor/payment/tests/test_payment.py
@@ -280,38 +280,73 @@ def test_gateway_charge_failed(
def test_gateway_charge_errors(payment_dummy, transaction_token, settings):
payment = payment_dummy
- gateway.authorize(payment, transaction_token, get_plugins_manager())
+ gateway.authorize(
+ payment,
+ transaction_token,
+ get_plugins_manager(),
+ channel_slug=payment_dummy.order.channel.slug,
+ )
with pytest.raises(PaymentError) as exc:
- gateway.capture(payment, get_plugins_manager(), Decimal("0"))
+ gateway.capture(
+ payment,
+ get_plugins_manager(),
+ amount=Decimal("0"),
+ channel_slug=payment_dummy.order.channel.slug,
+ )
assert exc.value.message == "Amount should be a positive number."
payment.charge_status = ChargeStatus.FULLY_REFUNDED
payment.save()
with pytest.raises(PaymentError) as exc:
- gateway.capture(payment, get_plugins_manager(), Decimal("10"))
+ gateway.capture(
+ payment,
+ get_plugins_manager(),
+ amount=Decimal("10"),
+ channel_slug=payment_dummy.order.channel.slug,
+ )
assert exc.value.message == "This payment cannot be captured."
payment.charge_status = ChargeStatus.NOT_CHARGED
payment.save()
with pytest.raises(PaymentError) as exc:
- gateway.capture(payment, get_plugins_manager(), Decimal("1000000"))
+ gateway.capture(
+ payment,
+ get_plugins_manager(),
+ amount=Decimal("1000000"),
+ channel_slug=payment_dummy.order.channel.slug,
+ )
assert exc.value.message == ("Unable to charge more than un-captured amount.")
def test_gateway_refund_errors(payment_txn_captured):
payment = payment_txn_captured
with pytest.raises(PaymentError) as exc:
- gateway.refund(payment, get_plugins_manager(), Decimal("1000000"))
+ gateway.refund(
+ payment,
+ get_plugins_manager(),
+ amount=Decimal("1000000"),
+ channel_slug=payment_txn_captured.order.channel.slug,
+ )
assert exc.value.message == "Cannot refund more than captured."
with pytest.raises(PaymentError) as exc:
- gateway.refund(payment, get_plugins_manager(), Decimal("0"))
+ gateway.refund(
+ payment,
+ get_plugins_manager(),
+ amount=Decimal("0"),
+ channel_slug=payment_txn_captured.order.channel.slug,
+ )
assert exc.value.message == "Amount should be a positive number."
payment.charge_status = ChargeStatus.NOT_CHARGED
payment.save()
with pytest.raises(PaymentError) as exc:
- gateway.refund(payment, get_plugins_manager(), Decimal("1"))
+ gateway.refund(
+ payment,
+ get_plugins_manager(),
+ amount=Decimal("1"),
+ channel_slug=payment_txn_captured.order.channel.slug,
+ )
assert exc.value.message == "This payment cannot be refunded."
@@ -479,7 +514,7 @@ def test_validate_gateway_response_not_json_serializable(gateway_response):
[("EUR", True), ("USD", True), ("PLN", False)],
)
def test_is_currency_supported(
- currency, exp_response, dummy_gateway_config, monkeypatch
+ currency, exp_response, dummy_gateway_config, monkeypatch, channel_USD
):
# given
manager = get_plugins_manager()
diff --git a/saleor/plugins/admin_email/plugin.py b/saleor/plugins/admin_email/plugin.py
index e7e1136500..5a660cf831 100644
--- a/saleor/plugins/admin_email/plugin.py
+++ b/saleor/plugins/admin_email/plugin.py
@@ -67,6 +67,7 @@ class AdminEmailPlugin(BasePlugin):
PLUGIN_NAME = "Admin emails"
PLUGIN_DESCRIPTION = "Plugin responsible for sending the staff emails."
DEFAULT_ACTIVE = True
+ CONFIGURATION_PER_CHANNEL = False
DEFAULT_CONFIGURATION = [
{
diff --git a/saleor/plugins/admin_email/tests/conftest.py b/saleor/plugins/admin_email/tests/conftest.py
index 40ca945e76..e2974ec639 100644
--- a/saleor/plugins/admin_email/tests/conftest.py
+++ b/saleor/plugins/admin_email/tests/conftest.py
@@ -66,6 +66,7 @@ def admin_email_plugin(settings):
):
manager.save_plugin_configuration(
AdminEmailPlugin.PLUGIN_ID,
+ None,
{
"active": active,
"configuration": [
@@ -121,6 +122,6 @@ def admin_email_plugin(settings):
},
)
manager = get_plugins_manager()
- return manager.plugins[0]
+ return manager.global_plugins[0]
return fun
diff --git a/saleor/plugins/anonymize/plugin.py b/saleor/plugins/anonymize/plugin.py
index 1505594d24..7f2baf57ff 100644
--- a/saleor/plugins/anonymize/plugin.py
+++ b/saleor/plugins/anonymize/plugin.py
@@ -19,6 +19,7 @@ class AnonymizePlugin(BasePlugin):
"Anonymize customer's personal data in the checkout, such as shipping "
"or billing address, email and phone number."
)
+ CONFIGURATION_PER_CHANNEL = False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
diff --git a/saleor/plugins/avatax/__init__.py b/saleor/plugins/avatax/__init__.py
index c31c30a677..d0e87c0fb8 100644
--- a/saleor/plugins/avatax/__init__.py
+++ b/saleor/plugins/avatax/__init__.py
@@ -49,6 +49,11 @@ DEFAULT_TAX_DESCRIPTION = "Unmapped Other SKU - taxable default"
class AvataxConfiguration:
username_or_account: str
password_or_license: str
+ from_street_address: str
+ from_city: str
+ from_country: str
+ from_postal_code: str
+ from_country_area: str = ""
use_sandbox: bool = True
company_name: str = "DEFAULT"
autocommit: bool = False
@@ -326,15 +331,6 @@ def generate_request_data(
config: AvataxConfiguration,
currency: str,
):
- company_address = Site.objects.get_current().settings.company_address
- if company_address:
- company_address = company_address.as_data()
- else:
- logging.warning(
- "To correct calculate taxes by Avatax, company address should be provided "
- "in dashboard.settings."
- )
- company_address = {}
data = {
"companyCode": config.company_name,
@@ -346,12 +342,12 @@ def generate_request_data(
"customerCode": 0,
"addresses": {
"shipFrom": {
- "line1": company_address.get("street_address_1"),
- "line2": company_address.get("street_address_2"),
- "city": company_address.get("city"),
- "region": company_address.get("country_area"),
- "country": company_address.get("country"),
- "postalCode": company_address.get("postal_code"),
+ "line1": config.from_street_address,
+ "line2": None,
+ "city": config.from_city,
+ "region": config.from_country_area,
+ "country": config.from_country,
+ "postalCode": config.from_postal_code,
},
"shipTo": {
"line1": address.get("street_address_1"),
diff --git a/saleor/plugins/avatax/plugin.py b/saleor/plugins/avatax/plugin.py
index c216836e17..4ffeefa5f1 100644
--- a/saleor/plugins/avatax/plugin.py
+++ b/saleor/plugins/avatax/plugin.py
@@ -7,6 +7,7 @@ from urllib.parse import urljoin
import opentracing
import opentracing.tags
from django.core.exceptions import ValidationError
+from django_countries import countries
from prices import Money, TaxedMoney, TaxedMoneyRange
from ...checkout import base_calculations
@@ -61,6 +62,11 @@ class AvataxPlugin(BasePlugin):
{"name": "Use sandbox", "value": True},
{"name": "Company name", "value": "DEFAULT"},
{"name": "Autocommit", "value": False},
+ {"name": "from_street_address", "value": None},
+ {"name": "from_city", "value": None},
+ {"name": "from_country", "value": None},
+ {"name": "from_country_area", "value": None},
+ {"name": "from_postal_code", "value": None},
]
CONFIG_STRUCTURE = {
"Username or account": {
@@ -92,18 +98,53 @@ class AvataxPlugin(BasePlugin):
"should be committed by default.",
"label": "Autocommit",
},
+ "from_street_address": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "To calculate taxes we need to provide `ship from` details.",
+ "label": "Ship from - street",
+ },
+ "from_city": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "To calculate taxes we need to provide `ship from` details.",
+ "label": "Ship from - city",
+ },
+ "from_country": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "To calculate taxes we need to provide `ship from` details. "
+ "Country code in ISO format. ",
+ "label": "Ship from - country",
+ },
+ "from_country_area": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "To calculate taxes we need to provide `ship from` details.",
+ "label": "Ship from - country area",
+ },
+ "from_postal_code": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "To calculate taxes we need to provide `ship from` details.",
+ "label": "Ship from - postal code",
+ },
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Convert to dict to easier take config elements
configuration = {item["name"]: item["value"] for item in self.configuration}
+
+ if from_country := configuration["from_country"]:
+ from_country = countries.alpha2(from_country.strip())
+
self.config = AvataxConfiguration(
username_or_account=configuration["Username or account"],
password_or_license=configuration["Password or license"],
use_sandbox=configuration["Use sandbox"],
company_name=configuration["Company name"],
autocommit=configuration["Autocommit"],
+ from_street_address=configuration["from_street_address"],
+ from_city=configuration["from_city"],
+ from_country=from_country,
+ from_country_area=configuration["from_country_area"],
+ from_postal_code=configuration["from_postal_code"],
)
def _skip_plugin(
@@ -656,6 +697,19 @@ class AvataxPlugin(BasePlugin):
if not configuration["Password or license"]:
missing_fields.append("Password or license")
+ required_from_address_fields = [
+ "from_street_address",
+ "from_city",
+ "from_country",
+ "from_postal_code",
+ ]
+
+ all_address_fields = all(
+ [configuration[field] for field in required_from_address_fields]
+ )
+ if not all_address_fields:
+ missing_fields.extend(required_from_address_fields)
+
if plugin_configuration.active:
if missing_fields:
error_msg = (
diff --git a/saleor/plugins/avatax/tests/conftest.py b/saleor/plugins/avatax/tests/conftest.py
index 80bc4fdf70..bc97b0507b 100644
--- a/saleor/plugins/avatax/tests/conftest.py
+++ b/saleor/plugins/avatax/tests/conftest.py
@@ -15,21 +15,35 @@ def vcr_config():
@pytest.fixture
-def plugin_configuration(db):
+def plugin_configuration(db, channel_USD):
def set_configuration(
username="test",
password="test",
sandbox=False,
+ channel=None,
+ active=True,
+ from_street_address="Teczowa 7",
+ from_city="Wroclaw",
+ from_country="PL",
+ from_country_area="",
+ from_postal_code="53-601",
):
+ channel = channel or channel_USD
data = {
- "active": True,
+ "active": active,
"name": AvataxPlugin.PLUGIN_NAME,
+ "channel": channel,
"configuration": [
{"name": "Username or account", "value": username},
{"name": "Password or license", "value": password},
{"name": "Use sandbox", "value": sandbox},
{"name": "Company name", "value": "DEFAULT"},
{"name": "Autocommit", "value": False},
+ {"name": "from_street_address", "value": from_street_address},
+ {"name": "from_city", "value": from_city},
+ {"name": "from_country", "value": from_country},
+ {"name": "from_country_area", "value": from_country_area},
+ {"name": "from_postal_code", "value": from_postal_code},
],
}
configuration = PluginConfiguration.objects.create(
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index 8f5ef1f2fe..e502ceaf31 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -674,7 +674,14 @@ def test_preprocess_order_creation_wrong_data(
def test_get_cached_tax_codes_or_fetch(monkeypatch):
monkeypatch.setattr("saleor.plugins.avatax.cache.get", lambda x, y: {})
config = AvataxConfiguration(
- username_or_account="test", password_or_license="test", use_sandbox=False
+ username_or_account="test",
+ password_or_license="test",
+ use_sandbox=False,
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_country_area="",
+ from_postal_code="53-601",
+ from_country="PL",
)
tax_codes = get_cached_tax_codes_or_fetch(config)
assert len(tax_codes) > 0
@@ -684,7 +691,13 @@ def test_get_cached_tax_codes_or_fetch(monkeypatch):
def test_get_cached_tax_codes_or_fetch_wrong_response(monkeypatch):
monkeypatch.setattr("saleor.plugins.avatax.cache.get", lambda x, y: {})
config = AvataxConfiguration(
- username_or_account="wrong_data", password_or_license="wrong_data"
+ username_or_account="wrong_data",
+ password_or_license="wrong_data",
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_country_area="",
+ from_postal_code="53-601",
+ from_country="PL",
)
tax_codes = get_cached_tax_codes_or_fetch(config)
assert len(tax_codes) == 0
@@ -697,7 +710,13 @@ def test_checkout_needs_new_fetch(
checkout_with_item.shipping_address = address
checkout_with_item.shipping_method = shipping_method
config = AvataxConfiguration(
- username_or_account="wrong_data", password_or_license="wrong_data"
+ username_or_account="wrong_data",
+ password_or_license="wrong_data",
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_country_area="",
+ from_postal_code="53-601",
+ from_country="PL",
)
manager = get_plugins_manager()
lines = fetch_checkout_lines(checkout_with_item)
@@ -712,7 +731,13 @@ def test_taxes_need_new_fetch_uses_cached_data(
checkout_with_item.shipping_address = address
config = AvataxConfiguration(
- username_or_account="wrong_data", password_or_license="wrong_data"
+ username_or_account="wrong_data",
+ password_or_license="wrong_data",
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_country_area="",
+ from_postal_code="53-601",
+ from_country="PL",
)
manager = get_plugins_manager()
lines = fetch_checkout_lines(checkout_with_item)
@@ -1315,7 +1340,7 @@ def test_get_order_shipping_tax_rate_skip_plugin(
assert tax_rate == Decimal("0.25")
-def test_get_plugin_configuration(settings):
+def test_get_plugin_configuration(settings, channel_USD):
settings.PLUGINS = ["saleor.plugins.avatax.plugin.AvataxPlugin"]
manager = get_plugins_manager()
plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
@@ -1331,12 +1356,16 @@ def test_get_plugin_configuration(settings):
@patch("saleor.plugins.avatax.plugin.api_get_request")
-def test_save_plugin_configuration(api_get_request_mock, settings):
+def test_save_plugin_configuration(
+ api_get_request_mock, settings, channel_USD, plugin_configuration
+):
settings.PLUGINS = ["saleor.plugins.avatax.plugin.AvataxPlugin"]
+ plugin_configuration()
api_get_request_mock.return_value = {"authenticated": True}
manager = get_plugins_manager()
manager.save_plugin_configuration(
AvataxPlugin.PLUGIN_ID,
+ channel_USD.slug,
{
"active": True,
"configuration": [
@@ -1345,7 +1374,9 @@ def test_save_plugin_configuration(api_get_request_mock, settings):
],
},
)
- manager.save_plugin_configuration(AvataxPlugin.PLUGIN_ID, {"active": True})
+ manager.save_plugin_configuration(
+ AvataxPlugin.PLUGIN_ID, channel_USD.slug, {"active": True}
+ )
plugin_configuration = PluginConfiguration.objects.get(
identifier=AvataxPlugin.PLUGIN_ID
)
@@ -1354,10 +1385,11 @@ def test_save_plugin_configuration(api_get_request_mock, settings):
@patch("saleor.plugins.avatax.plugin.api_get_request")
def test_save_plugin_configuration_authentication_failed(
- api_get_request_mock, settings
+ api_get_request_mock, settings, channel_USD, plugin_configuration
):
# given
settings.PLUGINS = ["saleor.plugins.avatax.plugin.AvataxPlugin"]
+ plugin_configuration(active=False)
api_get_request_mock.return_value = {"authenticated": False}
manager = get_plugins_manager()
@@ -1365,6 +1397,7 @@ def test_save_plugin_configuration_authentication_failed(
with pytest.raises(ValidationError) as e:
manager.save_plugin_configuration(
AvataxPlugin.PLUGIN_ID,
+ channel_USD.slug,
{
"active": True,
"configuration": [
@@ -1383,13 +1416,15 @@ def test_save_plugin_configuration_authentication_failed(
def test_save_plugin_configuration_cannot_be_enabled_without_config(
- settings, plugin_configuration
+ settings, plugin_configuration, channel_USD
):
plugin_configuration(None, None)
settings.PLUGINS = ["saleor.plugins.avatax.plugin.AvataxPlugin"]
manager = get_plugins_manager()
with pytest.raises(ValidationError):
- manager.save_plugin_configuration(AvataxPlugin.PLUGIN_ID, {"active": True})
+ manager.save_plugin_configuration(
+ AvataxPlugin.PLUGIN_ID, channel_USD.slug, {"active": True}
+ )
def test_show_taxes_on_storefront(plugin_configuration):
@@ -1402,7 +1437,12 @@ def test_show_taxes_on_storefront(plugin_configuration):
@override_settings(PLUGINS=["saleor.plugins.avatax.plugin.AvataxPlugin"])
def test_order_created(api_post_request_task_mock, order, plugin_configuration):
# given
- plugin_conf = plugin_configuration()
+ plugin_conf = plugin_configuration(
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_postal_code="53-601",
+ from_country="PL",
+ )
conf = {data["name"]: data["value"] for data in plugin_conf.configuration}
manager = get_plugins_manager()
@@ -1422,19 +1462,19 @@ def test_order_created(api_post_request_task_mock, order, plugin_configuration):
"customerCode": 0,
"addresses": {
"shipFrom": {
- "line1": None,
+ "line1": "Tęczowa 7",
"line2": None,
- "city": None,
- "region": None,
- "country": None,
- "postalCode": None,
+ "city": "WROCŁAW",
+ "region": "",
+ "country": "PL",
+ "postalCode": "53-601",
},
"shipTo": {
"line1": address.street_address_1,
"line2": address.street_address_2,
"city": address.city,
"region": address.city_area or "",
- "country": address.country,
+ "country": address.country.code,
"postalCode": address.postal_code,
},
},
@@ -1450,6 +1490,11 @@ def test_order_created(api_post_request_task_mock, order, plugin_configuration):
"use_sandbox": conf["Use sandbox"],
"company_name": conf["Company name"],
"autocommit": conf["Autocommit"],
+ "from_street_address": conf["from_street_address"],
+ "from_city": conf["from_city"],
+ "from_postal_code": conf["from_postal_code"],
+ "from_country": conf["from_country"],
+ "from_country_area": conf["from_country_area"],
}
api_post_request_task_mock.assert_called_once_with(
@@ -1541,6 +1586,11 @@ def test_api_get_request_handles_request_errors(product, monkeypatch):
username_or_account="test",
password_or_license="test",
use_sandbox=False,
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_country_area="",
+ from_postal_code="53-601",
+ from_country="PL",
)
url = "https://www.avatax.api.com/some-get-path"
@@ -1560,6 +1610,11 @@ def test_api_get_request_handles_json_errors(product, monkeypatch):
username_or_account="test",
password_or_license="test",
use_sandbox=False,
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_country_area="",
+ from_postal_code="53-601",
+ from_country="PL",
)
url = "https://www.avatax.api.com/some-get-path"
@@ -1579,6 +1634,11 @@ def test_api_post_request_handles_request_errors(product, monkeypatch):
username_or_account="test",
password_or_license="test",
use_sandbox=False,
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_country_area="",
+ from_postal_code="53-601",
+ from_country="PL",
)
url = "https://www.avatax.api.com/some-get-path"
@@ -1596,6 +1656,11 @@ def test_api_post_request_handles_json_errors(product, monkeypatch):
username_or_account="test",
password_or_license="test",
use_sandbox=False,
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_country_area="",
+ from_postal_code="53-601",
+ from_country="PL",
)
url = "https://www.avatax.api.com/some-get-path"
@@ -1625,6 +1690,11 @@ def test_get_order_request_data_checks_when_taxes_are_included_to_price(
username_or_account="",
password_or_license="",
use_sandbox=False,
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_country_area="",
+ from_postal_code="53-601",
+ from_country="PL",
)
request_data = get_order_request_data(order_with_lines, config)
lines_data = request_data["createTransactionModel"]["lines"]
@@ -1653,6 +1723,11 @@ def test_get_order_request_data_checks_when_taxes_are_not_included_to_price(
username_or_account="",
password_or_license="",
use_sandbox=False,
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_country_area="",
+ from_postal_code="53-601",
+ from_country="PL",
)
request_data = get_order_request_data(order_with_lines, config)
diff --git a/saleor/plugins/avatax/tests/test_avatax_caching.py b/saleor/plugins/avatax/tests/test_avatax_caching.py
index 08981d379b..b11b74b9e6 100644
--- a/saleor/plugins/avatax/tests/test_avatax_caching.py
+++ b/saleor/plugins/avatax/tests/test_avatax_caching.py
@@ -21,13 +21,14 @@ def test_calculate_checkout_total_use_cache(
plugin_configuration,
avalara_response_for_checkout_with_items_and_shipping,
monkeypatch,
+ channel_USD,
):
# given
checkout = checkout_with_items_and_shipping
checkout_info = checkout_with_items_and_shipping_info
plugin_configuration()
manager = get_plugins_manager()
- plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)
site_settings.company_address = address
site_settings.save()
lines = fetch_checkout_lines(checkout)
@@ -64,13 +65,14 @@ def test_calculate_checkout_total_save_avatax_response_in_cache(
plugin_configuration,
avalara_response_for_checkout_with_items_and_shipping,
monkeypatch,
+ channel_USD,
):
# given
checkout = checkout_with_items_and_shipping
checkout_info = checkout_with_items_and_shipping_info
plugin_configuration()
manager = get_plugins_manager()
- plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)
site_settings.company_address = address
site_settings.save()
lines = fetch_checkout_lines(checkout)
@@ -108,13 +110,14 @@ def test_calculate_checkout_subtotal_use_cache(
plugin_configuration,
avalara_response_for_checkout_with_items_and_shipping,
monkeypatch,
+ channel_USD,
):
# given
checkout = checkout_with_items_and_shipping
checkout_info = checkout_with_items_and_shipping_info
plugin_configuration()
manager = get_plugins_manager()
- plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)
site_settings.company_address = address
site_settings.save()
lines = fetch_checkout_lines(checkout)
@@ -151,13 +154,14 @@ def test_calculate_checkout_subtotal_save_avatax_response_in_cache(
plugin_configuration,
avalara_response_for_checkout_with_items_and_shipping,
monkeypatch,
+ channel_USD,
):
# given
checkout = checkout_with_items_and_shipping
checkout_info = checkout_with_items_and_shipping_info
plugin_configuration()
manager = get_plugins_manager()
- plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)
site_settings.company_address = address
site_settings.save()
lines = fetch_checkout_lines(checkout)
@@ -195,13 +199,14 @@ def test_calculate_checkout_shipping_use_cache(
plugin_configuration,
avalara_response_for_checkout_with_items_and_shipping,
monkeypatch,
+ channel_USD,
):
# given
checkout = checkout_with_items_and_shipping
checkout_info = checkout_with_items_and_shipping_info
plugin_configuration()
manager = get_plugins_manager()
- plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)
site_settings.company_address = address
site_settings.save()
lines = fetch_checkout_lines(checkout)
@@ -238,13 +243,14 @@ def test_calculate_checkout_shipping_save_avatax_response_in_cache(
plugin_configuration,
avalara_response_for_checkout_with_items_and_shipping,
monkeypatch,
+ channel_USD,
):
# given
checkout = checkout_with_items_and_shipping
checkout_info = checkout_with_items_and_shipping_info
plugin_configuration()
manager = get_plugins_manager()
- plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)
site_settings.company_address = address
site_settings.save()
lines = fetch_checkout_lines(checkout)
@@ -282,13 +288,14 @@ def test_calculate_checkout_line_total_use_cache(
plugin_configuration,
avalara_response_for_checkout_with_items_and_shipping,
monkeypatch,
+ channel_USD,
):
# given
checkout = checkout_with_items_and_shipping
checkout_info = checkout_with_items_and_shipping_info
plugin_configuration()
manager = get_plugins_manager()
- plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)
site_settings.company_address = address
site_settings.save()
lines = fetch_checkout_lines(checkout)
@@ -326,13 +333,14 @@ def test_calculate_checkout_line_save_avatax_response_in_cache(
plugin_configuration,
avalara_response_for_checkout_with_items_and_shipping,
monkeypatch,
+ channel_USD,
):
# given
checkout = checkout_with_items_and_shipping
checkout_info = checkout_with_items_and_shipping_info
plugin_configuration()
manager = get_plugins_manager()
- plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)
site_settings.company_address = address
site_settings.save()
lines = fetch_checkout_lines(checkout)
@@ -371,13 +379,14 @@ def test_calculate_checkout_line_unit_price_use_cache(
plugin_configuration,
avalara_response_for_checkout_with_items_and_shipping,
monkeypatch,
+ channel_USD,
):
# given
checkout = checkout_with_items_and_shipping
checkout_info = checkout_with_items_and_shipping_info
plugin_configuration()
manager = get_plugins_manager()
- plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)
site_settings.company_address = address
site_settings.save()
lines = fetch_checkout_lines(checkout)
@@ -423,13 +432,14 @@ def test_calculate_checkout_line_unit_price_save_avatax_response_in_cache(
plugin_configuration,
avalara_response_for_checkout_with_items_and_shipping,
monkeypatch,
+ channel_USD,
):
# given
checkout = checkout_with_items_and_shipping
checkout_info = checkout_with_items_and_shipping_info
plugin_configuration()
manager = get_plugins_manager()
- plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)
site_settings.company_address = address
site_settings.save()
lines = fetch_checkout_lines(checkout)
@@ -482,13 +492,14 @@ def test_get_checkout_line_tax_rate_use_cache(
plugin_configuration,
avalara_response_for_checkout_with_items_and_shipping,
monkeypatch,
+ channel_USD,
):
# given
checkout = checkout_with_items_and_shipping
checkout_info = checkout_with_items_and_shipping_info
plugin_configuration()
manager = get_plugins_manager()
- plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)
site_settings.company_address = address
site_settings.save()
lines = fetch_checkout_lines(checkout)
@@ -532,13 +543,14 @@ def test_get_checkout_line_tax_rate_save_avatax_response_in_cache(
plugin_configuration,
avalara_response_for_checkout_with_items_and_shipping,
monkeypatch,
+ channel_USD,
):
# given
checkout = checkout_with_items_and_shipping
checkout_info = checkout_with_items_and_shipping_info
plugin_configuration()
manager = get_plugins_manager()
- plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)
site_settings.company_address = address
site_settings.save()
lines = fetch_checkout_lines(checkout)
@@ -588,13 +600,14 @@ def test_get_checkout_shipping_tax_rate_use_cache(
plugin_configuration,
avalara_response_for_checkout_with_items_and_shipping,
monkeypatch,
+ channel_USD,
):
# given
checkout = checkout_with_items_and_shipping
checkout_info = checkout_with_items_and_shipping_info
plugin_configuration()
manager = get_plugins_manager()
- plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)
site_settings.company_address = address
site_settings.save()
lines = fetch_checkout_lines(checkout)
@@ -632,13 +645,14 @@ def test_get_checkout_shipping_tax_rate_save_avatax_response_in_cache(
plugin_configuration,
avalara_response_for_checkout_with_items_and_shipping,
monkeypatch,
+ channel_USD,
):
# given
checkout = checkout_with_items_and_shipping
checkout_info = checkout_with_items_and_shipping_info
plugin_configuration()
manager = get_plugins_manager()
- plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(AvataxPlugin.PLUGIN_ID, channel_USD.slug)
site_settings.company_address = address
site_settings.save()
lines = fetch_checkout_lines(checkout)
diff --git a/saleor/plugins/avatax/tests/test_tasks.py b/saleor/plugins/avatax/tests/test_tasks.py
index eecc08c5bc..f3a19492e9 100644
--- a/saleor/plugins/avatax/tests/test_tasks.py
+++ b/saleor/plugins/avatax/tests/test_tasks.py
@@ -26,6 +26,10 @@ def test_api_post_request_task_sends_request(
username_or_account="",
password_or_license="",
use_sandbox=False,
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_postal_code="53-601",
+ from_country="PL",
)
request_data = get_order_request_data(order_with_lines, config)
@@ -54,6 +58,10 @@ def test_api_post_request_task_creates_order_event(
username_or_account="",
password_or_license="",
use_sandbox=False,
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_postal_code="53-601",
+ from_country="PL",
)
request_data = get_order_request_data(order_with_lines, config)
@@ -83,6 +91,10 @@ def test_api_post_request_task_missing_response(
username_or_account="test",
password_or_license="test",
use_sandbox=False,
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_postal_code="53-601",
+ from_country="PL",
)
request_data = get_order_request_data(order_with_lines, config)
@@ -113,6 +125,10 @@ def test_api_post_request_task_order_doesnt_have_any_lines_with_taxes_to_calcula
username_or_account="test",
password_or_license="test",
use_sandbox=False,
+ from_street_address="Tęczowa 7",
+ from_city="WROCŁAW",
+ from_postal_code="53-601",
+ from_country="PL",
)
request_data = {}
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 5b39dc6f32..ee16f7a504 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -1,4 +1,4 @@
-from copy import copy
+from copy import copy, deepcopy
from dataclasses import dataclass
from decimal import Decimal
from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union
@@ -20,6 +20,7 @@ from .models import PluginConfiguration
if TYPE_CHECKING:
# flake8: noqa
from ..account.models import Address, User
+ from ..channel.models import Channel
from ..checkout.fetch import CheckoutInfo, CheckoutLineInfo
from ..checkout.models import Checkout
from ..core.notify_events import NotifyEventType
@@ -70,12 +71,20 @@ class BasePlugin:
PLUGIN_ID = ""
PLUGIN_DESCRIPTION = ""
CONFIG_STRUCTURE = None
+ CONFIGURATION_PER_CHANNEL = True
DEFAULT_CONFIGURATION = []
DEFAULT_ACTIVE = False
- def __init__(self, *, configuration: PluginConfigurationType, active: bool):
+ def __init__(
+ self,
+ *,
+ configuration: PluginConfigurationType,
+ active: bool,
+ channel: Optional["Channel"] = None
+ ):
self.configuration = self.get_plugin_configuration(configuration)
self.active = active
+ self.channel = channel
def __str__(self):
return self.PLUGIN_NAME
@@ -724,7 +733,7 @@ class BasePlugin:
for config_field in configuration:
if config_field["name"] not in desired_config_keys:
continue
- updated_configuration.append(config_field)
+ updated_configuration.append(copy(config_field))
configured_keys = set(d["name"] for d in updated_configuration)
missing_keys = desired_config_keys - configured_keys
diff --git a/saleor/plugins/invoicing/plugin.py b/saleor/plugins/invoicing/plugin.py
index 137714cdd3..2bd6e2ff6d 100644
--- a/saleor/plugins/invoicing/plugin.py
+++ b/saleor/plugins/invoicing/plugin.py
@@ -15,6 +15,7 @@ class InvoicingPlugin(BasePlugin):
PLUGIN_NAME = "Invoicing"
DEFAULT_ACTIVE = True
PLUGIN_DESCRIPTION = "Built-in saleor plugin that handles invoice creation."
+ CONFIGURATION_PER_CHANNEL = False
def invoice_request(
self,
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index 76c8eac738..1cb95dc9f2 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -1,5 +1,16 @@
+from collections import defaultdict
from decimal import Decimal
-from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Tuple, Union
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ Dict,
+ Iterable,
+ List,
+ Optional,
+ Tuple,
+ Type,
+ Union,
+)
import opentracing
from django.conf import settings
@@ -9,6 +20,7 @@ from django.utils.module_loading import import_string
from django_countries.fields import Country
from prices import Money, TaxedMoney
+from ..channel.models import Channel
from ..checkout import base_calculations
from ..core.payments import PaymentInterface
from ..core.prices import quantize_price
@@ -50,34 +62,74 @@ NotifyEventTypeChoice = str
class PluginsManager(PaymentInterface):
"""Base manager for handling plugins logic."""
- plugins: List["BasePlugin"] = []
+ plugins_per_channel: Dict[str, List["BasePlugin"]] = {}
+ global_plugins: List["BasePlugin"] = []
+ all_plugins: List["BasePlugin"] = []
+
+ def _load_plugin(
+ self,
+ PluginClass: Type["BasePlugin"],
+ config,
+ channel: Optional["Channel"] = None,
+ ) -> "BasePlugin":
+
+ if PluginClass.PLUGIN_ID in config:
+ existing_config = config[PluginClass.PLUGIN_ID]
+ plugin_config = existing_config.configuration
+ active = existing_config.active
+ channel = existing_config.channel
+ else:
+ plugin_config = PluginClass.DEFAULT_CONFIGURATION
+ active = PluginClass.get_default_active()
+
+ return PluginClass(configuration=plugin_config, active=active, channel=channel)
def __init__(self, plugins: List[str]):
with opentracing.global_tracer().start_active_span("PluginsManager.__init__"):
- self.plugins = []
- all_configs = self._get_all_plugin_configs()
+ self.plugins_per_channel = defaultdict(list)
+ self.all_plugins = []
+ (
+ self._global_config,
+ self._configs_per_channel,
+ ) = self._get_all_plugin_configs()
+ self.global_plugins = []
+ channels = Channel.objects.all()
for plugin_path in plugins:
+
with opentracing.global_tracer().start_active_span(f"{plugin_path}"):
PluginClass = import_string(plugin_path)
- if PluginClass.PLUGIN_ID in all_configs:
- existing_config = all_configs[PluginClass.PLUGIN_ID]
- plugin_config = existing_config.configuration
- active = existing_config.active
+ if not getattr(PluginClass, "CONFIGURATION_PER_CHANNEL", False):
+ plugin = self._load_plugin(PluginClass, self._global_config)
+ self.global_plugins.append(plugin)
+ self.all_plugins.append(plugin)
else:
- plugin_config = PluginClass.DEFAULT_CONFIGURATION
- active = PluginClass.get_default_active()
- plugin = PluginClass(configuration=plugin_config, active=active)
- self.plugins.append(plugin)
+ for channel in channels:
+ channel_configs = self._configs_per_channel.get(channel, {})
+ plugin = self._load_plugin(
+ PluginClass, channel_configs, channel
+ )
+ self.plugins_per_channel[channel.slug].append(plugin)
+ self.all_plugins.append(plugin)
+
+ for channel in channels:
+ self.plugins_per_channel[channel.slug].extend(self.global_plugins)
def __run_method_on_plugins(
- self, method_name: str, default_value: Any, *args, **kwargs
+ self,
+ method_name: str,
+ default_value: Any,
+ *args,
+ channel_slug: Optional[str] = None,
+ **kwargs
):
"""Try to run a method with the given name on each declared plugin."""
with opentracing.global_tracer().start_active_span(
f"PluginsManager.{method_name}"
):
value = default_value
- for plugin in self.plugins:
+ plugins = self.get_plugins(channel_slug=channel_slug)
+
+ for plugin in plugins:
value = self.__run_method_on_single_plugin(
plugin, method_name, value, *args, **kwargs
)
@@ -139,6 +191,7 @@ class PluginsManager(PaymentInterface):
lines,
address,
discounts,
+ channel_slug=checkout_info.channel.slug,
),
checkout_info.checkout.currency,
)
@@ -185,6 +238,7 @@ class PluginsManager(PaymentInterface):
lines,
address,
discounts,
+ channel_slug=checkout_info.channel.slug,
),
checkout_info.checkout.currency,
)
@@ -201,7 +255,10 @@ class PluginsManager(PaymentInterface):
)
return quantize_price(
self.__run_method_on_plugins(
- "calculate_order_shipping", default_value, order
+ "calculate_order_shipping",
+ default_value,
+ order,
+ channel_slug=order.channel.slug,
),
order.currency,
)
@@ -222,12 +279,16 @@ class PluginsManager(PaymentInterface):
lines,
address,
discounts,
+ channel_slug=checkout_info.channel.slug,
).quantize(Decimal(".0001"))
def get_order_shipping_tax_rate(self, order: "Order", shipping_price: TaxedMoney):
default_value = base_calculations.base_tax_rate(shipping_price)
return self.__run_method_on_plugins(
- "get_order_shipping_tax_rate", default_value, order
+ "get_order_shipping_tax_rate",
+ default_value,
+ order,
+ channel_slug=order.channel.slug,
).quantize(Decimal(".0001"))
def calculate_checkout_line_total(
@@ -252,6 +313,7 @@ class PluginsManager(PaymentInterface):
checkout_line_info,
address,
discounts,
+ channel_slug=checkout_info.channel.slug,
),
checkout_info.checkout.currency,
)
@@ -298,6 +360,7 @@ class PluginsManager(PaymentInterface):
checkout_line_info,
address,
discounts,
+ channel_slug=checkout_info.channel.slug,
),
total_line_price.currency,
)
@@ -319,6 +382,7 @@ class PluginsManager(PaymentInterface):
order_line,
variant,
product,
+ channel_slug=order.channel.slug,
),
order_line.currency,
)
@@ -341,6 +405,7 @@ class PluginsManager(PaymentInterface):
checkout_line_info,
address,
discounts,
+ channel_slug=checkout_info.channel.slug,
).quantize(Decimal(".0001"))
def get_order_line_tax_rate(
@@ -353,7 +418,13 @@ class PluginsManager(PaymentInterface):
) -> Decimal:
default_value = base_calculations.base_tax_rate(unit_price)
return self.__run_method_on_plugins(
- "get_order_line_tax_rate", default_value, order, product, variant, address
+ "get_order_line_tax_rate",
+ default_value,
+ order,
+ product,
+ variant,
+ address,
+ channel_slug=order.channel.slug,
).quantize(Decimal(".0001"))
def get_tax_rate_type_choices(self) -> List[TaxType]:
@@ -365,27 +436,36 @@ class PluginsManager(PaymentInterface):
return self.__run_method_on_plugins("show_taxes_on_storefront", default_value)
def apply_taxes_to_product(
- self, product: "Product", price: Money, country: Country
+ self, product: "Product", price: Money, country: Country, channel_slug: str
):
default_value = quantize_price(
TaxedMoney(net=price, gross=price), price.currency
)
return quantize_price(
self.__run_method_on_plugins(
- "apply_taxes_to_product", default_value, product, price, country
+ "apply_taxes_to_product",
+ default_value,
+ product,
+ price,
+ country,
+ channel_slug=channel_slug,
),
price.currency,
)
def apply_taxes_to_shipping(
- self, price: Money, shipping_address: "Address"
+ self, price: Money, shipping_address: "Address", channel_slug: str
) -> TaxedMoney:
default_value = quantize_price(
TaxedMoney(net=price, gross=price), price.currency
)
return quantize_price(
self.__run_method_on_plugins(
- "apply_taxes_to_shipping", default_value, price, shipping_address
+ "apply_taxes_to_shipping",
+ default_value,
+ price,
+ shipping_address,
+ channel_slug=channel_slug,
),
price.currency,
)
@@ -398,7 +478,12 @@ class PluginsManager(PaymentInterface):
):
default_value = None
return self.__run_method_on_plugins(
- "preprocess_order_creation", default_value, checkout_info, discounts, lines
+ "preprocess_order_creation",
+ default_value,
+ checkout_info,
+ discounts,
+ lines,
+ channel_slug=checkout_info.channel.slug,
)
def customer_created(self, customer: "User"):
@@ -443,59 +528,100 @@ class PluginsManager(PaymentInterface):
def order_created(self, order: "Order"):
default_value = None
- return self.__run_method_on_plugins("order_created", default_value, order)
+ return self.__run_method_on_plugins(
+ "order_created", default_value, order, channel_slug=order.channel.slug
+ )
def order_confirmed(self, order: "Order"):
default_value = None
- return self.__run_method_on_plugins("order_confirmed", default_value, order)
+ return self.__run_method_on_plugins(
+ "order_confirmed", default_value, order, channel_slug=order.channel.slug
+ )
def invoice_request(
self, order: "Order", invoice: "Invoice", number: Optional[str]
):
default_value = None
return self.__run_method_on_plugins(
- "invoice_request", default_value, order, invoice, number
+ "invoice_request",
+ default_value,
+ order,
+ invoice,
+ number,
+ channel_slug=order.channel.slug,
)
def invoice_delete(self, invoice: "Invoice"):
default_value = None
- return self.__run_method_on_plugins("invoice_delete", default_value, invoice)
+ channel_slug = invoice.order.channel.slug if invoice.order else None
+ return self.__run_method_on_plugins(
+ "invoice_delete",
+ default_value,
+ invoice,
+ channel_slug=channel_slug,
+ )
def invoice_sent(self, invoice: "Invoice", email: str):
default_value = None
+ channel_slug = invoice.order.channel.slug if invoice.order else None
return self.__run_method_on_plugins(
- "invoice_sent", default_value, invoice, email
+ "invoice_sent",
+ default_value,
+ invoice,
+ email,
+ channel_slug=channel_slug,
)
def order_fully_paid(self, order: "Order"):
default_value = None
- return self.__run_method_on_plugins("order_fully_paid", default_value, order)
+ return self.__run_method_on_plugins(
+ "order_fully_paid", default_value, order, channel_slug=order.channel.slug
+ )
def order_updated(self, order: "Order"):
default_value = None
- return self.__run_method_on_plugins("order_updated", default_value, order)
+ return self.__run_method_on_plugins(
+ "order_updated", default_value, order, channel_slug=order.channel.slug
+ )
def order_cancelled(self, order: "Order"):
default_value = None
- return self.__run_method_on_plugins("order_cancelled", default_value, order)
+ return self.__run_method_on_plugins(
+ "order_cancelled", default_value, order, channel_slug=order.channel.slug
+ )
def order_fulfilled(self, order: "Order"):
default_value = None
- return self.__run_method_on_plugins("order_fulfilled", default_value, order)
+ return self.__run_method_on_plugins(
+ "order_fulfilled", default_value, order, channel_slug=order.channel.slug
+ )
def fulfillment_created(self, fulfillment: "Fulfillment"):
default_value = None
return self.__run_method_on_plugins(
- "fulfillment_created", default_value, fulfillment
+ "fulfillment_created",
+ default_value,
+ fulfillment,
+ channel_slug=fulfillment.order.channel.slug,
)
def checkout_created(self, checkout: "Checkout"):
default_value = None
- return self.__run_method_on_plugins("checkout_created", default_value, checkout)
+ return self.__run_method_on_plugins(
+ "checkout_created",
+ default_value,
+ checkout,
+ channel_slug=checkout.channel.slug,
+ )
def checkout_updated(self, checkout: "Checkout"):
default_value = None
- return self.__run_method_on_plugins("checkout_updated", default_value, checkout)
+ return self.__run_method_on_plugins(
+ "checkout_updated",
+ default_value,
+ checkout,
+ channel_slug=checkout.channel.slug,
+ )
def page_created(self, page: "Page"):
default_value = None
@@ -510,11 +636,11 @@ class PluginsManager(PaymentInterface):
return self.__run_method_on_plugins("page_deleted", default_value, page)
def initialize_payment(
- self, gateway, payment_data: dict
+ self, gateway, payment_data: dict, channel_slug: str
) -> Optional["InitializedPaymentResponse"]:
method_name = "initialize_payment"
default_value = None
- gtw = self.get_plugin(gateway)
+ gtw = self.get_plugin(gateway, channel_slug)
if not gtw:
return None
@@ -526,45 +652,59 @@ class PluginsManager(PaymentInterface):
)
def authorize_payment(
- self, gateway: str, payment_information: "PaymentData"
+ self, gateway: str, payment_information: "PaymentData", channel_slug: str
) -> "GatewayResponse":
method_name = "authorize_payment"
- return self.__run_payment_method(gateway, method_name, payment_information)
+ return self.__run_payment_method(
+ gateway, method_name, payment_information, channel_slug=channel_slug
+ )
def capture_payment(
- self, gateway: str, payment_information: "PaymentData"
+ self, gateway: str, payment_information: "PaymentData", channel_slug: str
) -> "GatewayResponse":
method_name = "capture_payment"
- return self.__run_payment_method(gateway, method_name, payment_information)
+ return self.__run_payment_method(
+ gateway, method_name, payment_information, channel_slug=channel_slug
+ )
def refund_payment(
- self, gateway: str, payment_information: "PaymentData"
+ self, gateway: str, payment_information: "PaymentData", channel_slug: str
) -> "GatewayResponse":
method_name = "refund_payment"
- return self.__run_payment_method(gateway, method_name, payment_information)
+ return self.__run_payment_method(
+ gateway, method_name, payment_information, channel_slug=channel_slug
+ )
def void_payment(
- self, gateway: str, payment_information: "PaymentData"
+ self, gateway: str, payment_information: "PaymentData", channel_slug: str
) -> "GatewayResponse":
method_name = "void_payment"
- return self.__run_payment_method(gateway, method_name, payment_information)
+ return self.__run_payment_method(
+ gateway, method_name, payment_information, channel_slug=channel_slug
+ )
def confirm_payment(
- self, gateway: str, payment_information: "PaymentData"
+ self, gateway: str, payment_information: "PaymentData", channel_slug: str
) -> "GatewayResponse":
method_name = "confirm_payment"
- return self.__run_payment_method(gateway, method_name, payment_information)
+ return self.__run_payment_method(
+ gateway, method_name, payment_information, channel_slug=channel_slug
+ )
def process_payment(
- self, gateway: str, payment_information: "PaymentData"
+ self, gateway: str, payment_information: "PaymentData", channel_slug: str
) -> "GatewayResponse":
method_name = "process_payment"
- return self.__run_payment_method(gateway, method_name, payment_information)
+ return self.__run_payment_method(
+ gateway, method_name, payment_information, channel_slug=channel_slug
+ )
- def token_is_required_as_payment_input(self, gateway) -> bool:
+ def token_is_required_as_payment_input(
+ self, gateway: str, channel_slug: str
+ ) -> bool:
method_name = "token_is_required_as_payment_input"
default_value = True
- gtw = self.get_plugin(gateway)
+ gtw = self.get_plugin(gateway, channel_slug=channel_slug)
if gtw is not None:
return self.__run_method_on_single_plugin(
gtw,
@@ -573,35 +713,53 @@ class PluginsManager(PaymentInterface):
)
return default_value
- def get_client_token(self, gateway, token_config: "TokenConfig") -> str:
+ def get_client_token(
+ self,
+ gateway,
+ token_config: "TokenConfig",
+ channel_slug: str,
+ ) -> str:
method_name = "get_client_token"
default_value = None
- gtw = self.get_plugin(gateway)
+ gtw = self.get_plugin(gateway, channel_slug=channel_slug)
return self.__run_method_on_single_plugin(
gtw, method_name, default_value, token_config=token_config
)
def list_payment_sources(
- self, gateway: str, customer_id: str
+ self,
+ gateway: str,
+ customer_id: str,
+ channel_slug: str,
) -> List["CustomerSource"]:
default_value: list = []
- gtw = self.get_plugin(gateway)
+ gtw = self.get_plugin(gateway, channel_slug=channel_slug)
if gtw is not None:
return self.__run_method_on_single_plugin(
gtw, "list_payment_sources", default_value, customer_id=customer_id
)
raise Exception(f"Payment plugin {gateway} is inaccessible!")
- def get_active_plugins(self, plugins=None) -> List["BasePlugin"]:
- if plugins is None:
- plugins = self.plugins
- return [plugin for plugin in plugins if plugin.active]
+ def get_plugins(
+ self, channel_slug: Optional[str] = None, active_only=False
+ ) -> List["BasePlugin"]:
+ """Return list of plugins for a given channel."""
+ if channel_slug:
+ plugins = self.plugins_per_channel[channel_slug]
+ else:
+ plugins = self.all_plugins
- def list_payment_plugin(self, active_only: bool = False) -> Dict[str, "BasePlugin"]:
- payment_method = "process_payment"
- plugins = self.plugins
if active_only:
- plugins = self.get_active_plugins()
+ plugins = [plugin for plugin in plugins if plugin.active]
+ return plugins
+
+ def list_payment_plugin(
+ self, active_only: bool = False, channel_slug: Optional["str"] = None
+ ) -> Dict[str, "BasePlugin"]:
+ payment_method = "process_payment"
+
+ plugins = self.get_plugins(channel_slug=channel_slug, active_only=active_only)
+
return {
plugin.PLUGIN_ID: plugin
for plugin in plugins
@@ -612,9 +770,14 @@ class PluginsManager(PaymentInterface):
self,
currency: Optional[str] = None,
checkout: Optional["Checkout"] = None,
+ channel_slug: Optional[str] = None,
active_only: bool = True,
) -> List["PaymentGateway"]:
- payment_plugins = self.list_payment_plugin(active_only=active_only)
+ channel_slug = checkout.channel.slug if checkout else channel_slug
+
+ payment_plugins = self.list_payment_plugin(
+ active_only=active_only, channel_slug=channel_slug
+ )
# if currency is given return only gateways which support given currency
gateways = []
for plugin in payment_plugins.values():
@@ -626,10 +789,8 @@ class PluginsManager(PaymentInterface):
return gateways
def list_external_authentications(self, active_only: bool = True) -> List[dict]:
- plugins = self.plugins
auth_basic_method = "external_obtain_access_tokens"
- if active_only:
- plugins = self.get_active_plugins()
+ plugins = self.get_plugins(active_only=active_only)
return [
{"id": plugin.PLUGIN_ID, "name": plugin.PLUGIN_NAME}
for plugin in plugins
@@ -641,10 +802,11 @@ class PluginsManager(PaymentInterface):
gateway: str,
method_name: str,
payment_information: "PaymentData",
+ channel_slug: str,
**kwargs,
) -> "GatewayResponse":
default_value = None
- gtw = self.get_plugin(gateway)
+ gtw = self.get_plugin(gateway, channel_slug)
if gtw is not None:
resp = self.__run_method_on_single_plugin(
gtw,
@@ -664,10 +826,19 @@ class PluginsManager(PaymentInterface):
def _get_all_plugin_configs(self):
with opentracing.global_tracer().start_active_span("_get_all_plugin_configs"):
if not hasattr(self, "_plugin_configs"):
- self._plugin_configs = {
- pc.identifier: pc for pc in PluginConfiguration.objects.all()
- }
- return self._plugin_configs
+ plugin_configurations = PluginConfiguration.objects.prefetch_related(
+ "channel"
+ ).all()
+ self._plugin_configs_per_channel = defaultdict(dict)
+ self._global_plugin_configs = {}
+ for pc in plugin_configurations:
+ channel = pc.channel
+ if channel is None:
+ self._global_plugin_configs[pc.identifier] = pc
+ else:
+ self._plugin_configs_per_channel[channel][pc.identifier] = pc
+
+ return self._global_plugin_configs, self._plugin_configs_per_channel
# FIXME these methods should be more generic
@@ -695,11 +866,23 @@ class PluginsManager(PaymentInterface):
"get_tax_rate_percentage_value", default_value, obj, country
).quantize(Decimal("1."))
- def save_plugin_configuration(self, plugin_id, cleaned_data: dict):
- for plugin in self.plugins:
+ def save_plugin_configuration(
+ self, plugin_id, channel_slug: Optional[str], cleaned_data: dict
+ ):
+ if channel_slug:
+ plugins = self.get_plugins(channel_slug=channel_slug)
+ channel = Channel.objects.filter(slug=channel_slug).first()
+ if not channel:
+ return None
+ else:
+ channel = None
+ plugins = self.global_plugins
+
+ for plugin in plugins:
if plugin.PLUGIN_ID == plugin_id:
plugin_configuration, _ = PluginConfiguration.objects.get_or_create(
identifier=plugin_id,
+ channel=channel,
defaults={"configuration": plugin.configuration},
)
configuration = plugin.save_plugin_configuration(
@@ -707,10 +890,15 @@ class PluginsManager(PaymentInterface):
)
configuration.name = plugin.PLUGIN_NAME
configuration.description = plugin.PLUGIN_DESCRIPTION
+ plugin.active = configuration.active
+ plugin.configuration = configuration.configuration
return configuration
- def get_plugin(self, plugin_id: str) -> Optional["BasePlugin"]:
- for plugin in self.plugins:
+ def get_plugin(
+ self, plugin_id: str, channel_slug: Optional[str] = None
+ ) -> Optional["BasePlugin"]:
+ plugins = self.get_plugins(channel_slug=channel_slug)
+ for plugin in plugins:
if plugin.PLUGIN_ID == plugin_id:
return plugin
return None
@@ -725,6 +913,7 @@ class PluginsManager(PaymentInterface):
if len(split_path) == 2:
path = split_path[1]
+ # FIXME
default_value = HttpResponseNotFound()
plugin = self.get_plugin(plugin_id)
if not plugin:
@@ -733,9 +922,16 @@ class PluginsManager(PaymentInterface):
plugin, "webhook", default_value, request, path
)
- def notify(self, event: "NotifyEventTypeChoice", payload: dict):
+ def notify(
+ self,
+ event: "NotifyEventTypeChoice",
+ payload: dict,
+ channel_slug: Optional[str] = None,
+ ):
default_value = None
- return self.__run_method_on_plugins("notify", default_value, event, payload)
+ return self.__run_method_on_plugins(
+ "notify", default_value, event, payload, channel_slug=channel_slug
+ )
def external_obtain_access_tokens(
self, plugin_id: str, data: dict, request: WSGIRequest
diff --git a/saleor/plugins/migrations/0002_auto_20200417_0335.py b/saleor/plugins/migrations/0002_auto_20200417_0335.py
index 75e012f197..e0328fec22 100644
--- a/saleor/plugins/migrations/0002_auto_20200417_0335.py
+++ b/saleor/plugins/migrations/0002_auto_20200417_0335.py
@@ -1,8 +1,8 @@
# Generated by Django 3.0.5 on 2020-04-17 08:35
+from django.conf import settings
from django.db import migrations, models
-
-from saleor.plugins.manager import get_plugins_manager
+from django.utils.module_loading import import_string
def get_plugin(plugins, plugin_name):
@@ -13,13 +13,16 @@ def get_plugin(plugins, plugin_name):
def update_identifier_field(apps, schema):
- plugins_manager = get_plugins_manager()
+ plugins = []
+ for plugin_path in settings.PLUGINS:
+ plugins.append(import_string(plugin_path))
plugins_configuration = apps.get_model(
"plugins", "PluginConfiguration"
).objects.all()
+
for plugin_configuration in plugins_configuration:
- plugin = get_plugin(plugins_manager.plugins, plugin_configuration.name)
+ plugin = get_plugin(plugins, plugin_configuration.name)
plugin_configuration.identifier = plugin.PLUGIN_ID
plugin_configuration.save(update_fields=["identifier"])
diff --git a/saleor/plugins/migrations/0003_auto_20200429_0142.py b/saleor/plugins/migrations/0003_auto_20200429_0142.py
index 33ae629046..311da5478b 100644
--- a/saleor/plugins/migrations/0003_auto_20200429_0142.py
+++ b/saleor/plugins/migrations/0003_auto_20200429_0142.py
@@ -1,19 +1,29 @@
# Generated by Django 3.0.5 on 2020-04-29 06:42
+from django.conf import settings
from django.db import migrations, models
from django.db.models import Q
+from django.utils.module_loading import import_string
-from saleor.plugins.manager import get_plugins_manager
+
+def get_plugin(plugins, plugin_identifier):
+ for plugin in plugins:
+ if plugin.PLUGIN_ID == plugin_identifier:
+ return plugin
+ return None
def fill_plugins_name(apps, schema):
- plugins_manager = get_plugins_manager()
+ plugins = []
+ for plugin_path in settings.PLUGINS:
+ plugins.append(import_string(plugin_path))
+
plugins_configuration = apps.get_model(
"plugins", "PluginConfiguration"
).objects.filter(Q(name="") | Q(name__isnull=True))
for plugin_configuration in plugins_configuration:
- plugin = plugins_manager.get_plugin(plugin_configuration.identifier)
+ plugin = get_plugin(plugins, plugin_configuration.identifier)
plugin_configuration.name = plugin.PLUGIN_NAME
plugin_configuration.save()
diff --git a/saleor/plugins/migrations/0008_pluginconfiguration_channel.py b/saleor/plugins/migrations/0008_pluginconfiguration_channel.py
new file mode 100644
index 0000000000..45f59f87a8
--- /dev/null
+++ b/saleor/plugins/migrations/0008_pluginconfiguration_channel.py
@@ -0,0 +1,97 @@
+import django.db.models.deletion
+from django.db import migrations, models
+
+PLUGINS_ID_TO_SKIP = [
+ "mirumee.webhooks",
+ "mirumee.payments.dummy",
+ "mirumee.payments.dummy_credit_card",
+ "mirumee.invoicing",
+]
+
+
+def move_company_address_to_avatax_configuration(apps, schema):
+ avatax_configuration = (
+ apps.get_model("plugins", "PluginConfiguration")
+ .objects.filter(identifier="mirumee.taxes.avalara")
+ .first()
+ )
+ if avatax_configuration and avatax_configuration.configuration:
+ site_settings = apps.get_model("site", "SiteSettings").objects.first()
+ configuration = avatax_configuration.configuration
+
+ if company_address := site_settings.company_address:
+ configuration.extend(
+ [
+ {
+ "name": "from_street_address",
+ "value": company_address.street_address_1,
+ },
+ {
+ "name": "from_city",
+ "value": company_address.city,
+ },
+ {
+ "name": "from_country",
+ "value": company_address.country.code,
+ },
+ {
+ "name": "from_country_area",
+ "value": company_address.country_area,
+ },
+ {
+ "name": "from_postal_code",
+ "value": company_address.postal_code,
+ },
+ ]
+ )
+ avatax_configuration.save()
+
+
+def populate_plugin_configurations_for_channels(apps, schema):
+ PluginConfiguration = apps.get_model("plugins", "PluginConfiguration")
+ Channel = apps.get_model("channel", "Channel")
+
+ channels = Channel.objects.all()
+ configurations = PluginConfiguration.objects.exclude(
+ identifier__in=PLUGINS_ID_TO_SKIP
+ )
+
+ for channel in channels:
+ for configuration in configurations:
+ configuration.id = None
+ configuration.channel = channel
+ configuration.save()
+
+ configurations.filter(channel__isnull=True).delete()
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("channel", "0001_initial"),
+ ("plugins", "0007_add_user_emails_configuration"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="pluginconfiguration",
+ name="identifier",
+ field=models.CharField(max_length=128),
+ ),
+ migrations.AddField(
+ model_name="pluginconfiguration",
+ name="channel",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ to="channel.channel",
+ ),
+ ),
+ migrations.AlterUniqueTogether(
+ name="pluginconfiguration",
+ unique_together={("identifier", "channel")},
+ ),
+ migrations.RunPython(move_company_address_to_avatax_configuration),
+ migrations.RunPython(populate_plugin_configurations_for_channels),
+ ]
diff --git a/saleor/plugins/models.py b/saleor/plugins/models.py
index 68ef74de22..9c234256af 100644
--- a/saleor/plugins/models.py
+++ b/saleor/plugins/models.py
@@ -1,13 +1,17 @@
from django.db import models
from django.db.models import JSONField # type: ignore
+from ..channel.models import Channel
from ..core.permissions import PluginsPermissions
from ..core.utils.json_serializer import CustomJsonEncoder
class PluginConfiguration(models.Model):
- identifier = models.CharField(max_length=128, unique=True)
+ identifier = models.CharField(max_length=128)
name = models.CharField(max_length=128)
+ channel = models.ForeignKey(
+ Channel, blank=True, null=True, on_delete=models.CASCADE
+ )
description = models.TextField(blank=True)
active = models.BooleanField(default=False)
configuration = JSONField(
@@ -15,6 +19,7 @@ class PluginConfiguration(models.Model):
)
class Meta:
+ unique_together = ("identifier", "channel")
permissions = ((PluginsPermissions.MANAGE_PLUGINS.codename, "Manage plugins"),)
def __str__(self):
diff --git a/saleor/plugins/sendgrid/plugin.py b/saleor/plugins/sendgrid/plugin.py
index e6bf92d0cf..2c0036323d 100644
--- a/saleor/plugins/sendgrid/plugin.py
+++ b/saleor/plugins/sendgrid/plugin.py
@@ -94,6 +94,7 @@ class SendgridEmailPlugin(BasePlugin):
PLUGIN_ID = "mirumee.notifications.sendgrid_email"
PLUGIN_NAME = "Sendgrid"
DEFAULT_ACTIVE = False
+ CONFIGURATION_PER_CHANNEL = True
DEFAULT_CONFIGURATION = [
{"name": "sender_name", "value": ""},
diff --git a/saleor/plugins/sendgrid/tests/conftest.py b/saleor/plugins/sendgrid/tests/conftest.py
index ad3e26c332..662bc4d89a 100644
--- a/saleor/plugins/sendgrid/tests/conftest.py
+++ b/saleor/plugins/sendgrid/tests/conftest.py
@@ -5,7 +5,7 @@ from ..plugin import SendgridEmailPlugin
@pytest.fixture
-def sendgrid_email_plugin(settings):
+def sendgrid_email_plugin(settings, channel_USD):
def fun(
active=True,
sender_name=None,
@@ -31,6 +31,7 @@ def sendgrid_email_plugin(settings):
manager = get_plugins_manager()
manager.save_plugin_configuration(
SendgridEmailPlugin.PLUGIN_ID,
+ channel_USD.slug,
{
"active": active,
"configuration": [
@@ -97,6 +98,6 @@ def sendgrid_email_plugin(settings):
},
)
manager = get_plugins_manager()
- return manager.plugins[0]
+ return manager.plugins_per_channel[channel_USD.slug][0]
return fun
diff --git a/saleor/plugins/tests/fixtures.py b/saleor/plugins/tests/fixtures.py
index b2767faf81..86043eb181 100644
--- a/saleor/plugins/tests/fixtures.py
+++ b/saleor/plugins/tests/fixtures.py
@@ -1,10 +1,12 @@
+import copy
+
import pytest
from django_prices_vatlayer.models import VAT
from django_prices_vatlayer.utils import get_tax_for_rate
from ..base_plugin import ConfigurationTypeField
from ..models import PluginConfiguration
-from .sample_plugins import PluginInactive, PluginSample
+from .sample_plugins import ChannelPluginSample, PluginInactive, PluginSample
@pytest.fixture
@@ -22,10 +24,38 @@ def plugin_configuration(db):
return configuration
+def channel_plugin_configurations(db, channel_USD, channel_PLN):
+ usd_configuration = copy.deepcopy(ChannelPluginSample.DEFAULT_CONFIGURATION)
+ usd_configuration[0]["value"] = channel_USD.slug
+
+ pln_configuration = copy.deepcopy(ChannelPluginSample.DEFAULT_CONFIGURATION)
+ pln_configuration[0]["value"] = channel_PLN.slug
+
+ return PluginConfiguration.objects.bulk_create(
+ [
+ PluginConfiguration(
+ identifier=ChannelPluginSample.PLUGIN_ID,
+ channel=channel_USD,
+ name=ChannelPluginSample.PLUGIN_NAME,
+ active=ChannelPluginSample.DEFAULT_ACTIVE,
+ configuration=usd_configuration,
+ ),
+ PluginConfiguration(
+ identifier=ChannelPluginSample.PLUGIN_ID,
+ channel=channel_PLN,
+ name=ChannelPluginSample.PLUGIN_NAME,
+ active=ChannelPluginSample.DEFAULT_ACTIVE,
+ configuration=pln_configuration,
+ ),
+ ]
+ )
+
+
@pytest.fixture
def inactive_plugin_configuration(db):
return PluginConfiguration.objects.get_or_create(
- identifier=PluginSample.PLUGIN_ID,
+ identifier=PluginInactive.PLUGIN_ID,
name=PluginInactive.PLUGIN_NAME,
defaults={
"active": PluginInactive.DEFAULT_ACTIVE,
diff --git a/saleor/plugins/tests/sample_plugins.py b/saleor/plugins/tests/sample_plugins.py
index aa84c3ae08..db9af16bfa 100644
--- a/saleor/plugins/tests/sample_plugins.py
+++ b/saleor/plugins/tests/sample_plugins.py
@@ -26,6 +26,7 @@ class PluginSample(BasePlugin):
PLUGIN_NAME = "PluginSample"
PLUGIN_DESCRIPTION = "Test plugin description"
DEFAULT_ACTIVE = True
+ CONFIGURATION_PER_CHANNEL = False
DEFAULT_CONFIGURATION = [
{"name": "Username", "value": "admin"},
{"name": "Password", "value": None},
@@ -221,10 +222,28 @@ class PluginSample(BasePlugin):
return Decimal("0.080").quantize(Decimal(".01"))
+class ChannelPluginSample(PluginSample):
+ PLUGIN_ID = "channel.plugin.sample"
+ PLUGIN_NAME = "Channel Plugin"
+ PLUGIN_DESCRIPTION = "Test channel plugin"
+ DEFAULT_ACTIVE = True
+ CONFIGURATION_PER_CHANNEL = True
+ DEFAULT_CONFIGURATION = [{"name": "input-per-channel", "value": None}]
+ CONFIG_STRUCTURE = {
+ "input-per-channel": {
+ "type": ConfigurationTypeField.STRING,
+ "help_text": "Test input",
+ "label": "Input per channel",
+ }
+ }
+
+
class PluginInactive(BasePlugin):
- PLUGIN_ID = "plugin.inactive"
+ PLUGIN_ID = "mirumee.taxes.plugin.inactive"
PLUGIN_NAME = "PluginInactive"
PLUGIN_DESCRIPTION = "Test plugin description_2"
+ CONFIGURATION_PER_CHANNEL = False
+ DEFAULT_ACTIVE = False
def external_obtain_access_tokens(
self, data: dict, request: WSGIRequest, previous_value
@@ -235,14 +254,15 @@ class PluginInactive(BasePlugin):
class ActivePlugin(BasePlugin):
- PLUGIN_ID = "plugin.active"
+ PLUGIN_ID = "mirumee.x.plugin.active"
PLUGIN_NAME = "Active"
PLUGIN_DESCRIPTION = "Not working"
DEFAULT_ACTIVE = True
+ CONFIGURATION_PER_CHANNEL = False
class ActivePaymentGateway(BasePlugin):
- PLUGIN_ID = "gateway.active"
+ PLUGIN_ID = "mirumee.gateway.active"
CLIENT_CONFIG = [
{"field": "foo", "value": "bar"},
]
diff --git a/saleor/plugins/tests/test_manager.py b/saleor/plugins/tests/test_manager.py
index 6ec94da551..f364b77bfb 100644
--- a/saleor/plugins/tests/test_manager.py
+++ b/saleor/plugins/tests/test_manager.py
@@ -17,6 +17,7 @@ from ..models import PluginConfiguration
from ..tests.sample_plugins import (
ActiveDummyPaymentGateway,
ActivePaymentGateway,
+ ChannelPluginSample,
InactivePaymentGateway,
PluginInactive,
PluginSample,
@@ -28,7 +29,113 @@ def test_get_plugins_manager(settings):
settings.PLUGINS = [plugin_path]
manager = get_plugins_manager()
assert isinstance(manager, PluginsManager)
- assert len(manager.plugins) == 1
+ assert len(manager.all_plugins) == 1
+
+
+def test_manager_with_default_configuration_for_channel_plugins(
+ settings, channel_USD, channel_PLN
+):
+ settings.PLUGINS = [
+ "saleor.plugins.tests.sample_plugins.ChannelPluginSample",
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ ]
+ manager = get_plugins_manager()
+ assert len(manager.global_plugins) == 1
+ assert isinstance(manager.global_plugins[0], PluginSample)
+ assert {channel_PLN.slug, channel_USD.slug} == set(
+ manager.plugins_per_channel.keys()
+ )
+
+ for channel_slug, plugins in manager.plugins_per_channel.items():
+ assert len(plugins) == 2
+ assert all(
+ [
+ isinstance(plugin, (PluginSample, ChannelPluginSample))
+ for plugin in plugins
+ ]
+ )
+
+ # global plugin + plugins for each channel
+ assert len(manager.all_plugins) == 3
+
+
+def test_manager_with_channel_plugins(
+ settings, channel_USD, channel_PLN, channel_plugin_configurations
+):
+ settings.PLUGINS = [
+ "saleor.plugins.tests.sample_plugins.ChannelPluginSample",
+ ]
+ manager = get_plugins_manager()
+
+ assert {channel_PLN.slug, channel_USD.slug} == set(
+ manager.plugins_per_channel.keys()
+ )
+
+ for channel_slug, plugins in manager.plugins_per_channel.items():
+ assert len(plugins) == 1
+ # make sure that we load proper config from DB
+ assert plugins[0].configuration[0]["value"] == channel_slug
+
+ # global plugin + plugins for each channel
+ assert len(manager.all_plugins) == 2
+
+
+def test_manager_get_plugins_with_channel_slug(
+ settings, channel_USD, plugin_configuration, inactive_plugin_configuration
+):
+ settings.PLUGINS = [
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ ]
+ manager = get_plugins_manager()
+
+ plugins = manager.get_plugins(channel_slug=channel_USD.slug)
+
+ assert plugins == manager.plugins_per_channel[channel_USD.slug]
+
+
+def test_manager_get_active_plugins_with_channel_slug(
+ settings, channel_USD, plugin_configuration, inactive_plugin_configuration
+):
+ settings.PLUGINS = [
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ ]
+ manager = get_plugins_manager()
+
+ plugins = manager.get_plugins(channel_slug=channel_USD.slug, active_only=True)
+
+ assert len(plugins) == 1
+ assert isinstance(plugins[0], PluginSample)
+
+
+def test_manager_get_plugins_without_channel_slug(
+ settings, channel_USD, plugin_configuration, inactive_plugin_configuration
+):
+ settings.PLUGINS = [
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ ]
+ manager = get_plugins_manager()
+
+ plugins = manager.get_plugins(channel_slug=None)
+
+ assert plugins == manager.all_plugins
+
+
+def test_manager_get_active_plugins_without_channel_slug(
+ settings, channel_USD, plugin_configuration, inactive_plugin_configuration
+):
+ settings.PLUGINS = [
+ "saleor.plugins.tests.sample_plugins.PluginInactive",
+ "saleor.plugins.tests.sample_plugins.PluginSample",
+ ]
+ manager = get_plugins_manager()
+
+ plugins = manager.get_plugins(channel_slug=None, active_only=True)
+
+ assert len(plugins) == 1
+ assert isinstance(plugins[0], PluginSample)
@pytest.mark.parametrize(
@@ -422,6 +529,7 @@ def test_manager_apply_taxes_to_product(product, plugins, price, channel_USD):
variant.product, [], channel_USD, variant_channel_listing, None
),
country,
+ channel_USD.slug,
)
assert TaxedMoney(expected_price, expected_price) == taxed_price
@@ -438,7 +546,7 @@ def test_manager_apply_taxes_to_shipping(
).price
expected_price = Money(price_amount, "USD")
taxed_price = PluginsManager(plugins=plugins).apply_taxes_to_shipping(
- shipping_price, address
+ shipping_price, address, channel_slug=channel_USD.slug
)
assert TaxedMoney(expected_price, expected_price) == taxed_price
@@ -455,17 +563,6 @@ def test_manager_get_tax_rate_percentage_value(plugins, amount, product):
assert tax_rate_value == Decimal(amount)
-def test_manager_get_plugin_configurations(plugin_configuration):
- plugins = [
- "saleor.plugins.tests.sample_plugins.PluginSample",
- "saleor.plugins.tests.sample_plugins.PluginInactive",
- ]
- manager = PluginsManager(plugins=plugins)
- plugin_configs = manager._plugin_configs.values()
- assert len(plugin_configs) == 1
- assert set(plugin_configs) == set(list(PluginConfiguration.objects.all()))
-
-
def test_manager_get_plugin_configuration(plugin_configuration):
plugins = [
"saleor.plugins.tests.sample_plugins.PluginSample",
@@ -482,7 +579,7 @@ def test_manager_get_plugin_configuration(plugin_configuration):
def test_manager_save_plugin_configuration(plugin_configuration):
plugins = ["saleor.plugins.tests.sample_plugins.PluginSample"]
manager = PluginsManager(plugins=plugins)
- manager.save_plugin_configuration(PluginSample.PLUGIN_ID, {"active": False})
+ manager.save_plugin_configuration(PluginSample.PLUGIN_ID, None, {"active": False})
plugin_configuration.refresh_from_db()
assert not plugin_configuration.active
@@ -534,7 +631,7 @@ def test_plugin_add_new_configuration(
assert plugin.configuration[0] == {**new_config, **new_config_structure}
-def test_manager_serve_list_of_payment_gateways():
+def test_manager_serve_list_of_payment_gateways(channel_USD):
expected_gateway = PaymentGateway(
id=ActivePaymentGateway.PLUGIN_ID,
name=ActivePaymentGateway.PLUGIN_NAME,
@@ -550,7 +647,7 @@ def test_manager_serve_list_of_payment_gateways():
assert manager.list_payment_gateways() == [expected_gateway]
-def test_manager_serve_list_all_payment_gateways():
+def test_manager_serve_list_all_payment_gateways(channel_USD):
expected_gateways = [
PaymentGateway(
id=ActivePaymentGateway.PLUGIN_ID,
@@ -574,7 +671,7 @@ def test_manager_serve_list_all_payment_gateways():
assert manager.list_payment_gateways(active_only=False) == expected_gateways
-def test_manager_serve_list_all_payment_gateways_specified_currency():
+def test_manager_serve_list_all_payment_gateways_specified_currency(channel_USD):
expected_gateways = [
PaymentGateway(
id=ActiveDummyPaymentGateway.PLUGIN_ID,
@@ -596,7 +693,9 @@ def test_manager_serve_list_all_payment_gateways_specified_currency():
)
-def test_manager_serve_list_all_payment_gateways_specified_currency_two_gateways():
+def test_manager_serve_list_all_payment_gateways_specified_currency_two_gateways(
+ channel_USD,
+):
expected_gateways = [
PaymentGateway(
id=ActivePaymentGateway.PLUGIN_ID,
@@ -743,7 +842,7 @@ def test_manager_external_verify(rf, admin_user):
assert response_data == {"some_data": "data"}
-def test_list_external_authentications():
+def test_list_external_authentications(channel_USD):
plugins = [
"saleor.plugins.tests.sample_plugins.PluginInactive",
"saleor.plugins.tests.sample_plugins.ActivePaymentGateway",
@@ -762,7 +861,7 @@ def test_list_external_authentications():
} in external_auths
-def test_list_external_authentications_active_only():
+def test_list_external_authentications_active_only(channel_USD):
plugins = [
"saleor.plugins.tests.sample_plugins.PluginInactive",
"saleor.plugins.tests.sample_plugins.ActivePaymentGateway",
diff --git a/saleor/plugins/user_email/plugin.py b/saleor/plugins/user_email/plugin.py
index 9f30c6d1fa..c1cfb9b77b 100644
--- a/saleor/plugins/user_email/plugin.py
+++ b/saleor/plugins/user_email/plugin.py
@@ -108,6 +108,7 @@ def get_user_event_map():
class UserEmailPlugin(BasePlugin):
PLUGIN_ID = constants.PLUGIN_ID
PLUGIN_NAME = "User emails"
+ CONFIGURATION_PER_CHANNEL = True
DEFAULT_CONFIGURATION = [
{
diff --git a/saleor/plugins/user_email/tests/conftest.py b/saleor/plugins/user_email/tests/conftest.py
index 56b64dfe01..f15d0be84d 100644
--- a/saleor/plugins/user_email/tests/conftest.py
+++ b/saleor/plugins/user_email/tests/conftest.py
@@ -64,7 +64,7 @@ def user_email_dict_config():
@pytest.fixture
-def user_email_plugin(settings):
+def user_email_plugin(settings, channel_USD):
def fun(
host="localhost",
port="1025",
@@ -112,6 +112,7 @@ def user_email_plugin(settings):
):
manager.save_plugin_configuration(
UserEmailPlugin.PLUGIN_ID,
+ channel_USD.slug,
{
"active": active,
"configuration": [
@@ -239,6 +240,6 @@ def user_email_plugin(settings):
},
)
manager = get_plugins_manager()
- return manager.plugins[0]
+ return manager.plugins_per_channel[channel_USD.slug][0]
return fun
diff --git a/saleor/plugins/vatlayer/tests/conftest.py b/saleor/plugins/vatlayer/tests/conftest.py
index cc70336fd4..3cb0250a37 100644
--- a/saleor/plugins/vatlayer/tests/conftest.py
+++ b/saleor/plugins/vatlayer/tests/conftest.py
@@ -7,7 +7,7 @@ from ..plugin import VatlayerPlugin
@pytest.fixture
-def vatlayer_plugin(settings, vatlayer):
+def vatlayer_plugin(settings, vatlayer, channel_USD):
def fun(
active=True,
access_key="key",
@@ -20,6 +20,7 @@ def vatlayer_plugin(settings, vatlayer):
with patch("saleor.plugins.vatlayer.plugin.fetch_rate_types"):
manager.save_plugin_configuration(
VatlayerPlugin.PLUGIN_ID,
+ channel_USD.slug,
{
"active": active,
"configuration": [
@@ -34,6 +35,6 @@ def vatlayer_plugin(settings, vatlayer):
},
)
manager = get_plugins_manager()
- return manager.plugins[0]
+ return manager.plugins_per_channel[channel_USD.slug][0]
return fun
diff --git a/saleor/plugins/vatlayer/tests/test_vatlayer.py b/saleor/plugins/vatlayer/tests/test_vatlayer.py
index f154a1519f..ce5e1ae3f6 100644
--- a/saleor/plugins/vatlayer/tests/test_vatlayer.py
+++ b/saleor/plugins/vatlayer/tests/test_vatlayer.py
@@ -193,7 +193,7 @@ def test_vatlayer_plugin_caches_taxes(
)
manager = get_plugins_manager()
- plugin = manager.get_plugin(VatlayerPlugin.PLUGIN_ID)
+ plugin = manager.get_plugin(VatlayerPlugin.PLUGIN_ID, channel_slug=channel_USD.slug)
variant = product.variants.first()
channel_listing = variant.channel_listings.get(channel=channel_USD)
price = variant.get_price(product, [], channel_USD, channel_listing, None)
@@ -840,21 +840,26 @@ def test_get_tax_rate_percentage_value_with_excluded_country(
assert tax_rate == Decimal("0")
-def test_save_plugin_configuration(vatlayer, settings):
+def test_save_plugin_configuration(vatlayer, settings, channel_USD):
settings.PLUGINS = ["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
manager = get_plugins_manager()
- manager.save_plugin_configuration(VatlayerPlugin.PLUGIN_ID, {"active": False})
+ manager.save_plugin_configuration(
+ VatlayerPlugin.PLUGIN_ID, channel_USD.slug, {"active": False}
+ )
configuration = PluginConfiguration.objects.get(identifier=VatlayerPlugin.PLUGIN_ID)
assert not configuration.active
-def test_save_plugin_configuration_cannot_be_enabled_without_config(settings):
+def test_save_plugin_configuration_cannot_be_enabled_without_config(
+ settings, channel_USD
+):
settings.PLUGINS = ["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
manager = get_plugins_manager()
with pytest.raises(ValidationError):
manager.save_plugin_configuration(
VatlayerPlugin.PLUGIN_ID,
+ channel_USD.slug,
{"active": True},
)
@@ -904,6 +909,7 @@ def test_apply_taxes_to_product(
variant.product, [], channel_USD, variant_channel_listing, [discount_info]
),
country,
+ channel_USD.slug,
)
assert price == TaxedMoney(net=Money("4.07", "USD"), gross=Money("5.00", "USD"))
@@ -930,6 +936,7 @@ def test_apply_taxes_to_product_from_origin_country(
variant.product, [], channel_USD, variant_channel_listing, [discount_info]
),
country,
+ channel_USD.slug,
)
assert price == TaxedMoney(net=Money("4.20", "USD"), gross=Money("5.00", "USD"))
@@ -955,6 +962,7 @@ def test_apply_taxes_to_product_with_excluded_country(
variant.product, [], channel_USD, variant_channel_listing, [discount_info]
),
country,
+ channel_USD.slug,
)
assert price == TaxedMoney(net=Money("5.00", "USD"), gross=Money("5.00", "USD"))
@@ -979,6 +987,7 @@ def test_apply_taxes_to_product_uses_taxes_from_product_type(
product, [], channel_USD, variant_channel_listing, [discount_info]
),
country,
+ channel_USD.slug,
)
assert price == TaxedMoney(net=Money("4.07", "USD"), gross=Money("5.00", "USD"))
@@ -1037,10 +1046,12 @@ def test_calculations_checkout_shipping_price_with_vatlayer(
)
-def test_skip_diabled_plugin(settings):
+def test_skip_diabled_plugin(settings, channel_USD):
settings.PLUGINS = ["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
manager = get_plugins_manager()
- plugin: VatlayerPlugin = manager.get_plugin(VatlayerPlugin.PLUGIN_ID)
+ plugin: VatlayerPlugin = manager.get_plugin(
+ VatlayerPlugin.PLUGIN_ID, channel_USD.slug
+ )
assert (
plugin._skip_plugin(
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 903090cbf6..1c72ba42eb 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -31,6 +31,7 @@ class WebhookPlugin(BasePlugin):
PLUGIN_ID = "mirumee.webhooks"
PLUGIN_NAME = "Webhooks"
DEFAULT_ACTIVE = True
+ CONFIGURATION_PER_CHANNEL = False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
diff --git a/saleor/plugins/webhook/tests/test_webhook.py b/saleor/plugins/webhook/tests/test_webhook.py
index ab4169b31b..a35f173710 100644
--- a/saleor/plugins/webhook/tests/test_webhook.py
+++ b/saleor/plugins/webhook/tests/test_webhook.py
@@ -364,12 +364,12 @@ def test_invoice_sent(mocked_webhook_trigger, settings, fulfilled_order):
@freeze_time("2020-03-18 12:00:00")
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_for_event.delay")
-def test_notify_user(mocked_webhook_trigger, settings, customer_user):
+def test_notify_user(mocked_webhook_trigger, settings, customer_user, channel_USD):
settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
manager = get_plugins_manager()
redirect_url = "http://redirect.com/"
- send_account_confirmation(customer_user, redirect_url, manager)
+ send_account_confirmation(customer_user, redirect_url, manager, channel_USD.slug)
token = default_token_generator.make_token(customer_user)
params = urlencode({"email": customer_user.email, "token": token})
@@ -380,6 +380,7 @@ def test_notify_user(mocked_webhook_trigger, settings, customer_user):
"recipient_email": customer_user.email,
"token": token,
"confirm_url": confirm_url,
+ "channel_slug": channel_USD.slug,
**get_site_context(),
}
diff --git a/saleor/product/utils/availability.py b/saleor/product/utils/availability.py
index 027cc81621..fddc64b30d 100644
--- a/saleor/product/utils/availability.py
+++ b/saleor/product/utils/availability.py
@@ -152,6 +152,8 @@ def get_product_availability(
) -> ProductAvailability:
country = country or Country(settings.DEFAULT_COUNTRY)
with opentracing.global_tracer().start_active_span("get_product_availability"):
+ channel_slug = channel.slug
+
discounted = None
discounted_net_range = get_product_price_range(
product=product,
@@ -164,10 +166,16 @@ def get_product_availability(
if discounted_net_range is not None:
discounted = TaxedMoneyRange(
start=manager.apply_taxes_to_product(
- product, discounted_net_range.start, country
+ product,
+ discounted_net_range.start,
+ country,
+ channel_slug=channel_slug,
),
stop=manager.apply_taxes_to_product(
- product, discounted_net_range.stop, country
+ product,
+ discounted_net_range.stop,
+ country,
+ channel_slug=channel_slug,
),
)
@@ -183,10 +191,16 @@ def get_product_availability(
if undiscounted_net_range is not None:
undiscounted = TaxedMoneyRange(
start=manager.apply_taxes_to_product(
- product, undiscounted_net_range.start, country
+ product,
+ undiscounted_net_range.start,
+ country,
+ channel_slug=channel_slug,
),
stop=manager.apply_taxes_to_product(
- product, undiscounted_net_range.stop, country
+ product,
+ undiscounted_net_range.stop,
+ country,
+ channel_slug=channel_slug,
),
)
@@ -228,6 +242,7 @@ def get_variant_availability(
) -> VariantAvailability:
country = country or Country(settings.DEFAULT_COUNTRY)
with opentracing.global_tracer().start_active_span("get_variant_availability"):
+ channel_slug = channel.slug
discounted = plugins.apply_taxes_to_product(
product,
get_variant_price(
@@ -239,6 +254,7 @@ def get_variant_availability(
channel=channel,
),
country,
+ channel_slug=channel_slug,
)
undiscounted = plugins.apply_taxes_to_product(
product,
@@ -251,6 +267,7 @@ def get_variant_availability(
channel=channel,
),
country,
+ channel_slug=channel_slug,
)
discount = _get_total_discount(undiscounted, discounted)
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 8f37477c98..69cbf7ed3f 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -194,10 +194,11 @@ def assert_max_num_queries(capture_queries):
@pytest.fixture
-def setup_vatlayer(settings):
+def setup_vatlayer(settings, channel_USD):
settings.PLUGINS = ["saleor.plugins.vatlayer.plugin.VatlayerPlugin"]
data = {
"active": True,
+ "channel": channel_USD,
"configuration": [
{"name": "Access key", "value": "vatlayer_access_key"},
],